From 3a12a5f5a5efd663f732f39db2ecf8443233525f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:22:25 -0700 Subject: [PATCH 01/19] docs: reserve ADR 0048 for GPU binning and outlines (M3) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..f974a6d8 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0048 | m3/gpu-binning | GPU stage, fourth slice: tile binning on the GPU, cheap outlines | From 0fbf8c5d0f5b67aeef1d94ed5f9bf36c4095555b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:48:46 -0700 Subject: [PATCH 02/19] feat(render): hairlines for outline mode, and integer tile backdrops in the GPU binning (M3) Outline mode (an outlined layer, onion skin's outlines) draws hairlines straight from the flattened path: coverage 1 - the distance to the nearest segment, one edge per segment where a stroked hairline was four plus a disc at every bend. Exact for axis- aligned lines, no darkening at overlaps and joins. The GPU stage computes the same. The binning's per-row float backdrops become one integer per tile plus a piece on the tile's left edge wherever the outline crosses it (Vello's backdrops and y-edges), which lets the GPU compute the same lists without float atomics. Parity unchanged. --- crates/gpu/examples/gpu_bench.rs | 81 ++++++-- crates/gpu/src/binning.rs | 316 ++++++++++++++++++++----------- crates/gpu/src/fine.wgsl | 54 ++++-- crates/gpu/src/tests.rs | 58 +++++- crates/render/src/hairline.rs | 169 +++++++++++++++++ crates/render/src/lib.rs | 53 +++++- crates/render/src/raster.rs | 29 ++- 7 files changed, 612 insertions(+), 148 deletions(-) create mode 100644 crates/render/src/hairline.rs diff --git a/crates/gpu/examples/gpu_bench.rs b/crates/gpu/examples/gpu_bench.rs index b932f0fb..a8df5239 100644 --- a/crates/gpu/examples/gpu_bench.rs +++ b/crates/gpu/examples/gpu_bench.rs @@ -11,7 +11,7 @@ //! stage's way (512 px tiles drawn in parallel, as the render service does, until finished); //! the work the fine pass did; and how far the GPU's picture is from the oracle's. -use anicraft_doc::{Bitmap, BitmapId, ColorEffect, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; +use anicraft_doc::{Bitmap, BitmapId, ColorEffect, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; use anicraft_geom::{FillRule, Path}; use anicraft_gpu::{GpuRenderer, Output, compare_premul8}; use anicraft_geom::Affine; @@ -139,6 +139,57 @@ fn filtered() -> Document { doc } +/// Onion skin as the stage composes it (ADR 0047), for the bench: no onion skin, ±5 frames +/// tinted and fading, or ±5 frames as outlines. +#[derive(Clone, Copy, PartialEq)] +enum Onion { + Off, + Tinted, + Outlines, +} + +/// Frame `frame` with ±5 onion frames, as `anicraft_engine::onion::compose` draws them with +/// the default colours, tint and fade: each frame's items under the playhead's on their own +/// layer (nearest on top), at its alpha and tint, or as hairline outlines in its colour. (The +/// engine sits beside this crate, so the bench builds the same list itself.) +fn onion_list(doc: &Document, frame: u32, mode: Onion) -> DisplayList { + let now = evaluate(doc, frame); + if mode == Onion::Off { + return now; + } + let frames = doc.frame_count().max(1); + let (past, future) = (Rgba::hex(0x4f8dff), Rgba::hex(0x4cd07d)); + let rank: std::collections::HashMap = doc.timeline(0).layers.iter().enumerate().map(|(i, l)| (l.id, i)).collect(); + let mut dl = DisplayList::default(); + let mut part_of: Vec = Vec::new(); + for d in (1..=5u32).rev() { + for (is_past, f) in [(true, frame.checked_sub(d)), (false, Some(frame + d).filter(|f| *f < frames))] { + let Some(f) = f else { continue }; + // Fading from 0.5 next to the playhead to 0.12 at the marker; tinted at 0.8. + let alpha = 0.5 + (0.12 - 0.5) * (d - 1) as f32 / 4.0; + let color = if is_past { past } else { future }; + let mut part = evaluate(doc, f); + for item in &mut part.items { + item.color = item.color.concat(&ColorEffect { alpha, tint: color, tint_amount: 0.8 }); + if mode == Onion::Outlines && item.masks.is_none() { + item.outline = Some(color.with_alpha(alpha)); + } + } + part_of.extend(std::iter::repeat_n(part_of.last().map_or(0, |p| p + 1), part.items.len())); + dl.append(part); + } + } + let k = part_of.last().map_or(0, |p| p + 1); + part_of.extend(std::iter::repeat_n(k, now.items.len())); + dl.append(now); + // Layer by layer, bottom first; within a layer, the parts in order (a stable sort). + let mut order: Vec = (0..dl.items.len()).collect(); + order.sort_by_key(|&i| (std::cmp::Reverse(dl.items.get(i).and_then(|it| rank.get(&it.layer)).copied().unwrap_or(0)), part_of.get(i).copied().unwrap_or(0))); + let mut items: Vec> = std::mem::take(&mut dl.items).into_iter().map(Some).collect(); + dl.items = order.into_iter().filter_map(|i| items.get_mut(i).and_then(Option::take)).collect(); + dl +} + fn main() { let gpu = match GpuRenderer::new() { Ok(g) => g, @@ -150,24 +201,32 @@ fn main() { println!("adapter: {}", gpu.adapter); let (layers, shapes) = (arg("--layers", 50), arg("--shapes", 200)); let runs = arg("--runs", 12); - let scenes: Vec<(String, Document)> = vec![ - (format!("stress {layers}×{shapes}"), sample::stress(layers, shapes, 240)), - ("1,000 shapes".into(), sample::stress(5, 200, 240)), - (format!("masked {layers}×{shapes}"), masked(sample::stress(layers, shapes, 240))), - ("sample".into(), sample::demo()), - ("composited sample".into(), composited()), - ("filtered sample".into(), filtered()), - ("200 bitmaps".into(), bitmaps()), + let only: Option = std::env::args().skip_while(|a| a != "--only").nth(1); + let onion_doc = sample::stress(20, 100, 48); + let plain = |name: String, doc: Document| (name, doc, Onion::Off); + let scenes: Vec<(String, Document, Onion)> = vec![ + plain(format!("stress {layers}×{shapes}"), sample::stress(layers, shapes, 240)), + plain("1,000 shapes".into(), sample::stress(5, 200, 240)), + plain("50,000 shapes".into(), sample::stress(250, 200, 240)), + plain(format!("masked {layers}×{shapes}"), masked(sample::stress(layers, shapes, 240))), + plain("sample".into(), sample::demo()), + plain("composited sample".into(), composited()), + plain("filtered sample".into(), filtered()), + plain("200 bitmaps".into(), bitmaps()), + ("onion off 20×100".into(), onion_doc.clone(), Onion::Off), + ("onion ±5 tinted".into(), onion_doc.clone(), Onion::Tinted), + ("onion ±5 outlines".into(), onion_doc, Onion::Outlines), ]; println!( "{:<20} {:>10} {:>8} {:>9} {:>9} {:>9} {:>7} {:>22} {:>8} {:>8} parity (mean / max / differing px)", "scene", "size", "CPU ms", "readback", "direct", "direct+", "tiled", "prepare + bin + submit", "entries", "pieces" ); - for (name, doc) in &scenes { + for (name, doc, onion) in scenes.iter().filter(|(n, ..)| only.as_ref().is_none_or(|o| n.contains(o.as_str()))) { for scale in [1.0f32, 2.0] { let v = View::stage(doc, scale * 1920.0 / doc.stage.width as f32); let frames = doc.frame_count().max(1); - let dl0 = evaluate(doc, 0); + let evaluate = |doc: &Document, f: u32| onion_list(doc, f, *onion); + let dl0 = evaluate(doc, if *onion == Onion::Off { 0 } else { 30 }); // Warm-up (pipeline caches, allocations). let _ = gpu.render(&dl0, &v, Output::Premul8); let _ = gpu.render_texture(&dl0, &v); diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index c944a57d..7f0407c1 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -1,13 +1,26 @@ //! Tile binning: the CPU half of the GPU stage (ADR 0019, ADR 0029). //! //! The surface is cut into 16 × 16 pixel tiles. Every fill's edges are split at tile rows and -//! columns; each piece lands in the one tile it crosses. What a piece contributes to the tiles -//! to its right is a plain winding change per pixel row (it lies wholly to their left), so it -//! is summed into a **backdrop** of 16 values, one per pixel row, carried across the tile row -//! as in the public sparse-strips and Vello designs. A tile of a fill then needs only its own -//! pieces and its backdrop: the fine shader computes each pixel's exact area coverage from -//! those, the same integral the CPU oracle's accumulation buffer computes (ADR 0002). Tiles -//! with neither (outside the fill) get no entry; interior tiles get a backdrop and no pieces. +//! columns; each piece lands in the one tile it crosses. Everything left of a tile reaches it +//! as the fill's winding number along the tile's left edge (ADR 0048), which is +//! +//! * its **backdrop**, the winding number just below the tile's top-left corner: an integer, +//! the sum of the directions of the pieces further left that start on the tile row's top +//! edge (they are the edges crossing it), plus +//! * a step wherever the outline crosses the tile's left edge, kept as one more piece: a +//! vertical line on that edge from the crossing down to the tile's bottom, upwards where the +//! outline crosses rightwards (the winding there drops by one), downwards where it crosses +//! leftwards. +//! +//! These are the backdrops and "y-edges" of Vello's tiles (its public design notes). A tile of +//! a fill then needs only its own pieces and its backdrop: the fine shader computes each +//! pixel's exact area coverage from those, the same integral the CPU oracle's accumulation +//! buffer computes (ADR 0002). Tiles with neither (outside the fill) get no entry; interior +//! tiles get a backdrop and no pieces. Backdrops are integers, so they add up the same in any +//! order, and the GPU computes the same lists ([`crate::gpu_binning`]). +//! +//! A **hairline** (outline mode, ADR 0048) is binned by distance instead: each segment, whole, +//! into every tile with a pixel centre within its reach; the shader takes the nearest. //! //! Each tile then lists its entries in drawing order, so the shader composites every pixel in //! one pass, front to back in the display list's order. Masks and groups (ADR 0029) are more @@ -34,8 +47,10 @@ type Vec4 = [f32; 4]; /// Tile side in pixels (the shader's workgroup is one tile, one invocation per pixel). pub const TILE: u32 = 16; const T: f32 = TILE as f32; -/// "No backdrop" in an entry; "no clip" or "no group" in the tables. +/// "No clip" or "no group" in the tables. pub const NONE: u32 = u32::MAX; +/// Fill rule code of a hairline in an op header (`0` non-zero, `1` even-odd). +pub const HAIRLINE: u32 = 2; /// `vec4`s of paint data per fill. pub const PAINT_VEC4S: usize = 4; /// Gradient table entries (the oracle's LUT size). @@ -97,11 +112,10 @@ pub fn blend_code(m: BlendMode) -> u32 { /// A scene ready for the fine shader. /// /// * `index` (u32): `[start, count]` per tile into the entry list; then each entry as -/// `[op, first piece, pieces, backdrop]` (the backdrop's first `vec4` in `geo`, or [`NONE`]), -/// or a control entry ([`CTRL`] set); then each op's header `[kind, fill rule, ramp start in -/// paints, flags]`. +/// `[op, first piece, pieces, backdrop]` (the backdrop an `i32`), or a control entry ([`CTRL`] +/// set); then each op's header `[kind, fill rule (or HAIRLINE), ramp start in paints, flags]`. /// * `geo` (`vec4`): pieces `(x0, y0, x1, y1)` relative to their tile's top-left, in the -/// edge's direction; then backdrops, four `vec4`s (16 rows) each. +/// edge's direction (left-edge steps included); a hairline's are its segments, whole. /// * `paints` (`vec4`): per op its colour, then the inverse paint transform and gradient, /// bitmap or layer parameters; then the gradient tables (256 premultiplied colours each); /// then (filled in on the GPU, [`Binned::layer_at`]) the filtered layers' pixels. @@ -133,11 +147,9 @@ pub struct Binned { /// A chunk of fills' share of the scene (binned in parallel; chunking keeps allocations few). #[derive(Default)] struct Local { - /// `[op, tile, first piece, pieces, backdrop or NONE]`, piece and backdrop indices local. + /// `[op, tile, first piece, pieces, backdrop]`, piece indices local. entries: Vec<[u32; 5]>, pieces: Vec<[f32; 4]>, - /// Backdrops, four `vec4`s (16 pixel rows) each. - backdrops: Vec<[f32; 4]>, } /// An edge piece inside one tile row, in absolute pixels; `col` is the tile column relative to @@ -204,6 +216,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let op_group: Vec = scene.fills.iter().map(|f| f.group.filter(|&g| (g as usize) < scene.groups.len()).unwrap_or(NONE)).collect(); let tables = Tables { fills: nf as u32, op_clip, op_group, clip_chain, art_ops, scene }; + let __t=std::time::Instant::now(); let tiles_x = width.div_ceil(TILE); let tiles_y = height.div_ceil(TILE); let (tx, ty) = (tiles_x as usize, tiles_y as usize); @@ -232,20 +245,19 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result }) .collect(); - // Where each chunk's pieces and backdrops go in `geo`. + let __a=__t.elapsed().as_secs_f32()*1000.0; + // Where each chunk's pieces go in `geo`. let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum(); let mut piece_at = Vec::with_capacity(locals.len()); - let mut bd_at = Vec::with_capacity(locals.len()); - let (mut p, mut b) = (0usize, pieces); + let mut p = 0usize; for (l, _) in &locals { piece_at.push(p as u32); - bd_at.push(b as u32); p += l.pieces.len(); - b += l.backdrops.len(); } // Phase 2, parallel over tile rows: each tile's stream of entries. - let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &bd_at, &tables)).collect(); + let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &tables)).collect(); + let __b=__t.elapsed().as_secs_f32()*1000.0; let mut row_at = vec![0usize; ty + 1]; for (r, out) in rows.iter().enumerate() { row_at[r + 1] = row_at[r] + out.stream.len(); @@ -274,24 +286,24 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result } }); } - // Pieces, then backdrops, copied in parallel into their places. - let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; b]; + let __c=__t.elapsed().as_secs_f32()*1000.0; + // Pieces copied in parallel into their places. + let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces]; { - let (mut piece_dst, mut bd_dst) = geo.split_at_mut(pieces); - let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(2 * locals.len()); + let mut piece_dst = &mut geo[..]; + let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(locals.len()); for (l, _) in &locals { let (a, rest) = std::mem::take(&mut piece_dst).split_at_mut(l.pieces.len()); jobs.push((a, &l.pieces)); piece_dst = rest; - let (a, rest) = std::mem::take(&mut bd_dst).split_at_mut(l.backdrops.len()); - jobs.push((a, &l.backdrops)); - bd_dst = rest; } jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s)); } // Tens of thousands of small buffers: free them on the pool, off the frame's path. anicraft_render::drop_in_background((locals, rows)); + let __d=__t.elapsed().as_secs_f32()*1000.0; + if width>1000 {eprintln!("bin {width}: fills {__a:.2} rows {:.2} index {:.2} geo {:.2}", __b-__a, __c-__b, __d-__c);} // Paints: a fixed record per op, then the gradient tables, then the layers' pixels. let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len()); let mut ramps: Vec<[f32; 4]> = Vec::new(); @@ -316,6 +328,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let u = f32::from_bits; for (op, f) in ops.iter().enumerate() { let rule = match f.rule { + _ if f.hairline => HAIRLINE, FillRule::NonZero => 0, FillRule::EvenOdd => 1, }; @@ -403,7 +416,7 @@ fn colour_effect(fx: &anicraft_doc::ColorEffect) -> (f32, f32, [f32; 3], u32) { /// Tile row `r`'s streams: per tile, its fills in drawing order with the clip and group /// entries they need. -fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u32], bd_at: &[u32], t: &Tables) -> RowOut { +fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u32], t: &Tables) -> RowOut { let first_tile = (r * tx) as u32; let slices = || { locals.iter().enumerate().map(move |(c, (l, rows))| { @@ -430,13 +443,12 @@ fn row_streams(r: usize, tx: usize, locals: &[(Local, Vec)], piece_at: &[u3 let mut ae = vec![[0u32; 4]; nart]; let mut cursor: Vec<[u32; 2]> = count[..tx].to_vec(); for (c, es) in slices() { - let (p0, b0) = (piece_at.get(c).copied().unwrap_or(0), bd_at.get(c).copied().unwrap_or(0)); + let p0 = piece_at.get(c).copied().unwrap_or(0); for &[op, tile, s0, n, bd] in es { let Some(cur) = cursor.get_mut(tile.wrapping_sub(first_tile) as usize) else { continue }; let art = usize::from(op >= t.fills); let at = cur[art] as usize; cur[art] += 1; - let bd = if bd == NONE { NONE } else { b0 + bd }; let slot = if art == 1 { ae.get_mut(at) } else { fe.get_mut(at) }; if let Some(slot) = slot { *slot = [op, p0 + s0, n, bd]; @@ -514,30 +526,26 @@ fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec< } } -/// Splits one fill's edges into tile pieces and walks each tile row for backdrops. +/// Splits one fill's edges into tile pieces (with the steps where its outline crosses a tile's +/// left edge) and walks each tile row for the backdrops. fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, pieces: &mut Vec) { - let b = f.bounds; - if b.is_empty() { - return; - } - let tx0 = b.x0.max(0) as u32 / TILE; - let tx1 = (b.x1.max(0) as u32).div_ceil(TILE).min(tiles_x); - let ty0 = b.y0.max(0) as u32 / TILE; - let ty1 = (b.y1.max(0) as u32).div_ceil(TILE).min(tiles_y); - if tx1 <= tx0 || ty1 <= ty0 { - return; - } - let ncols = (tx1 - tx0) as i32; - let range = Range { ylo: (ty0 * TILE) as f32, yhi: (ty1 * TILE) as f32, xlo: (tx0 * TILE) as f32, xhi: (tx1 * TILE) as f32, ncols }; + let Some(range) = Range::of(f, tiles_x, tiles_y) else { return }; pieces.clear(); - for poly in &f.polys { - let n = poly.len(); - if n < 2 { - continue; + if f.hairline { + for poly in &f.polys { + for_segments(poly, |a, b| hairline_tiles(a, b, &range, |row, col| pieces.push(Piece { row, col, seg: [a.x, a.y, b.x, b.y] }))); } - for i in 0..n { - let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; - split_edge(a, c, &range, pieces); + } else { + for poly in &f.polys { + let n = poly.len(); + if n < 2 { + continue; + } + for i in 0..n { + let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; + split_edge(a, c, &range, |p| pieces.push(p)); + crossings(a, c, &range, |p| pieces.push(p)); + } } } if pieces.is_empty() { @@ -549,53 +557,37 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec let mut i = 0usize; while let Some(first) = pieces.get(i) { let row = first.row; - let row_y0 = ((ty0 + row) * TILE) as f32; - let mut wind = [0.0f32; 16]; - // Parts left of the fill's tiles only shift the winding. + let row_y0 = range.row_y0(row); + // Pieces left of the fill's tiles only count where they start on the row's top edge. + let mut backdrop = 0i32; while let Some(p) = pieces.get(i).filter(|p| p.row == row && p.col < 0) { - add_rows(&mut wind, &p.seg, row_y0); + backdrop += top_crossing(&p.seg, row_y0); i += 1; } - let mut last_bd: Option<(u32, [f32; 16])> = None; - for col in 0..ncols { + for col in 0..range.ncols { let start = i; while pieces.get(i).is_some_and(|p| p.row == row && p.col == col) { i += 1; } let here = pieces.get(start..i).unwrap_or(&[]); - let empty_wind = wind.iter().all(|w| w.abs() < 1e-6); - if empty_wind { - wind = [0.0; 16]; - } - if here.is_empty() && empty_wind { + if here.is_empty() && backdrop == 0 { // Nothing here; and nothing further right either once the row's pieces are used. if !pieces.get(i).is_some_and(|p| p.row == row) { break; } continue; } - let tile_x = tx0 + col as u32; - let tile = (ty0 + row) * tiles_x + tile_x; - let bd = if empty_wind { - NONE - } else { - match last_bd { - Some((k, w)) if w == wind => k, - _ => { - let k = out.backdrops.len() as u32; - out.backdrops.extend_from_slice(wind.as_chunks::<4>().0); - last_bd = Some((k, wind)); - k - } - } - }; + let tile_x = range.tx0 + col as u32; + let tile = (range.ty0 + row) * tiles_x + tile_x; let (ox, oy) = ((tile_x * TILE) as f32, row_y0); let s0 = out.pieces.len() as u32; for p in here { out.pieces.push([p.seg[0] - ox, p.seg[1] - oy, p.seg[2] - ox, p.seg[3] - oy]); - add_rows(&mut wind, &p.seg, row_y0); } - out.entries.push([op, tile, s0, here.len() as u32, bd]); + out.entries.push([op, tile, s0, here.len() as u32, backdrop as u32]); + if !f.hairline { + backdrop += here.iter().map(|p| top_crossing(&p.seg, row_y0)).sum::(); + } } // Skip whatever is left of this row (pieces right of the range never get here). while pieces.get(i).is_some_and(|p| p.row == row) { @@ -604,33 +596,67 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec } } -/// The fill's tile range, in pixels and tiles. -struct Range { - ylo: f32, - yhi: f32, - xlo: f32, - xhi: f32, - ncols: i32, -} - -/// Adds the winding a piece gives everything to its right, per pixel row of its tile row. -fn add_rows(wind: &mut [f32; 16], seg: &[f32; 4], row_y0: f32) { - let (ya, yb, dir) = if seg[1] < seg[3] { (seg[1], seg[3], 1.0) } else { (seg[3], seg[1], -1.0) }; - let r0 = ((ya - row_y0).floor().max(0.0)) as usize; - let r1 = ((yb - row_y0).ceil().min(T)) as usize; - for r in r0..r1 { - let lo = row_y0 + r as f32; - let d = yb.min(lo + 1.0) - ya.max(lo); - if d > 0.0 - && let Some(w) = wind.get_mut(r) - { - *w += dir * d; +/// The edges of a closed polygon (fills) or the segments of an open polyline (hairlines; a +/// single point is a dot). +fn for_segments(poly: &[Vec2], mut f: impl FnMut(Vec2, Vec2)) { + match poly { + [] => {} + [p] => f(*p, *p), + _ => { + for w in poly.windows(2) { + f(w[0], w[1]); + } } } } +/// The direction (`1` down, `−1` up) of a piece that starts on its tile row's top edge at +/// `row_y0`, which means its edge crosses that edge; `0` for any other piece. +pub(crate) fn top_crossing(seg: &[f32; 4], row_y0: f32) -> i32 { + if seg[1] == seg[3] || seg[1].min(seg[3]) != row_y0 { + return 0; + } + if seg[3] > seg[1] { 1 } else { -1 } +} + +/// A fill's tile range, in pixels and tiles. +#[derive(Clone, Copy)] +pub(crate) struct Range { + pub(crate) tx0: u32, + pub(crate) ty0: u32, + pub(crate) ylo: f32, + pub(crate) yhi: f32, + pub(crate) xlo: f32, + pub(crate) xhi: f32, + pub(crate) ncols: i32, + pub(crate) nrows: i32, +} + +impl Range { + /// The tiles `f`'s bounds cover, within the surface's; `None` when there are none. + pub(crate) fn of(f: &Fill, tiles_x: u32, tiles_y: u32) -> Option { + let b = f.bounds; + if b.is_empty() { + return None; + } + let tx0 = b.x0.max(0) as u32 / TILE; + let tx1 = (b.x1.max(0) as u32).div_ceil(TILE).min(tiles_x); + let ty0 = b.y0.max(0) as u32 / TILE; + let ty1 = (b.y1.max(0) as u32).div_ceil(TILE).min(tiles_y); + if tx1 <= tx0 || ty1 <= ty0 { + return None; + } + let (ncols, nrows) = ((tx1 - tx0) as i32, (ty1 - ty0) as i32); + Some(Range { tx0, ty0, ylo: (ty0 * TILE) as f32, yhi: (ty1 * TILE) as f32, xlo: (tx0 * TILE) as f32, xhi: (tx1 * TILE) as f32, ncols, nrows }) + } + + fn row_y0(&self, row: u32) -> f32 { + ((self.ty0 + row) * TILE) as f32 + } +} + /// Splits edge `a → b` at tile rows and columns inside the fill's range. -fn split_edge(a: Vec2, b: Vec2, r: &Range, out: &mut Vec) { +fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(Piece)) { if !(a.is_finite() && b.is_finite()) || a.y == b.y { return; } @@ -653,18 +679,18 @@ fn split_edge(a: Vec2, b: Vec2, r: &Range, out: &mut Vec) { continue; } let (xs, xe) = (x_at(ys), x_at(ye)); - split_row(row, Vec2::new(xs, ys), Vec2::new(xe, ye), down, r, out); + split_row(row, Vec2::new(xs, ys), Vec2::new(xe, ye), down, r, &mut out); } } /// Splits a piece inside one tile row at the fill's left and right edges and at tile columns. -fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec) { +fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut impl FnMut(Piece)) { let mut push = |col: i32, u: Vec2, v: Vec2| { if v.y <= u.y { return; } let seg = if down { [u.x, u.y, v.x, v.y] } else { [v.x, v.y, u.x, u.y] }; - out.push(Piece { row, col, seg }); + out(Piece { row, col, seg }); }; // Points where the piece crosses a column boundary (or the range's edges), top to bottom. let dx = e.x - s.x; @@ -674,7 +700,9 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut Vec hi { + continue; + } + let y = if a.y == b.y { a.y } else { a.y + (x - a.x) * slope }; + if !y.is_finite() || y <= r.ylo || y >= r.yhi { + continue; + } + let row = ((y - r.ylo) / T).floor(); + if row < 0.0 || row >= r.nrows as f32 { + continue; + } + let ry0 = r.ylo + row * T; + if y <= ry0 { + continue; // on the row's top edge: the backdrop has it + } + let bottom = ry0 + T; + let seg = if b.x > a.x { [x, bottom, x, y] } else { [x, y, x, bottom] }; + out(Piece { row: row as u32, col: k, seg }); + } +} + +/// Every tile of the range with a pixel centre within a hairline's reach of segment `a → b` +/// (conservatively: a little more), as `(row, col)` relative to the range. +fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32)) { + if !(a.is_finite() && b.is_finite()) { + return; + } + // Pixel centres within reach of the segment lie within these margins of it. + const M: f32 = anicraft_render::hairline::REACH + 1.0; + let (ymin, ymax) = (a.y.min(b.y), a.y.max(b.y)); + let r0 = (((ymin - M - r.ylo) / T).floor()).max(0.0); + let r1 = (((ymax + M - r.ylo) / T).floor()).min((r.nrows - 1) as f32); + if r1 < r0 { + return; + } + let (dx, dy) = (b.x - a.x, b.y - a.y); + for row in r0 as i32..=r1 as i32 { + let top = r.ylo + row as f32 * T; + // The segment's part within the row's band, then the columns within reach of it. + let (xa, xb) = if dy == 0.0 { + (a.x.min(b.x), a.x.max(b.x)) + } else { + let t0 = ((top - M - a.y) / dy).clamp(0.0, 1.0); + let t1 = ((top + T + M - a.y) / dy).clamp(0.0, 1.0); + let (u, v) = (a.x + dx * t0, a.x + dx * t1); + (u.min(v), u.max(v)) + }; + let c0 = (((xa - M - r.xlo) / T).floor()).max(0.0); + let c1 = (((xb + M - r.xlo) / T).floor()).min((r.ncols - 1) as f32); + if c1 < c0 { + continue; + } + for col in c0 as i32..=c1 as i32 { + out(row as u32, col); + } + } +} + /// Coverage of pixel `(px, py)` (tile-relative) from one piece: the same integral the oracle's /// accumulation buffer computes. Used by tests to check the binning on the CPU. #[cfg(test)] diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 60ead56f..9a81fc4c 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -1,11 +1,13 @@ // AniCraft GPU stage: fine rasterization (ADR 0019, ADR 0029). // // One workgroup per 16 × 16 tile, one invocation per pixel. Each pixel walks its tile's entries -// in drawing order. An entry's coverage is its backdrop (winding from edges left of the tile, -// per pixel row) plus the exact area each of the tile's edge pieces covers in the pixel: the -// same integral as the CPU oracle's accumulation buffer (crates/render/src/raster.rs). Then the -// fill rule, the paint (solid, or the oracle's own 256-entry gradient table) and src-over on -// premultiplied colour, all in f32, as the oracle does. +// in drawing order. An entry's coverage is its backdrop (the winding number just below the +// tile's top-left corner, an integer; ADR 0048) plus the exact area each of the tile's edge +// pieces covers in the pixel, the steps on the tile's left edge included: the same integral as +// the CPU oracle's accumulation buffer (crates/render/src/raster.rs). Then the fill rule, the +// paint (solid, or the oracle's own 256-entry gradient table) and src-over on premultiplied +// colour, all in f32, as the oracle does. A hairline (ADR 0048) is 1 − the distance from the +// pixel centre to its nearest segment (crates/render/src/hairline.rs). // // Masks and groups (ADR 0029) are control entries in the same list, mirroring the oracle's band // compositor (crates/render/src/lib.rs): clip artwork unites into a level's coverage, levels @@ -66,6 +68,7 @@ const LEVEL_END: u32 = 0x80000005u; const CLIPPED: u32 = 1u; const ART: u32 = 2u; const MAX_GROUP_DEPTH: u32 = 8u; +const HAIRLINE: u32 = 2u; // Mean of clamp(u, 0, 1) for u running linearly from u0 to u1. fn avg_clamp(u0: f32, u1: f32) -> f32 { @@ -102,6 +105,22 @@ fn piece_cover(s: vec4, px: f32, py: f32) -> f32 { return dir * (yb - ya) * avg_clamp(px + 1.0 - xa, px + 1.0 - xb); } +// Distance from `p` to the segment `s` (x0, y0, x1, y1): hairline.rs › seg_dist, step by step. +fn seg_dist(p: vec2, s: vec4) -> f32 { + let dx = s.z - s.x; + let dy = s.w - s.y; + let qx = p.x - s.x; + let qy = p.y - s.y; + let l = dx * dx + dy * dy; + var t = 0.0; + if l > 0.0 { + t = clamp((qx * dx + qy * dy) / l, 0.0, 1.0); + } + let ex = qx - dx * t; + let ey = qy - dy * t; + return sqrt(ex * ex + ey * ey); +} + fn fold(w: f32, rule: u32) -> f32 { if rule == 0u { return min(abs(w), 1.0); @@ -357,16 +376,23 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { } let first = index[e + 1u]; let pieces = index[e + 2u]; - let bd = index[e + 3u]; - var w = 0.0; - if bd != NONE { - w = geo[bd + (lid.y >> 2u)][lid.y & 3u]; - } - for (var k = 0u; k < pieces; k++) { - w += piece_cover(geo[first + k], px, py); - } let h = params.at.y + op * 4u; - var cov = fold(w, index[h + 1u]); + let rule = index[h + 1u]; + var cov = 0.0; + if rule == HAIRLINE { + var d = 2.0; + let pc = vec2(px + 0.5, py + 0.5); + for (var k = 0u; k < pieces; k++) { + d = min(d, seg_dist(pc, geo[first + k])); + } + cov = clamp(1.0 - d, 0.0, 1.0); + } else { + var w = f32(bitcast(index[e + 3u])); + for (var k = 0u; k < pieces; k++) { + w += piece_cover(geo[first + k], px, py); + } + cov = fold(w, rule); + } let flags = index[h + 3u]; if (flags & ART) != 0u { let k = clamp(cov, 0.0, 1.0); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 005fcf68..dfe406be 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -126,10 +126,40 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> { let mut huge = item(Path::ellipse(50.0, 40.0, 300.0, 200.0), Paint::Solid(red)); huge.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x4cd07d), tint_amount: 0.7 }; out.push(("off-surface", list(vec![huge]), view(100, 80, Some(Rgba::WHITE)))); + out.push(("outlines", outlined(), view(150, 110, Some(Rgba::WHITE)))); out.extend(composited_scenes()); out } +/// Outline mode (ADR 0048): hairlines along closed and open paths, crossing tiles in every +/// direction, overlapping, faded, past the surface, over a fill, and a point. +fn outlined() -> DisplayList { + let outline = |path: Path, c: Rgba, t: Affine| { + let mut i = item(path, Paint::Solid(Rgba::BLACK)); + i.outline = Some(c); + i.transform = t; + i + }; + let blue = Rgba::hex(0x4f8dff).with_alpha(0.5); + let green = Rgba::hex(0x4cd07d).with_alpha(0.8); + let mut wave = Path::default(); + wave.move_to(Vec2::new(-20.0, 90.0)); + for k in 0..12 { + wave.line_to(Vec2::new(k as f32 * 15.3, 90.0 + if k % 2 == 0 { 9.7 } else { -7.1 })); + } + list(vec![ + item(Path::rect(20.0, 20.0, 50.0, 40.0), Paint::Solid(Rgba::new(0.9, 0.8, 0.2, 1.0))), + outline(Path::ellipse(50.0, 45.0, 37.3, 29.1), blue, Affine::IDENTITY), + outline(Path::star(95.0, 50.0, 40.0, 16.0, 5), green, Affine::rotate(0.05)), + outline(Path::star(95.0, 50.0, 40.0, 16.0, 5), green, Affine::translate(0.25, 0.5)), + outline(Path::rect(16.0, 32.0, 112.0, 0.0), Rgba::BLACK, Affine::IDENTITY), + outline(Path::rect(8.5, 4.25, 133.0, 100.0), Rgba::new(0.8, 0.1, 0.1, 1.0), Affine::IDENTITY), + outline(wave, Rgba::new(0.2, 0.2, 0.2, 0.9), Affine::IDENTITY), + outline(Path::ellipse(140.0, 100.0, 60.0, 50.0), blue, Affine::IDENTITY), + outline(Path::line(Vec2::new(60.5, 70.5), Vec2::new(60.5, 70.5)), Rgba::BLACK, Affine::IDENTITY), + ]) +} + /// Masks and groups (ADR 0029): each stresses one part of the oracle's band compositor. fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { let red = Rgba::new(0.9, 0.1, 0.1, 1.0); @@ -264,13 +294,8 @@ fn emulate(b: &Binned, v: &View) -> Vec { } k => assert_eq!(k & bn::CTRL, 0, "unknown control entry {k:x}"), } - let mut wnd = if bd == binning::NONE { 0.0 } else { b.geo[bd as usize + ly / 4][ly % 4] }; - for k in 0..n { - let s = b.geo[first + k]; - wnd += piece_cover(s, lx as f32, ly as f32); - } let hd = b.ops_at as usize + op * 4; - let mut cov = if b.index[hd + 1] == 0 { wnd.abs().min(1.0) } else { let t = wnd.abs() % 2.0; if t > 1.0 { 2.0 - t } else { t } }; + let mut cov = entry_cover(&b.geo[first..first + n], bd, b.index[hd + 1], lx, ly); let flags = b.index[hd + 3]; if flags & bn::ART != 0 { let k = cov.clamp(0.0, 1.0); @@ -308,6 +333,26 @@ fn emulate(b: &Binned, v: &View) -> Vec { out } +/// An entry's coverage of pixel `(lx, ly)` of its tile, as `fine.wgsl` computes it: the +/// backdrop and its pieces under fill rule `rule`, or a hairline's distance. +fn entry_cover(pieces: &[[f32; 4]], backdrop: u32, rule: u32, lx: usize, ly: usize) -> f32 { + if rule == bn::HAIRLINE { + let p = Vec2::new(lx as f32 + 0.5, ly as f32 + 0.5); + let d = pieces.iter().fold(2.0f32, |d, s| d.min(anicraft_render::hairline::seg_dist(p, Vec2::new(s[0], s[1]), Vec2::new(s[2], s[3])))); + return (1.0 - d).clamp(0.0, 1.0); + } + let mut wnd = backdrop as i32 as f32; + for s in pieces { + wnd += piece_cover(*s, lx as f32, ly as f32); + } + if rule == 0 { + wnd.abs().min(1.0) + } else { + let t = wnd.abs() % 2.0; + if t > 1.0 { 2.0 - t } else { t } + } +} + /// `fine.wgsl` › `close_group` and `blend`, on the CPU (the oracle's formulas, written again /// from the shader's numbering). fn close_group(s: Premul, below: Premul, alpha: f32, m: u32) -> Premul { @@ -549,6 +594,7 @@ fn degenerate_geometry_bins_without_trouble() { clip, group, layer: None, + hairline: false, }; // A fill naming a layer that isn't there draws nothing. let mut lost = fill(None, None); diff --git a/crates/render/src/hairline.rs b/crates/render/src/hairline.rs new file mode 100644 index 00000000..5acf09dc --- /dev/null +++ b/crates/render/src/hairline.rs @@ -0,0 +1,169 @@ +//! Hairlines (ADR 0048): the one-pixel lines of outline mode (an outlined layer, onion skin's +//! outlines), drawn straight from the flattened path instead of as stroke polygons. +//! +//! A pixel's coverage is `1 − d`, clamped to `0..=1`, where `d` is the distance from the +//! pixel's centre to the nearest point of the line. Across a horizontal or vertical line that +//! is exactly the area a one-pixel-wide line covers in each pixel (a line through a pixel +//! centre covers it fully; one on a pixel boundary covers the two pixels beside it half each); +//! in other directions it is the line seen through a one-pixel tent filter. Overlaps and joins +//! never darken (the nearest point counts, not a sum), ends and corners are round, and each +//! segment is one edge to bin and test, where a stroked hairline was four plus a disc at every +//! bend. The GPU stage computes the same distance (`fine.wgsl` › `seg_dist`). + +use crate::raster::IRect; +use anicraft_geom::Vec2; + +/// How far a hairline reaches from its line, in pixels: beyond this its coverage is 0. +pub const REACH: f32 = 1.0; + +/// Distance from `p` to the segment `a → b` (a point when they coincide). The GPU computes it +/// with the same steps (`fine.wgsl` › `seg_dist`). +#[inline] +pub fn seg_dist(p: Vec2, a: Vec2, b: Vec2) -> f32 { + let (dx, dy) = (b.x - a.x, b.y - a.y); + let (qx, qy) = (p.x - a.x, p.y - a.y); + let l = dx * dx + dy * dy; + let t = if l > 0.0 { ((qx * dx + qy * dy) / l).clamp(0.0, 1.0) } else { 0.0 }; + let (ex, ey) = (qx - dx * t, qy - dy * t); + (ex * ex + ey * ey).sqrt() +} + +/// A hairline's coverage at distance `d` from it. +#[inline] +pub fn coverage(d: f32) -> f32 { + (REACH - d).clamp(0.0, 1.0) +} + +/// Pixel bounds of hairlines along `polys`, within `surface`. +pub fn bounds(polys: &[Vec], surface: IRect) -> Option { + let (mut x0, mut y0, mut x1, mut y1) = (f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); + for p in polys.iter().flatten().filter(|p| p.is_finite()) { + x0 = x0.min(p.x); + y0 = y0.min(p.y); + x1 = x1.max(p.x); + y1 = y1.max(p.y); + } + if !(x1 >= x0 && y1 >= y0) { + return None; + } + let b = IRect { + x0: (x0 - REACH).floor().max(surface.x0 as f32) as i32, + y0: (y0 - REACH).floor().max(surface.y0 as f32) as i32, + x1: (x1 + REACH).ceil().min(surface.x1 as f32) as i32, + y1: (y1 + REACH).ceil().min(surface.y1 as f32) as i32, + }; + (!b.is_empty()).then_some(b) +} + +/// Adds segment `a → b` to `acc` (coverage over `b`, row by row, `bounds.width()` per row), +/// keeping the larger coverage in every pixel it reaches. +pub fn add_segment(acc: &mut [f32], bounds: IRect, a: Vec2, b: Vec2) { + if !(a.is_finite() && b.is_finite()) || bounds.is_empty() { + return; + } + let w = bounds.width(); + // Pixel rows whose centres lie within reach of the segment. + let ylo = ((a.y.min(b.y) - REACH - 0.5).floor()).max(bounds.y0 as f32); + let yhi = ((a.y.max(b.y) + REACH + 0.5).ceil()).min(bounds.y1 as f32); + if yhi <= ylo { + return; + } + let (dx, dy) = (b.x - a.x, b.y - a.y); + for py in ylo as i32..yhi as i32 { + let yc = py as f32 + 0.5; + // The part of the segment within reach of this row's centres, then the pixels within + // reach of that part. + let (xa, xb) = if dy.abs() < 1e-12 { + (a.x.min(b.x), a.x.max(b.x)) + } else { + let t0 = ((yc - REACH - a.y) / dy).clamp(0.0, 1.0); + let t1 = ((yc + REACH - a.y) / dy).clamp(0.0, 1.0); + let (u, v) = (a.x + dx * t0, a.x + dx * t1); + (u.min(v), u.max(v)) + }; + let x0 = (xa - REACH - 0.5).floor().max(bounds.x0 as f32); + let x1 = (xb + REACH + 0.5).ceil().min(bounds.x1 as f32); + if x1 <= x0 { + continue; + } + let row = (py - bounds.y0) as usize * w; + for px in x0 as i32..x1 as i32 { + let c = coverage(seg_dist(Vec2::new(px as f32 + 0.5, yc), a, b)); + if let Some(v) = acc.get_mut(row + (px - bounds.x0) as usize) + && c > *v + { + *v = c; + } + } + } +} + +/// Adds an open polyline (a closed one repeats its first point at the end). +pub fn add_polyline(acc: &mut [f32], bounds: IRect, pts: &[Vec2]) { + match pts { + [] => {} + [p] => add_segment(acc, bounds, *p, *p), + _ => { + for w in pts.windows(2) { + add_segment(acc, bounds, w[0], w[1]); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn draw(pts: &[Vec2], w: i32, h: i32) -> Vec { + let b = IRect { x0: 0, y0: 0, x1: w, y1: h }; + let mut acc = vec![0.0; (w * h) as usize]; + add_polyline(&mut acc, b, pts); + acc + } + + #[test] + fn axis_aligned_lines_cover_exactly_one_pixel_of_area_per_row_or_column() { + // Through pixel centres: the row is covered fully, nothing else. + let a = draw(&[Vec2::new(-5.0, 4.5), Vec2::new(30.0, 4.5)], 20, 10); + for (i, v) in a.iter().enumerate() { + let want = if i / 20 == 4 { 1.0 } else { 0.0 }; + assert!((v - want).abs() < 1e-6, "pixel {i}: {v}"); + } + // On a pixel boundary: the two rows beside it, half each. A quarter off: 3/4 and 1/4. + for (y, rows) in [(4.0f32, [(3usize, 0.5f32), (4, 0.5)]), (4.25, [(3, 0.25), (4, 0.75)])] { + let a = draw(&[Vec2::new(7.5, -5.0), Vec2::new(7.5, 30.0)], 10, 20); + assert!(a.chunks(10).all(|r| (r[7] - 1.0).abs() < 1e-6 && r[6] == 0.0), "vertical through centres"); + let a = draw(&[Vec2::new(-5.0, y), Vec2::new(30.0, y)], 20, 10); + for (r, want) in rows { + assert!(a[r * 20..r * 20 + 20].iter().all(|v| (v - want).abs() < 1e-6), "y {y}, row {r}"); + } + assert!((a.iter().sum::() - 20.0).abs() < 1e-4, "one pixel of area per column"); + } + } + + #[test] + fn joins_and_overlaps_never_darken_and_ends_are_round() { + // A corner and the same segment twice: still at most 1 anywhere, 1 on the line. + let a = draw(&[Vec2::new(2.5, 2.5), Vec2::new(12.5, 2.5), Vec2::new(12.5, 12.5), Vec2::new(2.5, 2.5)], 16, 16); + assert!(a.iter().all(|v| (0.0..=1.0).contains(v))); + assert_eq!(a[2 * 16 + 12], 1.0); + assert_eq!(a[8 * 16 + 12], 1.0); + // Round end: the pixel centre half a pixel past the end, diagonally, is √0.5 away. + let a = draw(&[Vec2::new(4.0, 4.0), Vec2::new(10.0, 4.0)], 16, 10); + assert!((a[4 * 16 + 10] - (1.0 - 0.5f32.sqrt())).abs() < 1e-6, "{}", a[4 * 16 + 10]); + assert_eq!(a[4 * 16 + 11], 0.0, "beyond reach past the end"); + // A single point is a dot. + let a = draw(&[Vec2::new(3.5, 3.5)], 8, 8); + assert_eq!(a[3 * 8 + 3], 1.0); + assert_eq!(a.iter().filter(|v| **v > 0.0).count(), 1); + } + + #[test] + fn far_and_broken_points_stay_bounded() { + let a = draw(&[Vec2::new(-1e9, -1e9), Vec2::new(1e9, 1e9), Vec2::new(f32::NAN, 0.0), Vec2::new(3.0, f32::INFINITY)], 32, 32); + assert!(a.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))); + assert!(a.iter().any(|v| *v > 0.9), "the long diagonal shows"); + assert!(bounds(&[vec![Vec2::new(f32::NAN, 1.0)]], IRect { x0: 0, y0: 0, x1: 8, y1: 8 }).is_none()); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b79f4e11..e5a75183 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8,6 +8,7 @@ pub mod paint; pub mod raster; pub mod stroke; pub mod filters; +pub mod hairline; pub mod html; pub mod lottie; pub mod svg; @@ -218,9 +219,16 @@ pub fn render(dl: &DisplayList, view: &View) -> Result<(Pixmap, RenderStats), Re open.push(OpenGroup { id: g, buf: vec![[0.0; 4]; rows.len()], dirty: NO_PIXELS }); } let mask = op.clip.map(|c| band_clips.get(&clips, c, band, w, &mut cov, &mut row)); - cov.reset(b); - for poly in &op.polys { - cov.add_polygon(poly); + if op.hairline { + cov.reset_direct(b); + for poly in &op.polys { + cov.add_hairline(poly); + } + } else { + cov.reset(b); + for poly in &op.polys { + cov.add_polygon(poly); + } } match open.last_mut() { Some(top) => { @@ -294,6 +302,9 @@ pub struct Fill { /// [`render`] draws it: the layer's pixel at `(x, y)` is at `(x - x0, y - y0)` of its /// `bounds`, transparent outside. pub layer: Option, + /// A hairline (outline mode, ADR 0048): `polys` are open polylines (a closed one repeats + /// its first point), drawn by [`hairline`]'s distance coverage; `rule` doesn't apply. + pub hairline: bool, } /// A filtered group (a symbol instance with filters) as [`render`] draws it: its items on @@ -383,7 +394,7 @@ pub fn prepare_scene(dl: &DisplayList, view: &View) -> Result<(Scene, RenderStat op.bounds = op.bounds.intersect(&clips.bounds(c)); !op.bounds.is_empty() }); - let fill = |op: Prepared| Fill { polys: op.polys, rule: op.rule, shader: op.shader, bounds: op.bounds, clip: op.clip, group: op.group, layer: op.layer }; + let fill = |op: Prepared| Fill { polys: op.polys, rule: op.rule, shader: op.shader, bounds: op.bounds, clip: op.clip, group: op.group, layer: op.layer, hairline: op.hairline }; let mut fills = Vec::with_capacity(ops.len()); for op in ops { stats.edges += op.polys.iter().map(Vec::len).sum::(); @@ -465,6 +476,7 @@ impl FilterSetup { masks: None, group: Some(self.group), layer: None, + hairline: false, } } } @@ -656,6 +668,8 @@ struct Prepared { group: Option, /// A filtered layer's pixels instead of `shader` ([`Fill::layer`]; only in [`prepare_scene`]). layer: Option, + /// A hairline ([`Fill::hairline`]). + hairline: bool, } /// The clips of a display list: their mask artwork and where each can be non-zero. @@ -779,12 +793,36 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { return out; } let (clip, masks, group) = (item.clip, item.masks, item.group); + // (Mask artwork is never outlined: it draws nothing of its own.) + if let Some(color) = item.outline.filter(|_| !is_mask) { + // Outline mode: a hairline in the layer colour, no fill (ADR 0048). + let shader = Shader::Solid(premultiply(color)); + if shader.is_solid().is_some_and(|c| c[3] <= 0.0) { + return out; + } + let polys: Vec> = lines + .into_iter() + .map(|l| { + let mut pts = l.points; + if l.closed + && let Some(&first) = pts.first() + { + pts.push(first); + } + pts + }) + .collect(); + if let Some(b) = hairline::bounds(&polys, surface) { + out.push(Prepared { polys, rule: FillRule::NonZero, shader, bounds: b, clip, masks, group, layer: None, hairline: true }); + } + return out; + } let mut push = |polys: Vec>, rule, shader: Shader| { if shader.is_solid().is_some_and(|c| c[3] <= 0.0) { return; } if let Some(b) = pixel_bounds(&polys, surface) { - out.push(Prepared { polys, rule, shader, bounds: b, clip, masks, group, layer: None }); + out.push(Prepared { polys, rule, shader, bounds: b, clip, masks, group, layer: None, hairline: false }); } }; @@ -792,11 +830,6 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { push(lines.iter().map(|l| l.points.clone()).collect(), item.fill_rule, Shader::Solid([1.0; 4])); return out; } - if let Some(color) = item.outline { - // Outline mode: hairline in the layer colour, no fill. - push(stroke::stroke_polygons(&lines, 0.5), FillRule::NonZero, Shader::Solid(premultiply(color))); - return out; - } // The stroke is outlined from the flattened lines first, so the fill can then take them // without a copy; it is still drawn after the fill. let stroke = item.stroke.as_ref().and_then(|st| { diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 5f24b46a..76b7d0f2 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -46,16 +46,19 @@ pub struct Coverage { pub bounds: IRect, stride: usize, acc: Vec, + /// The buffer holds coverage itself (hairlines, ADR 0048), not area to sum along rows. + direct: bool, } impl Coverage { pub fn new(bounds: IRect) -> Coverage { let stride = bounds.width() + 2; - Coverage { bounds, stride, acc: vec![0.0; stride * bounds.height()] } + Coverage { bounds, stride, acc: vec![0.0; stride * bounds.height()], direct: false } } /// Re-targets the buffer at `bounds`, reusing its allocation (one buffer per render band). pub fn reset(&mut self, bounds: IRect) { + self.direct = false; self.bounds = bounds; self.stride = bounds.width() + 2; self.acc.clear(); @@ -180,6 +183,24 @@ impl Coverage { } } + /// Re-targets the buffer at `bounds` for hairlines ([`Coverage::add_hairline`]): it then + /// holds each pixel's coverage, and [`Coverage::resolve_row`] reads it as it is. + pub fn reset_direct(&mut self, bounds: IRect) { + self.direct = true; + self.bounds = bounds; + self.stride = bounds.width(); + self.acc.clear(); + self.acc.resize(self.stride * bounds.height(), 0.0); + } + + /// Adds a hairline along an open polyline ([`crate::hairline`]); the buffer must be in + /// direct mode ([`Coverage::reset_direct`]). + pub fn add_hairline(&mut self, pts: &[Vec2]) { + if self.direct { + crate::hairline::add_polyline(&mut self.acc, self.bounds, pts); + } + } + /// Resolves row `y` (relative to the bounds) into coverage values in `out` (len = width). pub fn resolve_row(&self, y: usize, rule: FillRule, out: &mut [f32]) { let start = y * self.stride; @@ -187,6 +208,12 @@ impl Coverage { out.fill(0.0); return; }; + if self.direct { + for (o, a) in out.iter_mut().zip(row) { + *o = *a; + } + return; + } let mut sum = 0.0f32; for (o, a) in out.iter_mut().zip(row) { sum += a; From 660bdcb0d8ca81b9cf633a4bbd098e9a48e1f6fd Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:55:24 -0700 Subject: [PATCH 03/19] fix(gpu): take the tiles' left-edge steps from the split pieces themselves (M3) Crossings computed apart from the splitting could disagree with it by a rounding near a tile corner and count one crossing twice (the backdrop and a step): 543 pixels off by up to 133/255 on a stress frame. The steps now come from consecutive pieces of a tile row in different columns, so the backdrop and the steps always describe the same pieces. A test on stress frames at awkward scales catches it. Also drops leftover timing prints. --- crates/gpu/src/binning.rs | 163 +++++++++++++++++++++++++------------- crates/gpu/src/tests.rs | 17 ++++ 2 files changed, 126 insertions(+), 54 deletions(-) diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index 7f0407c1..a8bb81d2 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -216,7 +216,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let op_group: Vec = scene.fills.iter().map(|f| f.group.filter(|&g| (g as usize) < scene.groups.len()).unwrap_or(NONE)).collect(); let tables = Tables { fills: nf as u32, op_clip, op_group, clip_chain, art_ops, scene }; - let __t=std::time::Instant::now(); let tiles_x = width.div_ceil(TILE); let tiles_y = height.div_ceil(TILE); let (tx, ty) = (tiles_x as usize, tiles_y as usize); @@ -227,7 +226,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result .enumerate() .map(|(c, chunk)| { let mut out = Local::default(); - let mut scratch = Vec::new(); + let mut scratch = (Vec::new(), Track::default()); for (i, f) in chunk.iter().enumerate() { bin_fill(f, (c * CHUNK + i) as u32, tiles_x, tiles_y, &mut out, &mut scratch); } @@ -245,7 +244,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result }) .collect(); - let __a=__t.elapsed().as_secs_f32()*1000.0; // Where each chunk's pieces go in `geo`. let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum(); let mut piece_at = Vec::with_capacity(locals.len()); @@ -257,7 +255,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result // Phase 2, parallel over tile rows: each tile's stream of entries. let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &tables)).collect(); - let __b=__t.elapsed().as_secs_f32()*1000.0; let mut row_at = vec![0usize; ty + 1]; for (r, out) in rows.iter().enumerate() { row_at[r + 1] = row_at[r] + out.stream.len(); @@ -286,7 +283,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result } }); } - let __c=__t.elapsed().as_secs_f32()*1000.0; // Pieces copied in parallel into their places. let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces]; { @@ -302,8 +298,6 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result // Tens of thousands of small buffers: free them on the pool, off the frame's path. anicraft_render::drop_in_background((locals, rows)); - let __d=__t.elapsed().as_secs_f32()*1000.0; - if width>1000 {eprintln!("bin {width}: fills {__a:.2} rows {:.2} index {:.2} geo {:.2}", __b-__a, __c-__b, __d-__c);} // Paints: a fixed record per op, then the gradient tables, then the layers' pixels. let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len()); let mut ramps: Vec<[f32; 4]> = Vec::new(); @@ -528,7 +522,7 @@ fn tile_stream(fills: &[[u32; 4]], arts: &[[u32; 4]], t: &Tables, out: &mut Vec< /// Splits one fill's edges into tile pieces (with the steps where its outline crosses a tile's /// left edge) and walks each tile row for the backdrops. -fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, pieces: &mut Vec) { +fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, (pieces, track): &mut (Vec, Track)) { let Some(range) = Range::of(f, tiles_x, tiles_y) else { return }; pieces.clear(); if f.hairline { @@ -541,11 +535,18 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, piec if n < 2 { continue; } + track.start(range.nrows as usize); + let mut keep = |p: Piece| pieces.push(p); for i in 0..n { let (Some(&a), Some(&c)) = (poly.get(i), poly.get((i + 1) % n)) else { continue }; - split_edge(a, c, &range, |p| pieces.push(p)); - crossings(a, c, &range, |p| pieces.push(p)); + split_edge(a, c, &range, |row, col, seg| { + if col < range.ncols { + keep(Piece { row, col, seg }); + } + track.see(row, Seen { col, end_y: seg[3] }, &range, &mut keep); + }); } + track.finish(&range, &mut keep); } } if pieces.is_empty() { @@ -655,13 +656,15 @@ impl Range { } } -/// Splits edge `a → b` at tile rows and columns inside the fill's range. -fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(Piece)) { +/// Splits edge `a → b` at tile rows and columns inside the fill's range, row by row, each row's +/// pieces in the edge's direction of travel. Parts right of the fill's tiles come as column +/// `ncols` (they draw nothing, but the steps on the tiles' left edges need to see them). +pub(crate) fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32, [f32; 4])) { if !(a.is_finite() && b.is_finite()) || a.y == b.y { return; } - // Work top to bottom; restore the direction when storing. - let (p, q, down) = if a.y < b.y { (a, b, true) } else { (b, a, false) }; + let down = a.y < b.y; + let (p, q) = if down { (a, b) } else { (b, a) }; let y0 = p.y.max(r.ylo); let y1 = q.y.min(r.yhi); if y1 <= y0 { @@ -678,21 +681,26 @@ fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(Piece)) { if ye <= ys { continue; } - let (xs, xe) = (x_at(ys), x_at(ye)); - split_row(row, Vec2::new(xs, ys), Vec2::new(xe, ye), down, r, &mut out); + let (top, bottom) = (Vec2::new(x_at(ys), ys), Vec2::new(x_at(ye), ye)); + if down { + split_row(row, top, bottom, r, &mut out); + } else { + split_row(row, bottom, top, r, &mut out); + } } } -/// Splits a piece inside one tile row at the fill's left and right edges and at tile columns. -fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut impl FnMut(Piece)) { +/// Splits a piece inside one tile row, from `s` to `e` (the edge's direction), at the fill's +/// left and right edges and at tile columns: column −1 left of the fill's tiles, `ncols` right. +fn split_row(row: u32, s: Vec2, e: Vec2, r: &Range, out: &mut impl FnMut(u32, i32, [f32; 4])) { + let down = e.y > s.y; let mut push = |col: i32, u: Vec2, v: Vec2| { - if v.y <= u.y { + if (down && v.y <= u.y) || (!down && v.y >= u.y) { return; } - let seg = if down { [u.x, u.y, v.x, v.y] } else { [v.x, v.y, u.x, u.y] }; - out(Piece { row, col, seg }); + out(row, col, [u.x, u.y, v.x, v.y]); }; - // Points where the piece crosses a column boundary (or the range's edges), top to bottom. + // Points where the piece crosses a column boundary (or the range's edges), in order. let dx = e.x - s.x; let at_x = |x: f32| -> Vec2 { let t = ((x - s.x) / dx).clamp(0.0, 1.0); @@ -707,7 +715,8 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut impl F return; } if lo >= r.xhi { - return; // wholly right of the fill's tiles: it covers none of their pixels + push(r.ncols, s, e); + return; } // Most pieces (flattened curves are short) lie inside one tile column. let cl = col_of(lo); @@ -737,47 +746,93 @@ fn split_row(row: u32, s: Vec2, e: Vec2, down: bool, r: &Range, out: &mut impl F push(-1, prev, next); } else if mid < r.xhi { push(col_of(mid).clamp(0, r.ncols - 1), prev, next); + } else { + push(r.ncols, prev, next); } prev = next; } } -/// The steps edge `a → b` makes in the winding along the left edges of the range's tiles: where -/// it crosses column boundary `x` (`lo < x ≤ hi`, horizontal edges too) strictly inside a tile -/// row, a vertical piece on that tile's left edge from the crossing to the row's bottom, upwards -/// when the edge runs right (the winding to the left drops by one) and downwards when it runs -/// left. -fn crossings(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(Piece)) { - if !(a.is_finite() && b.is_finite()) || a.x == b.x { +/// A piece as the left-edge steps see it: its column and the height where it ends. +#[derive(Clone, Copy)] +pub(crate) struct Seen { + pub(crate) col: i32, + pub(crate) end_y: f32, +} + +/// Per tile row of a fill, the last piece of the polygon walked so far there and its first: +/// consecutive pieces of a row in different columns are where the outline crosses tiles' left +/// edges. +#[derive(Default)] +pub(crate) struct Track { + last: Vec>, + first: Vec>, + touched: Vec, +} + +impl Track { + /// Ready for a polygon of a fill with `nrows` tile rows. + fn start(&mut self, nrows: usize) { + for &r in &self.touched { + if let Some(l) = self.last.get_mut(r as usize) { + *l = None; + } + if let Some(f) = self.first.get_mut(r as usize) { + *f = None; + } + } + self.touched.clear(); + if self.last.len() < nrows { + self.last.resize(nrows, None); + self.first.resize(nrows, None); + } + } + + /// The next piece of the polygon in tile row `row`; the steps between it and the row's + /// previous piece go to `out`. + fn see(&mut self, row: u32, s: Seen, r: &Range, out: &mut impl FnMut(Piece)) { + let (Some(last), Some(first)) = (self.last.get_mut(row as usize), self.first.get_mut(row as usize)) else { return }; + match *last { + Some(p) => steps(p, s, row, r, out), + None => { + *first = Some(s); + self.touched.push(row); + } + } + *last = Some(s); + } + + /// The polygon is closed: each row's last piece is followed by its first. + fn finish(&mut self, r: &Range, out: &mut impl FnMut(Piece)) { + for &row in &self.touched { + if let (Some(Some(l)), Some(Some(f))) = (self.last.get(row as usize), self.first.get(row as usize)) { + steps(*l, *f, row, r, out); + } + } + } +} + +/// The steps in the winding along the tiles' left edges between consecutive pieces `a` and `b` +/// of one tile row (ADR 0048): where the outline passes from column `a.col` to `b.col`, at the +/// height where `a` ends, each tile boundary between them gets a vertical piece on its left +/// edge from there to the row's bottom: upwards when the outline runs right (the winding left +/// of the tile drops by one), downwards when it runs left. On the row's top edge the backdrop +/// has the step already, on its bottom edge it changes nothing. +pub(crate) fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) { + if a.col == b.col { return; } - let (lo, hi) = (a.x.min(b.x), a.x.max(b.x)); - let kmin = (((lo - r.xlo) / T).floor() + 1.0).max(0.0); - let kmax = ((hi - r.xlo) / T).floor().min((r.ncols - 1) as f32); - if kmax < kmin { + let top = r.ylo + (row * TILE) as f32; + let (y, bottom) = (a.end_y, top + T); + if !(y > top && y < bottom) { return; } - let slope = (b.y - a.y) / (b.x - a.x); - for k in kmin as i32..=kmax as i32 { + let right = a.col < b.col; + let (lo, hi) = if right { (a.col, b.col) } else { (b.col, a.col) }; + for k in (lo + 1).max(0)..=hi.min(r.ncols - 1) { let x = r.xlo + k as f32 * T; - if x <= lo || x > hi { - continue; - } - let y = if a.y == b.y { a.y } else { a.y + (x - a.x) * slope }; - if !y.is_finite() || y <= r.ylo || y >= r.yhi { - continue; - } - let row = ((y - r.ylo) / T).floor(); - if row < 0.0 || row >= r.nrows as f32 { - continue; - } - let ry0 = r.ylo + row * T; - if y <= ry0 { - continue; // on the row's top edge: the backdrop has it - } - let bottom = ry0 + T; - let seg = if b.x > a.x { [x, bottom, x, y] } else { [x, y, x, bottom] }; - out(Piece { row: row as u32, col: k, seg }); + let seg = if right { [x, bottom, x, y] } else { [x, y, x, bottom] }; + out(Piece { row, col: k, seg }); } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index dfe406be..adce571b 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -488,6 +488,22 @@ fn binned_coverage_matches_the_oracle_on_the_cpu() { } } +/// Thousands of overlapping shapes at awkward scales: edges meet tile corners and boundaries +/// within float rounding, where the backdrops and the left-edge steps must agree (ADR 0048). +#[test] +fn binned_coverage_matches_the_oracle_on_stress_frames() { + let doc = sample::stress(20, 100, 48); + for (f, s, at) in [(0u32, 1.0f32, (0.0, 0.0)), (30, 0.5, (0.0, 0.0)), (7, 2.3, (-900.0, -700.0)), (41, 0.73, (-11.5, -3.25))] { + let dl = anicraft_doc::evaluate(&doc, f); + let v = View { transform: Affine::translate(at.0, at.1).mul(&Affine::scale(s, s)), width: 1920, height: 1080, background: Some(Rgba::WHITE) }; + let (scene, _) = prepare_scene(&dl, &v).unwrap(); + let b = binning::bin(&scene, v.width, v.height).unwrap(); + let (oracle, _) = render(&dl, &v).unwrap(); + let (mean, max) = f32_diff(&emulate(&b, &v), &oracle.data); + assert!(mean < 1e-4 && max < 4e-3, "frame {f} at {s}: mean {mean:e}, max {max:e}"); + } +} + #[test] fn the_composited_sample_really_has_masks_and_groups() { let comp = composited_sample(); @@ -960,3 +976,4 @@ fn gpu_matches_the_oracle_on_the_filtered_sample() { assert_parity(g, "filtered sample tile", &dl, &tile); } } + From 72da28d74ce69d8b18f83e2868f364cb4f179c9a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 19:55:38 -0700 Subject: [PATCH 04/19] fix(gpu): keep the binning's helpers private (M3) --- crates/gpu/src/binning.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index a8bb81d2..8338c0f1 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -659,7 +659,7 @@ impl Range { /// Splits edge `a → b` at tile rows and columns inside the fill's range, row by row, each row's /// pieces in the edge's direction of travel. Parts right of the fill's tiles come as column /// `ncols` (they draw nothing, but the steps on the tiles' left edges need to see them). -pub(crate) fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32, [f32; 4])) { +fn split_edge(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32, [f32; 4])) { if !(a.is_finite() && b.is_finite()) || a.y == b.y { return; } @@ -755,16 +755,16 @@ fn split_row(row: u32, s: Vec2, e: Vec2, r: &Range, out: &mut impl FnMut(u32, i3 /// A piece as the left-edge steps see it: its column and the height where it ends. #[derive(Clone, Copy)] -pub(crate) struct Seen { - pub(crate) col: i32, - pub(crate) end_y: f32, +struct Seen { + col: i32, + end_y: f32, } /// Per tile row of a fill, the last piece of the polygon walked so far there and its first: /// consecutive pieces of a row in different columns are where the outline crosses tiles' left /// edges. #[derive(Default)] -pub(crate) struct Track { +struct Track { last: Vec>, first: Vec>, touched: Vec, @@ -818,7 +818,7 @@ impl Track { /// edge from there to the row's bottom: upwards when the outline runs right (the winding left /// of the tile drops by one), downwards when it runs left. On the row's top edge the backdrop /// has the step already, on its bottom edge it changes nothing. -pub(crate) fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) { +fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) { if a.col == b.col { return; } From f18cf5bd688396557b0ac7588584aa2e88555493 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:06:54 -0700 Subject: [PATCH 05/19] feat(gpu): tile binning on the GPU: count, prefix sum, scatter, tile lists (M3) The CPU lays out the fills' points, each fill's tile range, each tile row's fills in drawing order and room for every tile the fills' bounds cover, with an upper bound of the pieces, so every buffer is sized up front and nothing is read back. bin.wgsl splits the edges (one invocation per row of tiles of each fill, so no atomics), scan.wgsl places the pieces, and a pass per tile keeps the fills with pieces or a backdrop there, in order: the same lists as the CPU binning, which stays the reference and the way for fills in masks and groups. Binning::Auto bins on the GPU from 4,096 edges; ANICRAFT_GPU_BINNING overrides. Tests: the GPU's lists against the CPU's, entry by entry and pixel by pixel (stress frames, outlines, the analytic scenes), and GPU-binned frames against the oracle, on Vulkan and Direct3D 12. --- crates/gpu/src/bin.wgsl | 426 ++++++++++++++++++++++++++++++++++ crates/gpu/src/binning.rs | 246 ++++++++++++-------- crates/gpu/src/gpu_binning.rs | 410 ++++++++++++++++++++++++++++++++ crates/gpu/src/lib.rs | 196 +++++++++++++--- crates/gpu/src/scan.wgsl | 83 +++++++ crates/gpu/src/tests.rs | 104 ++++++++- 6 files changed, 1336 insertions(+), 129 deletions(-) create mode 100644 crates/gpu/src/bin.wgsl create mode 100644 crates/gpu/src/gpu_binning.rs create mode 100644 crates/gpu/src/scan.wgsl diff --git a/crates/gpu/src/bin.wgsl b/crates/gpu/src/bin.wgsl new file mode 100644 index 00000000..e062c6b0 --- /dev/null +++ b/crates/gpu/src/bin.wgsl @@ -0,0 +1,426 @@ +// AniCraft GPU stage: tile binning on the GPU (ADR 0048). +// +// The same tile lists as the CPU binning (binning.rs, the reference), from the prepared fills' +// flattened polygons, in four kinds of dispatch: +// +// 1. `count`, one invocation per row of tiles of each fill (an "op-row"): its edges split at +// tile rows and columns (binning.rs › split_edge, split_row), plus the steps where the +// outline passes from one column to another (› Track, steps), or a hairline's segments by +// reach (› hairline_tiles), counted per tile of the fill (an "op-tile"); and the backdrops: the +// directions of the pieces starting on the row's top edge, summed along the row. Each +// op-row is one invocation's alone, so nothing needs atomics and integers add up the same +// in any order: the counts and backdrops are exact. +// 2. `scan_blocks` and `scan_add`: an exclusive prefix sum of the counts (the public +// work-efficient scan: per workgroup, then the workgroups' totals, then added back), which +// places every op-tile's pieces. +// 3. `scatter`: the same walk again, writing each piece where its op-tile's pieces go, in the +// walk's order (the same every frame). +// 4. `tiles`, one invocation per tile: its fills in drawing order (the fills overlapping its +// row, from the CPU, which only needs their bounds), keeping those with pieces or a +// backdrop there, as the entries the fine pass reads. +// +// The binding layout fits the smallest devices (four storage buffers per stage): one buffer of +// inputs, one of working values (counts, backdrops, offsets, cursors, scan totals), the pieces +// (`geo`) and the fine pass's index. + +struct Params { + // tiles across, tiles down, op-rows, tiles + size: vec4, + // op-tiles, piece capacity, where the entries start in `index`, 0 + more: vec4, + // where the ops, polygons, points and op-row owners start in `input` + at: vec4, + // where the rows' fills and the rows' starts are in `input` + at2: vec4, +} + +@group(0) @binding(0) var params: Params; +@group(0) @binding(1) var input: array; +@group(0) @binding(2) var work: array; +@group(0) @binding(3) var geo: array>; +@group(0) @binding(4) var index: array; + +const T: f32 = 16.0; +// gpu_binning.rs › HAIRLINE_BIT: the op is a hairline. +const HAIRLINE_BIT: u32 = 0x80000000u; +// Margins of a hairline's reach (binning.rs › hairline_tiles). +const M: f32 = 2.0; + +// What to do with a piece. +const COUNT: u32 = 0u; +const WRITE: u32 = 1u; + +struct Op { + first_poly: u32, + polys: u32, + tx0: u32, + ty0: u32, + ncols: u32, + nrows: u32, + tile_base: u32, + flags: u32, +} + +fn op_at(i: u32) -> Op { + let b = params.at.x + i * 8u; + return Op(input[b], input[b + 1u], input[b + 2u], input[b + 3u], input[b + 4u], input[b + 5u], input[b + 6u], input[b + 7u]); +} + +fn point(i: u32) -> vec2 { + let b = params.at.z + i * 2u; + return vec2(bitcast(input[b]), bitcast(input[b + 1u])); +} + +// Finite (not NaN or infinite), from the bits: comparisons with NaN may be optimized away. +fn finite(v: f32) -> bool { + return (bitcast(v) & 0x7f800000u) != 0x7f800000u; +} + +fn finite2(p: vec2) -> bool { + return finite(p.x) && finite(p.y); +} + +// The working values: counts, backdrops, offsets and cursors, `params.more.x` each. +fn counts_at(t: u32) -> u32 { + return t; +} +fn backdrop_at(t: u32) -> u32 { + return params.more.x + t; +} +fn offset_at(t: u32) -> u32 { + return 2u * params.more.x + t; +} +fn cursor_at(t: u32) -> u32 { + return 3u * params.more.x + t; +} + +// The walk of one op-row: what it is and where its pieces go. +struct Walk { + mode: u32, + // the op-tile of the row's first column + tile0: u32, + ncols: i32, + hairline: bool, + row_y0: f32, + // the row's top-left in pixels + ox: f32, +} + +// The fill's range (binning.rs › Range). +struct Rng { + xlo: f32, + xhi: f32, + ylo: f32, + yhi: f32, + ncols: i32, + nrows: i32, +} + +// binning.rs › top_crossing. +fn top_crossing(s: vec4, row_y0: f32) -> i32 { + if s.y == s.w || min(s.y, s.w) != row_y0 { + return 0; + } + return select(-1, 1, s.w > s.y); +} + +// One piece in column `col` of the walk's row (−1: left of the fill's tiles). +fn emit(w: Walk, col: i32, s: vec4) { + if w.mode == COUNT { + if col >= 0 && col < w.ncols { + let t = counts_at(w.tile0 + u32(col)); + work[t] = work[t] + 1u; + } + if !w.hairline { + let c = top_crossing(s, w.row_y0); + if c != 0 && col + 1 < w.ncols { + let t = backdrop_at(w.tile0 + u32(col + 1)); + work[t] = bitcast(bitcast(work[t]) + c); + } + } + return; + } + if col < 0 || col >= w.ncols { + return; + } + let tile = w.tile0 + u32(col); + let k = work[cursor_at(tile)]; + work[cursor_at(tile)] = k + 1u; + let at = work[offset_at(tile)] + k; + if at < params.more.y { + let ox = w.ox + f32(u32(col) * 16u); + geo[at] = vec4(s.x - ox, s.y - w.row_y0, s.z - ox, s.w - w.row_y0); + } +} + +// The polygon's last piece so far in this invocation's row, and its first (binning.rs › Track). +var tr_last: bool; +var tr_last_col: i32; +var tr_last_y: f32; +var tr_first: bool; +var tr_first_col: i32; + +// binning.rs › steps: where the outline passes from column `a` (its piece ending at height +// `y`) to column `b`, a vertical piece on each tile boundary between them, from there to the +// row's bottom. +fn steps(w: Walk, r: Rng, a: i32, y: f32, b: i32) { + if a == b { + return; + } + let top = w.row_y0; + let bottom = top + T; + if !(y > top && y < bottom) { + return; + } + let right = a < b; + let lo = min(a, b); + let hi = max(a, b); + for (var k = max(lo + 1, 0); k <= min(hi, r.ncols - 1); k++) { + let x = r.xlo + f32(k) * T; + if right { + emit(w, k, vec4(x, bottom, x, y)); + } else { + emit(w, k, vec4(x, y, x, bottom)); + } + } +} + +// A piece of the polygon in this row, in the direction of travel (column −1: left of the +// fill's tiles; `ncols`: right of them, drawing nothing): kept, and seen by the steps. +fn piece(w: Walk, r: Rng, col: i32, s: vec4) { + if col < r.ncols { + emit(w, col, s); + } + if tr_last { + steps(w, r, tr_last_col, tr_last_y, col); + } else { + tr_first = true; + tr_first_col = col; + } + tr_last = true; + tr_last_col = col; + tr_last_y = s.w; +} + +fn push(w: Walk, r: Rng, col: i32, u: vec2, v: vec2, down: bool) { + if (down && v.y <= u.y) || (!down && v.y >= u.y) { + return; + } + piece(w, r, col, vec4(u, v)); +} + +// binning.rs › split_row: a piece inside one tile row, from `s` to `e` (the edge's direction), +// split at the fill's left and right edges and at tile columns. +fn split_row(w: Walk, s: vec2, e: vec2, r: Rng) { + let down = e.y > s.y; + let dx = e.x - s.x; + let lo = min(s.x, e.x); + let hi = max(s.x, e.x); + if hi <= r.xlo && lo < r.xlo { + push(w, r, -1, s, e, down); + return; + } + if lo >= r.xhi { + push(w, r, r.ncols, s, e, down); + return; + } + let cl = i32(floor((lo - r.xlo) / T)); + if dx == 0.0 || (lo >= r.xlo && hi < r.xhi && cl == i32(floor((hi - r.xlo) / T))) { + push(w, r, clamp(cl, 0, r.ncols - 1), s, e, down); + return; + } + let kmin = max(i32(floor((lo - r.xlo) / T)) + 1, 0); + let kmax = min(i32(ceil((hi - r.xlo) / T)) - 1, r.ncols); + let count = max(kmax - kmin + 1, 0); + var prev = s; + for (var j = 0; j <= count; j++) { + var next = e; + if j != count { + let k = select(kmax - j, kmin + j, dx > 0.0); + let x = r.xlo + f32(k) * T; + if !(x > lo && x < hi) { + continue; + } + let t = clamp((x - s.x) / dx, 0.0, 1.0); + next = vec2(x, s.y + (e.y - s.y) * t); + } + let mid = 0.5 * (prev.x + next.x); + if mid < r.xlo { + push(w, r, -1, prev, next, down); + } else if mid < r.xhi { + push(w, r, clamp(i32(floor((mid - r.xlo) / T)), 0, r.ncols - 1), prev, next, down); + } else { + push(w, r, r.ncols, prev, next, down); + } + prev = next; + } +} + +// binning.rs › split_edge, for tile row `row` only. +fn split_edge(w: Walk, a: vec2, b: vec2, r: Rng, row: u32) { + if !(finite2(a) && finite2(b)) || a.y == b.y { + return; + } + let down = a.y < b.y; + let p = select(b, a, down); + let q = select(a, b, down); + let y0 = max(p.y, r.ylo); + let y1 = min(q.y, r.yhi); + if y1 <= y0 { + return; + } + let first = u32(max(floor((y0 - r.ylo) / T), 0.0)); + let last = u32(max(ceil((y1 - r.ylo) / T), 0.0)); + if row < first || row >= last { + return; + } + let dxdy = (q.x - p.x) / (q.y - p.y); + let ry0 = r.ylo + f32(row * 16u); + let ys = max(y0, ry0); + let ye = min(y1, ry0 + T); + if ye <= ys { + return; + } + let top = vec2(p.x + (ys - p.y) * dxdy, ys); + let bottom = vec2(p.x + (ye - p.y) * dxdy, ye); + if down { + split_row(w, top, bottom, r); + } else { + split_row(w, bottom, top, r); + } +} + +// binning.rs › hairline_tiles, for tile row `row` only: the segment, whole, into every column +// within reach. +fn hairline(w: Walk, a: vec2, b: vec2, r: Rng, row: u32) { + if !(finite2(a) && finite2(b)) { + return; + } + let r0 = max(floor((min(a.y, b.y) - M - r.ylo) / T), 0.0); + let r1 = min(floor((max(a.y, b.y) + M - r.ylo) / T), f32(r.nrows - 1)); + let rf = f32(row); + if !(r1 >= r0) || rf < r0 || rf > r1 { + return; + } + let top = r.ylo + rf * T; + let dx = b.x - a.x; + let dy = b.y - a.y; + var xa = min(a.x, b.x); + var xb = max(a.x, b.x); + if dy != 0.0 { + let t0 = clamp((top - M - a.y) / dy, 0.0, 1.0); + let t1 = clamp((top + T + M - a.y) / dy, 0.0, 1.0); + let u = a.x + dx * t0; + let v = a.x + dx * t1; + xa = min(u, v); + xb = max(u, v); + } + let c0 = max(floor((xa - M - r.xlo) / T), 0.0); + let c1 = min(floor((xb + M - r.xlo) / T), f32(r.ncols - 1)); + if !(c1 >= c0) { + return; + } + for (var col = i32(c0); col <= i32(c1); col++) { + emit(w, col, vec4(a, b)); + } +} + +// The invocation's index in a dispatch of 64-wide workgroups spread over x and y. +fn linear(wg: vec3, n: vec3, lid: vec3, width: u32) -> u32 { + return (wg.y * n.x + wg.x) * width + lid.x; +} + +fn walk(mode: u32, t: u32) { + if t >= params.size.z { + return; + } + let opi = input[params.at.w + t]; + let o = op_at(opi); + // This op-row's row within the fill: how far `t` is past the fill's first op-row, which + // `row_of` holds in the op's own slot of rows (op-rows are in op order). + let row = t - input[params.at.w + params.size.z + opi]; + let ylo = f32(o.ty0 * 16u); + let r = Rng(f32(o.tx0 * 16u), f32((o.tx0 + o.ncols) * 16u), ylo, f32((o.ty0 + o.nrows) * 16u), i32(o.ncols), i32(o.nrows)); + let hair = (o.flags & HAIRLINE_BIT) != 0u; + let w = Walk(mode, o.tile_base + row * o.ncols, i32(o.ncols), hair, f32((o.ty0 + row) * 16u), r.xlo); + for (var pi = 0u; pi < o.polys; pi++) { + let pb = params.at.y + (o.first_poly + pi) * 2u; + let start = input[pb]; + let n = input[pb + 1u]; + if hair { + if n == 1u { + let p = point(start); + hairline(w, p, p, r, row); + } + for (var i = 0u; i + 1u < n; i++) { + hairline(w, point(start + i), point(start + i + 1u), r, row); + } + } else if n >= 2u { + tr_last = false; + tr_first = false; + for (var i = 0u; i < n; i++) { + let a = point(start + i); + let b = point(start + select(i + 1u, 0u, i + 1u == n)); + split_edge(w, a, b, r, row); + } + if tr_last && tr_first { + steps(w, r, tr_last_col, tr_last_y, tr_first_col); + } + } + } + if mode == COUNT && !hair { + // The backdrop deltas, summed along the row. + var acc = 0; + for (var c = 0u; c < o.ncols; c++) { + let at = backdrop_at(w.tile0 + c); + acc += bitcast(work[at]); + work[at] = bitcast(acc); + } + } +} + +@compute @workgroup_size(64) +fn count(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) n: vec3, @builtin(local_invocation_id) lid: vec3) { + walk(COUNT, linear(wg, n, lid, 64u)); +} + +@compute @workgroup_size(64) +fn scatter(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) n: vec3, @builtin(local_invocation_id) lid: vec3) { + walk(WRITE, linear(wg, n, lid, 64u)); +} + +@compute @workgroup_size(64) +fn tiles(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) n: vec3, @builtin(local_invocation_id) lid: vec3) { + let t = linear(wg, n, lid, 64u); + if t >= params.size.w { + return; + } + let tx = t % params.size.x; + let ty = t / params.size.x; + let start = index[2u * t]; + let rs = params.at2.x + input[params.at2.y + ty]; + let re = params.at2.x + input[params.at2.y + ty + 1u]; + var k = 0u; + for (var i = rs; i < re; i++) { + let opi = input[i]; + let o = op_at(opi); + if tx < o.tx0 || tx >= o.tx0 + o.ncols { + continue; + } + let ot = o.tile_base + (ty - o.ty0) * o.ncols + (tx - o.tx0); + var c = work[counts_at(ot)]; + let bd = work[backdrop_at(ot)]; + if c == 0u && bd == 0u { + continue; + } + let off = min(work[offset_at(ot)], params.more.y); + c = min(c, params.more.y - off); + let e = params.more.z + (start + k) * 4u; + index[e] = opi; + index[e + 1u] = off; + index[e + 2u] = c; + index[e + 3u] = bd; + k++; + } + index[2u * t + 1u] = k; +} diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index 8338c0f1..809f68c4 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -51,6 +51,9 @@ const T: f32 = TILE as f32; pub const NONE: u32 = u32::MAX; /// Fill rule code of a hairline in an op header (`0` non-zero, `1` even-odd). pub const HAIRLINE: u32 = 2; +/// How far from a hairline segment its tiles reach: pixel centres within its reach lie within +/// this of it (`bin.wgsl` › `M`). +pub(crate) const HAIRLINE_MARGIN: f32 = anicraft_render::hairline::REACH + 1.0; /// `vec4`s of paint data per fill. pub const PAINT_VEC4S: usize = 4; /// Gradient table entries (the oracle's LUT size). @@ -113,7 +116,8 @@ pub fn blend_code(m: BlendMode) -> u32 { /// /// * `index` (u32): `[start, count]` per tile into the entry list; then each entry as /// `[op, first piece, pieces, backdrop]` (the backdrop an `i32`), or a control entry ([`CTRL`] -/// set); then each op's header `[kind, fill rule (or HAIRLINE), ramp start in paints, flags]`. +/// set); then, at `ops_at`, each op's header `[kind, fill rule (or HAIRLINE), ramp start in +/// paints, flags]` ([`Binned::op_heads`]). /// * `geo` (`vec4`): pieces `(x0, y0, x1, y1)` relative to their tile's top-left, in the /// edge's direction (left-edge steps included); a hairline's are its segments, whole. /// * `paints` (`vec4`): per op its colour, then the inverse paint transform and gradient, @@ -127,6 +131,8 @@ pub struct Binned { pub index: Vec, pub entries_at: u32, pub ops_at: u32, + /// The op headers, which go at `ops_at` in the index. + pub op_heads: Vec, pub geo: Vec<[f32; 4]>, pub paints: Vec<[f32; 4]>, /// The paint buffer's whole length in `vec4`s: `paints`, then room for the layers. @@ -142,6 +148,10 @@ pub struct Binned { /// Pieces plus entries the fine pass walks, summed over tiles (each for 256 pixels): what /// bounds how long the dispatch runs. pub work: u64, + /// Binned on the GPU: `index` holds only the tile headers (`[start, 0]`, room for every + /// tile the fills' bounds cover), `geo` is empty, and the GPU computes the entries and + /// pieces from this plan (`entries` and `pieces` are then upper bounds). + pub gpu: Option, } /// A chunk of fills' share of the scene (binned in parallel; chunking keeps allocations few). @@ -189,6 +199,12 @@ struct RowOut { /// shader holds ([`MAX_GROUP_DEPTH`], [`MAX_CLIP_DEPTH`]) or it has more bitmaps than /// [`MAX_IMAGES`]; the caller draws it on the CPU. pub fn bin(scene: &Scene, width: u32, height: u32) -> Result { + bin_with(scene, width, height, None) +} + +/// [`bin`], or with `gpu`, a plan for binning on the GPU instead ([`Binned::gpu`]) when the +/// scene can take it and fits `gpu`'s limits ([`crate::gpu_binning`]). +pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_binning::Limits>) -> Result { if scene.groups.iter().any(|g| g.chain.len() > MAX_GROUP_DEPTH) { return Err(NeedsFull::Groups); } @@ -218,85 +234,16 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let tiles_x = width.div_ceil(TILE); let tiles_y = height.div_ceil(TILE); - let (tx, ty) = (tiles_x as usize, tiles_y as usize); - // Phase 1, parallel over chunks of ops: pieces, backdrops and entries; each chunk's - // entries then sorted (stably, so drawing order holds) by tile row, with row offsets. - let locals: Vec<(Local, Vec)> = ops - .par_chunks(CHUNK) - .enumerate() - .map(|(c, chunk)| { - let mut out = Local::default(); - let mut scratch = (Vec::new(), Track::default()); - for (i, f) in chunk.iter().enumerate() { - bin_fill(f, (c * CHUNK + i) as u32, tiles_x, tiles_y, &mut out, &mut scratch); - } - out.entries.sort_by_key(|e| e[1] / tiles_x.max(1)); - let mut rows = vec![0u32; ty + 1]; - for e in &out.entries { - if let Some(r) = rows.get_mut((e[1] / tiles_x.max(1)) as usize + 1) { - *r += 1; - } - } - for r in 1..rows.len() { - rows[r] += rows[r - 1]; - } - (out, rows) - }) - .collect(); - - // Where each chunk's pieces go in `geo`. - let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum(); - let mut piece_at = Vec::with_capacity(locals.len()); - let mut p = 0usize; - for (l, _) in &locals { - piece_at.push(p as u32); - p += l.pieces.len(); - } - - // Phase 2, parallel over tile rows: each tile's stream of entries. - let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, &tables)).collect(); - let mut row_at = vec![0usize; ty + 1]; - for (r, out) in rows.iter().enumerate() { - row_at[r + 1] = row_at[r] + out.stream.len(); - } - let total = row_at[ty]; - let work = rows.iter().map(|r| r.work).sum(); - let entries_at = 2 * tx * ty; - let ops_at = entries_at + 4 * total; - let mut index = vec![0u32; ops_at + 4 * ops.len()]; - // Phase 3, parallel over tile rows: headers and streams copied into place. - { - let (headers, rest) = index.split_at_mut(entries_at); - let (mut entries, _) = rest.split_at_mut(4 * total); - let mut row_entries: Vec<&mut [u32]> = Vec::with_capacity(ty); - for r in 0..ty { - let (mine, after) = std::mem::take(&mut entries).split_at_mut(4 * (row_at[r + 1] - row_at[r])); - row_entries.push(mine); - entries = after; + // On the GPU when asked and the scene can take it (no fill in a mask or a group, for now): + // then the fills alone are the ops (no mask artwork draws). + let plan = gpu.filter(|_| scene.fills.iter().all(|f| f.clip.is_none() && f.group.is_none())).and_then(|lim| crate::gpu_binning::plan(&scene.fills, tiles_x, tiles_y, lim)); + let lists = match &plan { + Some(p) => { + ops.truncate(nf); + Lists::on_gpu(p, tiles_x, tiles_y) } - headers.par_chunks_mut(2 * tx.max(1)).zip(row_entries).zip(&rows).enumerate().for_each(|(r, ((head, out), row))| { - for (h, &[s, n]) in head.as_chunks_mut::<2>().0.iter_mut().zip(&row.heads) { - *h = [row_at[r] as u32 + s, n]; - } - for (d, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(&row.stream) { - *d = *s; - } - }); - } - // Pieces copied in parallel into their places. - let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces]; - { - let mut piece_dst = &mut geo[..]; - let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(locals.len()); - for (l, _) in &locals { - let (a, rest) = std::mem::take(&mut piece_dst).split_at_mut(l.pieces.len()); - jobs.push((a, &l.pieces)); - piece_dst = rest; - } - jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s)); - } - // Tens of thousands of small buffers: free them on the pool, off the frame's path. - anicraft_render::drop_in_background((locals, rows)); + None => cpu_lists(&ops, &tables, tiles_x, tiles_y), + }; // Paints: a fixed record per op, then the gradient tables, then the layers' pixels. let mut paints: Vec<[f32; 4]> = Vec::with_capacity(PAINT_VEC4S * ops.len()); @@ -319,6 +266,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result return Err(NeedsFull::Filters); } let paints_len = cursor; + let mut op_heads: Vec = Vec::with_capacity(4 * ops.len()); let u = f32::from_bits; for (op, f) in ops.iter().enumerate() { let rule = match f.rule { @@ -372,10 +320,7 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result } else { 0 }; - let at = ops_at + 4 * op; - if let Some(slot) = index.get_mut(at..at + 4) { - slot.copy_from_slice(&[kind, rule, ramp, flags]); - } + op_heads.extend_from_slice(&[kind, rule, ramp, flags]); } paints.extend_from_slice(&ramps); if paints.len() != PAINT_VEC4S * ops.len() + table_len { @@ -383,7 +328,115 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result return Err(NeedsFull::Filters); } - Ok(Binned { tiles_x, tiles_y, index, entries_at: entries_at as u32, ops_at: ops_at as u32, geo, paints, paints_len, layer_at, images, entries: total, pieces, work }) + let Lists { index, geo, entries_at, ops_at, entries, pieces, work } = lists; + Ok(Binned { tiles_x, tiles_y, index, entries_at, ops_at, op_heads, geo, paints, paints_len, layer_at, images, entries, pieces, work, gpu: plan }) +} + +/// The tile lists (or, binned on the GPU, room for them). +struct Lists { + index: Vec, + geo: Vec<[f32; 4]>, + entries_at: u32, + ops_at: u32, + entries: usize, + pieces: usize, + work: u64, +} + +impl Lists { + /// Headers `[start, 0]` with room for every tile its fills' bounds cover; the GPU fills in + /// the entries and the counts. Entries and pieces are upper bounds. + fn on_gpu(p: &crate::gpu_binning::Plan, tiles_x: u32, tiles_y: u32) -> Lists { + let entries_at = 2 * tiles_x * tiles_y; + let ops_at = entries_at + 4 * p.op_tiles; + let work = u64::from(p.op_tiles) + u64::from(p.piece_cap); + Lists { index: p.headers.clone(), geo: Vec::new(), entries_at, ops_at, entries: p.op_tiles as usize, pieces: p.piece_cap as usize, work } + } +} + +/// The tile lists, binned on the CPU (in parallel per chunk of fills, then per tile row). +fn cpu_lists(ops: &[&Fill], tables: &Tables, tiles_x: u32, tiles_y: u32) -> Lists { + let (tx, ty) = (tiles_x as usize, tiles_y as usize); + // Phase 1, parallel over chunks of ops: pieces, backdrops and entries; each chunk's + // entries then sorted (stably, so drawing order holds) by tile row, with row offsets. + let locals: Vec<(Local, Vec)> = ops + .par_chunks(CHUNK) + .enumerate() + .map(|(c, chunk)| { + let mut out = Local::default(); + let mut scratch = (Vec::new(), Track::default()); + for (i, f) in chunk.iter().enumerate() { + bin_fill(f, (c * CHUNK + i) as u32, tiles_x, tiles_y, &mut out, &mut scratch); + } + out.entries.sort_by_key(|e| e[1] / tiles_x.max(1)); + let mut rows = vec![0u32; ty + 1]; + for e in &out.entries { + if let Some(r) = rows.get_mut((e[1] / tiles_x.max(1)) as usize + 1) { + *r += 1; + } + } + for r in 1..rows.len() { + rows[r] += rows[r - 1]; + } + (out, rows) + }) + .collect(); + + // Where each chunk's pieces go in `geo`. + let pieces: usize = locals.iter().map(|(l, _)| l.pieces.len()).sum(); + let mut piece_at = Vec::with_capacity(locals.len()); + let mut p = 0usize; + for (l, _) in &locals { + piece_at.push(p as u32); + p += l.pieces.len(); + } + + // Phase 2, parallel over tile rows: each tile's stream of entries. + let rows: Vec = (0..ty).into_par_iter().map(|r| row_streams(r, tx, &locals, &piece_at, tables)).collect(); + let mut row_at = vec![0usize; ty + 1]; + for (r, out) in rows.iter().enumerate() { + row_at[r + 1] = row_at[r] + out.stream.len(); + } + let total = row_at[ty]; + let work = rows.iter().map(|r| r.work).sum(); + let entries_at = 2 * tx * ty; + let ops_at = entries_at + 4 * total; + let mut index = vec![0u32; ops_at]; + // Phase 3, parallel over tile rows: headers and streams copied into place. + { + let (headers, rest) = index.split_at_mut(entries_at); + let (mut entries, _) = rest.split_at_mut(4 * total); + let mut row_entries: Vec<&mut [u32]> = Vec::with_capacity(ty); + for r in 0..ty { + let (mine, after) = std::mem::take(&mut entries).split_at_mut(4 * (row_at[r + 1] - row_at[r])); + row_entries.push(mine); + entries = after; + } + headers.par_chunks_mut(2 * tx.max(1)).zip(row_entries).zip(&rows).enumerate().for_each(|(r, ((head, out), row))| { + for (h, &[s, n]) in head.as_chunks_mut::<2>().0.iter_mut().zip(&row.heads) { + *h = [row_at[r] as u32 + s, n]; + } + for (d, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(&row.stream) { + *d = *s; + } + }); + } + // Pieces copied in parallel into their places. + let mut geo: Vec<[f32; 4]> = vec![[0.0; 4]; pieces]; + { + let mut piece_dst = &mut geo[..]; + let mut jobs: Vec<(&mut [Vec4], &[Vec4])> = Vec::with_capacity(locals.len()); + for (l, _) in &locals { + let (a, rest) = std::mem::take(&mut piece_dst).split_at_mut(l.pieces.len()); + jobs.push((a, &l.pieces)); + piece_dst = rest; + } + jobs.into_par_iter().for_each(|(d, s)| d.copy_from_slice(s)); + } + // Tens of thousands of small buffers: free them on the pool, off the frame's path. + anicraft_render::drop_in_background((locals, rows)); + + Lists { index, geo, entries_at: entries_at as u32, ops_at: ops_at as u32, entries: total, pieces, work } } /// A colour effect as the shader applies it to each bitmap tap, the same arithmetic as @@ -527,7 +580,7 @@ fn bin_fill(f: &Fill, op: u32, tiles_x: u32, tiles_y: u32, out: &mut Local, (pie pieces.clear(); if f.hairline { for poly in &f.polys { - for_segments(poly, |a, b| hairline_tiles(a, b, &range, |row, col| pieces.push(Piece { row, col, seg: [a.x, a.y, b.x, b.y] }))); + for_segments(poly, |a, b| hairline_tiles(a, b, &range, HAIRLINE_MARGIN, |row, col| pieces.push(Piece { row, col, seg: [a.x, a.y, b.x, b.y] }))); } } else { for poly in &f.polys { @@ -622,6 +675,7 @@ pub(crate) fn top_crossing(seg: &[f32; 4], row_y0: f32) -> i32 { /// A fill's tile range, in pixels and tiles. #[derive(Clone, Copy)] +#[derive(Debug)] pub(crate) struct Range { pub(crate) tx0: u32, pub(crate) ty0: u32, @@ -836,17 +890,17 @@ fn steps(a: Seen, b: Seen, row: u32, r: &Range, out: &mut impl FnMut(Piece)) { } } -/// Every tile of the range with a pixel centre within a hairline's reach of segment `a → b` -/// (conservatively: a little more), as `(row, col)` relative to the range. -fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32)) { +/// Every tile of the range within `margin` of segment `a → b` (rows and columns padded by it), +/// as `(row, col)` relative to the range. With [`HAIRLINE_MARGIN`], every tile with a pixel +/// centre within a hairline's reach (`bin.wgsl` › `hairline` uses the same). +pub(crate) fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, margin: f32, mut out: impl FnMut(u32, i32)) { if !(a.is_finite() && b.is_finite()) { return; } - // Pixel centres within reach of the segment lie within these margins of it. - const M: f32 = anicraft_render::hairline::REACH + 1.0; + let m = margin; let (ymin, ymax) = (a.y.min(b.y), a.y.max(b.y)); - let r0 = (((ymin - M - r.ylo) / T).floor()).max(0.0); - let r1 = (((ymax + M - r.ylo) / T).floor()).min((r.nrows - 1) as f32); + let r0 = (((ymin - m - r.ylo) / T).floor()).max(0.0); + let r1 = (((ymax + m - r.ylo) / T).floor()).min((r.nrows - 1) as f32); if r1 < r0 { return; } @@ -857,13 +911,13 @@ fn hairline_tiles(a: Vec2, b: Vec2, r: &Range, mut out: impl FnMut(u32, i32)) { let (xa, xb) = if dy == 0.0 { (a.x.min(b.x), a.x.max(b.x)) } else { - let t0 = ((top - M - a.y) / dy).clamp(0.0, 1.0); - let t1 = ((top + T + M - a.y) / dy).clamp(0.0, 1.0); + let t0 = ((top - m - a.y) / dy).clamp(0.0, 1.0); + let t1 = ((top + T + m - a.y) / dy).clamp(0.0, 1.0); let (u, v) = (a.x + dx * t0, a.x + dx * t1); (u.min(v), u.max(v)) }; - let c0 = (((xa - M - r.xlo) / T).floor()).max(0.0); - let c1 = (((xb + M - r.xlo) / T).floor()).min((r.ncols - 1) as f32); + let c0 = (((xa - m - r.xlo) / T).floor()).max(0.0); + let c1 = (((xb + m - r.xlo) / T).floor()).min((r.ncols - 1) as f32); if c1 < c0 { continue; } diff --git a/crates/gpu/src/gpu_binning.rs b/crates/gpu/src/gpu_binning.rs new file mode 100644 index 00000000..7e9390ee --- /dev/null +++ b/crates/gpu/src/gpu_binning.rs @@ -0,0 +1,410 @@ +//! Tile binning on the GPU (ADR 0048): the host half. +//! +//! [`crate::binning`] is the reference: it splits every fill's edges into tile pieces on the +//! CPU. Here the CPU only lays out what the GPU needs, in time proportional to the fills and +//! their points, and `bin.wgsl` does the splitting, the backdrops and the tile lists: +//! +//! * the fills' points and polygons, one flat buffer, with each fill's tile range; +//! * one GPU invocation per row of tiles of each fill (an *op-row*), and room for each tile +//! of each fill's bounds (an *op-tile*): its piece count, backdrop, place and cursor; +//! * per tile row, the fills overlapping it in drawing order, and per tile where its entries +//! go: room for every fill whose bounds cover it (the GPU keeps those with pieces or a +//! backdrop there, in order); +//! * an upper bound of the pieces, from each edge's rows and columns, so every buffer is sized +//! before the GPU runs and nothing is read back. +//! +//! The passes count, scan (prefix sum), scatter and list; their output is the same tile lists +//! as the CPU's, bit for bit in everything but rounding (a test compares them per pixel). + +use crate::binning::{HAIRLINE_MARGIN, Range, TILE, hairline_tiles}; +use anicraft_render::Fill; +use rayon::prelude::*; + +/// An op that is a hairline (`bin.wgsl` › `HAIRLINE_BIT`). +const HAIRLINE_BIT: u32 = 1 << 31; +/// `u32`s per op in the input (`bin.wgsl` › `Op`). +const OP_WORDS: usize = 8; +/// Values one scan workgroup handles (`scan.wgsl`). +const SCAN_BLOCK: u32 = 1024; + +/// When and how far the GPU bins. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// The largest buffer the device binds (bytes). + pub binding: u64, + /// Fewer edges than this bin on the CPU, where it takes less than setting up the passes. + pub min_edges: u64, +} + +/// Most edge visits the GPU's per-row passes may make (each row of a fill walks all its +/// edges): far above real scenes (the 50k-shape 4K stress frame makes about 6 M), it keeps a +/// fill with very many edges over very many rows on the CPU, which splits each edge once. +pub const MAX_VISITS: u64 = 1 << 26; + +/// What the GPU needs to bin a scene, laid out by the CPU. +pub struct Plan { + /// The ops, polygons, points, op-row owners (and each op's first op-row), the rows' fills + /// and the rows' starts, at [`Plan::at`]. + pub(crate) input: Vec, + pub(crate) at: [u32; 6], + pub(crate) op_rows: u32, + /// Tiles of the fills' bounds: the entries' room and the working values' length. + pub op_tiles: u32, + /// Room for pieces: an upper bound. + pub piece_cap: u32, + /// `[start, 0]` per tile. + pub(crate) headers: Vec, + /// Edges, and edge visits by the per-row passes. + pub edges: u64, + pub visits: u64, +} + +/// What one fill needs: its range and how much room. +struct Info { + range: Option, + polys: u32, + points: u32, + edges: u64, + pieces: u64, +} + +fn info(f: &Fill, tiles_x: u32, tiles_y: u32) -> Info { + let Some(r) = Range::of(f, tiles_x, tiles_y) else { return Info { range: None, polys: 0, points: 0, edges: 0, pieces: 0 } }; + let mut pieces = 0u64; + let mut edges = 0u64; + for poly in &f.polys { + if f.hairline { + let mut seg = |a, b| { + // With a pixel more reach than the binning's, whatever the GPU's rounding. + let mut n = 0u64; + hairline_tiles(a, b, &r, HAIRLINE_MARGIN + 1.0, |_, _| n += 1); + pieces += n; + edges += 1; + }; + match poly.as_slice() { + [] => {} + [p] => seg(*p, *p), + _ => poly.windows(2).for_each(|w| seg(w[0], w[1])), + } + } else { + let n = poly.len(); + if n < 2 { + continue; + } + for i in 0..n { + if let (Some(&a), Some(&b)) = (poly.get(i), poly.get((i + 1) % n)) { + pieces += edge_pieces(a, b, &r); + } + } + edges += n as u64; + } + } + let points = f.polys.iter().map(Vec::len).sum::() as u32; + Info { range: Some(r), polys: f.polys.len() as u32, points, edges, pieces } +} + +/// At most how many pieces edge `a → b` gives (`binning.rs` › `split_edge` and `steps`): one +/// per tile row it spans, one more per column boundary it crosses, a left-edge step per column +/// boundary it passes, and one for where it meets the next edge; with slack for rounding. +fn edge_pieces(a: anicraft_geom::Vec2, b: anicraft_geom::Vec2, r: &Range) -> u64 { + if !(a.is_finite() && b.is_finite()) { + return 0; + } + let t = TILE as f32; + let (y0, y1) = (a.y.min(b.y).max(r.ylo), a.y.max(b.y).min(r.yhi)); + if y1 < y0 { + return 0; + } + let rows = ((y1 - r.ylo) / t).floor() - ((y0 - r.ylo) / t).floor() + 1.0; + let (x0, x1) = (a.x.min(b.x).max(r.xlo), a.x.max(b.x).min(r.xhi)); + let cols = if x1 >= x0 { ((x1 - r.xlo) / t).floor() - ((x0 - r.xlo) / t).floor() + 1.0 } else { 1.0 }; + (rows.clamp(0.0, r.nrows as f32 + 1.0) + 2.0 * cols.clamp(0.0, r.ncols as f32 + 1.0)) as u64 + 3 +} + +/// The plan for binning `fills` (the scene's, in drawing order) on a `tiles_x × tiles_y` +/// surface; `None` when the CPU should: too few edges to be worth it, too many visits, or a +/// buffer larger than the device binds. +pub fn plan(fills: &[Fill], tiles_x: u32, tiles_y: u32, lim: &Limits) -> Option { + let infos: Vec = fills.par_iter().map(|f| info(f, tiles_x, tiles_y)).collect(); + let n = fills.len(); + let (mut polys, mut points, mut op_tiles, mut op_rows, mut pieces, mut edges, mut visits) = (0u64, 0u64, 0u64, 0u64, 0u64, 0u64, 0u64); + for i in &infos { + polys += u64::from(i.polys); + points += u64::from(i.points); + pieces += i.pieces; + edges += i.edges; + if let Some(r) = &i.range { + op_tiles += (r.ncols as u64) * (r.nrows as u64); + op_rows += r.nrows as u64; + visits += (r.nrows as u64) * i.edges; + } + } + let tiles = u64::from(tiles_x) * u64::from(tiles_y); + let words = OP_WORDS as u64 * n as u64 + 2 * polys + 2 * points + op_rows + n as u64 + op_rows + u64::from(tiles_y) + 1; + let work_words = 4 * op_tiles + 2 * op_tiles.div_ceil(u64::from(SCAN_BLOCK)) + 64; + let fits = |bytes: u64| bytes <= lim.binding; + if edges < lim.min_edges || visits > MAX_VISITS || pieces >= u64::from(u32::MAX) || op_tiles >= u64::from(u32::MAX) / 4 { + return None; + } + if !(fits(4 * words) && fits(4 * work_words) && fits(16 * pieces) && fits(4 * (2 * tiles + 4 * op_tiles + 4 * n as u64))) { + return None; + } + + // Where everything goes. + let at_ops = 0usize; + let at_polys = at_ops + OP_WORDS * n; + let at_points = at_polys + 2 * polys as usize; + let at_row_of = at_points + 2 * points as usize; + let at_row_ops = at_row_of + op_rows as usize + n; + let at_row_start = at_row_ops + op_rows as usize; + let mut input = vec![0u32; at_row_start + tiles_y as usize + 1]; + + // Per op: its first polygon, point, op-tile and op-row. + let mut firsts = Vec::with_capacity(n); + let (mut p0, mut q0, mut t0, mut r0) = (0u32, 0u32, 0u32, 0u32); + for i in &infos { + firsts.push((p0, q0, t0, r0)); + p0 += i.polys; + q0 += i.points; + if let Some(r) = &i.range { + t0 += (r.ncols * r.nrows) as u32; + r0 += r.nrows as u32; + } + } + { + let (head, rest) = input.split_at_mut(at_polys); + let (poly_words, rest) = rest.split_at_mut(at_points - at_polys); + let (point_words, rest) = rest.split_at_mut(at_row_of - at_points); + let (row_of, rest) = rest.split_at_mut(op_rows as usize); + let (row_base, rest) = rest.split_at_mut(n); + let (row_ops, row_start) = rest.split_at_mut(op_rows as usize); + // Each op's slices of the polygon and point tables, then filled in parallel. + let mut jobs: Vec = Vec::with_capacity(n); + let (mut pw, mut qw) = (poly_words, point_words); + for ((h, f), (i, first)) in head.chunks_mut(OP_WORDS).zip(fills).zip(infos.iter().zip(&firsts)) { + let (a, b) = std::mem::take(&mut pw).split_at_mut(2 * i.polys as usize); + let (c, d) = std::mem::take(&mut qw).split_at_mut(2 * i.points as usize); + pw = b; + qw = d; + jobs.push((h, a, c, f, i, *first)); + } + jobs.into_par_iter().for_each(|(h, pw, qw, f, i, (p0, q0, t0, _))| { + let (tx0, ty0, ncols, nrows) = i.range.map_or((0, 0, 0, 0), |r| (r.tx0, r.ty0, r.ncols as u32, r.nrows as u32)); + let flags = if f.hairline { HAIRLINE_BIT } else { 0 }; + h.copy_from_slice(&[p0, i.polys, tx0, ty0, ncols, nrows, t0, flags]); + let mut q = q0; + for (slot, poly) in pw.chunks_exact_mut(2).zip(&f.polys) { + slot.copy_from_slice(&[q, poly.len() as u32]); + q += poly.len() as u32; + } + for (slot, p) in qw.chunks_exact_mut(2).zip(f.polys.iter().flatten()) { + slot.copy_from_slice(&[p.x.to_bits(), p.y.to_bits()]); + } + }); + // Op-rows in op order: who owns each, and each op's first. + let mut k = 0usize; + for (op, (i, first)) in infos.iter().zip(&firsts).enumerate() { + if let Some(b) = row_base.get_mut(op) { + *b = first.3; + } + for _ in 0..i.range.map_or(0, |r| r.nrows) { + if let Some(o) = row_of.get_mut(k) { + *o = op as u32; + } + k += 1; + } + } + // Each tile row's fills, in drawing order (a counting sort by row). + for i in &infos { + if let Some(r) = &i.range { + for row in r.ty0..r.ty0 + r.nrows as u32 { + if let Some(c) = row_start.get_mut(row as usize + 1) { + *c += 1; + } + } + } + } + for j in 1..row_start.len() { + row_start[j] += row_start[j - 1]; + } + let mut cursor: Vec = row_start.to_vec(); + for (op, i) in infos.iter().enumerate() { + if let Some(r) = &i.range { + for row in r.ty0..r.ty0 + r.nrows as u32 { + if let Some(c) = cursor.get_mut(row as usize) + && let Some(slot) = row_ops.get_mut(*c as usize) + { + *slot = op as u32; + *c += 1; + } + } + } + } + } + // Where each tile's entries go: room for every fill whose bounds cover it (a 2D running + // sum over the bounds' corners). + let (w, h) = (tiles_x as usize + 1, tiles_y as usize + 1); + let mut cover = vec![0i64; w * h]; + for r in infos.iter().filter_map(|i| i.range) { + let (x0, y0, x1, y1) = (r.tx0 as usize, r.ty0 as usize, r.tx0 as usize + r.ncols as usize, r.ty0 as usize + r.nrows as usize); + for (x, y, d) in [(x0, y0, 1), (x1, y0, -1), (x0, y1, -1), (x1, y1, 1)] { + if let Some(c) = cover.get_mut(y * w + x) { + *c += d; + } + } + } + for y in 0..h { + for x in 0..w { + let left = if x > 0 { cover[y * w + x - 1] } else { 0 }; + let up = if y > 0 { cover[(y - 1) * w + x] } else { 0 }; + let diag = if x > 0 && y > 0 { cover[(y - 1) * w + x - 1] } else { 0 }; + cover[y * w + x] += left + up - diag; + } + } + let mut headers = vec![0u32; 2 * tiles as usize]; + let mut start = 0u64; + for ty in 0..tiles_y as usize { + for tx in 0..tiles_x as usize { + if let Some(hd) = headers.get_mut(2 * (ty * tiles_x as usize + tx)) { + *hd = start as u32; + } + start += cover.get(ty * w + tx).copied().unwrap_or(0).max(0) as u64; + } + } + if start != op_tiles { + return None; // the room per tile must add up to the op-tiles (it always does) + } + let at = [at_ops, at_polys, at_points, at_row_of, at_row_ops, at_row_start].map(|a| a as u32); + Some(Plan { input, at, op_rows: op_rows as u32, op_tiles: op_tiles as u32, piece_cap: pieces as u32, headers, edges, visits }) +} + +/// One op's share of the input to fill in: its record, polygon and point words, the fill, its +/// sizes, and its first polygon, point, op-tile and op-row. +type Job<'a> = (&'a mut [u32], &'a mut [u32], &'a mut [u32], &'a Fill, &'a Info, (u32, u32, u32, u32)); + +/// The binning pipelines (`bin.wgsl`, `scan.wgsl`). +pub(crate) struct Pipelines { + count: wgpu::ComputePipeline, + scatter: wgpu::ComputePipeline, + tiles: wgpu::ComputePipeline, + layout: wgpu::BindGroupLayout, + scan_blocks: wgpu::ComputePipeline, + scan_add: wgpu::ComputePipeline, + scan_layout: wgpu::BindGroupLayout, +} + +impl Pipelines { + pub(crate) fn new(device: &wgpu::Device) -> Pipelines { + let entry = |binding: u32, ty: wgpu::BufferBindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }, count: None }; + let rw = wgpu::BufferBindingType::Storage { read_only: false }; + let bin_entries = [entry(0, wgpu::BufferBindingType::Uniform), entry(1, wgpu::BufferBindingType::Storage { read_only: true }), entry(2, rw), entry(3, rw), entry(4, rw)]; + let ([count, scatter, tiles], layout) = pipelines(device, "anicraft-bin", include_str!("bin.wgsl"), &bin_entries, ["count", "scatter", "tiles"]); + let ([scan_blocks, scan_add], scan_layout) = pipelines(device, "anicraft-scan", include_str!("scan.wgsl"), &[entry(0, wgpu::BufferBindingType::Uniform), entry(1, rw)], ["scan_blocks", "scan_add"]); + Pipelines { count, scatter, tiles, layout, scan_blocks, scan_add, scan_layout } + } +} + +/// One shader's entry points as pipelines sharing one bind group layout. +fn pipelines(device: &wgpu::Device, label: &str, src: &str, entries: &[wgpu::BindGroupLayoutEntry], points: [&str; N]) -> ([wgpu::ComputePipeline; N], wgpu::BindGroupLayout) { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(src.into()) }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: &[Some(&layout)], immediate_size: 0 }); + let pipes = points.map(|p| device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(p), layout: Some(&pl), module: &module, entry_point: Some(p), compilation_options: Default::default(), cache: None })); + (pipes, layout) +} + +/// Workgroups for `n` invocations of `width`, spread over x and y (at most 65,535 each way). +fn groups(n: u32, width: u32) -> (u32, u32) { + let g = n.div_ceil(width).max(1); + let x = g.min(65_535); + (x, g.div_ceil(x)) +} + +/// The fine pass's index and pieces, binned on the GPU into `enc` from `plan`: the index with +/// `heads` (the tile headers) at 0 and `op_heads` at `ops_at`. +#[allow(clippy::too_many_arguments)] +pub(crate) fn record(device: &wgpu::Device, pipes: &Pipelines, enc: &mut wgpu::CommandEncoder, plan: &Plan, tiles_x: u32, tiles_y: u32, entries_at: u32, ops_at: u32, op_heads: &[u32]) -> Result<(wgpu::Buffer, wgpu::Buffer), String> { + use wgpu::util::DeviceExt; + let index_len = (ops_at as usize + op_heads.len()).max(4); + let index = device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * index_len as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: true }); + { + let mut m = index.slice(..).get_mapped_range_mut().map_err(|e| e.to_string())?; + crate::write_words(&mut m, 0, &plan.headers); + crate::write_words(&mut m, ops_at as usize, op_heads); + } + index.unmap(); + let geo = device.create_buffer(&wgpu::BufferDescriptor { label: Some("geo"), size: 16 * u64::from(plan.piece_cap.max(1)), usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }); + if plan.op_rows == 0 { + return Ok((index, geo)); + } + let n = plan.op_tiles; + // Counts, backdrops, offsets, cursors, then the scan's totals level by level. New buffers + // start zeroed. + let mut levels: Vec<[u32; 4]> = Vec::new(); + let (mut src, mut dst, mut len, mut sums) = (0u32, 2 * n, n, 4 * n); + loop { + let blocks = len.div_ceil(SCAN_BLOCK); + levels.push([src, dst, sums, len]); + if blocks <= 1 { + break; + } + (src, dst, len) = (sums, sums, blocks); + sums += blocks; + } + let work_len = (sums + 2) as u64; + let work = device.create_buffer(&wgpu::BufferDescriptor { label: Some("bin-work"), size: 4 * work_len, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false }); + let input = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("bin-input"), contents: bytemuck::cast_slice(&plan.input), usage: wgpu::BufferUsages::STORAGE }); + let tiles = tiles_x * tiles_y; + let a = plan.at; + let params: [u32; 16] = [tiles_x, tiles_y, plan.op_rows, tiles, n, plan.piece_cap, entries_at, 0, a[0], a[1], a[2], a[3], a[4], a[5], 0, 0]; + let ubuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("bin-params"), contents: bytemuck::cast_slice(¶ms), usage: wgpu::BufferUsages::UNIFORM }); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("anicraft-bin"), + layout: &pipes.layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: work.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: geo.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: index.as_entire_binding() }, + ], + }); + let scans: Vec<(wgpu::BindGroup, u32)> = levels + .iter() + .map(|l| { + let u = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("scan-params"), contents: bytemuck::cast_slice(l), usage: wgpu::BufferUsages::UNIFORM }); + let b = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("anicraft-scan"), + layout: &pipes.scan_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: u.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: work.as_entire_binding() }], + }); + (b, l[3].div_ceil(SCAN_BLOCK)) + }) + .collect(); + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("anicraft-bin"), timestamp_writes: None }); + let rows = groups(plan.op_rows, 64); + pass.set_pipeline(&pipes.count); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(rows.0, rows.1, 1); + // The scan, level by level up, then each level's totals added back down. + pass.set_pipeline(&pipes.scan_blocks); + for (b, blocks) in &scans { + let g = groups(*blocks, 1); + pass.set_bind_group(0, b, &[]); + pass.dispatch_workgroups(g.0, g.1, 1); + } + pass.set_pipeline(&pipes.scan_add); + for (b, blocks) in scans.iter().rev().skip(1) { + let g = groups(*blocks, 1); + pass.set_bind_group(0, b, &[]); + pass.dispatch_workgroups(g.0, g.1, 1); + } + pass.set_pipeline(&pipes.scatter); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(rows.0, rows.1, 1); + let t = groups(tiles, 64); + pass.set_pipeline(&pipes.tiles); + pass.dispatch_workgroups(t.0, t.1, 1); + drop(pass); + Ok((index, geo)) +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index ce7251c2..1d1921ad 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -2,10 +2,11 @@ //! //! Draws the same scene as the CPU oracle (`anicraft-render`) with wgpu compute: the oracle //! prepares it ([`anicraft_render::prepare_scene`]: flattening, strokes, paints and their -//! gradient tables, clips and groups), [`binning`] sorts the edges into 16 × 16 tiles on the -//! CPU, and one compute pass computes every pixel's exact area coverage and composites the -//! fills in order, inside their masks and groups (alpha and blend modes) as the oracle's band -//! compositor does. Bitmap fills are sampled from textures uploaded once per image +//! gradient tables, clips and groups), the edges are sorted into 16 × 16 tiles, on the GPU +//! ([`gpu_binning`], ADR 0048) or on the CPU ([`binning`], the reference, and the way for fills +//! in masks and groups), and one compute pass computes every pixel's exact area coverage +//! (or a hairline's distance) and composites the fills in order, inside their masks and groups +//! (alpha and blend modes) as the oracle's band compositor does. Bitmap fills are sampled from textures uploaded once per image //! ([`images`]); a filtered symbol is drawn into a layer of its own, filtered by compute passes //! that run the oracle's filter steps ([`layers`]), and composited like any fill (ADR 0032). //! The output is the oracle's within float rounding (the parity tests check mean and maximum @@ -22,6 +23,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod binning; +pub mod gpu_binning; pub mod images; mod layers; @@ -29,6 +31,7 @@ use anicraft_doc::DisplayList; use anicraft_render::{MAX_PIXELS, NeedsFull, Pixmap, RenderStats, View, paint::premultiply, prepare_scene}; #[cfg(not(target_arch = "wasm32"))] use rayon::prelude::*; +use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use web_time::Instant; use wgpu::util::DeviceExt; @@ -68,11 +71,57 @@ pub struct GpuFrame { pub pixmap: Option, pub stats: RenderStats, pub timings: Timings, - /// Tile entries and edge pieces the fine pass walked. + /// Tile entries and edge pieces the fine pass walked (when binned on the GPU, the room + /// made for them: upper bounds). pub entries: usize, pub pieces: usize, + /// Whether the GPU binned the frame's tiles ([`Binning`]). + pub gpu_binned: bool, } +/// Where a frame's edges are sorted into tiles (ADR 0048). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Binning { + /// On the GPU when the scene can take it (no fill inside a mask or a group, for now) and + /// has enough edges to be worth the passes ([`AUTO_MIN_EDGES`]); otherwise on the CPU. + Auto, + /// Always on the CPU (the reference). + Cpu, + /// On the GPU whenever the scene can take it, however small (tests and benchmarks). + Gpu, +} + +impl Binning { + fn code(self) -> u8 { + match self { + Binning::Auto => 0, + Binning::Cpu => 1, + Binning::Gpu => 2, + } + } + + fn from_code(c: u8) -> Binning { + match c { + 1 => Binning::Cpu, + 2 => Binning::Gpu, + _ => Binning::Auto, + } + } + + /// `ANICRAFT_GPU_BINNING=cpu|gpu|auto` (for comparing them in the app); auto otherwise. + fn from_env() -> Binning { + match std::env::var("ANICRAFT_GPU_BINNING").map(|v| v.trim().to_ascii_lowercase()).as_deref() { + Ok("cpu") => Binning::Cpu, + Ok("gpu") => Binning::Gpu, + _ => Binning::Auto, + } + } +} + +/// Fewer edges than this are binned on the CPU in [`Binning::Auto`]: below it the CPU bins a +/// frame in less time than the GPU's passes take to set up (measured, docs/performance.md). +pub const AUTO_MIN_EDGES: u64 = 4096; + /// A frame rendered into a texture on the renderer's device: premultiplied RGBA8 /// (`Rgba8Unorm`, the bytes [`Pixmap::to_premul_rgba8`] gives), sampleable, ready for the window /// to show (egui's `register_native_texture`). The work is submitted, not waited for: anything @@ -86,6 +135,7 @@ pub struct GpuTexture { pub timings: Timings, pub entries: usize, pub pieces: usize, + pub gpu_binned: bool, } /// Where a frame's time went (milliseconds, on the calling thread). @@ -93,7 +143,8 @@ pub struct GpuTexture { pub struct Timings { /// Cull, flatten, stroke and paint set-up (shared with the oracle, parallel). pub prepare: f32, - /// Tile binning (parallel per fill and per tile row) and buffer packing. + /// Tile binning on the CPU (parallel per fill and per tile row), or laying out the GPU's + /// binning (per fill), and buffer packing. pub bin: f32, /// Upload and submit; for read-back frames also the wait for the GPU and the copy back. pub gpu: f32, @@ -131,6 +182,9 @@ pub struct GpuRenderer { texture_pipeline: wgpu::ComputePipeline, texture_layout: wgpu::BindGroupLayout, filters: layers::FilterPipelines, + bins: gpu_binning::Pipelines, + /// [`Binning`], as its code. + binning: AtomicU8, /// Bound where a texture slot or a buffer is unused. blank: wgpu::TextureView, /// Placeholders for a filter pass's coverage (written) and ramp (read): one buffer can't be @@ -316,6 +370,7 @@ impl GpuRenderer { let storage_texture = wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: wgpu::TextureFormat::Rgba8Unorm, view_dimension: wgpu::TextureViewDimension::D2 }; let (texture_pipeline, texture_layout) = make("anicraft-fine-texture", entry(5, storage_texture), "main_texture"); let filters = layers::FilterPipelines::new(&device); + let bins = gpu_binning::Pipelines::new(&device); let blank = device .create_texture(&wgpu::TextureDescriptor { label: Some("anicraft-blank"), @@ -341,6 +396,8 @@ impl GpuRenderer { texture_pipeline, texture_layout, filters, + bins, + binning: AtomicU8::new(Binning::from_env().code()), blank, blank_coverage, blank_ramp, @@ -402,7 +459,24 @@ impl GpuRenderer { }; check("read back", &self.render(&dl, &view, Output::Premul8)?.premul8)?; let t = self.render_texture(&dl, &view)?; - check("through a texture", &self.read_texture(&t)?) + check("through a texture", &self.read_texture(&t)?)?; + // And binned on the GPU (the plain fills; the bitmap and the symbol stay on the CPU's). + let plain = DisplayList { items: dl.items.iter().take(3).cloned().collect(), ..Default::default() }; + let (want, _) = anicraft_render::render(&plain, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; + let got = self.render_with(&plain, &view, Output::Premul8, Binning::Gpu)?; + match compare_premul8(&got.premul8, &want.to_premul_rgba8()) { + Some(d) if got.gpu_binned && d.max <= 2 && d.mean <= 0.1 => Ok(()), + d => Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong binned on the GPU ({d:?})", self.adapter))), + } + } + + /// Where frames' edges are sorted into tiles from now on. + pub fn set_binning(&self, b: Binning) { + self.binning.store(b.code(), Ordering::Relaxed); + } + + pub fn binning(&self) -> Binning { + Binning::from_code(self.binning.load(Ordering::Relaxed)) } /// Whether the device has failed (lost, or an error in or outside a render); then use the @@ -423,19 +497,29 @@ impl GpuRenderer { /// Renders a display list and reads it back. [`GpuError::NeedsFull`] means "draw this one /// on the CPU". pub fn render(&self, dl: &DisplayList, view: &View, output: Output) -> Result { + self.render_with(dl, view, output, self.binning()) + } + + /// [`GpuRenderer::render`], binned as `binning` says (tests and benchmarks). + pub fn render_with(&self, dl: &DisplayList, view: &View, output: Output, binning: Binning) -> Result { self.guard(|| { - let (job, stats, mut timings, cost) = self.prepare(dl, view)?; + let (job, stats, mut timings, cost) = self.prepare(dl, view, binning)?; let t = Instant::now(); let (premul8, pixmap) = self.run_readback(&job, view, output)?; timings.gpu = ms(t); - Ok(GpuFrame { width: view.width, height: view.height, premul8, pixmap, stats, timings, entries: cost.entries, pieces: cost.pieces }) + Ok(GpuFrame { width: view.width, height: view.height, premul8, pixmap, stats, timings, entries: cost.entries, pieces: cost.pieces, gpu_binned: job.binned.gpu.is_some() }) }) } /// Renders a display list into a new texture on this renderer's device (no readback). pub fn render_texture(&self, dl: &DisplayList, view: &View) -> Result { + self.render_texture_with(dl, view, self.binning()) + } + + /// [`GpuRenderer::render_texture`], binned as `binning` says (tests and benchmarks). + pub fn render_texture_with(&self, dl: &DisplayList, view: &View, binning: Binning) -> Result { self.guard(|| { - let (job, stats, mut timings, cost) = self.prepare(dl, view)?; + let (job, stats, mut timings, cost) = self.prepare(dl, view, binning)?; let t = Instant::now(); let (w, h) = (view.width, view.height); let max = self.limits.max_texture_dimension_2d; @@ -464,7 +548,7 @@ impl GpuRenderer { self.queue.submit([enc.finish()]); self.pop(scopes)?; timings.gpu = ms(t); - Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: cost.entries, pieces: cost.pieces }) + Ok(GpuTexture { texture, view: tex_view, width: w, height: h, stats, timings, entries: cost.entries, pieces: cost.pieces, gpu_binned: job.binned.gpu.is_some() }) }) } @@ -511,14 +595,14 @@ impl GpuRenderer { /// The oracle's preparation and the binning, for the scene and each filtered layer it shows /// (in parallel); checked against the limits and the device's. - fn prepare(&self, dl: &DisplayList, view: &View) -> Result<(Job, RenderStats, Timings, Cost), GpuError> { + fn prepare(&self, dl: &DisplayList, view: &View, binning: Binning) -> Result<(Job, RenderStats, Timings, Cost), GpuError> { let (w, h) = (view.width, view.height); if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { return Err(GpuError::TooLarge(format!("image {w}×{h} is outside the GPU stage's range"))); } let t0 = Instant::now(); let mut bin_ms = 0.0; - let (job, stats) = self.plan(dl, view, 0, &mut bin_ms)?; + let (job, stats) = self.plan(dl, view, 0, binning, &mut bin_ms)?; let total = ms(t0); let mut cost = Cost::default(); job.cost(&mut cost); @@ -533,10 +617,15 @@ impl GpuRenderer { } /// One scene: prepared and binned, then its shown layers planned the same way. - fn plan(&self, dl: &DisplayList, view: &View, depth: usize, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> { + fn plan(&self, dl: &DisplayList, view: &View, depth: usize, binning: Binning, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> { let (mut scene, stats) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?; let t = Instant::now(); - let binned = binning::bin(&scene, view.width, view.height).map_err(GpuError::NeedsFull)?; + let lim = match binning { + Binning::Cpu => None, + Binning::Auto => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: AUTO_MIN_EDGES }), + Binning::Gpu => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 }), + }; + let binned = binning::bin_with(&scene, view.width, view.height, lim.as_ref()).map_err(GpuError::NeedsFull)?; *bin_ms += ms(t); let shown: Vec<(u32, anicraft_render::FilterLayer)> = std::mem::take(&mut scene.layers).into_iter().zip(&binned.layer_at).filter_map(|(l, at)| Some(((*at)?, l))).collect(); // Free the prepared polygons on the pool, off this frame's path (as the oracle does). @@ -553,7 +642,7 @@ impl GpuRenderer { let shown = shown.into_iter(); let planned: Vec> = shown .map(|(at, l)| { - let (job, _) = self.plan(&l.list, &l.view, depth + 1, &mut 0.0)?; + let (job, _) = self.plan(&l.list, &l.view, depth + 1, binning, &mut 0.0)?; Ok(LayerJob { at, job: Box::new(job), view: l.view, ops: l.filters }) }) .collect(); @@ -561,11 +650,17 @@ impl GpuRenderer { Ok((Job { binned, layers }, stats)) } + /// The largest buffer the device binds. + fn binding_cap(&self) -> u64 { + self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size) + } + /// Every buffer a job binds fits what the device binds. fn check_sizes(&self, job: &Job) -> Result<(), GpuError> { - let cap = self.limits.max_storage_buffer_binding_size.min(self.limits.max_buffer_size); + let cap = self.binding_cap(); let b = &job.binned; - let sizes = [("tile lists", b.index.len() as u64 * 4), ("edges", b.geo.len() as u64 * 16), ("paints and layers", b.paints_len as u64 * 16)]; + let pieces = b.gpu.as_ref().map_or(b.geo.len() as u64, |p| u64::from(p.piece_cap)); + let sizes = [("tile lists", (u64::from(b.ops_at) + b.op_heads.len() as u64) * 4), ("edges", pieces * 16), ("paints and layers", b.paints_len as u64 * 16)]; for (what, n) in sizes { if n > cap { return Err(GpuError::TooLarge(format!("{what} need {} MB, more than this GPU binds ({} MB)", n >> 20, cap >> 20))); @@ -613,13 +708,34 @@ impl GpuRenderer { enc.copy_buffer_to_buffer(&img, 0, &pbuf, u64::from(l.at) * 16, 16 * n); } let views = self.images.lock().unwrap_or_else(PoisonError::into_inner).views(&self.device, &self.queue, self.limits.max_texture_dimension_2d, &b.images)?; - self.fine_pass(enc, b, &pbuf, &views, view, output, target); + let (ibuf, gbuf) = match &b.gpu { + Some(plan) => gpu_binning::record(&self.device, &self.bins, enc, plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?, + None => self.upload_lists(b)?, + }; + self.fine_pass(enc, b, &ibuf, &gbuf, &pbuf, &views, view, output, target); Ok(()) } + /// The CPU's tile lists and op headers, and its pieces, as buffers. + fn upload_lists(&self, b: &binning::Binned) -> Result<(wgpu::Buffer, wgpu::Buffer), GpuError> { + let len = (b.ops_at as usize + b.op_heads.len()).max(4); + let ibuf = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * len as u64, usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: true }); + { + let mut m = ibuf.slice(..).get_mapped_range_mut().map_err(|e| GpuError::Device(e.to_string()))?; + write_words(&mut m, 0, &b.index); + write_words(&mut m, b.ops_at as usize, &b.op_heads); + } + ibuf.unmap(); + // Bindings can't be empty: pad to one vec4. + let pad = [[0f32; 4]]; + let geo: &[[f32; 4]] = if b.geo.is_empty() { &pad } else { &b.geo }; + let gbuf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("geo"), contents: bytemuck::cast_slice(geo), usage: wgpu::BufferUsages::STORAGE }); + Ok((ibuf, gbuf)) + } + /// Uploads the binned scene and records the fine pass into `target`. #[allow(clippy::too_many_arguments)] - fn fine_pass(&self, enc: &mut wgpu::CommandEncoder, b: &binning::Binned, pbuf: &wgpu::Buffer, images: &[wgpu::TextureView], view: &View, output: Output, target: Target) { + fn fine_pass(&self, enc: &mut wgpu::CommandEncoder, b: &binning::Binned, ibuf: &wgpu::Buffer, gbuf: &wgpu::Buffer, pbuf: &wgpu::Buffer, images: &[wgpu::TextureView], view: &View, output: Output, target: Target) { let bg = view.background.map_or([0.0; 4], premultiply); let mut uniform = [0u32; 12]; uniform[..4].copy_from_slice(&[view.width, view.height, b.tiles_x, u32::from(output == Output::Float)]); @@ -627,15 +743,7 @@ impl GpuRenderer { for (u, f) in uniform[8..].iter_mut().zip(bg) { *u = f.to_bits(); } - let storage = |label: &str, bytes: &[u8]| { - // Bindings can't be empty: pad to one vec4. - let pad = [0u8; 16]; - let contents = if bytes.is_empty() { &pad[..] } else { bytes }; - self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage: wgpu::BufferUsages::STORAGE }) - }; let ubuf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("params"), contents: bytemuck::cast_slice(&uniform), usage: wgpu::BufferUsages::UNIFORM }); - let ibuf = storage("index", bytemuck::cast_slice(&b.index)); - let gbuf = storage("geo", bytemuck::cast_slice(&b.geo)); let mut entries = vec![ wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, wgpu::BindGroupEntry { binding: 1, resource: ibuf.as_entire_binding() }, @@ -695,6 +803,30 @@ impl GpuRenderer { }) } + /// The tile lists the GPU bins for `dl` (forced, however small), read back as a + /// [`binning::Binned`] like the CPU's: `None` when the scene isn't one the GPU bins. + #[cfg(test)] + pub(crate) fn gpu_lists(&self, dl: &DisplayList, view: &View) -> Result, GpuError> { + let (scene, _) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?; + let lim = gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 }; + let mut b = binning::bin_with(&scene, view.width, view.height, Some(&lim)).map_err(GpuError::NeedsFull)?; + let Some(plan) = b.gpu.take() else { return Ok(None) }; + let scopes = Scopes::push(&self.device); + let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-bin-test") }); + let (ibuf, gbuf) = gpu_binning::record(&self.device, &self.bins, &mut enc, &plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?; + let (isize, gsize) = (ibuf.size(), gbuf.size()); + let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: isize + gsize, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + enc.copy_buffer_to_buffer(&ibuf, 0, &read, 0, isize); + enc.copy_buffer_to_buffer(&gbuf, 0, &read, isize, gsize); + self.queue.submit([enc.finish()]); + let bytes = self.map(&read, scopes)?; + let words: Vec = bytes.as_chunks::<4>().0.iter().map(|w| u32::from_le_bytes(*w)).collect(); + let n = isize as usize / 4; + b.index = words.get(..b.ops_at as usize).unwrap_or(&[]).to_vec(); + b.geo = words.get(n..).unwrap_or(&[]).as_chunks::<4>().0.iter().map(|v| v.map(f32::from_bits)).collect(); + Ok(Some(b)) + } + /// Waits for `read`'s copy, pops the error scopes and returns its bytes. fn map(&self, read: &wgpu::Buffer, scopes: Scopes) -> Result, GpuError> { let (tx, rx) = std::sync::mpsc::channel(); @@ -766,6 +898,14 @@ pub(crate) fn describe(e: &wgpu::Error) -> String { } } +/// Writes `words` at word `at` of a mapped buffer, if they fit. +pub(crate) fn write_words(m: &mut wgpu::BufferViewMut, at: usize, words: &[u32]) { + let (a, b) = (4 * at, 4 * (at + words.len())); + if !words.is_empty() && b <= m.len() { + m.slice(a..b).copy_from_slice(bytemuck::cast_slice(words)); + } +} + fn ms(t: Instant) -> f32 { t.elapsed().as_secs_f32() * 1000.0 } diff --git a/crates/gpu/src/scan.wgsl b/crates/gpu/src/scan.wgsl new file mode 100644 index 00000000..82be5c04 --- /dev/null +++ b/crates/gpu/src/scan.wgsl @@ -0,0 +1,83 @@ +// AniCraft GPU stage: the prefix sum for the GPU binning (ADR 0048, bin.wgsl). +// +// An exclusive scan of `n` values in `values` (the binning's working buffer): each workgroup +// scans 1024 of them (four per invocation, then the invocations' totals in workgroup memory) +// and leaves its total; the totals are scanned the same way, level by level, and added back. +// The public work-efficient scan (Blelloch's "Prefix sums and their applications", 1990), in +// its simplest form. + +// `src`, `dst` and the workgroups' totals (`sums`) in `work`, and how many values. +struct ScanParams { + src: u32, + dst: u32, + sums: u32, + n: u32, +} + +@group(0) @binding(0) var sp: ScanParams; +@group(0) @binding(1) var values: array; + +var sh: array; + +fn load(i: u32) -> u32 { + if i < sp.n { + return values[sp.src + i]; + } + return 0u; +} + +fn store(i: u32, v: u32) { + if i < sp.n { + values[sp.dst + i] = v; + } +} + +// Each workgroup scans 1024 values (four per invocation), exclusive, and leaves its total. +@compute @workgroup_size(256) +fn scan_blocks(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) nw: vec3, @builtin(local_invocation_id) lid: vec3) { + let block = wg.y * nw.x + wg.x; + let base = block * 1024u + lid.x * 4u; + // Four values by name, not a loop over an array: FXC (Direct3D's compiler) must unroll + // loops that index local arrays. + let v0 = load(base); + let v1 = load(base + 1u); + let v2 = load(base + 2u); + let v3 = load(base + 3u); + let total = v0 + v1 + v2 + v3; + sh[lid.x] = total; + workgroupBarrier(); + for (var off = 1u; off < 256u; off <<= 1u) { + var t = 0u; + if lid.x >= off { + t = sh[lid.x - off]; + } + workgroupBarrier(); + sh[lid.x] += t; + workgroupBarrier(); + } + let acc = sh[lid.x] - total; + store(base, acc); + store(base + 1u, acc + v0); + store(base + 2u, acc + v0 + v1); + store(base + 3u, acc + v0 + v1 + v2); + // (A dispatch spread over x and y may have a few workgroups past the end.) + if lid.x == 255u && block * 1024u < sp.n { + values[sp.sums + block] = sh[255]; + } +} + +// Adds each workgroup's scanned total to its values. +@compute @workgroup_size(256) +fn scan_add(@builtin(workgroup_id) wg: vec3, @builtin(num_workgroups) nw: vec3, @builtin(local_invocation_id) lid: vec3) { + let block = wg.y * nw.x + wg.x; + if block * 1024u >= sp.n { + return; + } + let add = values[sp.sums + block]; + for (var i = 0u; i < 4u; i++) { + let at = block * 1024u + lid.x * 4u + i; + if at < sp.n { + values[sp.dst + at] += add; + } + } +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index adce571b..0bbb4730 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -294,9 +294,9 @@ fn emulate(b: &Binned, v: &View) -> Vec { } k => assert_eq!(k & bn::CTRL, 0, "unknown control entry {k:x}"), } - let hd = b.ops_at as usize + op * 4; - let mut cov = entry_cover(&b.geo[first..first + n], bd, b.index[hd + 1], lx, ly); - let flags = b.index[hd + 3]; + let hd = op * 4; + let mut cov = entry_cover(&b.geo[first..first + n], bd, b.op_heads[hd + 1], lx, ly); + let flags = b.op_heads[hd + 3]; if flags & bn::ART != 0 { let k = cov.clamp(0.0, 1.0); level = level + k - level * k; @@ -308,7 +308,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { if cov <= 1e-4 { continue; } - let s = match b.index[hd] { + let s = match b.op_heads[hd] { 0 => solid_of(b, op), kind => { let base = op * PAINT_VEC4S; @@ -318,7 +318,7 @@ fn emulate(b: &Binned, v: &View) -> Vec { let d = q - Vec2::new(nn[2], nn[3]); let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { d.length() * g[2] }; let i = (t.clamp(0.0, 1.0) * 255.0 + 0.5) as usize & 255; - b.paints[b.index[hd + 2] as usize + i] + b.paints[b.op_heads[hd + 2] as usize + i] } }; let sa = s[3] * cov; @@ -977,3 +977,97 @@ fn gpu_matches_the_oracle_on_the_filtered_sample() { } } + +// ----- binning on the GPU (ADR 0048) ---------------------------------------------------------- + +/// Scenes the GPU bins (no fill in a mask or a group): the analytic ones, the sample, stress +/// frames at awkward scales and offsets, and onion-skin style outlines over them. +fn gpu_binned_scenes() -> Vec<(String, DisplayList, View)> { + let plain = |dl: &DisplayList| dl.items.iter().all(|i| i.clip.is_none() && i.group.is_none()); + let mut out: Vec<(String, DisplayList, View)> = scenes().into_iter().filter(|(_, dl, _)| plain(dl)).map(|(n, dl, v)| (n.to_string(), dl, v)).collect(); + let demo = sample::demo(); + out.push(("sample".into(), anicraft_doc::evaluate(&demo, 13), View::stage(&demo, 0.37))); + let doc = sample::stress(20, 100, 48); + for (f, s, at) in [(0u32, 1.0f32, (0.0, 0.0)), (30, 0.5, (0.0, 0.0)), (7, 2.3, (-900.0, -700.0)), (41, 0.73, (-11.5, -3.25))] { + let dl = anicraft_doc::evaluate(&doc, f); + let v = View { transform: Affine::translate(at.0, at.1).mul(&Affine::scale(s, s)), width: 1920, height: 1080, background: Some(Rgba::WHITE) }; + out.push((format!("stress frame {f} at {s}"), dl, v)); + } + // Onion skin's outlines: the frames before and after as hairlines, under the playhead's. + let mut dl = DisplayList::default(); + for f in [25u32, 27, 33, 35] { + let mut part = anicraft_doc::evaluate(&doc, f); + for i in &mut part.items { + i.outline = Some(Rgba::hex(if f < 30 { 0x4f8dff } else { 0x4cd07d }).with_alpha(0.4)); + } + dl.append(part); + } + dl.append(anicraft_doc::evaluate(&doc, 30)); + out.push(("stress with outlined frames".into(), dl, View::stage(&doc, 0.8))); + out +} + +/// What an entry covers in each of its tile's 256 pixels. +fn entry_pixels(b: &Binned, e: usize) -> [f32; 256] { + let (op, first, n, bd) = (b.index[e] as usize, b.index[e + 1] as usize, b.index[e + 2] as usize, b.index[e + 3]); + let rule = b.op_heads[4 * op + 1]; + let pieces = b.geo.get(first..first + n).unwrap_or(&[]); + std::array::from_fn(|i| entry_cover(pieces, bd, rule, i % 16, i / 16)) +} + +#[test] +fn gpu_binning_produces_the_cpus_tile_lists() { + let Some(g) = gpu() else { return }; + for (name, dl, v) in gpu_binned_scenes() { + let Some(gb) = g.gpu_lists(&dl, &v).unwrap() else { panic!("{name}: the GPU should bin this") }; + let (scene, _) = prepare_scene(&dl, &v).unwrap(); + let cb = binning::bin(&scene, v.width, v.height).unwrap(); + assert_eq!((gb.tiles_x, gb.tiles_y, &gb.op_heads), (cb.tiles_x, cb.tiles_y, &cb.op_heads), "{name}"); + let (mut entries, mut pieces) = (0usize, 0usize); + for t in 0..(cb.tiles_x * cb.tiles_y) as usize { + let list = |b: &Binned| -> Vec<(u32, [f32; 256])> { + let (s, n) = (b.index[2 * t] as usize, b.index[2 * t + 1] as usize); + (s..s + n).map(|i| b.entries_at as usize + 4 * i).map(|e| (b.index[e], entry_pixels(b, e))).collect() + }; + let (a, c) = (list(&gb), list(&cb)); + let ops = |l: &[(u32, [f32; 256])]| l.iter().map(|x| x.0).collect::>(); + assert_eq!(ops(&a), ops(&c), "{name}: tile {t}'s fills"); + for ((op, pa), (_, pc)) in a.iter().zip(&c) { + let worst = pa.iter().zip(pc).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(worst < 1e-3, "{name}: tile {t}, op {op}: coverage off by {worst}"); + } + entries += a.len(); + let (s, n) = (gb.index[2 * t] as usize, gb.index[2 * t + 1] as usize); + pieces += (s..s + n).map(|i| gb.index[gb.entries_at as usize + 4 * i + 2] as usize).sum::(); + } + assert_eq!(entries, cb.entries, "{name}"); + assert!(pieces <= gb.pieces && entries <= gb.entries, "{name}: within the room made for them"); + // And the fine pass's arithmetic over the GPU's lists draws the oracle's picture. + let (oracle, _) = render(&dl, &v).unwrap(); + let eg = emulate(&gb, &v); + let (mean, max) = f32_diff(&eg, &oracle.data); + assert!(mean < 1e-4 && max < 4e-3, "{name}: mean {mean:e}, max {max:e}"); + } +} + +#[test] +fn gpu_binned_frames_match_the_oracle() { + let Some(g) = gpu() else { return }; + for (name, dl, v) in gpu_binned_scenes() { + let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap(); + assert!(f.gpu_binned, "{name}"); + let (oracle, _) = render(&dl, &v).unwrap(); + let d = compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap(); + assert!(d.mean <= MEAN_TARGET / 16.0 && d.max <= 2, "{name}: {d:?}"); + let t = g.render_texture_with(&dl, &v, Binning::Gpu).unwrap(); + assert!(t.gpu_binned && g.read_texture(&t).unwrap() == f.premul8, "{name}: the texture holds the read-back bytes"); + } + // Masks and groups stay on the CPU's binning, and still draw right. + for (name, dl, v) in composited_scenes() { + let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap(); + let uses = |dl: &DisplayList| dl.items.iter().any(|i| i.clip.is_some() || i.group.is_some()); + assert_eq!(f.gpu_binned, !uses(&dl), "{name}: binned on the GPU {}", f.gpu_binned); + let (oracle, _) = render(&dl, &v).unwrap(); + assert!(compare_premul8(&f.premul8, &oracle.to_premul_rgba8()).unwrap().max <= 2, "{name}"); + } +} From f375849413376bb9282c6bb47b76565069767285 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:14:10 -0700 Subject: [PATCH 06/19] perf(gpu): upload only the tile headers when the GPU bins, bin from 32,768 edges, cheap hairline rejects (M3) Mapping the GPU-binned index at creation zeroed and copied its whole room for entries on the CPU; the headers and op headers now go through the queue and the rest starts zeroed on the GPU. 50k shapes at 4K, direct: 50 -> 24 ms (CPU-binned: 121 ms). Auto bins on the GPU from 32,768 edges: forcing it on every 512 px stage tile made the 1,000-shape 4K stage 1.9x slower and the 10k-shape one 1.3x (per-tile pass set-up); with the threshold the tiled stage never loses (10k at 4K 10.5 -> 10.0 ms, 50k 63.6 -> 38.4 ms). A hairline segment whose box is out of reach of a pixel is skipped before the distance (same coverage). gpu_bench compares CPU and Auto binning and checks budgets (--check). --- crates/gpu/examples/gpu_bench.rs | 156 ++++++++++++++++++------------- crates/gpu/src/fine.wgsl | 10 +- crates/gpu/src/gpu_binning.rs | 17 ++-- crates/gpu/src/lib.rs | 6 +- 4 files changed, 114 insertions(+), 75 deletions(-) diff --git a/crates/gpu/examples/gpu_bench.rs b/crates/gpu/examples/gpu_bench.rs index a8df5239..14c54690 100644 --- a/crates/gpu/examples/gpu_bench.rs +++ b/crates/gpu/examples/gpu_bench.rs @@ -1,19 +1,21 @@ -//! GPU stage timings and parity against the CPU oracle (ADR 0019, ADR 0029, ADR 0032; numbers +//! GPU stage timings and parity against the CPU oracle (ADR 0019, 0029, 0032, 0048; numbers //! in docs/performance.md). //! //! ```sh //! cargo run --release -p anicraft-gpu --example gpu_bench //! cargo run --release -p anicraft-gpu --example gpu_bench -- --layers 50 --shapes 200 +//! cargo run --release -p anicraft-gpu --example gpu_bench -- --only onion +//! cargo run --release -p anicraft-gpu --example gpu_bench -- --check # fails past a budget //! ``` -//! Prints the adapter, then for each scene and size: CPU ms; the first slice's read-back path -//! (prepare + bin + upload, compute, copy back); the direct path the window uses (into a -//! texture, no readback): what the calling thread spends, and until the GPU has finished; the -//! stage's way (512 px tiles drawn in parallel, as the render service does, until finished); -//! the work the fine pass did; and how far the GPU's picture is from the oracle's. +//! Prints the adapter, then for each scene and size: CPU ms; then, with the tiles binned on +//! the CPU and then on the GPU (ADR 0048), the direct path the window uses (into a texture, no +//! readback): what the calling thread spends, and until the GPU has finished; the stage's way +//! (512 px tiles drawn in parallel, as the render service does, until finished); and how far +//! the GPU-binned picture is from the oracle's. use anicraft_doc::{Bitmap, BitmapId, ColorEffect, DisplayList, Document, Element, ElementId, ElementKind, Filter, FilterSide, Keyframe, Layer, LayerId, LayerKind, Paint, Pixels, Rgba, Shape, evaluate, sample}; use anicraft_geom::{FillRule, Path}; -use anicraft_gpu::{GpuRenderer, Output, compare_premul8}; +use anicraft_gpu::{Binning, GpuRenderer, compare_premul8}; use anicraft_geom::Affine; use anicraft_render::{View, render}; use rayon::prelude::*; @@ -190,7 +192,21 @@ fn onion_list(doc: &Document, frame: u32, mode: Onion) -> DisplayList { dl } +/// Timing budgets for the stage on the GPU (docs/performance.md › Budgets), checked with +/// `--check` on a known machine: `(scene, width, what, limit in ms)`, `what` being the Auto +/// column's `direct` or `tiled` (the stage's way). +const BUDGETS: &[(&str, u32, &str, f64)] = &[ + ("1,000 shapes", 3840, "tiled", 16.7), + ("stress 50×200", 3840, "tiled", 16.7), + ("50,000 shapes", 1920, "tiled", 33.3), + ("50,000 shapes", 3840, "direct", 33.3), +]; +/// Outline mode against tinted onion skin (ADR 0048: no slower), at 1080p in stage tiles. +const OUTLINE_RATIO: f64 = 1.25; + fn main() { + let check = std::env::args().any(|a| a == "--check"); + let mut measured: Vec<(String, u32, &str, f64)> = Vec::new(); let gpu = match GpuRenderer::new() { Ok(g) => g, Err(e) => { @@ -217,9 +233,12 @@ fn main() { ("onion ±5 tinted".into(), onion_doc.clone(), Onion::Tinted), ("onion ±5 outlines".into(), onion_doc, Onion::Outlines), ]; + println!("Per scene and size: the CPU oracle, then the GPU stage with the tiles binned on the CPU, then as Binning::Auto bins them (on the GPU with --forced):"); + println!("direct = the calling thread's time with render_texture (prepare + bin + upload/submit), waited = until the GPU has finished,"); + println!("tiled = 512 px stage tiles in parallel until finished. Parity: the GPU-binned picture against the oracle (mean / max / px)."); println!( - "{:<20} {:>10} {:>8} {:>9} {:>9} {:>9} {:>7} {:>22} {:>8} {:>8} parity (mean / max / differing px)", - "scene", "size", "CPU ms", "readback", "direct", "direct+", "tiled", "prepare + bin + submit", "entries", "pieces" + "{:<20} {:>10} {:>7} | {:>7} {:>7} {:>7} {:>19} | {:>7} {:>7} {:>7} {:>19} | parity", + "scene", "size", "CPU", "direct", "waited", "tiled", "prep + bin + gpu", "direct", "waited", "tiled", "prep + bin + gpu" ); for (name, doc, onion) in scenes.iter().filter(|(n, ..)| only.as_ref().is_none_or(|o| n.contains(o.as_str()))) { for scale in [1.0f32, 2.0] { @@ -227,77 +246,88 @@ fn main() { let frames = doc.frame_count().max(1); let evaluate = |doc: &Document, f: u32| onion_list(doc, f, *onion); let dl0 = evaluate(doc, if *onion == Onion::Off { 0 } else { 30 }); - // Warm-up (pipeline caches, allocations). - let _ = gpu.render(&dl0, &v, Output::Premul8); - let _ = gpu.render_texture(&dl0, &v); - let _ = gpu.wait_idle(); - let _ = render(&dl0, &v); let lists: Vec<_> = (0..runs).map(|i| evaluate(doc, (i * 20) % frames)).collect(); let per = |t: Instant| t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs); + let _ = render(&dl0, &v); let t = Instant::now(); for dl in &lists { let _ = render(dl, &v); } let cpu_ms = per(t); - let t = Instant::now(); - for dl in &lists { - let _ = gpu.render(dl, &v, Output::Premul8); - } - let readback_ms = per(t); - // Direct: what the calling thread spends (the stage's cost per tile), then each frame - // waited for to the end (the latency until the window can show it). - let mut sum = [0.0f32; 3]; - let mut work = (0, 0); - let t = Instant::now(); - let mut keep = Vec::with_capacity(lists.len()); - for dl in &lists { - if let Ok(f) = gpu.render_texture(dl, &v) { - sum[0] += f.timings.prepare; - sum[1] += f.timings.bin; - sum[2] += f.timings.gpu; - work = (f.entries, f.pieces); - keep.push(f); - } - } - let direct_ms = per(t); - let _ = gpu.wait_idle(); - drop(keep); - let t = Instant::now(); - for dl in &lists { - let _ = gpu.render_texture(dl, &v); - let _ = gpu.wait_idle(); - } - let done_ms = per(t); - // The stage: 512 px tiles of the same frame, in parallel, then waited for. + // The stage's tiles: 512 px of the same frame, drawn in parallel. let tiles: Vec = (0..v.height.div_ceil(512)) .flat_map(|ty| (0..v.width.div_ceil(512)).map(move |tx| (tx, ty))) .map(|(tx, ty)| View { transform: Affine::translate(-((tx * 512) as f32), -((ty * 512) as f32)).mul(&v.transform), width: 512.min(v.width - tx * 512), height: 512.min(v.height - ty * 512), background: v.background }) .collect(); - let t = Instant::now(); - for dl in &lists { - let _: Vec<_> = tiles.par_iter().map(|tv| gpu.render_texture(dl, tv).ok()).collect(); + let mut cols = Vec::new(); + let mut binned_on_gpu = false; + let second = if std::env::args().any(|a| a == "--forced") { Binning::Gpu } else { Binning::Auto }; + for binning in [Binning::Cpu, second] { + // Warm-up (pipeline caches, allocations). + let _ = gpu.render_texture_with(&dl0, &v, binning); let _ = gpu.wait_idle(); + let mut sum = [0.0f32; 3]; + let t = Instant::now(); + let mut keep = Vec::with_capacity(lists.len()); + for dl in &lists { + if let Ok(f) = gpu.render_texture_with(dl, &v, binning) { + sum[0] += f.timings.prepare; + sum[1] += f.timings.bin; + sum[2] += f.timings.gpu; + binned_on_gpu |= f.gpu_binned; + keep.push(f); + } + } + let direct = per(t); + let _ = gpu.wait_idle(); + drop(keep); + let t = Instant::now(); + for dl in &lists { + let _ = gpu.render_texture_with(dl, &v, binning); + let _ = gpu.wait_idle(); + } + let waited = per(t); + let t = Instant::now(); + for dl in &lists { + let _: Vec<_> = tiles.par_iter().map(|tv| gpu.render_texture_with(dl, tv, binning).ok()).collect(); + let _ = gpu.wait_idle(); + } + let tiled = per(t); + let n = runs as f32; + if binning == Binning::Auto { + measured.push((name.clone(), v.width, "direct", direct)); + measured.push((name.clone(), v.width, "tiled", tiled)); + } + cols.push(format!("{direct:>7.2} {waited:>7.2} {tiled:>7.2} {:>19}", format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n))); } - let tiled_ms = per(t); - let n = runs as f32; - let parity = match (gpu.render_texture(&dl0, &v).and_then(|t| gpu.read_texture(&t)), render(&dl0, &v)) { + let parity = match (gpu.render_texture_with(&dl0, &v, Binning::Gpu).and_then(|t| gpu.read_texture(&t)), render(&dl0, &v)) { (Ok(g), Ok((c, _))) => compare_premul8(&g, &c.to_premul_rgba8()).map_or("size mismatch".into(), |d| format!("{:.4} / {} / {}", d.mean, d.max, d.differing)), (Err(e), _) => format!("GPU: {e}"), (_, Err(e)) => format!("CPU: {e}"), }; - println!( - "{:<20} {:>10} {:>8.2} {:>9.2} {:>9.2} {:>9.2} {:>7.2} {:>22} {:>8} {:>8} {parity}", - name, - format!("{}×{}", v.width, v.height), - cpu_ms, - readback_ms, - direct_ms, - done_ms, - tiled_ms, - format!("{:.2} + {:.2} + {:.2}", sum[0] / n, sum[1] / n, sum[2] / n), - work.0, - work.1 - ); + let note = if binned_on_gpu { "" } else { " (binned on the CPU: masks, groups or few edges)" }; + println!("{:<20} {:>10} {:>7.2} | {} | {} | {parity}{note}", name, format!("{}×{}", v.width, v.height), cpu_ms, cols[0], cols[1]); } } + if !check { + return; + } + let get = |scene: &str, w: u32, what: &str| measured.iter().find(|m| m.0 == scene && m.1 == w && m.2 == what).map(|m| m.3); + let mut missed = 0; + println!(); + println!("budgets (the means above; run on a quiet machine)"); + for &(scene, w, what, limit) in BUDGETS { + let got = get(scene, w, what); + let ok = got.is_some_and(|g| g <= limit); + missed += usize::from(!ok); + println!(" {} {scene} at {w} px, {what}: {} (budget {limit} ms)", if ok { "ok " } else { "MISS" }, got.map_or("not measured".into(), |g| format!("{g:.2} ms"))); + } + let ratio = get("onion ±5 outlines", 1920, "tiled").zip(get("onion ±5 tinted", 1920, "tiled")).map(|(o, t)| o / t); + let ok = ratio.is_some_and(|r| r <= OUTLINE_RATIO); + missed += usize::from(!ok); + println!(" {} onion outlines / tinted at 1920 px, tiled: {} (budget {OUTLINE_RATIO})", if ok { "ok " } else { "MISS" }, ratio.map_or("not measured".into(), |r| format!("{r:.2}"))); + if missed > 0 { + println!("{missed} budget(s) missed"); + std::process::exit(1); + } } diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 9a81fc4c..c95ed41e 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -383,7 +383,15 @@ fn pixel(wg: vec3, lid: vec3) -> vec4 { var d = 2.0; let pc = vec2(px + 0.5, py + 0.5); for (var k = 0u; k < pieces; k++) { - d = min(d, seg_dist(pc, geo[first + k])); + let sg = geo[first + k]; + // Out of reach of the segment's box: at least 1 away, so it can't be nearest + // within reach (the coverage comes out the same, without the division). + let lo = min(sg.xy, sg.zw) - vec2(1.0); + let hi = max(sg.xy, sg.zw) + vec2(1.0); + if any(pc < lo) || any(pc > hi) { + continue; + } + d = min(d, seg_dist(pc, sg)); } cov = clamp(1.0 - d, 0.0, 1.0); } else { diff --git a/crates/gpu/src/gpu_binning.rs b/crates/gpu/src/gpu_binning.rs index 7e9390ee..106488b7 100644 --- a/crates/gpu/src/gpu_binning.rs +++ b/crates/gpu/src/gpu_binning.rs @@ -321,18 +321,19 @@ fn groups(n: u32, width: u32) -> (u32, u32) { } /// The fine pass's index and pieces, binned on the GPU into `enc` from `plan`: the index with -/// `heads` (the tile headers) at 0 and `op_heads` at `ops_at`. +/// the tile headers at 0 and `op_heads` at `ops_at`. Only those are uploaded (through `queue`, +/// ahead of `enc`'s submission): the entries' room starts zeroed on the GPU. #[allow(clippy::too_many_arguments)] -pub(crate) fn record(device: &wgpu::Device, pipes: &Pipelines, enc: &mut wgpu::CommandEncoder, plan: &Plan, tiles_x: u32, tiles_y: u32, entries_at: u32, ops_at: u32, op_heads: &[u32]) -> Result<(wgpu::Buffer, wgpu::Buffer), String> { +pub(crate) fn record(device: &wgpu::Device, queue: &wgpu::Queue, pipes: &Pipelines, enc: &mut wgpu::CommandEncoder, plan: &Plan, tiles_x: u32, tiles_y: u32, entries_at: u32, ops_at: u32, op_heads: &[u32]) -> Result<(wgpu::Buffer, wgpu::Buffer), String> { use wgpu::util::DeviceExt; let index_len = (ops_at as usize + op_heads.len()).max(4); - let index = device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * index_len as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: true }); - { - let mut m = index.slice(..).get_mapped_range_mut().map_err(|e| e.to_string())?; - crate::write_words(&mut m, 0, &plan.headers); - crate::write_words(&mut m, ops_at as usize, op_heads); + let index = device.create_buffer(&wgpu::BufferDescriptor { label: Some("index"), size: 4 * index_len as u64, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); + if !plan.headers.is_empty() && plan.headers.len() <= index_len { + queue.write_buffer(&index, 0, bytemuck::cast_slice(&plan.headers)); + } + if !op_heads.is_empty() && ops_at as usize + op_heads.len() <= index_len { + queue.write_buffer(&index, 4 * u64::from(ops_at), bytemuck::cast_slice(op_heads)); } - index.unmap(); let geo = device.create_buffer(&wgpu::BufferDescriptor { label: Some("geo"), size: 16 * u64::from(plan.piece_cap.max(1)), usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }); if plan.op_rows == 0 { return Ok((index, geo)); diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 1d1921ad..c1b9dd15 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -120,7 +120,7 @@ impl Binning { /// Fewer edges than this are binned on the CPU in [`Binning::Auto`]: below it the CPU bins a /// frame in less time than the GPU's passes take to set up (measured, docs/performance.md). -pub const AUTO_MIN_EDGES: u64 = 4096; +pub const AUTO_MIN_EDGES: u64 = 32_768; /// A frame rendered into a texture on the renderer's device: premultiplied RGBA8 /// (`Rgba8Unorm`, the bytes [`Pixmap::to_premul_rgba8`] gives), sampleable, ready for the window @@ -709,7 +709,7 @@ impl GpuRenderer { } let views = self.images.lock().unwrap_or_else(PoisonError::into_inner).views(&self.device, &self.queue, self.limits.max_texture_dimension_2d, &b.images)?; let (ibuf, gbuf) = match &b.gpu { - Some(plan) => gpu_binning::record(&self.device, &self.bins, enc, plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?, + Some(plan) => gpu_binning::record(&self.device, &self.queue, &self.bins, enc, plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?, None => self.upload_lists(b)?, }; self.fine_pass(enc, b, &ibuf, &gbuf, &pbuf, &views, view, output, target); @@ -813,7 +813,7 @@ impl GpuRenderer { let Some(plan) = b.gpu.take() else { return Ok(None) }; let scopes = Scopes::push(&self.device); let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("anicraft-bin-test") }); - let (ibuf, gbuf) = gpu_binning::record(&self.device, &self.bins, &mut enc, &plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?; + let (ibuf, gbuf) = gpu_binning::record(&self.device, &self.queue, &self.bins, &mut enc, &plan, b.tiles_x, b.tiles_y, b.entries_at, b.ops_at, &b.op_heads).map_err(GpuError::Device)?; let (isize, gsize) = (ibuf.size(), gbuf.size()); let read = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: isize + gsize, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }); enc.copy_buffer_to_buffer(&ibuf, 0, &read, 0, isize); From ba34521d0cfb9f7b696790179e2571af344a4317 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:19:22 -0700 Subject: [PATCH 07/19] perf(gpu): hairlines reach only the tiles they can touch, and bound in O(1) (M3) A hairline segment went into every tile within 2 px of it; 1.25 px is enough (a pixel centre within its reach is within 1 px of a point of it, plus rounding). The room for its pieces is its padded box's tiles, row by row only for long segments. Onion outlines against tinted, GPU stage, best of three: 1080p tiles 10.2 vs 9.5 ms, 4K tiles 15.1 vs 15.4 ms, one texture 7.2 vs 7.1 ms. --- crates/gpu/src/bin.wgsl | 4 ++-- crates/gpu/src/binning.rs | 7 ++++--- crates/gpu/src/gpu_binning.rs | 24 ++++++++++++++++++++---- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/gpu/src/bin.wgsl b/crates/gpu/src/bin.wgsl index e062c6b0..817e92ee 100644 --- a/crates/gpu/src/bin.wgsl +++ b/crates/gpu/src/bin.wgsl @@ -43,8 +43,8 @@ struct Params { const T: f32 = 16.0; // gpu_binning.rs › HAIRLINE_BIT: the op is a hairline. const HAIRLINE_BIT: u32 = 0x80000000u; -// Margins of a hairline's reach (binning.rs › hairline_tiles). -const M: f32 = 2.0; +// How far around a hairline segment its tiles are taken (binning.rs › HAIRLINE_MARGIN). +const M: f32 = 1.25; // What to do with a piece. const COUNT: u32 = 0u; diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index 809f68c4..14cda964 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -51,9 +51,10 @@ const T: f32 = TILE as f32; pub const NONE: u32 = u32::MAX; /// Fill rule code of a hairline in an op header (`0` non-zero, `1` even-odd). pub const HAIRLINE: u32 = 2; -/// How far from a hairline segment its tiles reach: pixel centres within its reach lie within -/// this of it (`bin.wgsl` › `M`). -pub(crate) const HAIRLINE_MARGIN: f32 = anicraft_render::hairline::REACH + 1.0; +/// How far around a hairline segment its tiles are taken (`bin.wgsl` › `M`): a pixel centre +/// within its reach is within `REACH` of a point of it, so the tile holding that centre holds a +/// point within `REACH` of the segment's box; a quarter pixel more absorbs rounding. +pub(crate) const HAIRLINE_MARGIN: f32 = anicraft_render::hairline::REACH + 0.25; /// `vec4`s of paint data per fill. pub const PAINT_VEC4S: usize = 4; /// Gradient table entries (the oracle's LUT size). diff --git a/crates/gpu/src/gpu_binning.rs b/crates/gpu/src/gpu_binning.rs index 106488b7..31cc3dcb 100644 --- a/crates/gpu/src/gpu_binning.rs +++ b/crates/gpu/src/gpu_binning.rs @@ -75,10 +75,7 @@ fn info(f: &Fill, tiles_x: u32, tiles_y: u32) -> Info { for poly in &f.polys { if f.hairline { let mut seg = |a, b| { - // With a pixel more reach than the binning's, whatever the GPU's rounding. - let mut n = 0u64; - hairline_tiles(a, b, &r, HAIRLINE_MARGIN + 1.0, |_, _| n += 1); - pieces += n; + pieces += hairline_pieces(a, b, &r); edges += 1; }; match poly.as_slice() { @@ -103,6 +100,25 @@ fn info(f: &Fill, tiles_x: u32, tiles_y: u32) -> Info { Info { range: Some(r), polys: f.polys.len() as u32, points, edges, pieces } } +/// At most how many tiles a hairline segment reaches (`binning.rs` › `hairline_tiles`), with a +/// pixel more reach than the binning's, whatever the GPU's rounding: the tiles of its padded +/// box (most segments are short), or row by row for a long one, where the box would be loose. +fn hairline_pieces(a: anicraft_geom::Vec2, b: anicraft_geom::Vec2, r: &Range) -> u64 { + if !(a.is_finite() && b.is_finite()) { + return 0; + } + let (t, m) = (TILE as f32, HAIRLINE_MARGIN + 1.0); + let span = |lo: f32, hi: f32, base: f32, n: i32| (((hi + m - base) / t).floor().min((n - 1) as f32) - ((lo - m - base) / t).floor().max(0.0) + 1.0).max(0.0); + let rows = span(a.y.min(b.y), a.y.max(b.y), r.ylo, r.nrows); + let cols = span(a.x.min(b.x), a.x.max(b.x), r.xlo, r.ncols); + if rows * cols <= 16.0 { + return (rows * cols) as u64; + } + let mut n = 0u64; + hairline_tiles(a, b, r, m, |_, _| n += 1); + n +} + /// At most how many pieces edge `a → b` gives (`binning.rs` › `split_edge` and `steps`): one /// per tile row it spans, one more per column boundary it crosses, a left-edge step per column /// boundary it passes, and one for where it meets the next edge; with slack for rounding. From 750c90edeccadbde8048fc8042393f67a09aebf7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:23:00 -0700 Subject: [PATCH 08/19] fix(gpu): a device whose GPU binning fails its self-test bins on the CPU; Auto bins on the GPU on Vulkan only (M3) The start-up self-test checks the GPU binning apart: if it comes back wrong only the binning stays on the CPU (gpu_binning_off says why), instead of the whole GPU stage switching off; the tests require it to work wherever the GPU stage runs (lavapipe in CI). On Direct3D 12 the binning passes cost more per stage tile than the CPU binning (onion +-5 at 1080p in tiles: 9.7 -> 14.4 ms, measured twice), so Auto keeps the CPU's there and on backends not yet measured; ANICRAFT_GPU_BINNING=gpu still forces it. --- crates/gpu/src/lib.rs | 51 ++++++++++++++++++++++++++++++----------- crates/gpu/src/tests.rs | 2 ++ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index c1b9dd15..0bbec69a 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -82,8 +82,9 @@ pub struct GpuFrame { /// Where a frame's edges are sorted into tiles (ADR 0048). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Binning { - /// On the GPU when the scene can take it (no fill inside a mask or a group, for now) and - /// has enough edges to be worth the passes ([`AUTO_MIN_EDGES`]); otherwise on the CPU. + /// On the GPU when the scene can take it (no fill inside a mask or a group, for now), has + /// enough edges to be worth the passes ([`AUTO_MIN_EDGES`]) and the device runs Vulkan + /// (where it was measured to win); otherwise on the CPU. Auto, /// Always on the CPU (the reference). Cpu, @@ -185,6 +186,13 @@ pub struct GpuRenderer { bins: gpu_binning::Pipelines, /// [`Binning`], as its code. binning: AtomicU8, + /// Why the GPU doesn't bin on this device (its self-test came back wrong); then every + /// frame bins on the CPU, and the rest of the GPU stage still runs. + no_gpu_binning: Mutex>, + /// Whether [`Binning::Auto`] bins on the GPU on this backend: on Vulkan, where it was + /// measured to win in the stage's tiles. On Direct3D 12 the passes cost more per stage tile + /// than the CPU's binning (ADR 0048), and other backends aren't measured yet. + auto_bins: bool, /// Bound where a texture slot or a buffer is unused. blank: wgpu::TextureView, /// Placeholders for a filter pass's coverage (written) and ramp (read): one buffer can't be @@ -301,7 +309,7 @@ impl GpuRenderer { } let limits = device.limits(); check(adapter, &limits, &name)?; - Self::build(device, queue, limits, name, true, Arc::new(Mutex::new(None))) + Self::build(device, queue, limits, name, info.backend, true, Arc::new(Mutex::new(None))) })) .unwrap_or_else(|_| Err(GpuError::Unavailable("the GPU driver failed while starting".into()))) } @@ -339,10 +347,10 @@ impl GpuRenderer { g.get_or_insert_with(|| format!("device lost: {msg}")); }); } - Self::build(device, queue, want, name, false, broken) + Self::build(device, queue, want, name, info.backend, false, broken) } - fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, shared: bool, broken: Arc>>) -> Result { + fn build(device: wgpu::Device, queue: wgpu::Queue, limits: wgpu::Limits, name: String, backend: wgpu::Backend, shared: bool, broken: Arc>>) -> Result { let scopes = Scopes::push(&device); let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("anicraft-fine"), source: wgpu::ShaderSource::Wgsl(include_str!("fine.wgsl").into()) }); let entry = |binding: u32, ty: wgpu::BindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }; @@ -398,6 +406,8 @@ impl GpuRenderer { filters, bins, binning: AtomicU8::new(Binning::from_env().code()), + no_gpu_binning: Mutex::new(None), + auto_bins: backend == wgpu::Backend::Vulkan, blank, blank_coverage, blank_ramp, @@ -457,17 +467,29 @@ impl GpuRenderer { let off = d.map_or("a wrong size".to_string(), |d| format!("{} of {} pixels off, by up to {}/255{at}", d.differing, d.pixels, d.max)); Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong {how} ({off})", self.adapter))) }; - check("read back", &self.render(&dl, &view, Output::Premul8)?.premul8)?; - let t = self.render_texture(&dl, &view)?; + check("read back", &self.render_with(&dl, &view, Output::Premul8, Binning::Cpu)?.premul8)?; + let t = self.render_texture_with(&dl, &view, Binning::Cpu)?; check("through a texture", &self.read_texture(&t)?)?; - // And binned on the GPU (the plain fills; the bitmap and the symbol stay on the CPU's). + // Binned on the GPU (the plain fills; the bitmap and the symbol bin on the CPU): if that + // comes back wrong, only the binning stays on the CPU here. let plain = DisplayList { items: dl.items.iter().take(3).cloned().collect(), ..Default::default() }; let (want, _) = anicraft_render::render(&plain, &view).map_err(|e| GpuError::Unavailable(e.to_string()))?; - let got = self.render_with(&plain, &view, Output::Premul8, Binning::Gpu)?; - match compare_premul8(&got.premul8, &want.to_premul_rgba8()) { - Some(d) if got.gpu_binned && d.max <= 2 && d.mean <= 0.1 => Ok(()), - d => Err(GpuError::Unavailable(format!("{}: the self-test render came back wrong binned on the GPU ({d:?})", self.adapter))), - } + let why = match self.render_with(&plain, &view, Output::Premul8, Binning::Gpu) { + Ok(got) => match compare_premul8(&got.premul8, &want.to_premul_rgba8()) { + Some(d) if got.gpu_binned && d.max <= 2 && d.mean <= 0.1 => None, + Some(d) if got.gpu_binned => Some(format!("{} of {} pixels off, by up to {}/255", d.differing, d.pixels, d.max)), + _ => Some("it wasn't binned on the GPU".to_string()), + }, + Err(GpuError::Device(e)) => return Err(GpuError::Unavailable(format!("{}: the GPU binning failed: {e}", self.adapter))), + Err(e) => Some(e.to_string()), + }; + *self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner) = why.map(|w| format!("{}: the self-test came back wrong binned on the GPU ({w}); binning on the CPU", self.adapter)); + Ok(()) + } + + /// Why the GPU doesn't bin on this device, if it doesn't (for Preferences and reports). + pub fn gpu_binning_off(&self) -> Option { + self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner).clone() } /// Where frames' edges are sorted into tiles from now on. @@ -620,8 +642,11 @@ impl GpuRenderer { fn plan(&self, dl: &DisplayList, view: &View, depth: usize, binning: Binning, bin_ms: &mut f32) -> Result<(Job, RenderStats), GpuError> { let (mut scene, stats) = prepare_scene(dl, view).map_err(GpuError::NeedsFull)?; let t = Instant::now(); + let off = self.no_gpu_binning.lock().unwrap_or_else(PoisonError::into_inner).is_some(); let lim = match binning { + _ if off => None, Binning::Cpu => None, + Binning::Auto if !self.auto_bins => None, Binning::Auto => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: AUTO_MIN_EDGES }), Binning::Gpu => Some(gpu_binning::Limits { binding: self.binding_cap(), min_edges: 0 }), }; diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 0bbb4730..1f11e14e 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -1053,6 +1053,8 @@ fn gpu_binning_produces_the_cpus_tile_lists() { #[test] fn gpu_binned_frames_match_the_oracle() { let Some(g) = gpu() else { return }; + // Where the GPU stage runs (lavapipe in CI included), its binning must too. + assert_eq!(g.gpu_binning_off(), None); for (name, dl, v) in gpu_binned_scenes() { let f = g.render_with(&dl, &v, Output::Premul8, Binning::Gpu).unwrap(); assert!(f.gpu_binned, "{name}"); From 340512ef4fe387a3317d31f6ab43a0df6c5492e7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:23:52 -0700 Subject: [PATCH 09/19] docs: ADR 0048 GPU binning and hairlines, performance, roadmap, changelog, attribution (M3) --- ATTRIBUTION.md | 4 +- CHANGELOG.md | 17 ++ docs/adr/0048-gpu-binning-and-hairlines.md | 179 +++++++++++++++++++++ docs/adr/README.md | 1 - docs/architecture.md | 17 +- docs/performance.md | 60 ++++++- docs/roadmap.md | 6 +- 7 files changed, 270 insertions(+), 14 deletions(-) create mode 100644 docs/adr/0048-gpu-binning-and-hairlines.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 0ee9d2b8..241beff1 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -78,7 +78,9 @@ OR Apache-2.0) is noted in the table. | Technique | Where | Reference | Notes | |---|---|---|---| | Signed-area coverage accumulation rasterizer | `crates/render/src/raster.rs` | Raph Levien, *font-rs* (2016), , Apache-2.0; also stb_truetype v2 (public domain) | Our implementation follows the published accumulate-and-prefix-sum approach. Credited here; Apache-2.0 includes a patent licence. | -| Tile binning with per-row backdrops; per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019). | +| Tile binning with integer backdrops and left-edge steps ("y-edges"); per-pixel exact area coverage on the GPU | `crates/gpu/src/binning.rs`, `crates/gpu/src/fine.wgsl` | Raph Levien et al., *Vello* (, Apache-2.0 OR MIT) and its design notes; the *sparse strips* rendering work from the same group (2025); the coverage integral is our oracle's (font-rs row above) | Written from the public descriptions; no Vello code or shaders copied (ADR 0019, ADR 0048). | +| Tile binning on the GPU: count, prefix sum, scatter, per-tile lists | `crates/gpu/src/gpu_binning.rs`, `crates/gpu/src/bin.wgsl`, `crates/gpu/src/scan.wgsl` | The binning stages described for *Vello* (above) and Patrick Walton's *Pathfinder* (, Apache-2.0 OR MIT) design posts; the work-efficient scan of G. E. Blelloch, *Prefix Sums and Their Applications* (CMU-CS-90-190, 1990) | Our own arrangement (one invocation per row of a fill's tiles, no atomics) written from the public descriptions; no code or shaders copied (ADR 0048). | +| Hairlines: coverage falling off with the distance from the pixel centre to the line | `crates/render/src/hairline.rs`, `crates/gpu/src/fine.wgsl` | S. Gupta and R. F. Sproull, *Filtering Edges for Gray-Scale Displays* (SIGGRAPH 1981): anti-aliased lines by distance; standard | Public method; a one-pixel tent filter of the distance (ADR 0048). | | Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), , Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. | | Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). | | Adaptive Bézier flattening (Wang's formula) | `crates/geom/src/path.rs` | G.-J. Wang (1984); public mathematical result | | diff --git a/CHANGELOG.md b/CHANGELOG.md index 19a9b140..2543557a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +* **The GPU stage sorts heavy frames into tiles on the graphics card, and outlines are cheap** + (ADR 0048, M3). + * Frames with many shapes are binned on the GPU (count, prefix sum, scatter and tile-list + compute passes) instead of on the CPU: the CPU only lays out the shapes' points, and every + buffer is sized up front, so nothing is read back. On Vulkan, a 10,000-shape 4K frame + drawn as one texture takes about 5 ms instead of 22, a 50,000-shape one about 23 ms + instead of 122, and the 50,000-shape 4K stage about 37 ms instead of 75. Frames with few + shapes, shapes inside masks or faded symbols, and Direct3D 12 (where the passes cost more + per stage tile) are still binned on the CPU, which stays the reference + (`ANICRAFT_GPU_BINNING=cpu|gpu|auto` to compare). + * **Outline mode** (an outlined layer, and onion skin's Outlines) draws true one-pixel + hairlines, one edge per segment where the old half-pixel strokes had four and a disc at + every bend, in the CPU renderer and on the GPU alike. On a 2,000-shape scene with ±5 onion + frames, outlines are now as fast as tinted onion frames: 10 ms on the GPU stage at 1080p + (was 73) and 17 ms on the CPU stage (was 34–39). Lines look the same, with smoother joins. + * Parity with the CPU renderer is unchanged (at most 1/255 on every test scene), and a test + checks that the GPU's tile lists are the CPU's, entry by entry and pixel by pixel. * **Motion path points pinned to frames** (ADR 0049, M2). As in Animate, a motion tween's position keyframes are now points on its path: move the object at a frame and the path gets a point there that the object passes exactly on that frame, whatever else you do to the path. diff --git a/docs/adr/0048-gpu-binning-and-hairlines.md b/docs/adr/0048-gpu-binning-and-hairlines.md new file mode 100644 index 00000000..9cf75094 --- /dev/null +++ b/docs/adr/0048-gpu-binning-and-hairlines.md @@ -0,0 +1,179 @@ +# ADR 0048: GPU stage, fourth slice: tile binning on the GPU, and hairlines + +* Status: accepted (2026-11-10) +* Relates to: roadmap M3, ADR 0019 (GPU stage), ADR 0029 (no readback, masks and groups; binning + kept on the CPU), ADR 0032 (bitmaps, filters, the default), ADR 0047 (onion skin outlines), + ADR 0002 (the oracle's coverage), AGENTS.md rule 4 (the CPU renderer is the oracle) + +## Context + +Two costs were left in the GPU stage: + +* **Binning on the CPU.** The CPU split every prepared edge into 16 × 16 tile pieces, summed + 16 floats of backdrop per tile, and uploaded it all. ADR 0029 kept it there because stage tiles + spread it over every core; it was still the largest term of a heavy frame (10k shapes: 4.0 ms + of 8.8 at 1080p, 10.6 of 16.7 at 4K; 50k shapes: 17–76 ms) and grew with every shape. +* **Outlines.** Outline mode (an outlined layer, and onion skin's Outlines, ADR 0047) drew each + item as a stroke of half a pixel: four edges per segment and a hexagon at every bend, all + overlapping, so an outlined item had 5–10× the edges of its fill. On the 2,000-item stress + scene with ±5 onion frames, outlines took 34–39 ms on the CPU stage against 16–17 tinted, and + 73 ms against 12.6 on the GPU stage. + +## Decision + +### 1. One tile format the GPU can compute: integer backdrops and left-edge steps + +The per-row float backdrop (the winding of everything left of a tile, per pixel row) needed a +float sum in a fixed order; on the GPU that means float atomics (which WGSL doesn't have) or +serial work. The binning now describes the same winding as **Vello's tiles do** (its public +design notes: a backdrop and "y-edges"): + +* **Backdrop:** one integer per tile, the winding number just below its top-left corner. It is + the sum of the directions of the pieces further left in the tile row that start on the row's + top edge (exactly the edges crossing it). +* **Left-edge steps:** where the outline passes from one tile column to another inside a row + (consecutive pieces in different columns), each tile boundary between them gets one more + piece, a vertical line on that tile's left edge from the crossing down to the row's bottom: + upwards where the outline runs right (the winding left of the tile drops by one), downwards + where it runs left. The fine shader treats it like any piece, so its coverage formula is + unchanged. + +Both come **from the split pieces themselves**, so they can never disagree. A first version +computed the crossings geometrically, apart from the split; near a tile corner a rounding +could count one crossing twice, which a stress frame showed (543 pixels off by up to 133/255). +A test on stress frames at awkward scales now catches it. + +Integers add up the same in any order, the CPU binning (the reference) and the GPU produce the +same lists, and the CPU's own binning got smaller (no 64-byte backdrops). + +### 2. Binning on the GPU + +The CPU lays out only what is proportional to the fills and their points (`gpu_binning.rs`): + +* the prepared polygons' points, one flat buffer, and each fill's tile range; +* one GPU invocation per **row of tiles of each fill** (an op-row), with room for each tile of + each fill's bounds (an op-tile); +* per tile row, the fills overlapping it in drawing order (from their bounds), and per tile + room for every fill whose bounds cover it (a 2D running sum over the bounds' corners); +* an **upper bound of the pieces** per edge (its rows, twice its columns, slack), so every + buffer is sized before the GPU runs and **nothing is read back**. + +`bin.wgsl` then runs, in one compute pass: + +1. `count`: each op-row walks its fill's edges, splits the ones in its row (the CPU's + `split_edge`/`split_row`, line for line), adds the left-edge steps, and counts pieces per + op-tile; the backdrop deltas are summed along the row. An op-row belongs to one invocation, + so **no atomics**: counts and backdrops are exact. +2. `scan_blocks`/`scan_add` (`scan.wgsl`): an exclusive prefix sum of the counts (the public + work-efficient scan, Blelloch 1990: per workgroup, then the workgroups' totals, added back). +3. `scatter`: the same walk, writing each piece at its op-tile's place, in walk order (the + same every frame). +4. `tiles`: one invocation per tile walks its row's fills in drawing order and keeps those + with pieces or a backdrop there, as the entries the fine pass reads. + +This is the count, prefix-sum and scatter structure of Vello's and Pathfinder's binning stages +(public descriptions; no code or shaders copied), arranged per op-row instead of per segment +so that it needs no atomics and is deterministic. The binding layout uses four storage buffers +per stage, the smallest any device offers. + +**Scope.** Fills inside a mask or a group still bin on the CPU: their tile streams carry clip +and group control entries whose number depends on which fills reach each tile, which needs +either a CPU pass over the candidates or a GPU stream pass with counted room. That is the next +step. The CPU binning stays the reference and this fallback. + +**When.** `Binning::Auto` (the default) bins on the GPU when the scene can take it, has at +least 32,768 edges and the device runs Vulkan (below, Direct3D 12 measured slower in stage +tiles; other backends aren't measured yet). Below that many edges the CPU bins a stage tile faster than the GPU's passes set up +(measured: forcing the GPU on every 512 px tile made the 1,000-shape 4K stage 1.9× slower, and +the 10k-shape one 1.3× slower). `ANICRAFT_GPU_BINNING=cpu|gpu|auto` overrides it for +comparisons; `render_with`/`render_texture_with` take it per call (tests, the bench). The +start-up self-test also renders its rectangles binned on the GPU; if that comes back wrong, +only the binning stays on the CPU on that device (`gpu_binning_off` says why), and the tests +require it to work wherever the GPU stage runs (lavapipe in CI included). + +Limits: at most `MAX_VISITS` (2²⁶) edge visits by the per-row passes (a fill with very many +edges over very many rows bins on the CPU, which splits each edge once), and every buffer +within the device's binding size; otherwise the CPU bins. The work bound (`MAX_WORK`) counts +the room made, an upper bound. + +### 3. Hairlines in both renderers + +Outline mode draws **hairlines**: the oracle's prepared fill carries the flattened polylines +(closed ones repeat their first point) and `Fill::hairline`. A pixel's coverage is +`1 − d`, clamped, where `d` is the distance from its centre to the nearest segment +(`render::hairline`). That is exactly the area a one-pixel line covers for horizontal and +vertical lines (a line through pixel centres covers them fully, one on a boundary half each +side), a tent-filtered line in other directions (diagonals look up to about 12 % heavier), +with round ends and joins and no darkening where segments overlap. Each segment is one piece +to bin and test, where the stroked hairline was four plus a disc at every bend. + +* The oracle computes it per segment over the rows and columns within reach (a direct-coverage + mode of its accumulation buffer); the GPU's fine shader takes the nearest of the tile's + segments (with a cheap box reject first) by the same steps (`seg_dist`). +* The binning puts each segment, whole, into every tile with a pixel centre within reach + (conservatively: two pixels around it); no backdrops. +* This changes the oracle's outline mode slightly (anti-aliasing of 1 px lines); it is an + editing aid, never exported (vector exports draw outlines as their own strokes), and the + engine's tests and goldens are unchanged. + +Not hairlines (yet): strokes thinner than a pixel. They keep a one-pixel stroke polygon faded +by their width; drawing them as hairlines would change exported pictures and the XFL goldens, +which is its own decision. + +## Measured (2026-11-10, release, RTX 5090, 32 threads, a machine shared with other builds) + +`cargo run --release -p anicraft-gpu --example gpu_bench`: *direct* is what the calling thread +spends with `render_texture` (prepare + bin + upload and submit), *tiled* is the stage's way +(512 px tiles in parallel until the GPU has finished). Before: binned on the CPU; after: as +`Binning::Auto` bins (the GPU from 32,768 edges, on Vulkan). Best of three runs, Vulkan. + +| Scene | Size | CPU oracle | Before: direct / tiled | After, binned on the CPU: direct / tiled | After, Auto: direct / tiled | Parity (mean / max, 1/255) | +|---|---|---|---|---|---|---| +| Stress, 50 × 200 (≈10k shapes) | 1920×1080 | 9.8 ms | 9.0 / 7.4 ms | 8.6 / 5.5 ms | **3.9** / 5.5 ms | < 0.0001 / 1 | +| Stress, 50 × 200 | 3840×2160 | 25.9 ms | 21.7 / 10.9 ms | 16.4 / 10.1 ms | **4.7** / 10.1 ms | < 0.0001 / 1 | +| 1,000 shapes (binned on the CPU: few edges) | 3840×2160 | 16.9 ms | 2.2 / 4.5 ms | 1.6 / 4.2 ms | 1.7 / 4.5 ms | < 0.0001 / 1 | +| 50,000 shapes (250 × 200) | 1920×1080 | 31.7 ms | 52.2 / 32.4 ms | 33.5 / 26.8 ms | **17.7** / 24.8 ms | < 0.0001 / 1 | +| 50,000 shapes | 3840×2160 | 73.1 ms | 122.1 / 75.3 ms | 103.9 / 61.5 ms | **22.5** / **36.7** ms | < 0.0001 / 1 | +| Masked stress (binned on the CPU: masks) | 3840×2160 | 72.4 ms | 13.8 / 12.3 ms | 12.0 / 10.7 ms | 11.3 / 10.5 ms | < 0.0001 / 1 | +| Onion skin off (stress 20 × 100) | 1920×1080 | 5.0 ms | 2.1 / 2.7 ms | 1.8 / 2.2 ms | 1.1 / 2.3 ms | < 0.0001 / 1 | +| Onion ±5, tinted (22,000 items) | 1920×1080 | 15.1 ms | 15.7 / 12.6 ms | 12.8 / 10.5 ms | 7.1 / 9.8 ms | < 0.0001 / 1 | +| Onion ±5, tinted | 3840×2160 | 37.3 ms | 32.1 / 25.1 ms | 20.3 / 22.0 ms | 8.5 / 16.5 ms | 0.0001 / 1 | +| Onion ±5, **outlines** | 1920×1080 | 20.0 ms (was 36.0) | 74.7 / 73.0 ms | 12.9 / 10.4 ms | 7.3 / **10.1** ms | < 0.0001 / 1 | +| Onion ±5, **outlines** | 3840×2160 | 37.9 ms (was 60.2) | 135.4 / 95.4 ms | 20.3 / 18.1 ms | 8.6 / **15.3** ms | < 0.0001 / 1 | + +*Before* is `main` before this slice (CPU binning with float backdrops, stroked hairlines), +measured the same day on the same machine. In stage tiles the GPU binning wins once frames are +heavy (50k shapes: 61.5 → 36.7 ms at 4K) and never loses below `AUTO_MIN_EDGES`; a whole frame +in one texture gains most (10k shapes at 4K: 16.4 → 4.7 ms). **Outline mode is as fast as +tinted onion skin** on the GPU stage: 10.1 vs 9.8 ms at 1080p in tiles, 15.3 vs 16.5 ms at 4K, +7.3 vs 7.1 ms in one texture (it was 73 vs 12.6 ms in tiles). + +On **Direct3D 12** (same card, `WGPU_BACKEND=dx12`, two runs) the GPU binning still wins in +one texture (10k shapes at 4K: 17.5 → 6.3 ms; 50k: 154 → 30 ms) but loses in stage tiles +(onion ±5 at 1080p: 9.7 → 14.4 ms tinted, 10.0 → 15.4 ms outlines; the passes cost more per +dispatch there, as ADR 0032 saw for the fine pass), so `Binning::Auto` bins on the GPU on +Vulkan only. With CPU binning, DX12's onion outlines take 10.1 ms in tiles against 10.0 tinted. + +The CPU stage (the oracle through the render service's 256 px tiles, `onion_timings`, best of +frames 12, 30 and 48) with hairlines: onion ±5 outlines **17.1 ms** against 14.8 tinted at +1080p (was 34–39 against 16.2–17.2). + +## Not in this slice + +* GPU binning for fills inside masks and groups (their tile streams, ADR 0029). +* Flattening and stroking on the GPU (preparation is now the largest CPU term of a heavy + frame: 8–9 ms of 50k shapes). +* Fewer, larger dispatches for the stage's tiles (each 512 px tile is its own submission, so the + binning passes' set-up repeats per tile). +* Hairlines for strokes thinner than a pixel (above). +* Guide lines and selection outlines: the stage never renders guides, and selection outlines + are drawn by the shell's painter, not the stage renderer. + +## Consequences + +* The tile format is one integer backdrop per tile plus left-edge steps, on the CPU and the GPU + alike; `Binned` carries the op headers apart (`op_heads`) and, when the GPU bins, the plan. +* A test compares the GPU's tile lists with the CPU's, tile by tile, entry by entry and pixel + by pixel, on stress frames, outlined onion frames and the analytic scenes; GPU-binned frames + are checked against the oracle read back and through a texture; on Vulkan and Direct3D 12. +* `gpu_bench --check` enforces the GPU stage's timing budgets (docs/performance.md). diff --git a/docs/adr/README.md b/docs/adr/README.md index f974a6d8..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0048 | m3/gpu-binning | GPU stage, fourth slice: tile binning on the GPU, cheap outlines | diff --git a/docs/architecture.md b/docs/architecture.md index 5f1cad2d..9c8a78b9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -36,7 +36,7 @@ app/ workspace root; the root package is the desktop app doc L1 Document model + timeline evaluation (keyframes, tweens, easing, symbols) + player render L2 CPU oracle rasterizer, paints/gradients, compositor, PNG encode engine L3 Session (document + history + selection + playhead), command registry, file format - gpu L3 wgpu stage renderer over the oracle's prepared fills (ADR 0019, 0029, 0031; shell feature `gpu-stage`, on by default) + gpu L3 wgpu stage renderer over the oracle's prepared fills (ADR 0019, 0029, 0032, 0048; shell feature `gpu-stage`, on by default) cli L4 `anicraft-cli`: info / render / render-seq / commands / run / serve (JSON-lines) src/ L5 egui shell: menus (from registry), tools, stage, timeline, properties, library docs/ requirements, architecture, roadmap @@ -185,11 +185,16 @@ DisplayList ──► for each item: Output is bit-identical to serial. Numbers are in [performance.md](performance.md). **GPU stage** ([ADR 0019](adr/0019-gpu-stage.md), [ADR 0029](adr/0029-gpu-stage-direct-masks-groups.md), -[ADR 0032](adr/0032-gpu-stage-bitmaps-filters-default.md); the shell's `gpu-stage` feature, on -by default, and the default stage renderer): `render::prepare_scene` hands the oracle's own -prepared fills, with their clips, groups, bitmap shaders and filtered layers, to `anicraft-gpu`, which bins edge pieces into -16 × 16 tiles with per-row backdrops (CPU, parallel) and writes each tile's stream of entries -in drawing order, with clip-coverage and group open/close entries. One compute pass computes +[ADR 0032](adr/0032-gpu-stage-bitmaps-filters-default.md), [ADR 0048](adr/0048-gpu-binning-and-hairlines.md); +the shell's `gpu-stage` feature, on by default, and the default stage renderer): +`render::prepare_scene` hands the oracle's own prepared fills, with their clips, groups, bitmap +shaders and filtered layers, to `anicraft-gpu`, which bins edge pieces into 16 × 16 tiles with +an integer backdrop per tile and steps on the tiles' left edges, and writes each tile's stream +of entries in drawing order. Heavy scenes without masks or groups are binned on the GPU (count, +prefix sum, scatter and tile-list passes; the CPU only lays out the points and the fills' +ranges, and sizes every buffer up front, so nothing is read back); the rest, with their +clip-coverage and group open/close entries, on the CPU, which is also the reference. Outline +mode's hairlines are one piece per segment, covered by distance in both renderers. One compute pass computes each pixel's exact area coverage and composites it as the oracle's band compositor does (clip coverage, a per-pixel group stack, the W3C blend modes). On the window's wgpu device it draws each stage tile into a texture egui shows as it is (no readback); otherwise on a headless diff --git a/docs/performance.md b/docs/performance.md index f10e5bb3..e034b22c 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -37,6 +37,11 @@ The default `bench` scenario: 50 layers × 200 shapes × 240 frames, 200k elemen | UI frame while rendering | never blocked | worker thread ✅ | design (ADR 0002) | | Autosave: time on the editing thread | < 1 ms | 7–15 µs ✅ | `bench --check` | | Autosave of the 65 MB file, in the background | < 2 s | 183–184 ms ✅ | `bench --check` | +| GPU stage, 1,000 shapes at 4K, stage tiles (M3 exit) | < 16.7 ms | 4.5–4.7 ms ✅ (2026-11-10, RTX 5090) | `gpu_bench --check` | +| GPU stage, 10k shapes at 4K, stage tiles | < 16.7 ms | 10.1–10.4 ms ✅ | `gpu_bench --check` | +| GPU stage, 50k shapes at 1080p, stage tiles | < 33.3 ms (30 fps) | 24.8–26.3 ms ✅ | `gpu_bench --check` | +| GPU stage, 50k shapes at 4K, one texture | < 33.3 ms | 22.5–23.8 ms ✅ | `gpu_bench --check` | +| GPU stage, onion ±5 outlines / tinted at 1080p, stage tiles | ≤ 1.25 | 1.03–1.06 ✅ | `gpu_bench --check` | **1080p render, back under budget (2026-11-06).** It had drifted to 19.4–20.2 ms (v0.1.0 measured 18.0–18.9 ms on the same machine; the 16.5 ms of 2026-10-28 didn't reproduce). @@ -68,8 +73,16 @@ order (an append, then a reorder). One k-way merge by layer, each item moved onc to 0.85 ms, and evaluating the extra frames in parallel brought the whole to 3.0–3.3 ms. Output is unchanged (the onion tests compare items and pixels). The settings are part of every tile's key, so the frame cache keeps working: looking at the same frame again is 40 hits in 0.02 ms, -and other settings are other pictures. Hairline outlines cost more to rasterize than fills, so -outline mode on very heavy scenes is the slow case. +and other settings are other pictures. + +**Outlines as hairlines (2026-11-10, ADR 0048).** Outline mode drew half-pixel strokes (four +edges per segment and a disc at every bend); it now draws hairlines, one edge per segment, +covered by distance. Same test, same machine: + +| Scene | Off | ±5 tinted, fading | ±5 outlines | Keyframes only ±5 | Edit Multiple Frames ±5 | +|---|---|---|---|---|---| +| Sample | 5.7 ms | 5.9 ms | 5.5 ms | 5.9 ms | 5.7 ms | +| Stress 20 × 100 | 7.6 ms | 14.8 ms | **17.1 ms** (was 34–39) | 7.3 ms | 7.2 ms | **Crash-recovery autosave (2026-11-09, ADR 0015).** `bench` now runs one autosave the way the app does: an `Autosaver` in a scratch recovery folder. The editing thread only hands over an @@ -147,6 +160,44 @@ layer across a frame's tiles is next. The one large difference is a single pixel falls within float rounding of a non-repeating bitmap's edge (ADR 0032). Bitmaps are uploaded once per image and cached (256 MB budget), so after the first frame they cost no transfer. +### GPU stage, fourth slice: binning on the GPU, hairlines (M3, ADR 0048) + +`cargo run --release -p anicraft-gpu --example gpu_bench` (2026-11-10, RTX 5090 over Vulkan, +32 threads, a machine shared with other builds: best of three runs). *Direct* is the calling +thread's time with `render_texture`, *tiled* the stage's way (512 px tiles in parallel until +the GPU has finished). + +| Scene | Size | CPU oracle | Before: direct / tiled | After, binned on the CPU: direct / tiled | After, Auto: direct / tiled | Parity (mean / max, 1/255) | +|---|---|---|---|---|---|---| +| Stress, 50 × 200 (≈10k shapes) | 1920×1080 | 9.8 ms | 9.0 / 7.4 ms | 8.6 / 5.5 ms | **3.9** / 5.5 ms | < 0.0001 / 1 | +| Stress, 50 × 200 | 3840×2160 | 25.9 ms | 21.7 / 10.9 ms | 16.4 / 10.1 ms | **4.7** / 10.1 ms | < 0.0001 / 1 | +| 1,000 shapes (binned on the CPU: few edges) | 3840×2160 | 16.9 ms | 2.2 / 4.5 ms | 1.6 / 4.2 ms | 1.7 / 4.5 ms | < 0.0001 / 1 | +| 50,000 shapes (250 × 200) | 1920×1080 | 31.7 ms | 52.2 / 32.4 ms | 33.5 / 26.8 ms | **17.7** / 24.8 ms | < 0.0001 / 1 | +| 50,000 shapes | 3840×2160 | 73.1 ms | 122.1 / 75.3 ms | 103.9 / 61.5 ms | **22.5** / **36.7** ms | < 0.0001 / 1 | +| Masked stress (binned on the CPU: masks) | 3840×2160 | 72.4 ms | 13.8 / 12.3 ms | 12.0 / 10.7 ms | 11.3 / 10.5 ms | < 0.0001 / 1 | +| Onion skin off (stress 20 × 100) | 1920×1080 | 5.0 ms | 2.1 / 2.7 ms | 1.8 / 2.2 ms | 1.1 / 2.3 ms | < 0.0001 / 1 | +| Onion ±5, tinted (22,000 items) | 1920×1080 | 15.1 ms | 15.7 / 12.6 ms | 12.8 / 10.5 ms | 7.1 / 9.8 ms | < 0.0001 / 1 | +| Onion ±5, tinted | 3840×2160 | 37.3 ms | 32.1 / 25.1 ms | 20.3 / 22.0 ms | 8.5 / 16.5 ms | 0.0001 / 1 | +| Onion ±5, **outlines** | 1920×1080 | 20.0 ms (was 36.0) | 74.7 / 73.0 ms | 12.9 / 10.4 ms | 7.3 / **10.1** ms | < 0.0001 / 1 | +| Onion ±5, **outlines** | 3840×2160 | 37.9 ms (was 60.2) | 135.4 / 95.4 ms | 20.3 / 18.1 ms | 8.6 / **15.3** ms | < 0.0001 / 1 | + +*Before* is `main` before this slice (CPU binning with float backdrops, stroked hairlines), +measured the same day on the same machine. In stage tiles the GPU binning wins once frames are +heavy (50k shapes: 61.5 → 36.7 ms at 4K) and never loses below `AUTO_MIN_EDGES`; a whole frame +in one texture gains most (10k shapes at 4K: 16.4 → 4.7 ms). **Outline mode is as fast as +tinted onion skin** on the GPU stage: 10.1 vs 9.8 ms at 1080p in tiles, 15.3 vs 16.5 ms at 4K, +7.3 vs 7.1 ms in one texture (it was 73 vs 12.6 ms in tiles). + +On **Direct3D 12** (same card, `WGPU_BACKEND=dx12`, two runs) the GPU binning still wins in +one texture (10k shapes at 4K: 17.5 → 6.3 ms; 50k: 154 → 30 ms) but loses in stage tiles +(onion ±5 at 1080p: 9.7 → 14.4 ms tinted, 10.0 → 15.4 ms outlines; the passes cost more per +dispatch there, as ADR 0032 saw for the fine pass), so `Binning::Auto` bins on the GPU on +Vulkan only. With CPU binning, DX12's onion outlines take 10.1 ms in tiles against 10.0 tinted. + +The CPU stage (the oracle through the render service's 256 px tiles, `onion_timings`, best of +frames 12, 30 and 48) with hairlines: onion ±5 outlines **17.1 ms** against 14.8 tinted at +1080p (was 34–39 against 16.2–17.2). + ### How budgets are enforced * **Budgets that don't depend on the machine** (undo memory, snapshot sharing, file size, @@ -158,7 +209,8 @@ once per image and cached (256 MB budget), so after the first frame they cost no machine before a release and after performance work. A dedicated benchmark runner would let CI run it too. * The limits live in `TIME_BUDGETS` in `crates/cli/src/lib.rs`; keep that list and this - table in step. + table in step. The GPU stage's are `BUDGETS` in `crates/gpu/examples/gpu_bench.rs` + (`--check`; the CLI has no GPU). ## Sound (2026-11-09, ADR 0020) @@ -187,3 +239,5 @@ buffer is tiny; the stage never waits on sound. groups on the GPU, binning kept on the CPU * [ADR 0032](adr/0032-gpu-stage-bitmaps-filters-default.md): bitmaps and filters on the GPU, Direct3D 12, and the GPU as the default stage renderer +* [ADR 0048](adr/0048-gpu-binning-and-hairlines.md): tile binning on the GPU, one tile format + for both binnings, and hairlines for outline mode diff --git a/docs/roadmap.md b/docs/roadmap.md index 87d4fec4..d5c8d175 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -9,7 +9,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | Dimension | Status | |---|---| | Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). | -| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning (ADR 0029), buffer reuse across tiles, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | +| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes ``. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower there in stage tiles); and **hairlines** for outline mode in both renderers (coverage by distance, one edge per segment): onion outlines on the 2,000-item stress scene as fast as tinted (GPU stage 73 → 10 ms, CPU stage 34–39 → 17 ms at 1080p). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning inside masks and groups, flattening and stroking on the GPU, buffer reuse and fewer dispatches across tiles, hairlines for sub-pixel strokes, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. | | Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. Not yet: per-layer onion toggles, deleting/transforming/copying across keyframes in Edit Multiple Frames, re-merging raw shapes moved there. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. **Path points** (ADR 0038): with Subselection, double-click the path to add a point (shape and motion unchanged), Shift-click to select several anchors, Delete to remove them (the path refits through the rest; the ends stay), right-click for smooth/corner and Straighten; the Pen's Alt-click adds a point to a motion path or a selected shape; Ctrl-drag (⌘-drag) the path or its object, or edit Properties › Path start, to move the whole path with its timing exact. **Anchors pinned to frames** (ADR 0049): moving the object at a frame pins a path point there (a new anchor where it was put; after the last position key the path carries on), and the object passes every pinned point exactly on its frame, the X/Y eases timing it between pins; pinned points are diamonds with their frame number on the stage, blue keys in the Motion Editor's X/Y (dragging one moves its point) and holed diamonds on the timeline; Subselection's right-click pins to the playhead's frame or unpins, Properties › Frame has Pin Here / Unpin, F6 pins where the object is; point edits keep pins on their anchors; files without pins evaluate exactly as before. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient/add_point/delete_points/convert_point/move_path/pin_point/unpin_point`; `motion.info` reports `pins`). Not yet: retiming a pin by dragging its key in time, two pins on one anchor, XFL motion path keyframes, a marquee over path anchors, nudging or transforming a whole path, retiming keys, rescaling keys with the span, XFL motion-tween import. **Bones and IK, first slice** (ADR 0043): the Bone tool (M) drags from one symbol instance to another to join them with a bone on an armature layer (chains join end to start, branches allowed, up to 256 bones); bones show as wedges in the layer colour; the Selection tool drags a bone or a posed instance to pose by cyclic coordinate descent (joint limits, pinned bones, one undo step per drag) and the root to move it all; poses are joint angles keyed per frame and tweened with the span's easing; Properties › Bone (angle, constrain min/max, pin, remove); `bone.*` headless; every export sees the pose. Not yet: shape armatures, spring, joint translation, runtime armatures, XFL import, editing members' properties in place. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tools pause there); hiding the camera layer turns it off; every export, Test Movie and the GPU stage see it. Headless: `camera.add/remove/set/info`, `layer.set_depth`. Not yet: editing through the preview, perspective depth, XFL camera import. **Motion guides**: guided layers (children of a guide through `Layer.parent`) have their classic tweens follow the guide's first path by arc length, from the point nearest each start keyframe to the point nearest its end (`geom::walk::PathWalk`), optionally orienting to the path; guide artwork is listed for picking and editing, drawn on the stage as a line, and never rendered or exported. | | Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **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: a marquee across several layers, snapping while drawing, width profiles in the merge, deleting or adding raw anchors, smooth handle pairs. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and Paint Inside, a brush library, pressure curves and tilt. **Eraser (E)** (ADR 0034, first slice): sweeps the Brush's tip and takes what it covers out of the raw shapes on the active layer (the sweep is a fill in the planar merge that comes out empty); Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside; the Faucet deletes a whole fill or line with a click; drawing objects, symbols and text are kept; a stroke that erases nothing leaves no undo step; live preview, `[` and `]` sizes, one undo step per stroke; double-clicking the tool (or Erase Everything… in its options) clears the visible, unlocked layers at this frame after asking. **Eyedropper (I)** (first slice): a click on a fill picks its paint (solid, or a gradient or bitmap kept where it is on the stage, as Lock Fill) into the fill swatch, a click on a line picks its colour, width and profile; with shapes selected it applies the style to them; then it becomes the Paint Bucket or the Ink Bottle; Shift-click picks into the other swatch only. Headless: `draw.erase`, `draw.faucet`, `draw.erase_all`, `paint.pick`, `paint.apply_style`. Not yet: erasing inside symbols, erasing width-profiled shapes (gradient fills erase since ADR 0042), eraser pressure, picking a bitmap's pixel colour or text styles, an eyedropper cursor. | | 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. | @@ -33,7 +33,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | -| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); GPU binning deferred (not the bottleneck as tiles); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: shared filtered layers across tiles, an image atlas, GPU exports. | +| **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); not yet: `.fla` variants of the corpus, sound and video items; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **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 XFL sounds later); ~~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~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. | @@ -54,7 +54,7 @@ titled with its milestone. | Track | Next task | Depends on (all done) | |---|---|---| | M2 | Motion tweens with property curves and the Motion Editor | timeline evaluation, classic tweens | -| M3 | GPU stage: filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032) | CPU oracle, tiled stage, GPU stage slices 1–3 | +| M3 | GPU stage: GPU binning inside masks and groups, filtered layers shared across a frame's tiles, more than 16 images per tile (first slice ✅ ADR 0019, no readback and masks/groups ✅ ADR 0029, bitmaps, filters and the default ✅ ADR 0032, GPU binning and hairlines ✅ ADR 0048) | CPU oracle, tiled stage, GPU stage slices 1–4 | | M4 | Text from Animate files | XFL import, text engine (M5 first slice) | | M5 | Audio layers: import, waveform, playback sync | timeline, layers | | M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); next: command macros, or growing the ActionScript subset (variables and conditions) | command registry, plug-in host, action IR and player | From a6df58e30da59d6c4d744dd22bc42425cacbb4f2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:40:02 -0700 Subject: [PATCH 10/19] fix(gpu): as_chunks_mut for the input layout (newer clippy) (M3) --- crates/gpu/src/gpu_binning.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/gpu/src/gpu_binning.rs b/crates/gpu/src/gpu_binning.rs index 31cc3dcb..3212934a 100644 --- a/crates/gpu/src/gpu_binning.rs +++ b/crates/gpu/src/gpu_binning.rs @@ -209,11 +209,11 @@ pub fn plan(fills: &[Fill], tiles_x: u32, tiles_y: u32, lim: &Limits) -> Option< let flags = if f.hairline { HAIRLINE_BIT } else { 0 }; h.copy_from_slice(&[p0, i.polys, tx0, ty0, ncols, nrows, t0, flags]); let mut q = q0; - for (slot, poly) in pw.chunks_exact_mut(2).zip(&f.polys) { + for (slot, poly) in pw.as_chunks_mut::<2>().0.iter_mut().zip(&f.polys) { slot.copy_from_slice(&[q, poly.len() as u32]); q += poly.len() as u32; } - for (slot, p) in qw.chunks_exact_mut(2).zip(f.polys.iter().flatten()) { + for (slot, p) in qw.as_chunks_mut::<2>().0.iter_mut().zip(f.polys.iter().flatten()) { slot.copy_from_slice(&[p.x.to_bits(), p.y.to_bits()]); } }); From ac9a6ac351ec297eadc60bb7bed5b9512143fda8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:27:38 -0700 Subject: [PATCH 11/19] docs(adr): reserve ADR 0050 for library management (M2) --- docs/adr/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/README.md b/docs/adr/README.md index 8a35fed1..0390bd99 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,3 +23,4 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | +| 0050 | m2/library-management | Library folders, item management and Swap Symbol | From eb1037a6daedda5a1191fb3e320b018723c641a8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:31:17 -0700 Subject: [PATCH 12/19] feat(doc): Library folders, item placement, unique names, use counts and unused items (M2) --- crates/doc/src/bitmap.rs | 16 +- crates/doc/src/lib.rs | 18 +- crates/doc/src/library.rs | 523 ++++++++++++++++++++++++++++++++ crates/doc/src/library_tests.rs | 195 ++++++++++++ crates/doc/src/sample.rs | 6 +- crates/engine/src/history.rs | 2 +- 6 files changed, 751 insertions(+), 9 deletions(-) create mode 100644 crates/doc/src/library.rs create mode 100644 crates/doc/src/library_tests.rs diff --git a/crates/doc/src/bitmap.rs b/crates/doc/src/bitmap.rs index 0ec3c6ff..196de0bd 100644 --- a/crates/doc/src/bitmap.rs +++ b/crates/doc/src/bitmap.rs @@ -43,13 +43,25 @@ pub struct Bitmap { /// The image as PNG. #[serde(with = "base64_bytes")] pub png: Arc>, + /// Allow Smoothing (ADR 0050): scaled or turned, the image is filtered between its pixels; + /// off, each pixel stays a hard-edged square (pixel art). On unless a file says otherwise. + #[serde(default = "yes", skip_serializing_if = "is_yes")] + pub smoothing: bool, #[serde(skip)] decoded: Arc>>>, } +fn yes() -> bool { + true +} + +fn is_yes(b: &bool) -> bool { + *b +} + impl PartialEq for Bitmap { fn eq(&self, o: &Bitmap) -> bool { - self.id == o.id && self.name == o.name && self.width == o.width && self.height == o.height && (Arc::ptr_eq(&self.png, &o.png) || self.png == o.png) + self.id == o.id && self.name == o.name && self.width == o.width && self.height == o.height && self.smoothing == o.smoothing && (Arc::ptr_eq(&self.png, &o.png) || self.png == o.png) } } @@ -60,7 +72,7 @@ impl Bitmap { let (width, height) = (px.width, px.height); let decoded = OnceLock::new(); let _ = decoded.set(Some(Arc::new(px))); - Some(Bitmap { id, name: name.into(), width, height, png: Arc::new(png), decoded: Arc::new(decoded) }) + Some(Bitmap { id, name: name.into(), width, height, png: Arc::new(png), smoothing: true, decoded: Arc::new(decoded) }) } /// A bitmap from PNG or JPEG data (told apart by their signatures; JPEGs become PNG). diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 086e9914..734961ac 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -14,6 +14,7 @@ mod filter; mod easing; mod eval; mod hints; +pub mod library; pub mod motion; pub mod path_table; pub mod width; @@ -26,6 +27,7 @@ pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; pub use easing::Easing; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; +pub use library::{FolderId, LibraryEntry, LibraryFolder, LibraryItem, LibraryTree, NameError}; pub use motion::{MotionTween, OnPath, Pin, PinError, Property, PropertyKey, Props, Track, motion_path}; pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, SoundId, SoundSync}; pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; @@ -1095,6 +1097,9 @@ pub struct Document { /// Sounds in the library, placed on keyframes through [`FrameSound`]. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sounds: Vec>, + /// The Library's folders and which folder each item is in (ADR 0050). + #[serde(default, skip_serializing_if = "library_tree_is_empty")] + pub library_tree: Arc, /// The class scripts run the main timeline as (Animate's "document class"), kept as text /// (ADR 0013 tier 1); empty when there is none. #[serde(default, skip_serializing_if = "String::is_empty")] @@ -1119,6 +1124,8 @@ struct DocumentFile { #[serde(default)] sounds: Vec>, #[serde(default)] + library_tree: Arc, + #[serde(default)] document_class: String, #[serde(default = "first_id")] next_id: u64, @@ -1130,7 +1137,7 @@ impl From for Document { if let Some(tl) = f.timeline { scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl })); } - Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, document_class: f.document_class, next_id: f.next_id } + Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, next_id: f.next_id } } } @@ -1138,18 +1145,22 @@ fn first_id() -> u64 { 1 } +fn library_tree_is_empty(t: &Arc) -> bool { + t.is_empty() +} + /// What `timeline(i)` returns for a scene that does not exist (never for a sanitized document). static NO_TIMELINE: Timeline = Timeline { layers: Vec::new() }; impl PartialEq for Document { fn eq(&self, o: &Document) -> bool { - self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) + self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) } } impl Default for Document { fn default() -> Self { - let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), next_id: 1 }; let id = LayerId(d.alloc_id()); d.timeline_mut(0).layers.push(Arc::new(Layer::new(id, "Layer 1"))); d @@ -1280,6 +1291,7 @@ impl Document { for s in &self.sounds { max_id = max_id.max(s.id.0); } + self.sanitize_library_tree(&mut max_id); self.next_id = self.next_id.max(max_id.saturating_add(1)); } } diff --git a/crates/doc/src/library.rs b/crates/doc/src/library.rs new file mode 100644 index 00000000..6d5f6b6e --- /dev/null +++ b/crates/doc/src/library.rs @@ -0,0 +1,523 @@ +//! How the Library is organised (ADR 0050): folders, the folder each item is in, names unique +//! within a folder, how often each item is used, and which items nothing reaches. +//! +//! The organisation is kept apart from the items themselves ([`Document::library_tree`]): moving +//! or renaming a folder touches one small table, never a symbol's timeline, and documents from +//! before folders open with every item at the top level. + +use crate::{BitmapId, Document, ElementId, ElementKind, LayerId, Paint, SoundId, Symbol, SymbolId, Timeline}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::sync::Arc; + +/// Unique id of a Library folder (from the document's id counter). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub struct FolderId(pub u64); + +/// A symbol, bitmap or sound in the Library. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum LibraryItem { + Symbol(SymbolId), + Bitmap(BitmapId), + Sound(SoundId), +} + +impl LibraryItem { + /// The id inside, whatever the kind (ids are unique across kinds within a document). + pub fn raw(self) -> u64 { + match self { + LibraryItem::Symbol(i) => i.0, + LibraryItem::Bitmap(i) => i.0, + LibraryItem::Sound(i) => i.0, + } + } +} + +/// One row of the Library: an item or a folder. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum LibraryEntry { + Item(LibraryItem), + Folder(FolderId), +} + +/// A Library folder. Folders nest; `parent` is `None` at the top level. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LibraryFolder { + pub id: FolderId, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent: Option, +} + +/// The Library's folders and where each item is. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct LibraryTree { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub folders: Vec, + /// The folder each item is in. An item not listed is at the top level. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty", with = "placed_list")] + pub placed: BTreeMap, +} + +impl LibraryTree { + pub fn is_empty(&self) -> bool { + self.folders.is_empty() && self.placed.is_empty() + } +} + +/// `placed` as a list of `{"symbol": 3, "folder": 7}` (JSON object keys must be strings). +mod placed_list { + use super::{FolderId, LibraryItem}; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use std::collections::BTreeMap; + + #[derive(Serialize, Deserialize)] + struct Placed { + #[serde(flatten)] + item: LibraryItem, + folder: FolderId, + } + + pub fn serialize(m: &BTreeMap, s: S) -> Result { + s.collect_seq(m.iter().map(|(item, folder)| Placed { item: *item, folder: *folder })) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let v: Vec = Vec::deserialize(d)?; + Ok(v.into_iter().map(|p| (p.item, p.folder)).collect()) + } +} + +/// Most folders in a Library. +pub const MAX_FOLDERS: usize = 10_000; +/// Deepest folder nesting (a top-level folder is at depth 1). +pub const MAX_FOLDER_DEPTH: usize = 32; +/// Longest Library name (characters). +pub const MAX_NAME_CHARS: usize = 256; + +/// Why a name can't be used for a Library item or folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum NameError { + Empty, + TooLong, + /// `/` separates folders in a path (`Characters/Ball`). + Slash, + /// The folder already holds an item or folder of that name (case aside). + Taken(String), +} + +impl std::fmt::Display for NameError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + NameError::Empty => write!(f, "a Library name can't be empty"), + NameError::TooLong => write!(f, "a Library name is at most {MAX_NAME_CHARS} characters"), + NameError::Slash => write!(f, "a Library name can't contain “/” (it separates folders)"), + NameError::Taken(n) => write!(f, "this folder already has an item named “{n}”"), + } + } +} + +/// Library names compare without case, as in Animate. +fn same_name(a: &str, b: &str) -> bool { + a == b || a.to_lowercase() == b.to_lowercase() +} + +/// A name trimmed and checked for the Library's rules (not for clashes). +pub fn clean_name(name: &str) -> Result { + let n = name.trim(); + if n.is_empty() { + return Err(NameError::Empty); + } + if n.chars().count() > MAX_NAME_CHARS { + return Err(NameError::TooLong); + } + if n.contains('/') { + return Err(NameError::Slash); + } + Ok(n.to_string()) +} + +impl Document { + /// Every item in the Library: symbols, then bitmaps, then sounds. + pub fn library_items(&self) -> impl Iterator + '_ { + self.library + .iter() + .map(|s| LibraryItem::Symbol(s.id)) + .chain(self.bitmaps.iter().map(|b| LibraryItem::Bitmap(b.id))) + .chain(self.sounds.iter().map(|s| LibraryItem::Sound(s.id))) + } + + pub fn has_item(&self, item: LibraryItem) -> bool { + self.item_name(item).is_some() + } + + pub fn item_name(&self, item: LibraryItem) -> Option<&str> { + match item { + LibraryItem::Symbol(id) => self.symbol(id).map(|s| s.name.as_str()), + LibraryItem::Bitmap(id) => self.bitmap(id).map(|b| b.name.as_str()), + LibraryItem::Sound(id) => self.sound(id).map(|s| s.name.as_str()), + } + } + + pub fn folder(&self, id: FolderId) -> Option<&LibraryFolder> { + self.library_tree.folders.iter().find(|f| f.id == id) + } + + pub fn has_entry(&self, e: LibraryEntry) -> bool { + match e { + LibraryEntry::Item(i) => self.has_item(i), + LibraryEntry::Folder(f) => self.folder(f).is_some(), + } + } + + pub fn entry_name(&self, e: LibraryEntry) -> Option<&str> { + match e { + LibraryEntry::Item(i) => self.item_name(i), + LibraryEntry::Folder(f) => self.folder(f).map(|f| f.name.as_str()), + } + } + + /// The folder `e` is in (`None`: the top level). + pub fn parent_of(&self, e: LibraryEntry) -> Option { + match e { + LibraryEntry::Item(i) => self.library_tree.placed.get(&i).copied(), + LibraryEntry::Folder(f) => self.folder(f).and_then(|f| f.parent), + } + } + + /// The folders from the top level down to `id` (inclusive). Bounded, so a damaged tree can't + /// loop. + pub fn folder_chain(&self, id: FolderId) -> Vec { + let mut out = Vec::new(); + let mut at = Some(id); + while let Some(f) = at.and_then(|i| self.folder(i)) { + if out.len() >= MAX_FOLDER_DEPTH || out.contains(&f.id) { + break; + } + out.push(f.id); + at = f.parent; + } + out.reverse(); + out + } + + /// `e`'s place as a path, `Characters/Hero/Ball` (`/` joins folder names). + pub fn entry_path(&self, e: LibraryEntry) -> String { + let mut parts: Vec<&str> = self.parent_of(e).map(|p| self.folder_chain(p)).unwrap_or_default().into_iter().filter_map(|f| self.folder(f).map(|x| x.name.as_str())).collect(); + parts.push(self.entry_name(e).unwrap_or("")); + parts.join("/") + } + + /// Whether `inner` is `outer` or inside it, at any depth. + pub fn folder_within(&self, inner: FolderId, outer: FolderId) -> bool { + self.folder_chain(inner).contains(&outer) + } + + /// The folders and items directly in `parent` (`None`: the top level), folders first. + pub fn library_children(&self, parent: Option) -> Vec { + let folders = self.library_tree.folders.iter().filter(|f| f.parent == parent).map(|f| LibraryEntry::Folder(f.id)); + let items = self.library_items().filter(|i| self.library_tree.placed.get(i).copied() == parent).map(LibraryEntry::Item); + folders.chain(items).collect() + } + + /// Everything inside folder `id` at any depth (not the folder itself): folders, then items. + pub fn folder_contents(&self, id: FolderId) -> Vec { + let inside: Vec = self.library_tree.folders.iter().filter(|f| f.id != id && self.folder_within(f.id, id)).map(|f| f.id).collect(); + let mut all = inside.clone(); + all.push(id); + let items = self.library_items().filter(|i| self.library_tree.placed.get(i).is_some_and(|f| all.contains(f))); + inside.into_iter().map(LibraryEntry::Folder).chain(items.map(LibraryEntry::Item)).collect() + } + + /// How deep folder `id` is (1 at the top level). + pub fn folder_depth(&self, id: FolderId) -> usize { + self.folder_chain(id).len() + } + + /// How many folder levels `id` holds, itself included (1 for a folder without subfolders). + pub fn folder_height(&self, id: FolderId) -> usize { + let base = self.folder_depth(id); + self.library_tree.folders.iter().filter(|f| self.folder_within(f.id, id)).map(|f| self.folder_depth(f.id) + 1 - base).max().unwrap_or(1) + } + + /// Whether folder `parent` already holds something named `name` (case aside), other than + /// `except`. + pub fn name_taken(&self, parent: Option, name: &str, except: Option) -> bool { + self.library_children(parent).into_iter().filter(|e| Some(*e) != except).any(|e| self.entry_name(e).is_some_and(|n| same_name(n, name))) + } + + /// `name` checked for the Library's rules and for a clash in `parent`. + pub fn check_name(&self, parent: Option, name: &str, except: Option) -> Result { + let n = clean_name(name)?; + if self.name_taken(parent, &n, except) { + return Err(NameError::Taken(n)); + } + Ok(n) + } + + /// `wanted`, or `wanted 2`, `wanted 3`, … whichever `parent` doesn't hold yet. + pub fn unique_name(&self, parent: Option, wanted: &str) -> String { + let base: String = wanted.trim().replace('/', "-").chars().take(MAX_NAME_CHARS - 8).collect(); + let base = if base.is_empty() { "Item".to_string() } else { base }; + if !self.name_taken(parent, &base, None) { + return base; + } + let siblings = self.library_children(parent).len() + 2; + (2..=siblings).map(|n| format!("{base} {n}")).find(|c| !self.name_taken(parent, c, None)).unwrap_or(base) + } + + /// `stem 1`, `stem 2`, … the first that `parent` doesn't hold, counting from `start`. + pub fn numbered_name(&self, parent: Option, stem: &str, start: usize) -> String { + let end = start + self.library_children(parent).len() + 1; + (start.max(1)..=end).map(|n| format!("{stem} {n}")).find(|c| !self.name_taken(parent, c, None)).unwrap_or_else(|| format!("{stem} {end}")) + } + + /// Moves `e` into folder `to` (`None`: the top level). No checks: see `library.move`. + pub fn place_entry(&mut self, e: LibraryEntry, to: Option) { + let tree = Arc::make_mut(&mut self.library_tree); + match e { + LibraryEntry::Item(i) => match to { + Some(f) => { + tree.placed.insert(i, f); + } + None => { + tree.placed.remove(&i); + } + }, + LibraryEntry::Folder(id) => { + if let Some(f) = tree.folders.iter_mut().find(|f| f.id == id) { + f.parent = to; + } + } + } + } + + /// The folder at `path` (`Characters/Hero`), made where missing. `None` for an empty path, + /// or when the Library can't hold more folders or nesting. + pub fn ensure_folder_path(&mut self, path: &str) -> Option { + let mut parent: Option = None; + for (depth, part) in path.split('/').map(str::trim).filter(|p| !p.is_empty()).enumerate() { + if depth >= MAX_FOLDER_DEPTH { + break; + } + let part: String = part.chars().take(MAX_NAME_CHARS).collect(); + let found = self.library_tree.folders.iter().find(|f| f.parent == parent && same_name(&f.name, &part)).map(|f| f.id); + parent = Some(match found { + Some(id) => id, + None => { + if self.library_tree.folders.len() >= MAX_FOLDERS { + return parent; + } + let id = FolderId(self.alloc_id()); + Arc::make_mut(&mut self.library_tree).folders.push(LibraryFolder { id, name: part, parent }); + id + } + }); + } + parent + } + + /// How many times each item is used: symbol instances, shapes filled with a bitmap and + /// keyframes playing a sound, counted once per keyframe on every timeline (scenes and + /// symbols). Items used nowhere are left out. + pub fn library_uses(&self) -> HashMap { + let mut uses: HashMap = HashMap::new(); + for tl in self.timelines() { + visit_refs(tl, |item| *uses.entry(item).or_default() += 1); + } + uses + } + + /// The items nothing in the movie reaches: not placed in any scene, nor inside a symbol + /// that is (at any depth). Symbols with a linkage class count as reached, since scripts + /// can make them by name. In Library order. + pub fn unused_items(&self) -> Vec { + let mut reached: HashSet = HashSet::new(); + let mut stack: Vec = self.library.iter().filter(|s| s.linkage.is_some()).map(|s| s.id).collect(); + for s in &stack { + reached.insert(LibraryItem::Symbol(*s)); + } + let reach = |item: LibraryItem, reached: &mut HashSet, stack: &mut Vec| { + if reached.insert(item) + && let LibraryItem::Symbol(id) = item + { + stack.push(id); + } + }; + for scene in &self.scenes { + visit_refs(&scene.timeline, |item| reach(item, &mut reached, &mut stack)); + } + // Each symbol is walked at most once (it enters the stack when first reached). + while let Some(id) = stack.pop() { + if let Some(sym) = self.symbol(id) { + visit_refs(&sym.timeline, |item| reach(item, &mut reached, &mut stack)); + } + } + self.library_items().filter(|i| !reached.contains(i)).collect() + } + + /// Whether symbol `outer` is `inner` or holds an instance of it at any depth (so placing + /// `inner` inside `outer` would make a symbol contain itself). + pub fn symbol_contains(&self, outer: SymbolId, inner: SymbolId) -> bool { + let mut seen: HashSet = HashSet::new(); + let mut stack = vec![outer]; + while let Some(id) = stack.pop() { + if id == inner { + return true; + } + if !seen.insert(id) { + continue; + } + if let Some(sym) = self.symbol(id) { + visit_refs(&sym.timeline, |item| { + if let LibraryItem::Symbol(s) = item { + stack.push(s); + } + }); + } + } + false + } + + /// A copy of symbol `id` named `name`, with fresh layer and element ids, in the same + /// folder, right after it in the Library. Its linkage class stays with the original (a + /// class names one symbol). The new symbol's id, or `None` if there is no such symbol. + pub fn duplicate_symbol(&mut self, id: SymbolId, name: String) -> Option { + let at = self.library.iter().position(|s| s.id == id)?; + let src = self.library.get(at)?.clone(); + let new_id = SymbolId(self.alloc_id()); + let timeline = fresh_ids(&src.timeline, &mut || self.alloc_id()); + let copy = Symbol { id: new_id, name, kind: src.kind, linkage: None, timeline }; + self.library.insert(at + 1, Arc::new(copy)); + if let Some(f) = self.library_tree.placed.get(&LibraryItem::Symbol(id)).copied() { + Arc::make_mut(&mut self.library_tree).placed.insert(LibraryItem::Symbol(new_id), f); + } + Some(new_id) + } + + /// Repairs a loaded Library tree: folders with unique ids and usable names, parents that + /// exist, no cycles, nesting within [`MAX_FOLDER_DEPTH`], and only placements of items and + /// folders that exist. Touches the tree only if something needs it. + pub(crate) fn sanitize_library_tree(&mut self, max_id: &mut u64) { + let ok = |d: &Document| { + let t = &d.library_tree; + let mut ids = HashSet::new(); + t.folders.len() <= MAX_FOLDERS + && t.folders.iter().all(|f| ids.insert(f.id) && clean_name(&f.name).as_deref() == Ok(f.name.as_str()) && f.parent.is_none_or(|p| p != f.id && d.folder(p).is_some())) + && t.folders.iter().all(|f| d.folder_chain(f.id).first().is_some_and(|top| d.folder(*top).is_some_and(|x| x.parent.is_none()))) + && t.placed.iter().all(|(i, f)| d.has_item(*i) && d.folder(*f).is_some()) + }; + for f in &self.library_tree.folders { + *max_id = (*max_id).max(f.id.0); + } + if ok(self) { + return; + } + let mut tree = (*self.library_tree).clone(); + let mut seen = HashSet::new(); + tree.folders.retain(|f| seen.insert(f.id)); + tree.folders.truncate(MAX_FOLDERS); + for (i, f) in tree.folders.iter_mut().enumerate() { + let name: String = f.name.trim().replace('/', "-").chars().take(MAX_NAME_CHARS).collect(); + f.name = if name.is_empty() { format!("Folder {}", i + 1) } else { name }; + } + let ids: HashSet = tree.folders.iter().map(|f| f.id).collect(); + for f in &mut tree.folders { + if f.parent.is_some_and(|p| p == f.id || !ids.contains(&p)) { + f.parent = None; + } + } + // Cycles and over-deep chains: the first folder found on one goes to the top level. + for i in 0..tree.folders.len() { + let Some(start) = tree.folders.get(i).map(|f| f.id) else { continue }; + let mut at = tree.folders.get(i).and_then(|f| f.parent); + let mut steps = 1; + let mut bad = false; + while let Some(p) = at { + steps += 1; + if p == start || steps > MAX_FOLDER_DEPTH { + bad = true; + break; + } + at = tree.folders.iter().find(|f| f.id == p).and_then(|f| f.parent); + } + if bad && let Some(f) = tree.folders.get_mut(i) { + f.parent = None; + } + } + let items: HashSet = self.library_items().collect(); + tree.placed.retain(|i, f| items.contains(i) && ids.contains(f)); + self.library_tree = Arc::new(tree); + } +} + +/// Calls `f` once per Library reference on each keyframe of `tl`: symbol instances, bitmap +/// fills and the keyframe's sound. +pub fn visit_refs(tl: &Timeline, mut f: impl FnMut(LibraryItem)) { + for l in &tl.layers { + for k in &l.keyframes { + for e in &k.elements { + match &e.kind { + ElementKind::Symbol { symbol, .. } => f(LibraryItem::Symbol(*symbol)), + ElementKind::Shape(s) => { + if let Some(Paint::Bitmap { bitmap, .. }) = &s.fill { + f(LibraryItem::Bitmap(*bitmap)); + } + } + ElementKind::Text(_) | ElementKind::Camera => {} + } + } + if let Some(s) = &k.sound { + f(LibraryItem::Sound(s.sound)); + } + } + } +} + +/// `tl` with new layer and element ids from `alloc`, every reference to them (layer parents, +/// motion tween targets, bone ends) following. An element keeps one id across keyframes, as +/// tweens need. +pub fn fresh_ids(tl: &Timeline, alloc: &mut dyn FnMut() -> u64) -> Timeline { + let mut layers: HashMap = HashMap::new(); + let mut elements: HashMap = HashMap::new(); + for l in &tl.layers { + layers.entry(l.id).or_insert_with(|| LayerId(alloc())); + for k in &l.keyframes { + for e in &k.elements { + elements.entry(e.id).or_insert_with(|| ElementId(alloc())); + } + } + } + let el = |id: ElementId| elements.get(&id).copied().unwrap_or(id); + let out = tl + .layers + .iter() + .map(|l| { + let mut l = (**l).clone(); + l.id = layers.get(&l.id).copied().unwrap_or(l.id); + l.parent = l.parent.map(|p| layers.get(&p).copied().unwrap_or(p)); + if let Some(a) = &mut l.armature { + for b in &mut Arc::make_mut(a).bones { + b.parent = el(b.parent); + b.child = el(b.child); + } + } + for k in &mut l.keyframes { + let k = Arc::make_mut(k); + for e in &mut k.elements { + Arc::make_mut(e).id = el(e.id); + } + if let Some(m) = &mut k.motion { + m.target = el(m.target); + } + } + Arc::new(l) + }) + .collect(); + Timeline { layers: out } +} + +#[cfg(test)] +#[path = "library_tests.rs"] +mod tests; diff --git a/crates/doc/src/library_tests.rs b/crates/doc/src/library_tests.rs new file mode 100644 index 00000000..f5a66bbe --- /dev/null +++ b/crates/doc/src/library_tests.rs @@ -0,0 +1,195 @@ +use super::*; +use crate::{Element, Layer, Linkage, Symbol, SymbolKind, sample}; + +fn instance(d: &mut Document, symbol: SymbolId) -> Arc { + Arc::new(Element { + id: ElementId(d.alloc_id()), + name: String::new(), + transform: Default::default(), + color: Default::default(), + kind: ElementKind::Symbol { symbol, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + }) +} + +/// A symbol named `name` holding instances of `inside`. +fn add_symbol(d: &mut Document, name: &str, inside: &[SymbolId]) -> SymbolId { + let id = SymbolId(d.alloc_id()); + let mut layer = Layer::new(LayerId(d.alloc_id()), "Layer 1"); + let els: Vec<_> = inside.iter().map(|s| instance(d, *s)).collect(); + if let Some(k) = layer.keyframe_mut(0) { + k.elements = els; + } + d.library.push(Arc::new(Symbol { id, name: name.into(), kind: SymbolKind::Graphic, linkage: None, timeline: Timeline { layers: vec![Arc::new(layer)] } })); + id +} + +fn sym(d: &Document, name: &str) -> SymbolId { + d.library.iter().find(|s| s.name == name).map(|s| s.id).unwrap_or(SymbolId(0)) +} + +#[test] +fn folders_round_trip_and_older_files_open_without_them() { + let mut d = sample::demo(); + let plain = serde_json::to_string(&d).unwrap(); + assert!(!plain.contains("library_tree"), "a Library without folders writes nothing new"); + let back: Document = serde_json::from_str(&plain).unwrap(); + assert!(back.library_tree.is_empty()); + + let chars = d.ensure_folder_path("Characters/Hero").unwrap(); + let ball = sym(&d, "Ball"); + d.place_entry(LibraryEntry::Item(LibraryItem::Symbol(ball)), Some(chars)); + let json = serde_json::to_string(&d).unwrap(); + assert!(json.contains(&format!("{{\"symbol\":{},\"folder\":{}}}", ball.0, chars.0)), "{json}"); + let mut back: Document = serde_json::from_str(&json).unwrap(); + back.sanitize(); + assert_eq!(back.library_tree, d.library_tree); + assert_eq!(back.entry_path(LibraryEntry::Item(LibraryItem::Symbol(ball))), "Characters/Hero/Ball"); +} + +#[test] +fn folder_paths_are_made_once_and_matched_without_case() { + let mut d = Document::default(); + let a = d.ensure_folder_path("Characters/Hero").unwrap(); + let b = d.ensure_folder_path(" characters / HERO ").unwrap(); + assert_eq!(a, b); + assert_eq!(d.library_tree.folders.len(), 2); + assert_eq!(d.folder_depth(a), 2); + assert_eq!(d.ensure_folder_path(""), None); + assert_eq!(d.ensure_folder_path("//"), None); + let top = d.folder_chain(a)[0]; + assert_eq!(d.folder_height(top), 2); + assert!(d.folder_within(a, top) && !d.folder_within(top, a)); + // Nesting stops at the limit instead of growing without end. + let deep = vec!["x"; MAX_FOLDER_DEPTH + 10].join("/"); + let f = d.ensure_folder_path(&deep).unwrap(); + assert_eq!(d.folder_depth(f), MAX_FOLDER_DEPTH); +} + +#[test] +fn names_are_unique_per_folder_without_case() { + let mut d = sample::demo(); + let f = d.ensure_folder_path("Props").unwrap(); + let ball = LibraryEntry::Item(LibraryItem::Symbol(sym(&d, "Ball"))); + assert_eq!(d.check_name(None, "ball", None), Err(NameError::Taken("ball".into()))); + assert_eq!(d.check_name(None, " Ball ", Some(ball)).as_deref(), Ok("Ball"), "an item may keep its own name"); + assert_eq!(d.check_name(Some(f), "Ball", None).as_deref(), Ok("Ball"), "another folder may hold the same name"); + assert_eq!(d.check_name(None, "a/b", None), Err(NameError::Slash)); + assert_eq!(d.check_name(None, " ", None), Err(NameError::Empty)); + assert_eq!(d.check_name(None, &"x".repeat(MAX_NAME_CHARS + 1), None), Err(NameError::TooLong)); + assert_eq!(d.check_name(None, "props", None), Err(NameError::Taken("props".into())), "folders and items share a folder's names"); + assert_eq!(d.unique_name(None, "Ball"), "Ball 2"); + assert_eq!(d.unique_name(None, "Ball copy"), "Ball copy"); + assert_eq!(d.numbered_name(None, "Symbol", 1), "Symbol 1"); + add_symbol(&mut d, "Symbol 1", &[]); + assert_eq!(d.numbered_name(None, "Symbol", 1), "Symbol 2"); +} + +#[test] +fn damaged_trees_are_repaired_on_load() { + let mut d = sample::demo(); + let ball = LibraryItem::Symbol(sym(&d, "Ball")); + let t = Arc::make_mut(&mut d.library_tree); + let f = |id: u64, name: &str, parent: Option| LibraryFolder { id: FolderId(id), name: name.into(), parent: parent.map(FolderId) }; + t.folders = vec![f(900, "A", Some(901)), f(901, "B", Some(900)), f(902, " ", Some(902)), f(903, "C/D", Some(999)), f(900, "Dup", None)]; + t.placed.insert(ball, FolderId(901)); + t.placed.insert(LibraryItem::Sound(SoundId(12345)), FolderId(900)); + t.placed.insert(LibraryItem::Symbol(SymbolId(77777)), FolderId(900)); + d.sanitize(); + let t = &d.library_tree; + assert_eq!(t.folders.len(), 4, "the duplicate id is dropped"); + assert!(t.folders.iter().all(|f| d.folder_chain(f.id).len() <= 2), "the cycle is broken"); + assert!(t.folders.iter().all(|f| f.parent != Some(f.id) && f.parent.is_none_or(|p| d.folder(p).is_some()))); + assert!(t.folders.iter().all(|f| clean_name(&f.name).is_ok()), "{:?}", t.folders); + assert_eq!(t.placed.len(), 1, "only items that exist stay placed"); + assert!(d.next_id > 903, "folder ids stay unique"); + // A sane tree is left alone (same Arc). + let before = d.library_tree.clone(); + d.sanitize(); + assert!(Arc::ptr_eq(&before, &d.library_tree)); +} + +#[test] +fn uses_count_every_keyframe_and_unused_follows_reachability() { + let mut d = sample::demo(); + let (ball, star) = (sym(&d, "Ball"), sym(&d, "Star")); + let uses = d.library_uses(); + assert!(uses.get(&LibraryItem::Symbol(ball)).copied().unwrap_or(0) > 0); + assert!(uses.get(&LibraryItem::Symbol(star)).copied().unwrap_or(0) > 0); + assert!(d.unused_items().is_empty(), "the sample uses everything"); + + // Inner is used only inside Outer, which nothing places: both are unused, though Inner + // has a use. + let inner = add_symbol(&mut d, "Inner", &[]); + let outer = add_symbol(&mut d, "Outer", &[inner, inner]); + assert_eq!(d.library_uses().get(&LibraryItem::Symbol(inner)), Some(&2)); + assert_eq!(d.unused_items(), vec![LibraryItem::Symbol(inner), LibraryItem::Symbol(outer)]); + // A linkage class makes a symbol reachable (scripts make it by name), and what it holds. + if let Some(s) = d.library.iter_mut().find(|s| s.id == outer) { + Arc::make_mut(s).linkage = Some(Linkage { class: "Outer".into(), base: String::new() }); + } + assert!(d.unused_items().is_empty()); + // Cycles terminate. + let a = add_symbol(&mut d, "A", &[]); + let b = add_symbol(&mut d, "B", &[a]); + if let Some(s) = d.library.iter_mut().find(|s| s.id == a) { + let layer = Arc::make_mut(&mut Arc::make_mut(s).timeline.layers[0]); + let e = Arc::new(Element { id: ElementId(5_000_000), name: String::new(), transform: Default::default(), color: Default::default(), kind: ElementKind::Symbol { symbol: b, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() } }); + layer.keyframe_mut(0).unwrap().elements.push(e); + } + assert_eq!(d.unused_items(), vec![LibraryItem::Symbol(a), LibraryItem::Symbol(b)]); + assert!(d.symbol_contains(a, b) && d.symbol_contains(b, a) && d.symbol_contains(a, a)); + assert!(!d.symbol_contains(inner, outer) && d.symbol_contains(outer, inner)); +} + +#[test] +fn a_duplicate_has_fresh_ids_and_keeps_its_folder() { + let mut d = sample::demo(); + let star = sym(&d, "Star"); + let f = d.ensure_folder_path("FX").unwrap(); + d.place_entry(LibraryEntry::Item(LibraryItem::Symbol(star)), Some(f)); + if let Some(s) = d.library.iter_mut().find(|s| s.id == star) { + Arc::make_mut(s).linkage = Some(Linkage { class: "Star".into(), base: String::new() }); + } + let copy = d.duplicate_symbol(star, "Star copy".into()).unwrap(); + let (a, b) = (d.symbol(star).unwrap(), d.symbol(copy).unwrap()); + assert_eq!(b.name, "Star copy"); + assert_eq!(b.kind, a.kind); + assert!(b.linkage.is_none(), "a class names one symbol"); + assert_eq!(d.parent_of(LibraryEntry::Item(LibraryItem::Symbol(copy))), Some(f)); + let ids = |s: &Symbol| -> HashSet { s.timeline.layers.iter().flat_map(|l| std::iter::once(l.id.0).chain(l.keyframes.iter().flat_map(|k| k.elements.iter().map(|e| e.id.0)))).collect() }; + assert!(ids(a).is_disjoint(&ids(b))); + assert_eq!(ids(a).len(), ids(b).len()); + // Same artwork: only ids differ, and an element keeps one id across its keyframes. + for (la, lb) in a.timeline.layers.iter().zip(&b.timeline.layers) { + assert_eq!(la.keyframes.len(), lb.keyframes.len()); + for (ka, kb) in la.keyframes.iter().zip(&lb.keyframes) { + for (ea, eb) in ka.elements.iter().zip(&kb.elements) { + assert_eq!((&ea.kind, ea.transform), (&eb.kind, eb.transform)); + } + } + let first: Vec = lb.keyframes.iter().filter_map(|k| k.elements.first().map(|e| e.id.0)).collect(); + if first.len() > 1 && la.keyframes.iter().filter_map(|k| k.elements.first().map(|e| e.id.0)).collect::>().len() == 1 { + assert!(first.windows(2).all(|w| w[0] == w[1])); + } + } + let order: Vec = d.library.iter().map(|s| s.id).collect(); + let at = order.iter().position(|s| *s == star).unwrap(); + assert_eq!(order[at + 1], copy, "the copy sits right after its original"); + assert_eq!(d.duplicate_symbol(SymbolId(424242), "x".into()), None); +} + +#[test] +fn folder_contents_reach_every_depth() { + let mut d = sample::demo(); + let a = d.ensure_folder_path("A").unwrap(); + let ab = d.ensure_folder_path("A/B").unwrap(); + let c = d.ensure_folder_path("C").unwrap(); + let ball = LibraryItem::Symbol(sym(&d, "Ball")); + d.place_entry(LibraryEntry::Item(ball), Some(ab)); + let inside = d.folder_contents(a); + assert_eq!(inside, vec![LibraryEntry::Folder(ab), LibraryEntry::Item(ball)]); + assert!(d.folder_contents(c).is_empty()); + assert_eq!(d.library_children(Some(ab)), vec![LibraryEntry::Item(ball)]); + assert!(d.library_children(None).starts_with(&[LibraryEntry::Folder(a), LibraryEntry::Folder(c)])); + assert!(!d.library_children(None).contains(&LibraryEntry::Item(ball))); +} diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 2d94e4c7..4633a16b 100644 --- a/crates/doc/src/sample.rs +++ b/crates/doc/src/sample.rs @@ -41,7 +41,7 @@ fn key(start: u32, duration: u32, elements: Vec>, tween: Option Document { - let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 }; let (w, h) = (1280.0, 720.0); // --- library ------------------------------------------------------------------------- @@ -147,7 +147,7 @@ pub fn demo() -> Document { /// whose last frame traces a line and goes back to the menu. pub fn interactive() -> Document { use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, Target}; - let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 }; const LEN: u32 = 36; let solid = |c: u32| Paint::Solid(Rgba::hex(c)); @@ -211,7 +211,7 @@ pub fn interactive() -> Document { /// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens. /// Every element keeps one `Arc` across its keyframes, as a real tweened shape does. pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document { - let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: 1 }; let (layers, shapes, frames) = (layers.clamp(1, 1000), shapes.clamp(1, 100_000), frames.clamp(1, 10_000)); let mut seed = 0x2545_f491_u32; let mut rnd = move || { diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index bc77a119..3ada0b02 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -245,6 +245,6 @@ pub fn unique_bytes(old: &Document, new: &Document) -> usize { /// Estimated total bytes of a document (as if nothing were shared). Used for reporting. pub fn document_bytes(doc: &Document) -> usize { - let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), document_class: String::new(), next_id: doc.next_id }; + let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), next_id: doc.next_id }; unique_bytes(doc, &empty) } From e6c0f5a91aabe576473a1079cc0339a4ce1dc649 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 20:36:51 -0700 Subject: [PATCH 13/19] feat(engine): library.* folder, rename, move, duplicate, delete and unused commands, element.swap_symbol, smoothing (M2) --- crates/engine/src/cmds_draw.rs | 4 +- crates/engine/src/cmds_library.rs | 396 +++++++++++++++++++++++++++++ crates/engine/src/confirm.rs | 47 ++++ crates/engine/src/lib.rs | 2 + crates/engine/src/library_tests.rs | 269 ++++++++++++++++++++ crates/engine/src/tests.rs | 23 +- 6 files changed, 737 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/cmds_library.rs create mode 100644 crates/engine/src/library_tests.rs diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index b7df7971..6a980d01 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -648,8 +648,8 @@ pub(crate) fn convert_to_symbol(s: &mut Session, p: &Value) -> Result { let Some(&top) = layers.first() else { return Err(EngineError::State("select something to convert".into())); }; - let n = s.doc.library.len() + 1; - let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| format!("Symbol {n}")); + // The next free “Symbol n” at the Library's top level, where new symbols go (ADR 0050). + let name: String = opt_str(p, "name")?.map(|x| x.chars().take(128).collect()).unwrap_or_else(|| s.doc.numbered_name(None, "Symbol", s.doc.library.len() + 1)); let bounds = s.selection_bounds(); let center = if bounds.is_empty() { Vec2::ZERO } else { bounds.center() }; let sym_id = SymbolId(s.doc.alloc_id()); diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs new file mode 100644 index 00000000..9ff8a965 --- /dev/null +++ b/crates/engine/src/cmds_library.rs @@ -0,0 +1,396 @@ +//! Library management (ADR 0050): folders, renaming, moving, duplicating and deleting items, +//! use counts and unused items, bitmap smoothing, and Swap Symbol. +//! +//! An item or folder is named in params as `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}` +//! or `{"folder": id}`. Sorting and filtering the list are views (the shell's); `library.items` +//! gives a script everything it needs to do the same. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::library::{MAX_FOLDER_DEPTH, MAX_FOLDERS}; +use anicraft_doc::{BitmapId, ElementKind, FolderId, LibraryEntry, LibraryFolder, LibraryItem, Paint, SoundId, SymbolId, SymbolKind, Timeline}; +use serde_json::{Value, json}; +use std::collections::HashSet; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c("library.items", "List Library", "", None, "{} every folder (id, name, parent, path) and item (symbol | bitmap | sound id, kind, name, folder, path, uses, unused) in Library order; `uses` counts instances, bitmap fills and keyframe sounds once per keyframe", false, items as crate::RunFn), + c("library.new_folder", "New Folder", "", None, "{name? (default: the next free “Folder n”), parent?: folder id} → {folder, name}; names are unique within a folder (case aside) and can't hold “/”", true, new_folder), + c("library.rename", "Rename", "", None, "{symbol | bitmap | sound | folder: id, name} renames a Library item or folder; the name must be free in its folder (case aside) and can't hold “/”", true, rename), + c("library.move", "Move to Folder", "", None, "{items: [{symbol | bitmap | sound | folder: id}, ..], to: folder id | null (the top level)} moves items and folders (with what they hold) into a folder; a folder can't go inside itself, and a name the folder already has stops the move", true, move_to), + c("library.duplicate", "Duplicate Symbol", "", None, "{symbol, name? (default: “ copy”)} → {symbol, name}: a copy in the same folder, with its own layers and elements and no linkage class", true, duplicate), + c("library.delete", "Delete", "", None, "{items: [{symbol | bitmap | sound | folder: id}, ..]} deletes items and folders with everything in them; instances of deleted symbols, shapes filled with deleted bitmaps and keyframes' deleted sounds go too (asks first when anything deleted is in use or a folder isn't empty)", true, delete), + c("library.unused", "Select Unused Items", "", None, "{} → {items: [..]} the items nothing in the movie reaches: not in a scene, nor inside a symbol that is; symbols with a linkage class count as used", false, unused), + c("library.delete_unused", "Delete Unused Items", "", None, "{} deletes every item `library.unused` lists (asks first)", true, delete_unused), + c("library.set_smoothing", "Allow Smoothing", "", None, "{bitmap, on?: bool (default: toggle)} whether the bitmap is filtered when scaled or turned (off: hard-edged pixels)", true, set_smoothing), + c("element.swap_symbol", "Swap Symbol", "", None, "{symbol} the selected instances show another symbol, keeping their transform, colour effect, blending, filters, looping, actions and instance name", true, |s, p| s.each_layer(false, |s| swap_symbol(s, p))), + ] +} + +/// Most entries one command takes. +const MAX_ENTRIES: usize = 100_000; + +/// The entry a JSON object names: `{"symbol": id}`, `{"bitmap": id}`, `{"sound": id}` or +/// `{"folder": id}`. +pub(crate) fn entry_of(v: &Value) -> Result { + let id = |k: &str| v.get(k).and_then(Value::as_u64); + match (id("symbol"), id("bitmap"), id("sound"), id("folder")) { + (Some(i), None, None, None) => Ok(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(i)))), + (None, Some(i), None, None) => Ok(LibraryEntry::Item(LibraryItem::Bitmap(BitmapId(i)))), + (None, None, Some(i), None) => Ok(LibraryEntry::Item(LibraryItem::Sound(SoundId(i)))), + (None, None, None, Some(i)) => Ok(LibraryEntry::Folder(FolderId(i))), + _ => Err(EngineError::Param("name one Library entry: {\"symbol\" | \"bitmap\" | \"sound\" | \"folder\": id}".into())), + } +} + +/// `entry` as params name it. +pub fn entry_json(e: LibraryEntry) -> Value { + match e { + LibraryEntry::Item(LibraryItem::Symbol(i)) => json!({"symbol": i.0}), + LibraryEntry::Item(LibraryItem::Bitmap(i)) => json!({"bitmap": i.0}), + LibraryEntry::Item(LibraryItem::Sound(i)) => json!({"sound": i.0}), + LibraryEntry::Folder(f) => json!({"folder": f.0}), + } +} + +/// The entries in list `key`, each checked to exist (no repeats). +pub(crate) fn entries_of(s: &Session, p: &Value, key: &str) -> Result> { + let list = p.get(key).and_then(Value::as_array).ok_or_else(|| EngineError::Param(format!("param '{key}' must be a list of Library entries")))?; + if list.len() > MAX_ENTRIES { + return Err(EngineError::Param(format!("at most {MAX_ENTRIES} entries"))); + } + let mut out = Vec::with_capacity(list.len()); + let mut seen = HashSet::new(); + for v in list { + let e = entry_of(v)?; + if !s.doc.has_entry(e) { + return Err(EngineError::State(format!("the Library has no {}", describe(e)))); + } + if seen.insert(e) { + out.push(e); + } + } + Ok(out) +} + +fn describe(e: LibraryEntry) -> String { + match e { + LibraryEntry::Item(LibraryItem::Symbol(i)) => format!("symbol {}", i.0), + LibraryEntry::Item(LibraryItem::Bitmap(i)) => format!("bitmap {}", i.0), + LibraryEntry::Item(LibraryItem::Sound(i)) => format!("sound {}", i.0), + LibraryEntry::Folder(f) => format!("folder {}", f.0), + } +} + +fn opt_folder(s: &Session, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + let id = v.as_u64().map(FolderId).ok_or_else(|| EngineError::Param(format!("param '{key}' must be a folder id or null")))?; + if s.doc.folder(id).is_none() { + return Err(EngineError::State(format!("the Library has no folder {}", id.0))); + } + Ok(Some(id)) + } + } +} + +fn kind_key(k: SymbolKind) -> &'static str { + match k { + SymbolKind::Graphic => "graphic", + SymbolKind::MovieClip => "movie_clip", + SymbolKind::Button => "button", + } +} + +fn items(s: &mut Session, _: &Value) -> Result { + let d = &s.doc; + let uses = d.library_uses(); + let unused: HashSet = d.unused_items().into_iter().collect(); + let folders: Vec = d + .library_tree + .folders + .iter() + .map(|f| json!({"folder": f.id.0, "name": f.name, "parent": f.parent.map(|p| p.0), "path": d.entry_path(LibraryEntry::Folder(f.id))})) + .collect(); + let items: Vec = d + .library_items() + .map(|i| { + let e = LibraryEntry::Item(i); + let mut v = entry_json(e); + v["name"] = json!(d.item_name(i)); + v["folder"] = json!(d.parent_of(e).map(|f| f.0)); + v["path"] = json!(d.entry_path(e)); + v["uses"] = json!(uses.get(&i).copied().unwrap_or(0)); + v["unused"] = json!(unused.contains(&i)); + match i { + LibraryItem::Symbol(id) => { + if let Some(sym) = d.symbol(id) { + v["kind"] = json!(kind_key(sym.kind)); + v["frames"] = json!(sym.timeline.frame_count()); + v["linkage"] = json!(sym.linkage.as_ref().map(|l| &l.class)); + } + } + LibraryItem::Bitmap(id) => { + if let Some(b) = d.bitmap(id) { + v["kind"] = json!("bitmap"); + v["width"] = json!(b.width); + v["height"] = json!(b.height); + v["smoothing"] = json!(b.smoothing); + } + } + LibraryItem::Sound(id) => { + if let Some(x) = d.sound(id) { + v["kind"] = json!("sound"); + v["seconds"] = json!(x.seconds()); + } + } + } + v + }) + .collect(); + Ok(json!({"folders": folders, "items": items, "unused": unused.len()})) +} + +fn new_folder(s: &mut Session, p: &Value) -> Result { + let parent = opt_folder(s, p, "parent")?; + if s.doc.library_tree.folders.len() >= MAX_FOLDERS { + return Err(EngineError::State(format!("the Library holds at most {MAX_FOLDERS} folders"))); + } + if parent.is_some_and(|f| s.doc.folder_depth(f) >= MAX_FOLDER_DEPTH) { + return Err(EngineError::State(format!("folders nest at most {MAX_FOLDER_DEPTH} deep"))); + } + let name = match opt_str(p, "name")? { + Some(n) => s.doc.check_name(parent, n, None).map_err(|e| EngineError::Param(e.to_string()))?, + None => s.doc.numbered_name(parent, "Folder", 1), + }; + let id = FolderId(s.doc.alloc_id()); + Arc::make_mut(&mut s.doc.library_tree).folders.push(LibraryFolder { id, name: name.clone(), parent }); + Ok(json!({"folder": id.0, "name": name})) +} + +fn rename(s: &mut Session, p: &Value) -> Result { + let e = entry_of(p)?; + if !s.doc.has_entry(e) { + return Err(EngineError::State(format!("the Library has no {}", describe(e)))); + } + let name = s.doc.check_name(s.doc.parent_of(e), str_req(p, "name")?, Some(e)).map_err(|err| EngineError::Param(err.to_string()))?; + let d = &mut s.doc; + match e { + LibraryEntry::Item(LibraryItem::Symbol(id)) => { + if let Some(x) = d.library.iter_mut().find(|x| x.id == id) { + Arc::make_mut(x).name = name.clone(); + } + } + LibraryEntry::Item(LibraryItem::Bitmap(id)) => { + if let Some(x) = d.bitmaps.iter_mut().find(|x| x.id == id) { + Arc::make_mut(x).name = name.clone(); + } + } + LibraryEntry::Item(LibraryItem::Sound(id)) => { + if let Some(x) = d.sounds.iter_mut().find(|x| x.id == id) { + Arc::make_mut(x).name = name.clone(); + } + } + LibraryEntry::Folder(id) => { + if let Some(f) = Arc::make_mut(&mut d.library_tree).folders.iter_mut().find(|f| f.id == id) { + f.name = name.clone(); + } + } + } + let mut v = entry_json(e); + v["name"] = json!(name); + Ok(v) +} + +fn move_to(s: &mut Session, p: &Value) -> Result { + let list = entries_of(s, p, "items")?; + if p.get("to").is_none() { + return Err(EngineError::Param("param 'to' is required: a folder id, or null for the top level".into())); + } + let to = opt_folder(s, p, "to")?; + let mut moved = 0; + for e in list { + if s.doc.parent_of(e) == to { + continue; + } + if let LibraryEntry::Folder(f) = e { + if to.is_some_and(|t| s.doc.folder_within(t, f)) { + return Err(EngineError::State(format!("“{}” can't go inside itself", s.doc.entry_name(e).unwrap_or("")))); + } + if to.map_or(0, |t| s.doc.folder_depth(t)) + s.doc.folder_height(f) > MAX_FOLDER_DEPTH { + return Err(EngineError::State(format!("folders nest at most {MAX_FOLDER_DEPTH} deep"))); + } + } + let name = s.doc.entry_name(e).unwrap_or("").to_string(); + if s.doc.name_taken(to, &name, Some(e)) { + let place = to.and_then(|t| s.doc.folder(t)).map_or_else(|| "The top level of the Library".to_string(), |f| format!("“{}”", f.name)); + return Err(EngineError::State(format!("{place} already has an item named “{name}”; rename one of them first"))); + } + s.doc.place_entry(e, to); + moved += 1; + } + Ok(json!({"moved": moved, "to": to.map(|f| f.0)})) +} + +fn duplicate(s: &mut Session, p: &Value) -> Result { + let id = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?); + let Some(src) = s.doc.symbol(id) else { + return Err(EngineError::State(format!("no symbol with id {}", id.0))); + }; + let parent = s.doc.parent_of(LibraryEntry::Item(LibraryItem::Symbol(id))); + let name = match opt_str(p, "name")? { + Some(n) => s.doc.check_name(parent, n, None).map_err(|e| EngineError::Param(e.to_string()))?, + None => s.doc.unique_name(parent, &format!("{} copy", src.name)), + }; + let copy = s.doc.duplicate_symbol(id, name.clone()).ok_or_else(|| EngineError::State(format!("no symbol with id {}", id.0)))?; + Ok(json!({"symbol": copy.0, "name": name})) +} + +/// What deleting `entries` takes: the items (folders expanded into what they hold) and the +/// folders. +pub(crate) fn deletion(s: &Session, entries: &[LibraryEntry]) -> (Vec, Vec) { + let mut items: Vec = Vec::new(); + let mut folders: Vec = Vec::new(); + let add = |e: LibraryEntry, items: &mut Vec, folders: &mut Vec| match e { + LibraryEntry::Item(i) if !items.contains(&i) => items.push(i), + LibraryEntry::Folder(f) if !folders.contains(&f) => folders.push(f), + _ => {} + }; + for &e in entries { + add(e, &mut items, &mut folders); + if let LibraryEntry::Folder(f) = e { + for inner in s.doc.folder_contents(f) { + add(inner, &mut items, &mut folders); + } + } + } + (items, folders) +} + +/// Takes every reference to `gone` off `tl` (instances, bitmap-filled shapes, keyframe sounds), +/// un-sharing only the layers and keyframes that had one. How many references went. +fn strip(tl: &mut Timeline, gone: &HashSet) -> usize { + let refers = |e: &anicraft_doc::Element| match &e.kind { + ElementKind::Symbol { symbol, .. } => gone.contains(&LibraryItem::Symbol(*symbol)), + ElementKind::Shape(sh) => matches!(&sh.fill, Some(Paint::Bitmap { bitmap, .. }) if gone.contains(&LibraryItem::Bitmap(*bitmap))), + ElementKind::Text(_) | ElementKind::Camera => false, + }; + let sounds = |k: &anicraft_doc::Keyframe| k.sound.as_ref().is_some_and(|f| gone.contains(&LibraryItem::Sound(f.sound))); + let hit = |k: &anicraft_doc::Keyframe| sounds(k) || k.elements.iter().any(|e| refers(e)); + let mut n = 0; + for l in tl.layers.iter_mut().filter(|l| l.keyframes.iter().any(|k| hit(k))) { + for k in Arc::make_mut(l).keyframes.iter_mut().filter(|k| hit(k)) { + let k = Arc::make_mut(k); + if sounds(k) { + k.sound = None; + n += 1; + } + let before = k.elements.len(); + k.elements.retain(|e| !refers(e)); + n += before - k.elements.len(); + } + } + n +} + +/// Deletes `items` and `folders` from the Library and every use of the items from the movie. +fn remove(s: &mut Session, items: &[LibraryItem], folders: &[FolderId]) -> Value { + let gone: HashSet = items.iter().copied().collect(); + let mut uses = 0; + if !gone.is_empty() { + for scene in &mut s.doc.scenes { + if strip_needed(&scene.timeline, &gone) { + uses += strip(&mut Arc::make_mut(scene).timeline, &gone); + } + } + s.doc.library.retain(|x| !gone.contains(&LibraryItem::Symbol(x.id))); + s.doc.bitmaps.retain(|x| !gone.contains(&LibraryItem::Bitmap(x.id))); + s.doc.sounds.retain(|x| !gone.contains(&LibraryItem::Sound(x.id))); + for sym in &mut s.doc.library { + if strip_needed(&sym.timeline, &gone) { + uses += strip(&mut Arc::make_mut(sym).timeline, &gone); + } + } + // The fill swatch may hold a deleted bitmap (picked with the Eyedropper). + if let Some(Paint::Bitmap { bitmap, .. }) = &s.style.fill_paint + && gone.contains(&LibraryItem::Bitmap(*bitmap)) + { + s.style.fill_paint = None; + } + } + let dead: HashSet = folders.iter().copied().collect(); + if !dead.is_empty() || s.doc.library_tree.placed.keys().any(|i| gone.contains(i)) { + let t = Arc::make_mut(&mut s.doc.library_tree); + t.placed.retain(|i, f| !gone.contains(i) && !dead.contains(f)); + t.folders.retain(|f| !dead.contains(&f.id)); + // A folder whose parent went (it was named on its own) goes to the top level. + let ids: HashSet = t.folders.iter().map(|f| f.id).collect(); + for f in &mut t.folders { + if f.parent.is_some_and(|p| !ids.contains(&p)) { + f.parent = None; + } + } + } + json!({"deleted": items.len(), "folders": folders.len(), "uses": uses}) +} + +fn strip_needed(tl: &Timeline, gone: &HashSet) -> bool { + let mut any = false; + anicraft_doc::library::visit_refs(tl, |i| any |= gone.contains(&i)); + any +} + +fn delete(s: &mut Session, p: &Value) -> Result { + let list = entries_of(s, p, "items")?; + if list.is_empty() { + return Err(EngineError::State("nothing to delete".into())); + } + let (items, folders) = deletion(s, &list); + Ok(remove(s, &items, &folders)) +} + +fn unused(s: &mut Session, _: &Value) -> Result { + let list: Vec = s.doc.unused_items().into_iter().map(|i| entry_json(LibraryEntry::Item(i))).collect(); + Ok(json!({"items": list})) +} + +fn delete_unused(s: &mut Session, _: &Value) -> Result { + let items = s.doc.unused_items(); + Ok(remove(s, &items, &[])) +} + +fn set_smoothing(s: &mut Session, p: &Value) -> Result { + let id = BitmapId(opt_u64(p, "bitmap")?.ok_or_else(|| EngineError::Param("param 'bitmap' is required".into()))?); + let on = opt_bool(p, "on")?; + let b = s.doc.bitmaps.iter_mut().find(|b| b.id == id).ok_or_else(|| EngineError::State(format!("no bitmap with id {}", id.0)))?; + let on = on.unwrap_or(!b.smoothing); + if b.smoothing != on { + Arc::make_mut(b).smoothing = on; + } + Ok(json!({"bitmap": id.0, "smoothing": on})) +} + +fn swap_symbol(s: &mut Session, p: &Value) -> Result { + let to = SymbolId(opt_u64(p, "symbol")?.ok_or_else(|| EngineError::Param("param 'symbol' is required".into()))?); + if s.doc.symbol(to).is_none() { + return Err(EngineError::State(format!("no symbol with id {}", to.0))); + } + let mut swapped = 0; + for e in s.selected_elements_mut()? { + if let ElementKind::Symbol { symbol, .. } = &mut e.kind { + *symbol = to; + swapped += 1; + } + } + if swapped == 0 { + return Err(EngineError::State("select a symbol instance to swap".into())); + } + Ok(json!({"swapped": swapped, "symbol": to.0})) +} + +#[cfg(test)] +#[path = "library_tests.rs"] +mod tests; diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 66410e71..57de4cc9 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -144,6 +144,53 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: false, }) } + "library.delete" => { + // Routine when nothing deleted is in use and no folder holds anything (undo is there); + // asks when instances go with it or a folder takes its contents (ADR 0050). + let list = crate::cmds_library::entries_of(s, p, "items").ok()?; + let (items, folders) = crate::cmds_library::deletion(s, &list); + let uses = s.doc.library_uses(); + let used: Vec<&anicraft_doc::LibraryItem> = items.iter().filter(|i| uses.get(i).is_some_and(|n| *n > 0)).collect(); + let n_uses: usize = used.iter().filter_map(|i| uses.get(*i)).sum(); + let inside = items.len() + folders.len() - list.len(); + if used.is_empty() && inside == 0 { + return None; + } + let what = match list.as_slice() { + [one] => format!("“{}”", s.doc.entry_name(*one).unwrap_or("")), + _ => plural(list.len(), "item"), + }; + let mut parts = Vec::new(); + if inside > 0 { + parts.push(format!("{what} {} {}, deleted with {}.", if list.len() == 1 { "holds" } else { "hold" }, plural(inside, "item"), if list.len() == 1 { "it" } else { "them" })); + } + if !used.is_empty() { + parts.push(format!("{} used {} in the movie; {} go too.", if used.len() == 1 { "One of them is".to_string() } else { format!("{} of them are", used.len()) }, plural(n_uses, "time"), if n_uses == 1 { "that use" } else { "those uses" })); + } + parts.push("You can undo this.".into()); + Some(Confirmation { + title: if inside > 0 && list.len() == 1 { "Delete folder?".into() } else { "Delete from Library?".into() }, + message: parts.join(" "), + action: "Delete".into(), + irreversible: false, + }) + } + "library.delete_unused" => { + let unused = s.doc.unused_items(); + let names: Vec = unused.iter().take(5).filter_map(|i| s.doc.item_name(*i)).map(|n| format!("“{n}”")).collect(); + let more = unused.len().saturating_sub(names.len()); + (!unused.is_empty()).then(|| Confirmation { + title: "Delete unused items?".into(), + message: format!( + "Nothing in the movie uses {}: {}{}. They leave the Library. You can undo this.", + if unused.len() == 1 { "this item".to_string() } else { format!("these {} items", unused.len()) }, + names.join(", "), + if more > 0 { format!(" and {more} more") } else { String::new() } + ), + action: "Delete Unused".into(), + irreversible: false, + }) + } "draw.erase_all" => { // Double-clicking the Eraser: everything on the stage at this frame (ADR 0034). let layers = crate::cmds_erase::erasable_layers(s); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 399dc279..1ff53205 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ mod cmds_frames; mod cmds_modify; mod cmds_motion; mod cmds_hints; +pub mod cmds_library; mod cmds_paint; mod cmds_path; pub mod cmds_raw; @@ -116,6 +117,7 @@ pub fn commands() -> Vec { v.extend(cmds_frames::specs()); v.extend(onion::specs()); v.extend(cmds_draw::specs()); + v.extend(cmds_library::specs()); v.extend(merge::specs()); v.extend(cmds_modify::specs()); v.extend(cmds_path::specs()); diff --git a/crates/engine/src/library_tests.rs b/crates/engine/src/library_tests.rs new file mode 100644 index 00000000..89e7d9d3 --- /dev/null +++ b/crates/engine/src/library_tests.rs @@ -0,0 +1,269 @@ +//! Library management end to end (ADR 0050): folders, names, moves, duplicates, Swap Symbol, +//! deletion with its confirmations, unused items, smoothing, the file format and undo. + +use crate::Session; +use anicraft_doc::{BitmapId, ElementKind, FolderId, LibraryEntry, LibraryItem, SymbolId, sample}; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn err(s: &mut Session, id: &str, p: Value) -> String { + match s.execute(id, &p) { + Ok(v) => panic!("{id} {p} should fail, gave {v}"), + Err(e) => e.to_string(), + } +} + +fn sym(s: &Session, name: &str) -> u64 { + s.doc.library.iter().find(|x| x.name == name).map(|x| x.id.0).unwrap_or_else(|| panic!("no symbol {name}")) +} + +fn folder(v: &Value) -> u64 { + v["folder"].as_u64().unwrap() +} + +fn path(s: &Session, symbol: u64) -> String { + s.doc.entry_path(LibraryEntry::Item(LibraryItem::Symbol(SymbolId(symbol)))) +} + +/// Instances of `symbol` on every timeline. +fn instances(s: &Session, symbol: u64) -> usize { + s.doc.timelines().flat_map(|t| &t.layers).flat_map(|l| &l.keyframes).flat_map(|k| &k.elements).filter(|e| matches!(e.kind, ElementKind::Symbol { symbol: x, .. } if x.0 == symbol)).count() +} + +#[test] +fn folders_are_made_named_and_nested() { + let mut s = Session::new(sample::demo()); + let a = run(&mut s, "library.new_folder", json!({})); + assert_eq!(a["name"], "Folder 1"); + let b = run(&mut s, "library.new_folder", json!({})); + assert_eq!(b["name"], "Folder 2"); + let inner = run(&mut s, "library.new_folder", json!({"name": "Hero", "parent": folder(&a)})); + assert_eq!(s.doc.entry_path(LibraryEntry::Folder(FolderId(folder(&inner)))), "Folder 1/Hero"); + // Names: unique per folder without case, no slashes, not empty. + assert!(err(&mut s, "library.new_folder", json!({"name": "folder 1"})).contains("already has")); + assert!(err(&mut s, "library.new_folder", json!({"name": "a/b"})).contains("/")); + assert!(err(&mut s, "library.new_folder", json!({"name": " "})).contains("empty")); + assert!(err(&mut s, "library.new_folder", json!({"parent": 999_999})).contains("no folder")); + run(&mut s, "library.new_folder", json!({"name": "Hero"})); + // Renaming. + run(&mut s, "library.rename", json!({"folder": folder(&a), "name": "Characters"})); + assert_eq!(s.doc.folder(FolderId(folder(&a))).unwrap().name, "Characters"); + let ball = sym(&s, "Ball"); + assert!(err(&mut s, "library.rename", json!({"symbol": ball, "name": "star"})).contains("already has")); + run(&mut s, "library.rename", json!({"symbol": ball, "name": "BALL"})); + run(&mut s, "library.rename", json!({"symbol": ball, "name": "Ball"})); + assert!(err(&mut s, "library.rename", json!({"symbol": ball, "folder": 1, "name": "x"})).contains("one Library entry")); + // One undo step each. + s.undo().unwrap(); + assert_eq!(s.doc.symbol(SymbolId(ball)).unwrap().name, "BALL"); +} + +#[test] +fn items_move_in_and_out_of_folders() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + let chars = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"}))); + let hero = folder(&run(&mut s, "library.new_folder", json!({"name": "Hero", "parent": chars}))); + let v = run(&mut s, "library.move", json!({"items": [{"symbol": ball}, {"symbol": star}], "to": hero})); + assert_eq!(v["moved"], 2); + assert_eq!(path(&s, ball), "Characters/Hero/Ball"); + // Out again, one step for the whole move. + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": null})); + assert_eq!(path(&s, ball), "Ball"); + s.undo().unwrap(); + assert_eq!(path(&s, ball), "Characters/Hero/Ball"); + // A folder moves with what it holds, but never into itself. + let props = folder(&run(&mut s, "library.new_folder", json!({"name": "Props"}))); + run(&mut s, "library.move", json!({"items": [{"folder": hero}], "to": props})); + assert_eq!(path(&s, star), "Props/Hero/Star"); + assert!(err(&mut s, "library.move", json!({"items": [{"folder": props}], "to": hero})).contains("inside itself")); + assert!(err(&mut s, "library.move", json!({"items": [{"folder": props}], "to": props})).contains("inside itself")); + // A name clash stops the move and leaves everything where it was. + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": null})); + let star2 = run(&mut s, "library.duplicate", json!({"symbol": star, "name": "Ball"})); + let before = s.doc.library_tree.clone(); + let e = err(&mut s, "library.move", json!({"items": [{"symbol": star}, {"symbol": star2["symbol"]}], "to": null})); + assert!(e.contains("already has an item named “Ball”"), "{e}"); + assert_eq!(s.doc.library_tree, before); + assert!(err(&mut s, "library.move", json!({"items": [{"symbol": ball}]})).contains("'to'")); + assert!(err(&mut s, "library.move", json!({"items": [{"symbol": 424_242}], "to": null})).contains("no symbol")); +} + +#[test] +fn folders_survive_save_and_open() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"}))); + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = Session::new(crate::format::from_json(&text).unwrap()); + assert_eq!(path(&back, ball), "Characters/Ball"); + assert_eq!(back.doc.library_tree, s.doc.library_tree); + assert!(back.doc.next_id > f); +} + +#[test] +fn duplicates_are_named_after_their_original() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Props"}))); + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f})); + let a = run(&mut s, "library.duplicate", json!({"symbol": ball})); + assert_eq!(a["name"], "Ball copy"); + let b = run(&mut s, "library.duplicate", json!({"symbol": ball})); + assert_eq!(b["name"], "Ball copy 2"); + assert_eq!(path(&s, a["symbol"].as_u64().unwrap()), "Props/Ball copy"); + assert!(err(&mut s, "library.duplicate", json!({"symbol": ball, "name": "ball COPY"})).contains("already has")); + assert!(err(&mut s, "library.duplicate", json!({"symbol": 424_242})).contains("no symbol")); + assert_eq!(instances(&s, a["symbol"].as_u64().unwrap()), 0, "a copy isn't placed"); + s.undo().unwrap(); + assert!(s.doc.symbol(SymbolId(b["symbol"].as_u64().unwrap())).is_none()); +} + +#[test] +fn swap_symbol_keeps_everything_but_the_symbol() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + let el = run(&mut s, "library.place", json!({"symbol": ball, "x": 100, "y": 50}))["element"].as_u64().unwrap(); + run(&mut s, "symbol.set_kind", json!({"symbol": ball, "kind": "movie_clip"})); + run(&mut s, "element.set_transform", json!({"sx": 2, "rotation": 30})); + run(&mut s, "element.set_alpha", json!({"alpha": 0.5})); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "blur"}]})); + run(&mut s, "element.rename", json!({"name": "hero"})); + let find = |s: &Session| s.elements_on(s.layer).iter().find(|e| e.id.0 == el).map(|e| (**e).clone()).unwrap(); + let before = find(&s); + let v = run(&mut s, "element.swap_symbol", json!({"symbol": star})); + assert_eq!(v["swapped"], 1); + let after = find(&s); + assert_eq!((after.transform, after.color, &after.name), (before.transform, before.color, &before.name)); + match (&before.kind, &after.kind) { + (ElementKind::Symbol { symbol: a, loop_mode: la, filters: fa, blend: ba, .. }, ElementKind::Symbol { symbol: b, loop_mode: lb, filters: fb, blend: bb, .. }) => { + assert_eq!((a.0, b.0), (ball, star)); + assert_eq!((la, fa, ba), (lb, fb, bb)); + } + _ => panic!("still an instance"), + } + assert_eq!(s.selection.on(s.layer).first().map(|e| e.0), Some(el), "it stays selected"); + assert!(err(&mut s, "element.swap_symbol", json!({"symbol": 424_242})).contains("no symbol")); + assert!(err(&mut s, "element.swap_symbol", json!({})).contains("'symbol'")); + run(&mut s, "edit.deselect", json!({})); + assert!(s.execute("element.swap_symbol", &json!({"symbol": ball})).is_err(), "nothing selected"); + s.undo().unwrap(); + assert!(matches!(find(&s).kind, ElementKind::Symbol { symbol, .. } if symbol.0 == ball)); +} + +#[test] +fn deleting_asks_when_it_takes_uses_or_folder_contents() { + let mut s = Session::new(sample::demo()); + let (ball, star) = (sym(&s, "Ball"), sym(&s, "Star")); + assert!(instances(&s, star) > 0, "the sample places Star (inside Ball too)"); + // An unused item goes without asking. + let copy = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap(); + let p = json!({"items": [{"symbol": copy}]}); + assert!(s.confirmation("library.delete", &p).is_none()); + run(&mut s, "library.delete", p); + assert!(s.doc.symbol(SymbolId(copy)).is_none()); + // A used one asks (undoable tier), and its instances go everywhere, inside symbols too. + let p = json!({"items": [{"symbol": star}]}); + let c = s.confirmation("library.delete", &p).expect("asks"); + assert!(!c.irreversible && c.message.contains("used") && c.message.contains("undo"), "{c:?}"); + run(&mut s, "library.delete", p); + assert_eq!(instances(&s, star), 0); + assert!(s.doc.symbol(SymbolId(ball)).is_some()); + s.undo().unwrap(); + assert!(instances(&s, star) > 0); + // A folder that holds items asks, and takes them with it. + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Old"}))); + let inner = folder(&run(&mut s, "library.new_folder", json!({"name": "Older", "parent": f}))); + let spare = run(&mut s, "library.duplicate", json!({"symbol": ball}))["symbol"].as_u64().unwrap(); + run(&mut s, "library.move", json!({"items": [{"symbol": spare}], "to": inner})); + let p = json!({"items": [{"folder": f}]}); + let c = s.confirmation("library.delete", &p).expect("asks"); + assert!(c.title.contains("folder") && c.message.contains("holds 2 items"), "{c:?}"); + let v = run(&mut s, "library.delete", p); + assert_eq!((v["deleted"].as_u64(), v["folders"].as_u64()), (Some(1), Some(2))); + assert!(s.doc.library_tree.is_empty() && s.doc.symbol(SymbolId(spare)).is_none()); + // An empty folder goes without asking. + let empty = folder(&run(&mut s, "library.new_folder", json!({}))); + assert!(s.confirmation("library.delete", &json!({"items": [{"folder": empty}]})).is_none()); + assert!(err(&mut s, "library.delete", json!({"items": []})).contains("nothing")); + assert!(err(&mut s, "library.delete", json!({"items": [{"folder": 1}]})).contains("no folder")); +} + +#[test] +fn deleting_a_bitmap_or_a_sound_takes_its_uses() { + let mut s = Session::new(sample::demo()); + let id = BitmapId(s.doc.alloc_id()); + let mut px = Vec::new(); + for _ in 0..4 { + px.extend_from_slice(&[255, 0, 0, 255]); + } + let bytes = anicraft_render::encode_png(2, 2, &px).unwrap(); + s.doc.bitmaps.push(Arc::new(anicraft_doc::Bitmap::from_png(id, "red.png", bytes).unwrap())); + let el = run(&mut s, "library.place", json!({"bitmap": id.0}))["element"].as_u64().unwrap(); + let item = LibraryItem::Bitmap(id); + assert_eq!(s.doc.library_uses().get(&item), Some(&1)); + // Smoothing toggles, is one undo step, and is kept by the file. + assert_eq!(run(&mut s, "library.set_smoothing", json!({"bitmap": id.0}))["smoothing"], false); + let back = crate::format::from_json(&crate::format::to_json(&s.doc).unwrap()).unwrap(); + assert!(!back.bitmap(id).unwrap().smoothing); + s.undo().unwrap(); + assert!(s.doc.bitmap(id).unwrap().smoothing); + assert!(!crate::format::to_json(&s.doc).unwrap().contains("smoothing"), "the default is written as nothing"); + run(&mut s, "library.delete", json!({"items": [{"bitmap": id.0}]})); + assert!(s.doc.bitmap(id).is_none()); + assert!(s.elements_on(s.layer).iter().all(|e| e.id.0 != el), "the placed bitmap goes with it"); + assert!(err(&mut s, "library.set_smoothing", json!({"bitmap": id.0})).contains("no bitmap")); +} + +#[test] +fn unused_items_are_listed_and_deleted_after_asking() { + let mut s = Session::new(sample::demo()); + let star = sym(&s, "Star"); + assert_eq!(run(&mut s, "library.unused", json!({}))["items"], json!([])); + assert!(s.confirmation("library.delete_unused", &json!({})).is_none()); + let a = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap(); + let b = run(&mut s, "library.duplicate", json!({"symbol": star}))["symbol"].as_u64().unwrap(); + // In Library order: each copy sits right after its original, so the later one comes first. + assert_eq!(run(&mut s, "library.unused", json!({}))["items"], json!([{"symbol": b}, {"symbol": a}])); + let c = s.confirmation("library.delete_unused", &json!({})).expect("asks"); + assert!(c.message.contains("these 2 items") && c.message.contains("Star copy"), "{c:?}"); + let v = run(&mut s, "library.delete_unused", json!({})); + assert_eq!(v["deleted"], 2); + assert!(s.doc.symbol(SymbolId(a)).is_none() && s.doc.symbol(SymbolId(star)).is_some()); + s.undo().unwrap(); + assert!(s.doc.symbol(SymbolId(a)).is_some()); +} + +#[test] +fn the_listing_has_paths_kinds_and_uses() { + let mut s = Session::new(sample::demo()); + let ball = sym(&s, "Ball"); + let f = folder(&run(&mut s, "library.new_folder", json!({"name": "Characters"}))); + run(&mut s, "library.move", json!({"items": [{"symbol": ball}], "to": f})); + let v = run(&mut s, "library.items", json!({})); + assert_eq!(v["folders"], json!([{"folder": f, "name": "Characters", "parent": null, "path": "Characters"}])); + let b = v["items"].as_array().unwrap().iter().find(|i| i["symbol"] == ball).unwrap(); + assert_eq!((b["path"].as_str(), b["folder"].as_u64(), b["kind"].as_str(), b["unused"].as_bool()), (Some("Characters/Ball"), Some(f), Some("graphic"), Some(false))); + assert!(b["uses"].as_u64().unwrap() > 0); + assert_eq!(v["unused"], 0); +} + +#[test] +fn convert_to_symbol_picks_a_free_name() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + let first = run(&mut s, "modify.convert_to_symbol", json!({})); + assert_eq!(first["name"], "Symbol 1"); + run(&mut s, "library.rename", json!({"symbol": first["symbol"], "name": "Symbol 2"})); + run(&mut s, "draw.rect", json!({"x": 20, "y": 0, "w": 10, "h": 10})); + let second = run(&mut s, "modify.convert_to_symbol", json!({})); + assert_eq!(second["name"], "Symbol 3", "“Symbol 2” is taken"); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c85b61fb..fe754a44 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -513,7 +513,7 @@ fn save_load_round_trip() { /// Adversarial params for every command: must return Ok or Err, never panic. #[test] fn panic_hunt_every_command() { - let hostile: Vec = vec![ + let mut hostile: Vec = vec![ Value::Null, json!({}), json!([]), @@ -691,7 +691,22 @@ fn panic_hunt_every_command() { in_symbol.execute(id, &p).unwrap(); } assert_eq!(in_symbol.editing.len(), 1, "the fuzz starts inside a symbol"); - for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol] { + // Library folders, nested, with items in them (ADR 0050); the fuzz moves, renames and + // deletes them, folders into themselves, names that clash or hold a slash. + let mut library = Session::new(sample::demo()); + let outer = library.execute("library.new_folder", &json!({"name": "Characters"})).unwrap()["folder"].as_u64().unwrap(); + let inner = library.execute("library.new_folder", &json!({"name": "Hero", "parent": outer})).unwrap()["folder"].as_u64().unwrap(); + let ball = library.doc.library.first().map(|x| x.id.0).unwrap(); + library.execute("library.move", &json!({"items": [{"symbol": ball}], "to": inner})).unwrap(); + library.execute("library.duplicate", &json!({"symbol": ball})).unwrap(); + hostile.extend([ + json!({"items": [{"folder": outer}], "to": inner, "folder": outer, "name": "Hero", "parent": inner, "confirm": true}), + json!({"items": [{"folder": inner}, {"symbol": ball}, {"folder": inner}], "to": null, "folder": inner, "name": "a/b", "symbol": ball}), + json!({"items": [{"symbol": ball, "folder": outer}, "x", {"sound": u64::MAX}], "to": u64::MAX, "parent": "x", "name": " "}), + json!({"items": (0..200).map(|i| json!({"folder": i})).collect::>(), "to": outer, "symbol": ball, "name": "x".repeat(300), "on": "x", "bitmap": 1}), + json!({"items": [{"symbol": ball}], "to": outer, "symbol": ball, "name": "Ball copy", "confirm": true}), + ]); + for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, layered, in_symbol, library] { let mut s = start; for spec in commands().iter().filter(|c| !skip(c.id)) { for p in &hostile { @@ -713,6 +728,10 @@ fn panic_hunt_every_command() { let voices = anicraft_doc::sound::voices(&s.doc, 8000); let mut out = vec![0.0; 2 * 4096]; anicraft_doc::audio::mix(&voices, 8000, Default::default(), 0, &mut out); + // ...and its Library tree stays whole: nothing a load would have to repair. + let mut loaded = s.doc.clone(); + loaded.sanitize(); + assert_eq!(loaded.library_tree, s.doc.library_tree); } } From 18b07fffe0424f38cb424a27b1a1176276350ce4 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:41:49 -0700 Subject: [PATCH 14/19] feat(render): bitmaps without Allow Smoothing keep hard pixel edges in the oracle, the GPU stage, SVG and HTML (M2) --- crates/doc/src/eval.rs | 8 ++++++ crates/gpu/src/binning.rs | 7 ++--- crates/gpu/src/fine.wgsl | 10 +++++-- crates/gpu/src/lib.rs | 1 + crates/gpu/src/tests.rs | 7 +++++ crates/render/src/html.rs | 3 +++ crates/render/src/html/canvas.js | 4 +++ crates/render/src/html_tests.rs | 9 +++++++ crates/render/src/lib.rs | 3 ++- crates/render/src/paint.rs | 46 +++++++++++++++++++++++++++----- crates/render/src/svg.rs | 20 ++++++++------ 11 files changed, 97 insertions(+), 21 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 9fbf3a82..a543eb38 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -37,6 +37,9 @@ pub struct DisplayItem { pub group: Option, /// The decoded pixels a [`Paint::Bitmap`] fill shows (shared, never copied). pub image: Option>, + /// Whether `image` is filtered between its pixels (the bitmap's Allow Smoothing, ADR 0050); + /// off, each pixel is a hard-edged square. + pub smooth: bool, } /// Back-to-front list of shapes. @@ -440,6 +443,10 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).and_then(crate::Bitmap::pixels), _ => None, }, + smooth: match &s.fill { + Some(Paint::Bitmap { bitmap, .. }) => doc.bitmap(*bitmap).is_none_or(|b| b.smoothing), + _ => true, + }, }), ElementKind::Text(t) => out.items.push(DisplayItem { path: t.outline.clone(), @@ -456,6 +463,7 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut guide, group: cx.group, image: None, + smooth: true, }), ElementKind::Camera => {} ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => { diff --git a/crates/gpu/src/binning.rs b/crates/gpu/src/binning.rs index c944a57d..be61e540 100644 --- a/crates/gpu/src/binning.rs +++ b/crates/gpu/src/binning.rs @@ -336,8 +336,8 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result let m = inv.m; (RADIAL, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]]) } - // The oracle's bilinear sample of a bitmap (crates/render/src/paint.rs › sample). - (Shader::Bitmap { inv, pixels, repeat, fx }, _) => { + // The oracle's sample of a bitmap (crates/render/src/paint.rs › sample). + (Shader::Bitmap { inv, pixels, repeat, fx, smooth }, _) => { if pixels.width == 0 || pixels.height == 0 { (SOLID, [[0.0; 4]; 4]) } else { @@ -351,7 +351,8 @@ pub fn bin(scene: &Scene, width: u32, height: u32) -> Result }; let m = inv.m; let (k, alpha, tint, keep) = colour_effect(fx); - (BITMAP, [[u(slot as u32), u(u32::from(*repeat)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], k, alpha], [tint[0], tint[1], tint[2], u(keep)]]) + // Bit 0: repeat; bit 1: the nearest pixel instead of bilinear (no smoothing). + (BITMAP, [[u(slot as u32), u(u32::from(*repeat) | (u32::from(!*smooth) << 1)), u(pixels.width), u(pixels.height)], [m[0], m[1], m[2], m[3]], [m[4], m[5], k, alpha], [tint[0], tint[1], tint[2], u(keep)]]) } } // `prepare_scene` never hands these over; draw nothing rather than guess. diff --git a/crates/gpu/src/fine.wgsl b/crates/gpu/src/fine.wgsl index 60ead56f..a9f40943 100644 --- a/crates/gpu/src/fine.wgsl +++ b/crates/gpu/src/fine.wgsl @@ -160,14 +160,17 @@ fn rem_euclid(u: f32, n: f32) -> f32 { return select(r, r + n, r < 0.0); } -// The oracle's bilinear sample of a bitmap at pixel centre `p` (paint.rs › sample). +// The oracle's sample of a bitmap at pixel centre `p` (paint.rs › sample): bilinear, or the +// pixel `p` falls in when the bitmap doesn't allow smoothing (flag bit 1). fn bitmap(base: u32, p: vec2) -> vec4 { let h0 = paints[base]; let m = paints[base + 1u]; let n = paints[base + 2u]; let tint = paints[base + 3u]; let slot = bitcast(h0.x); - let repeat = bitcast(h0.y) != 0u; + let flags = bitcast(h0.y); + let repeat = (flags & 1u) != 0u; + let nearest = (flags & 2u) != 0u; let size = vec2(i32(bitcast(h0.z)), i32(bitcast(h0.w))); let w = f32(size.x); let h = f32(size.y); @@ -182,6 +185,9 @@ fn bitmap(base: u32, p: vec2) -> vec4 { } else if u < 0.0 || v < 0.0 || u >= w || v >= h { return vec4(0.0); } + if nearest { + return tap(slot, i32(floor(u)), i32(floor(v)), size, repeat, n, tint); + } let fx_ = u - 0.5; let fy_ = v - 0.5; let x0 = floor(fx_); diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index ce7251c2..4d814c63 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -376,6 +376,7 @@ impl GpuRenderer { guide: false, group: None, image: None, + smooth: true, }; let solid = |x: f32, c: Rgba| item(Path::rect(x, 2.0, 8.0, 16.0), Paint::Solid(c)); let mut bitmap = item(Path::rect(2.0, 18.0, 20.0, 2.0), Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: true, matrix: Affine::scale(3.0, 1.0) }); diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 005fcf68..f59b0a6a 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -31,6 +31,7 @@ fn item(path: Path, fill: Paint) -> DisplayItem { guide: false, group: None, image: None, + smooth: true, } } @@ -734,6 +735,12 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0); let dl = DisplayList { items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] }; out.push(("bitmap masked and multiplied", dl, view(80, 60, white))); + // Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated. + let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned); + hard.smooth = false; + let mut hard_tiled = bitmap_item(Path::ellipse(50.0, 40.0, 45.0, 35.0), &c, true, Affine::scale(4.0, 3.0)); + hard_tiled.smooth = false; + out.push(("bitmaps without smoothing", list(vec![hard_tiled, hard]), view(100, 80, white))); out } diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index d8716d93..21cb4b25 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -354,6 +354,9 @@ impl<'a> Bake<'a> { self.images.push(format!("data:image/png;base64,{}", base64_encode(&b.png))); } let mut o = json!({"b": i, "rep": repeat}); + if !b.smoothing { + o["px"] = json!(true); + } if let Some(m) = matrix(m) { o["m"] = m; } diff --git a/crates/render/src/html/canvas.js b/crates/render/src/html/canvas.js index 7858c20f..6cda20cf 100644 --- a/crates/render/src/html/canvas.js +++ b/crates/render/src/html/canvas.js @@ -153,7 +153,11 @@ g.globalAlpha = bitmap ? Math.min(Math.max(it.c[0], 0), 1) : 1; set(g, it.m); g.fillStyle = style; + // A bitmap without Allow Smoothing keeps hard pixel edges (ADR 0050). + const hard = bitmap && movie.paints[it.f].px === true; + if (hard) g.imageSmoothingEnabled = false; g.fill(path, it.eo ? "evenodd" : "nonzero"); + if (hard) g.imageSmoothingEnabled = true; g.globalAlpha = 1; } } diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index 015a5f76..84b22ce7 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -548,6 +548,15 @@ fn bitmaps_and_sounds_are_embedded_once() { assert_eq!(js.eval("P.start().sounds"), json!([[0, "event", 1, false, 1, 1, null]])); let silent = movie(&doc, &HtmlOptions { sound: false, ..Default::default() }); assert_eq!((silent.stats.sounds, silent.json["timelines"][0].get("snd")), (0, None)); + // A bitmap without Allow Smoothing says so; the page draws it with hard pixel edges, and + // an SVG frame marks its image pixelated (ADR 0050). + if let Some(b) = doc.bitmaps.first_mut() { + Arc::make_mut(b).smoothing = false; + } + let hard = movie(&doc, &HtmlOptions::default()); + assert_eq!(hard.json["paints"][0], json!({"b": 0, "rep": true, "m": [2, 0, 0, 2, 0, 0], "px": true})); + let svg = crate::svg::to_svg(&anicraft_doc::evaluate(&doc, 0), &doc.stage); + assert!(svg.contains("image-rendering=\"pixelated\""), "{svg}"); } #[test] diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b79f4e11..38fdcf78 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -808,7 +808,7 @@ fn prepare(item: &DisplayItem, view: &Affine, surface: IRect) -> Vec { }); if let Some(fill) = &item.fill { let polys: Vec> = lines.into_iter().map(|l| l.points).collect(); - push(polys, item.fill_rule, Shader::new(fill, &m, &item.color, item.image.as_ref())); + push(polys, item.fill_rule, Shader::new(fill, &m, &item.color, item.image.as_ref()).smoothed(item.smooth)); } if let Some((polys, shader)) = stroke { push(polys, FillRule::NonZero, shader); @@ -893,6 +893,7 @@ mod tests { guide: false, group: None, image: None, + smooth: true, } } diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index f33175fe..4b675cf9 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -18,8 +18,9 @@ pub enum Shader { Solid(Premul), Linear { inv: Affine, start: Vec2, dir: Vec2, lut: Box<[Premul; LUT]> }, Radial { inv: Affine, center: Vec2, inv_radius: f32, lut: Box<[Premul; LUT]> }, - /// Bilinear samples of a bitmap: `inv` maps pixels back to the bitmap's own pixel grid. - Bitmap { inv: Affine, pixels: Arc, repeat: bool, fx: ColorEffect }, + /// Samples of a bitmap: `inv` maps pixels back to the bitmap's own pixel grid. Bilinear + /// when `smooth` (Allow Smoothing, ADR 0050), else the nearest pixel. + Bitmap { inv: Affine, pixels: Arc, repeat: bool, fx: ColorEffect, smooth: bool }, /// Premultiplied pixels already in surface space (a filtered group): `w` wide, its top-left /// at `(x0, y0)`; transparent outside. Image { data: Arc>, x0: i32, y0: i32, w: usize }, @@ -75,7 +76,7 @@ impl Shader { } (Paint::Bitmap { repeat, matrix, .. }, Some(inv)) => match (image, matrix.inverse()) { // Pixel → shape space → image pixels. - (Some(px), Some(to_image)) => Shader::Bitmap { inv: to_image.mul(&inv), pixels: px.clone(), repeat: *repeat, fx: *fx }, + (Some(px), Some(to_image)) => Shader::Bitmap { inv: to_image.mul(&inv), pixels: px.clone(), repeat: *repeat, fx: *fx, smooth: true }, // A collapsed image matrix shows nothing. (Some(_), None) => Shader::Solid([0.0; 4]), (None, _) => Shader::Solid(premultiply(fx.apply(paint.primary_color()))), @@ -84,6 +85,14 @@ impl Shader { } } + /// This shader with a bitmap's Allow Smoothing (other shaders are unchanged). + pub fn smoothed(mut self, on: bool) -> Shader { + if let Shader::Bitmap { smooth, .. } = &mut self { + *smooth = on; + } + self + } + #[inline] pub fn is_solid(&self) -> Option { match self { @@ -104,7 +113,7 @@ impl Shader { Shader::Solid(c) => *c, Shader::Linear { inv, start, dir, lut } => lookup(lut, (inv.apply(p) - *start).dot(*dir)), Shader::Radial { inv, center, inv_radius, lut } => lookup(lut, (inv.apply(p) - *center).length() * inv_radius), - Shader::Bitmap { inv, pixels, repeat, fx } => sample(pixels, inv.apply(p), *repeat, fx), + Shader::Bitmap { inv, pixels, repeat, fx, smooth } => sample(pixels, inv.apply(p), *repeat, *smooth, fx), Shader::Image { data, x0, y0, w } => { let (dx, dy) = (x - x0, y - y0); if dx < 0 || dy < 0 || dx as usize >= *w { @@ -116,9 +125,10 @@ impl Shader { } } -/// A bilinear sample at bitmap position `q` (pixel (i, j) covers [i, i+1) × [j, j+1)), with the -/// colour effect applied and premultiplied. Outside a non-repeating bitmap: transparent. -fn sample(px: &Pixels, q: Vec2, repeat: bool, fx: &ColorEffect) -> Premul { +/// A sample at bitmap position `q` (pixel (i, j) covers [i, i+1) × [j, j+1)), bilinear when +/// `smooth`, else the pixel `q` is in, with the colour effect applied and premultiplied. +/// Outside a non-repeating bitmap: transparent. +fn sample(px: &Pixels, q: Vec2, repeat: bool, smooth: bool, fx: &ColorEffect) -> Premul { let (w, h) = (px.width as f32, px.height as f32); if !(q.x.is_finite() && q.y.is_finite()) || w < 1.0 || h < 1.0 { return [0.0; 4]; @@ -130,6 +140,10 @@ fn sample(px: &Pixels, q: Vec2, repeat: bool, fx: &ColorEffect) -> Premul { } else if u < 0.0 || v < 0.0 || u >= w || v >= h { return [0.0; 4]; } + if !smooth { + let c = px.at(u.floor() as i64, v.floor() as i64); + return premultiply(fx.apply(Rgba::new(c[0], c[1], c[2], c[3]))); + } let (fx_, fy_) = (u - 0.5, v - 0.5); let (x0, y0) = (fx_.floor(), fy_.floor()); let (tx, ty) = (fx_ - x0, fy_ - y0); @@ -168,6 +182,24 @@ mod tests { assert!((s2.at(99, 0)[0] - 0.5).abs() < 0.02); } + #[test] + fn bitmaps_without_smoothing_keep_hard_pixel_edges() { + // A 2×1 image, black then white, drawn 10× larger: smoothed, the middle is a ramp; + // without smoothing, each half is one flat colour up to the edge between them. + let px = Arc::new(Pixels { width: 2, height: 1, rgba: vec![0, 0, 0, 255, 255, 255, 255, 255] }); + let paint = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(1), repeat: false, matrix: Affine::IDENTITY }; + let smooth = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px)); + let hard = Shader::new(&paint, &Affine::scale(10.0, 10.0), &ColorEffect::default(), Some(&px)).smoothed(false); + assert!(smooth.at(9, 5)[0] > 0.3 && smooth.at(9, 5)[0] < 0.7, "{:?}", smooth.at(9, 5)); + assert_eq!(hard.at(9, 5), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(hard.at(10, 5), [1.0, 1.0, 1.0, 1.0]); + assert_eq!(hard.at(0, 0), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(hard.at(19, 9), [1.0, 1.0, 1.0, 1.0]); + assert_eq!(hard.at(20, 5), [0.0; 4], "outside stays transparent"); + // Solid shaders ignore it. + assert!(Shader::new(&Paint::Solid(Rgba::WHITE), &Affine::IDENTITY, &ColorEffect::default(), None).smoothed(false).is_solid().is_some()); + } + #[test] fn bitmaps_sample_bilinear_once_or_tiled() { // 2×1: black, white. diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 4859cb31..55ea01dc 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -28,7 +28,7 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { let mut body = String::new(); let mut grad = 0usize; // Each bitmap is embedded once (by its pixels), then used by every fill that shows it. - let mut images: Vec<(usize, String)> = Vec::new(); + let mut images: Vec<(usize, bool, String)> = Vec::new(); // Clips, in order (a parent always precedes its children; anything else clips all). for (i, parent) in dl.clip_parents.iter().enumerate() { @@ -82,7 +82,7 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String { continue; } if let Some(fill) = &item.fill - && let Some(paint) = paint_attr(fill, &item.transform, &item.color, &mut defs, &mut grad, item.image.as_ref(), &mut images) + && let Some(paint) = paint_attr(fill, &item.transform, &item.color, &mut defs, &mut grad, item.image.as_ref().map(|px| (px, item.smooth)), &mut images) { let _ = write!(body, "", rule_attr("fill-rule", item.fill_rule)); } @@ -340,7 +340,7 @@ fn effect_svg(f: &anicraft_doc::Filter, i: usize, prims: &mut String) { /// The fill attribute for `paint`, defining a gradient in `defs` when needed. `None` when the /// paint draws nothing. -fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n: &mut usize, image: Option<&std::sync::Arc>, images: &mut Vec<(usize, String)>) -> Option { +fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n: &mut usize, image: Option<(&std::sync::Arc, bool)>, images: &mut Vec<(usize, bool, String)>) -> Option { let stops = match paint { Paint::Solid(c) => { let c = fx.apply(*c).sanitized(); @@ -351,15 +351,17 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n // A pattern of the bitmap at its own pixel size, placed by the shape's transform // and the fill's image matrix. // (Opacity comes across; tint has no SVG equivalent and is left out.) - let px = image?; + // Without Allow Smoothing (ADR 0050) the image keeps hard pixel edges. + let (px, smooth) = image?; let key = std::sync::Arc::as_ptr(px) as usize; - let img_id = match images.iter().find(|(k, _)| *k == key) { - Some((_, id)) => id.clone(), + let img_id = match images.iter().find(|(k, sm, _)| *k == key && *sm == smooth) { + Some((_, _, id)) => id.clone(), None => { let png = crate::encode_png(px.width, px.height, &px.rgba).ok()?; let id = format!("img{}", images.len()); - let _ = write!(defs, "", px.width, px.height, anicraft_doc::base64_encode(&png)); - images.push((key, id.clone())); + let look = if smooth { "" } else { " image-rendering=\"pixelated\"" }; + let _ = write!(defs, "", px.width, px.height, anicraft_doc::base64_encode(&png)); + images.push((key, smooth, id.clone())); id } }; @@ -435,6 +437,7 @@ mod tests { guide: false, group: None, image: None, + smooth: true, } } @@ -554,6 +557,7 @@ mod group_tests { guide: false, group: g, image: None, + smooth: true, }; let dl = DisplayList { items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }; let svg = to_svg(&dl, &Stage { width: 4, height: 4, fps: 24.0, background: Rgba::WHITE }); From 721e1ddffb1abe97da41119699342a45b02969fe Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:43:44 -0700 Subject: [PATCH 15/19] feat(import): XFL library folders and Allow Smoothing come across; the checker golden is drawn unsmoothed as its file asks (M2) --- crates/xfl/src/import.rs | 28 ++++++++++++++++++ crates/xfl/src/tests.rs | 16 ++++++++-- crates/xfl/tests/corpus.rs | 2 +- .../tests/corpus/bitmaps/golden/frame-000.png | Bin 9064 -> 7962 bytes 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index e97c96c5..870fd762 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -707,6 +707,9 @@ impl<'a> Builder<'a> { match bitmap { Some(mut b) => { b.id = BitmapId(self.doc.alloc_id()); + // Animate leaves out the default (smoothing on in current versions). + b.smoothing = item.bool("allowSmoothing").unwrap_or(true); + self.place_in_folder(name, anicraft_doc::LibraryItem::Bitmap(b.id)); self.bitmaps.insert(name.to_string(), b.id); self.doc.bitmaps.push(Arc::new(b)); } @@ -801,6 +804,27 @@ impl<'a> Builder<'a> { }; let short = name.rsplit('/').next().unwrap_or(&name).to_string(); self.doc.library.push(Arc::new(Symbol { id, name: short, kind, linkage, timeline })); + self.place_in_folder(&name, anicraft_doc::LibraryItem::Symbol(id)); + } + } + + /// The Library's folders (``, so empty ones come across too), each a path such as + /// `Characters/Hero` (ADR 0050). + fn register_folders(&mut self, root: &X) { + for f in root.list("folders").iter().filter(|f| f.name == "DOMFolderItem").take(anicraft_doc::library::MAX_FOLDERS) { + if let Some(path) = f.attr("name") { + self.doc.ensure_folder_path(path); + } + } + } + + /// Puts `item` in the folder its library name's path names (`Characters/Ball` is in + /// `Characters`), made if `` didn't list it. + fn place_in_folder(&mut self, name: &str, item: anicraft_doc::LibraryItem) { + if let Some((dir, _)) = name.rsplit_once('/') + && let Some(f) = self.doc.ensure_folder_path(dir) + { + self.doc.place_entry(anicraft_doc::LibraryEntry::Item(item), Some(f)); } } } @@ -837,6 +861,7 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do fps: root.f32("frameRate").unwrap_or(24.0).clamp(1.0, 120.0), background: color(&root, "backgroundColor", "__none"), }; + b.register_folders(&root); b.register_bitmaps(&root)?; b.register_symbols(&root)?; b.build_symbols(); @@ -847,6 +872,9 @@ fn import_from<'a>(read: &'a Reader<'a>, fonts: Option<&'a Fonts>) -> Result<(Do let timeline = b.timeline(tl); b.doc.scenes.push(Arc::new(Scene { name, timeline })); } + if !b.doc.library_tree.folders.is_empty() { + b.report.keep("library folders"); + } if b.doc.scenes.is_empty() { let timeline = Timeline { layers: vec![Arc::new(Layer::new(LayerId(b.doc.alloc_id()), "Layer 1"))] }; b.doc.scenes.push(Arc::new(Scene { name: "Scene 1".into(), timeline })); diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 0cfb1d90..a8ea11f3 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -101,7 +101,9 @@ fn stage_layers_frames_and_tweens() { // Frame scripts, on the scene's frames and inside symbols, are kept verbatim (ADR 0013 // tier 1); these are in the subset that runs (tier 2). assert_eq!(report.runs.get("frame scripts in ActionScript 3.0"), Some(&2)); - assert!(report.kept.is_empty(), "{report:?}"); + // The symbol's path puts it in a Library folder (ADR 0050). + assert_eq!(report.kept.keys().collect::>(), ["library folders"], "{report:?}"); + assert_eq!(doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Symbol(doc.library[0].id))), "Characters/Ball"); assert!(report.skipped.keys().all(|k| !k.contains("script")), "{report:?}"); assert_eq!(ball.keyframes[1].script.as_ref().and_then(|s| s.source()).map(|s| s.text.as_str()), Some("stop();")); let inner = &doc.library[0].timeline.layers[0].keyframes[0]; @@ -257,9 +259,10 @@ fn png_2x1() -> Vec { } const BITMAP_DOC: &str = r##" + - + @@ -309,6 +312,15 @@ fn bitmaps_come_across_when_their_image_is_png_or_jpeg() { // The renderer gets the pixels with the items. let list = evaluate(&doc, 0); assert_eq!(list.items.iter().filter(|i| i.image.is_some()).count(), 3); + // Library folders come across (ADR 0050): the item's path places it, empty ones are kept, + // and Allow Smoothing is read (on unless the file turns it off). + let path = |i| doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Bitmap(i))); + assert_eq!((path(doc.bitmaps[0].id).as_str(), path(doc.bitmaps[1].id).as_str()), ("Art/photo.png", "packed.png")); + let folders: Vec = doc.library_tree.folders.iter().map(|f| doc.entry_path(anicraft_doc::LibraryEntry::Folder(f.id))).collect(); + assert_eq!(folders, ["Art", "Empty", "Empty/Inner"]); + assert_eq!(report.kept.get("library folders"), Some(&1)); + assert_eq!((doc.bitmaps[0].smoothing, doc.bitmaps[1].smoothing), (true, false)); + assert!(list.items.iter().any(|i| i.image.is_some() && !i.smooth)); } /// A square (0, 0)–(100, 100) shape-tweening to a triangle (200, 0), (300, 50), (200, 100), diff --git a/crates/xfl/tests/corpus.rs b/crates/xfl/tests/corpus.rs index 44e019d6..87843e84 100644 --- a/crates/xfl/tests/corpus.rs +++ b/crates/xfl/tests/corpus.rs @@ -83,7 +83,7 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[ /// What each package keeps without running (ADR 0013 tier 1: scripts outside the subset, and /// class names); packages not listed keep nothing. -const KEPT: &[(&str, &[(&str, usize)])] = &[("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)])]; +const KEPT: &[(&str, &[(&str, usize)])] = &[("bitmaps", &[("library folders", 1)]), ("scripts", &[("document class", 1), ("frame scripts in ActionScript 3.0", 1), ("linkage classes", 1)]), ("symbols", &[("library folders", 1)])]; /// The frame scripts each package brings that run (ADR 0013 tier 2: in the subset). const RUNS: &[(&str, &[(&str, usize)])] = &[ diff --git a/crates/xfl/tests/corpus/bitmaps/golden/frame-000.png b/crates/xfl/tests/corpus/bitmaps/golden/frame-000.png index 62510fb12cf83e506b874e92c672eab1f962ec35..6a80390f5284e2feda2c7e4621045839ebb2a3c7 100644 GIT binary patch literal 7962 zcmd5>2~<;O77nr~0)k5gMGYbqt(HXG2P9xoKpj(S9a>8XP+M0-iWS0=$D&0i77YoDLX;&(DJlg?*pg8M5(0#nm-ihH~C4AegsQYjwX zafDZq@$K5LF8bHyJpI~!n3=LBi)p{mxYu?{-v&;%3**~b^dZY>pyVFfp{5V3Olu$efdY{d%{;a6l?tPZD&dt%Ee=d5Ru1{J9 z+La*tG30V5x}!t>MM9{(JnXcsQ?yc5qGT+RhYkPvJ@%hVC0>dCvaD`Dfue>@=JuSo zl@+tACK8K`WTu_U+idbRfeb?ve1p;o?blzrUfr9-M<3`iIRW#3FyvW>KkU&_Tthyv1<|!WYo=mmco}d1M-8`(wwwA3JbQnu|b^y-xsO zhWKKQ5ft^&O`75|O7$&NW4L*dd;Pve(w~rsqjjdXW{Gk7b3<;CR5m0YDC3~v38q~6 z#@M5v%HIHOnJMjwAxgEjEVuZ0>RPqgUB?lGm`nVp&6#zD79m|(=p+&^0+INRRB-bI zFXv(?Jp@r5U=`yw)(d=$w>#H!rYTO^*57C^H?%xv7#U@Y-=a#R>*b?~rEi;hZR`3w z=*z(BZzKHHK}u4Cm!012mTJ6o2RX&y9jW@Yn z8`)NJRZ(o<)5iC5cwS||-+$aownI<|>N1E9CW7|~Q0;VISTzR}0A}W*lb%Wg^)K)% zd=WB1$H16p5_v5}SFpFuzdnEJrJ3%=_eE;ctJzkti4K47cm>=gV5B&jZ>e)kg*~C) zT+j&m{ea!_fZ{Y23&%1pnHbDEY`B!ru{ld|w~kqKI&(3>#n1Slt*T3n8TS2P#^P7} zt6^$_1K$ouIGC1RgY*?mPtO&Xm-E!_paLaBNgmwz7?udjGGW$bu4bh|;ure^9xTp7uXh&`<+-*-V z7(&_=LSDeKCbuf5qra7mCmhi;^l*HbikvdPp*@N~M)L(Da1J0Wj^33nhJ52CPN-p9 zz&AFT(#;X@@HvwYmLJwx<}gEY)_g`;zLc=*6NA9oWTf?7f*f>YX+MwEW{9$aPQ?W^ zsVy93SZ*;ZJ*avnC10L;+?NLhg|8cQ^g{tsF`pxu32KLKQixFFDEhh6#z6 z3T^DYwv9$BZqoue(<6)4n^{TE(Xe+%xR~XDda%iWgh~cmf5Mv`!cFmHUTNglg}kPf z4np%%Zp+F#Hv_Vjvtwf_a@f2DINwjm-$g57EwJDl;bExrjcH32eRHDYE>Aebep zO`jnt#}@9B5vEw_=oB?058dc49m*Kf=HVpZ180x+h<;Y4-wKG~7X2I0APXF=S41hs zrx{GmCPYnm|8Xdb7Ek&5o{|?iVZK!eN>a^vXN=JchOB=P8ib`AHAu=7#8q+gw?s{t zvahx|_X(vXNj}r%cA?K`YF{f+tPd&B@b3_>B9d^-fmJRa^40$3UNeWD!XD6gQiYh) zK$THqbrSW*Y~$^TTZ>kq^89ma=jbf9`z@sS|GL3Awf&By;2v9an(P-J6D8S6uUT@- zXQX~S^^d%jj?z@*ka-Ir&G}lZ!0>Zj4XJ@U+Ym;Qm;MM4kf#-`MR0~lO!mB|%~GL1 z$^tF+`qt;q+u7?`-X@8*lrZAzM?MS$sp5rVff88|*v4?0c0h(*(-_!Nhf3%1ENyl; zQ0f}?jc=%29rx6R`>-fK1EVxx@CN(sb>zRzDc6tzzb-4fCKnnOwu^fU(KRl1b`*bQB zV)1o4c_;23UfWp12}}LY@g-AY>98qsnt;80#ZkfNqF=?z*cObHA!lc#fBA)a=u)c4LPVKoa2+wW@=H-_0=PN~{Nx(b@Cj?5X*PJ%?^;d9A<#(y>8 zgSKY?{kNr(|paX97>iIFhZz-)bWY0W&Go-Qgz)=IC z<{fRhIf|a(a0+$=hV5vuY8V*T>kMS$##A-kfo8@)-j= zM=X_bEYmwL3zJcVbyzQ-&<7gP=umhE(*joyaOM1U$kcUtIXy?FAM1uYj;6+*xl>WtA1KTsR zRg&Olfgwl+KeV0IN=cq?&a%_K+Lw(dG&A`Y_VRFG@cq}Em{txO72}?h+{5*uTCCV zL2+kZPW~hOa4=d+Y$8@YFe-$Z9)JK%{Hr7DJTP zfxpv4Otx`WU%DJ~$70ll^(&q{ZntWCN-#dTDo&FyO>M*CQPAaO9Aj43t*jde8Q6^c z`BNEU)MkVj6#`S)R)DJMN&pB=_xf>!azRf_A2o7UdL~B8lX$ZDJJFiSFGdA0VJsO2 z&eOYRG$(Cs+k2W8!lyo9|By^l{es%6_4iG9XLu1&HJQ@2pL=$>MtN_6QJ)Cy&TYU` zkt9+*X2N9E{*o%Xf0h!7yTWi4$Pj7mm732xGR~i(AJ1x}Ov(1Yc=b_Q6(%if%<*gf zd8uEUOTbOUUhUF%HM-LrRb{oIygC_8-9=Ed`<|78tYx4XiuEGx4p}zAbc&u9Q KdU2&s^#1@|f_nh~ literal 9064 zcmdT~3se*5)(rxpA|hZ7g<|l5)K(2*5iEf~Yefo@_Ig`wNHtvn?nwlcA!`oBLrjxvisWHWu2&r=xoa(1R)$O}w(K&Tdc5^d6j{PBT* zgY`JoPNIqi+E|Y>?S#Sz@?t7`ot*mQn3qsU!Yt7Q@2_vTztoGR?g+yr3eRUpT5l;W2Q>`sSCq?2aHm4IiIMKBqm_9FXB$n8M*2HC z+W4Pu=RWdR#pEYy*{XP*sKFn6fYHXMNgA};d+rh9{vWBt^w?IdwmrciFvk{?Iqx zsr+_o*Zdj@vIwdCS8!fXk!dZo{dom64cII6$Y>;)mH~Tp9ymOfce$GvRVM%1zZi!H zGXE{5-DP#L8MC>bkg5(NuuoM41|Ni$O|QO;vfAN$^S-V~XfOpOJtn*{&wXaD55e5T zl7686Ok#K-QgY@D#VK^}5;AOb#yp*AyFxeq=PRjK$q(rg^Icy zIT8W4{aY>fX>*}m4o8q7G^_)Me#l05W5l|1)UAq<3ywWNVdTEHZ7W{ydYIFU2GvW2 z0ow!ipH6n2!~~Dv;p9F4z~6-hl^S_>T`&zMdjH3SUOHQQGi*0slKx{+t)w5Pb{ZS^ zUwXS`iBm(X1%J6taI*g3LTJ&h78{$E{N}mLWFPeh0DWJ_4EOz>F7|Jzx=G+vV*c|$ zA_w)gij;ep`YB@z=;1kLn~5kt#E_1`<6nBa9?3b={z{_xHS+*7P@l^mi8T)>0x5K) zN@!*8TB@IpREh2kz6q{=N~pOr6MqWb+e$KA1_@j1;o6YBvqrS{9rf2h=J5_k@0t0B zY!^{(V@(UNEk`ot(W&FJ@H*q4<_SbN<)unS>qr`z3KHhI-*NrOEdmZka{>S`9L(AU zUq;ruQZ#IE7Pci5P;GrxiKvnMZ{B|6u^1#Xlu*S_yb^rf5VbR)R?56Avo-8XGtVNPJd;SrGXyS*uHl~j4!3RU>x+P% za`8nuf#cj(Px9F}sC7slk}` zW85D#a@$3R`qawfRUA~257;&Wn0_}T$AM~-TkbTz_i6-yPTq?{{&ZzVG%Lk zXqGnC{N1wtmitp0-4EOHB6%DmoY)pW_OJujhY#&w37`d&rn~05qtcex z)jfIGQIqPo<^6ouO9CV_)KKC;ApexnG#=IcJg9yZ-)C315be^IYU)z#a2ZKpuX&M5 zj?qv16hxh{ZOROdT#G-D=;OLIvc_t6d%A!l9-gj<`Oa#Jb8HCiNeOTm-Q85Dt*Ctt z-_JkF%hTBCKrQt23)T>2;CjADF2@Kd3`wMKxB-sb0-T^&*E7vAbKN`@8`=81fvmfa z`(K;9D&+v>9u}H7QWN$d3kd_{Ma(>gvqLRFJzzM%7)de9eF8#JUu_K$T_t-bBJlm-juL>5dmFesyjJ`+g8?*>K8 z$57;i&I1Oq4*b-7%V*2J{o9Tf2x_0?vqZ*Cch}l&DRQ-OM#!vi;>avTg2`~jwv6&$ zV+7`RomqzQdWJW2Zh`04ec^F6-_OvOp5u3A1fp`vJVOwGxxnOzkpB30$z$s5Sr4v4 zjMgt8LsT2?B}X-uW9aL5TTXXLCr!^(#T-kF5AUW-s)kVBah&tFEbhFqZ47 zGd1KT|JRuPZ$mZyf)k_NDXB-iKx(bhG59FDdz6Lwb8}NSl1R^jmhDxCSQ_jo`qOU17iP`d-`yQni@vGVrxJ=1o0%6 zrp0suGprppWQ81Z-pdoRn^;%+Gvh+0&Yp=gm(agJch}+dKEImHKW*m!hDZAaeb3k# zL4`USF_y}ez+ryyMiq!yPTjkEm?h%%8gTS0*%lLlZ9{WA8Cv{d=M62BynF|)+#(MF zEndp^v%lKcFoUVOgTFgr#`C4X7OWehpMq9S&srQ3@_ueaOjlYjU+A^@y{X?Mmo~Z3 z4c-&jc=AUQFhctj*a7(8v4!n`PzXDKh$Y3a9T;s7vcdX5U>de9o;NJi;14YhiMfz_ zFXo;XJx!MOv&{L!9JlC$-ewI!o&9_Z@Qi}SX$&x$;4EV>Wa1Pf9?at(M0a0H>i&9m zL}mYKCX3d5oWEgdP5c0b4*yTwc^P@pmfGmAPpQm)-s`{eVbaU=U2jdq^e)EI;-I@< zG$IKCowl7qk zF`8ssi_91x_Vb#i2!EX@zYGaL6%#aPxd<(r zpkY;o`PT0+-?P!l_{=LtrwpJ-7`@1(91ePdfLz;m5t`Fd{pt@?C(FhWYY_^4|5WlK z?xQqi;njN!Wj+K$4@Q0wdIQL4PXwhhD3_hd<4F0gR}zUfa=zBuKsd3`{`<&^h6Jdd z8k4gtWUXZ*;1fuFA+k=&pdZ0xc1f&MxsG%j($F<>GvE~0!JVQ2n;m8NbqU!%=Ud&l zYJ&J!g0#5iMiHR)uIZB~+|7LqYNH+gOxT$Kfwk$zI#xZr*Fa9)!Rw+|{e!A3p==1& zY$Kh3;^0x46RxKsI2Vd64RPh{cjGo;#m7GkS+TKx9sP-SZJ(r<2dHlus%Q%7Yn9gz z`KPzcr<}{fWfy536hSzty;;xEAB)GGknc^!s}6Cda}^2nccDXY|1eK)#2Qwam$!!7 zAN<#;?6i@x@_TQ7vv$2@&{;Xcp;~s!yrswHXx51TGnXM{HfGj!6X+#!c~I15X(oYX z_hkotiZ@XsGZ316#mNo$!M z4aX^YJe9bE)`W@K4i2U?So69+YYijPit_{yai>p`w1)?9T|oxN{m3PinSF8k^10>0`@?=>ro>APw6z^G;+7ls(p-W zy^FPLm>mS=9C?B=sIfGu>ncY_9UQctvz%n5YD7n=mc$dZpv9U%t1aP3jTtUb=|G6@ zp#p(iG_+}dQTS?KBn@2`(Sjzv!M8bQ6Ez7)uW2p%bU6`-M|KSC(jQ%eZ*V=AzjEVl zewZMdJ3MUVSn80`UR#7q_LJ9c=3f=C`7)!LY)N$*w?9qA3SacbydAR|(IjwN+$Hz@ zmLX^~Z@Yz*4TiJ!-uj1C<Dun3Z2%5Olp9g$gP?_(r`atOXbG#^5nygcUF>U z5$BOW~zil+EVprgI#Ego6*NXBb)%6tNWx_*MKSvXZPV&vQp{MOXbb zJo4}iFc4JijK(?T2jgan`(zS#C8dJ!$0Q%Jj~<5h0XC$^bE%jU7g0 zNf;;DwGw}ES}x`~<&1o91YUJ5&8lrO(q1H;cq$tlZJq{)AR!QBBW%q#Fi zm8=%N3jzQZG#TFjyyaD3`{PG05}vwoyYu0x@v8kK^Hlh5#9mt6@w0v?V#ejJtJRh) zGcTReUez%>2mVP-V)LtnVZ_wp_~{;e9$x^LPjb>l6xVP$BBT3i{F69l$AKcY;2cH^ zhc*`pZ3Ej>1;!WJ+H7C2P+u1-Aw*`a_CyA|v!Z!hFhlNmAsa7SgyXb77Rw|3)iN~W z{^B|Ri7eB%BnUNqo9skN-HdAeplJ#7+9`Es`h4zrHO`m6Z9%js7~WuovDGe4b3k9XVQs6L%c#k9%siIXgP(~!4PI^pOh+h< zO&&PTw#k;e8t%))NiZK^fJ(4>*qcA)bfA^<8Gib^P!){TI>nCFUGB=@+5 Date: Tue, 10 Nov 2026 23:44:42 -0700 Subject: [PATCH 16/19] feat(engine): Swap Symbol inside an open symbol never nests it in itself (M2) --- crates/engine/src/cmds_library.rs | 4 ++++ crates/engine/src/library_tests.rs | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/engine/src/cmds_library.rs b/crates/engine/src/cmds_library.rs index 9ff8a965..0002b8d4 100644 --- a/crates/engine/src/cmds_library.rs +++ b/crates/engine/src/cmds_library.rs @@ -378,6 +378,10 @@ fn swap_symbol(s: &mut Session, p: &Value) -> Result { if s.doc.symbol(to).is_none() { return Err(EngineError::State(format!("no symbol with id {}", to.0))); } + // Inside a symbol open for editing (ADR 0045), never swap in that symbol or one that holds it. + if crate::editing::would_nest(s, to) { + return Err(EngineError::State("a symbol can't be placed inside itself".into())); + } let mut swapped = 0; for e in s.selected_elements_mut()? { if let ElementKind::Symbol { symbol, .. } = &mut e.kind { diff --git a/crates/engine/src/library_tests.rs b/crates/engine/src/library_tests.rs index 89e7d9d3..cc350a87 100644 --- a/crates/engine/src/library_tests.rs +++ b/crates/engine/src/library_tests.rs @@ -267,3 +267,19 @@ fn convert_to_symbol_picks_a_free_name() { let second = run(&mut s, "modify.convert_to_symbol", json!({})); assert_eq!(second["name"], "Symbol 3", "“Symbol 2” is taken"); } + +#[test] +fn inside_an_open_symbol_swap_never_nests_and_deleting_it_closes_it() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10})); + let outer = run(&mut s, "modify.convert_to_symbol", json!({"name": "Outer"}))["symbol"].as_u64().unwrap(); + run(&mut s, "draw.rect", json!({"x": 40, "y": 0, "w": 10, "h": 10})); + let other = run(&mut s, "modify.convert_to_symbol", json!({"name": "Other"}))["symbol"].as_u64().unwrap(); + run(&mut s, "symbol.edit", json!({"symbol": outer})); + assert_eq!(s.editing.len(), 1); + run(&mut s, "library.place", json!({"symbol": other})); + assert!(err(&mut s, "element.swap_symbol", json!({"symbol": outer})).contains("inside itself")); + // Deleting the open symbol takes the editor back to the scene. + run(&mut s, "library.delete", json!({"items": [{"symbol": outer}], "confirm": true})); + assert!(s.editing.is_empty() && s.doc.symbol(SymbolId(outer)).is_none()); +} From 8a2ed97981e2da9fa80d5b74775e36ec1cec9dee Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:51:24 -0700 Subject: [PATCH 17/19] feat(ui): Library folders, inline rename, drag into folders, sort, search, use counts, unused items, preview and item properties; Swap Symbol in Properties (M2) --- src/a11y.rs | 2 +- src/app.rs | 42 ++- src/library.rs | 890 +++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 3 +- src/panels.rs | 162 ++------- 5 files changed, 954 insertions(+), 145 deletions(-) create mode 100644 src/library.rs diff --git a/src/a11y.rs b/src/a11y.rs index 15318b84..6b8f29b5 100644 --- a/src/a11y.rs +++ b/src/a11y.rs @@ -352,7 +352,7 @@ mod tests { for tool in [Tool::Bone, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] { found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool)); } - for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple"] { + 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"] { found.extend(check(panel, |a, _| a.open_panel(Some(panel)))); } // The layer depth row shows on artwork layers once the scene has a camera. diff --git a/src/app.rs b/src/app.rs index 5d04f74d..6c788c05 100644 --- a/src/app.rs +++ b/src/app.rs @@ -269,19 +269,7 @@ pub struct Shot { pub const SHOT_FRAMES: u32 = 120; /// The item picked in the Library panel (view state). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LibraryItem { - Symbol(anicraft_engine::doc::SymbolId), - Bitmap(anicraft_engine::doc::BitmapId), - Sound(anicraft_engine::doc::SoundId), -} - -impl LibraryItem { - /// The first item in the Library: its first symbol, else its first bitmap, else sound. - pub fn first(doc: &anicraft_engine::doc::Document) -> Option { - doc.library.first().map(|s| LibraryItem::Symbol(s.id)).or_else(|| doc.bitmaps.first().map(|b| LibraryItem::Bitmap(b.id))).or_else(|| doc.sounds.first().map(|s| LibraryItem::Sound(s.id))) - } -} +pub use anicraft_engine::doc::LibraryItem; pub struct App { pub s: Session, @@ -317,6 +305,8 @@ pub struct App { /// Folders shown closed on the timeline (view state: not saved, not undoable). pub tl_collapsed: HashSet, pub library_sel: Option, + /// The Library panel's folders, selection, sorting, search and preview (ADR 0050). + pub library: crate::library::LibraryView, /// Text being typed on the stage. pub text_edit: Option, /// Font families on this computer, listed once on first need. @@ -460,7 +450,7 @@ impl App { let prefs = if shot_mode { prefs::Prefs::default() } else { prefs::Prefs::load() }; let keymap = keymap::Keymap::new(&prefs.shortcuts); let shortcuts = keymap.table(); - let library_sel = LibraryItem::first(&session.doc); + let library_sel = crate::library::first_item(&session.doc); let (recovery, recovery_err) = autosave::Recovery::start(shot_mode); // Text lays out with the fonts on this computer plus the embedded interface font (so new // text has the same default everywhere). Scan them now, off the UI thread. @@ -500,6 +490,7 @@ impl App { tl_last_layer: None, tl_collapsed: HashSet::new(), library_sel, + library: Default::default(), text_edit: None, font_families: None, star_points: 5, @@ -784,6 +775,22 @@ impl App { self.scan_system_fonts(); } Some("confirm") => self.request("layer.delete", json!({})), + Some(which @ ("library" | "librarymenu")) => { + // Library folders with an item inside, a copy, the item previewed (ADR 0050). + let ball = self.s.doc.library.first().map(|s| s.id); + let folder = self.run("library.new_folder", json!({"name": "Characters"})).and_then(|v| v["folder"].as_u64()); + self.run("library.new_folder", json!({"name": "Props"})); + if let (Some(ball), Some(f)) = (ball, folder) { + self.run("library.duplicate", json!({"symbol": ball.0})); + self.run("library.move", json!({"items": [{"symbol": ball.0}], "to": f})); + self.library.expanded.insert(anicraft_engine::doc::FolderId(f)); + self.library_sel = Some(LibraryItem::Symbol(ball)); + self.library.sel = vec![anicraft_engine::doc::LibraryEntry::Item(LibraryItem::Symbol(ball))]; + } + if which == "librarymenu" { + crate::library::select_unused(self); + } + } Some(which @ ("onion" | "onionmenu")) => { // Onion skin ±5 on a frame with frames before and after it, the markers on the // ruler; with its menu open, in outlines (ADR 0047). @@ -1341,7 +1348,7 @@ impl App { if let Some(session) = restored { self.view.fit = true; self.frame_sel = None; - self.library_sel = LibraryItem::first(&self.s.doc); + self.library_sel = crate::library::first_item(&self.s.doc); self.decode_sounds(); self.recovery.restored(&session); let name = self.s.path.as_deref().and_then(std::path::Path::file_name).map_or_else(|| tr!("Untitled").to_string(), |n| n.to_string_lossy().into_owned()); @@ -1358,7 +1365,7 @@ impl App { match id { "file.new" | "file.new_sample" | "file.open" => { self.view.fit = true; - self.library_sel = LibraryItem::first(&self.s.doc); + self.library_sel = crate::library::first_item(&self.s.doc); self.decode_sounds(); match v.get("report").and_then(Value::as_str) { // An imported file: say what came across and what didn't, and that saving @@ -1370,7 +1377,7 @@ impl App { "file.recover" => { self.view.fit = true; self.frame_sel = None; - self.library_sel = LibraryItem::first(&self.s.doc); + self.library_sel = crate::library::first_item(&self.s.doc); self.recovery.restored(v["recovered"].as_str().unwrap_or("")); let name = v["name"].as_str().unwrap_or(tr!("Untitled")); self.status_ok(if v["original_newer"].as_bool() == Some(true) { @@ -1804,6 +1811,7 @@ impl App { crate::widthtool::consume_keys(self, ctx); crate::bone_tool::consume_keys(self, ctx); } + crate::library::consume_keys(self, ctx); let mut fire: Vec<&'static str> = Vec::new(); let mut tool = None; let mut play = false; diff --git a/src/library.rs b/src/library.rs new file mode 100644 index 00000000..02b61972 --- /dev/null +++ b/src/library.rs @@ -0,0 +1,890 @@ +//! The Library panel (ADR 0050): folders, sorting and search, inline rename, drag into and out +//! of folders, multiple selection, an item preview (a symbol's first frame, a bitmap, a +//! sound's waveform with play) and the item's properties. Every change is a `library.*` +//! command; what is sorted, filtered, expanded or selected is view state, kept here. + +use crate::a11y::{self, Named}; +use crate::app::App; +use crate::icons::{self, Icon}; +use crate::theme::{T, TARGET, Type, color, font, text, with_type}; +use anicraft_engine::StateId; +use anicraft_engine::cmds_library::entry_json; +use anicraft_engine::doc::library::MAX_FOLDER_DEPTH; +use anicraft_engine::doc::{Document, FolderId, LibraryEntry, LibraryItem, SymbolKind}; +use egui::{Align2, Key, Modifiers, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; +use serde_json::json; +use std::collections::{HashMap, HashSet}; + +/// How the list is ordered (folders always come first, by name). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Sort { + #[default] + Name, + Type, + Uses, + /// When the item came into the Library (ids grow with time). + Added, +} + +impl Sort { + const ALL: [Sort; 4] = [Sort::Name, Sort::Type, Sort::Uses, Sort::Added]; + fn label(self) -> &'static str { + match self { + Sort::Name => tr!("Name"), + Sort::Type => tr!("Type"), + Sort::Uses => tr!("Use count"), + Sort::Added => tr!("Date added"), + } + } +} + +/// What the Library panel shows and holds between frames. +#[derive(Default)] +pub struct LibraryView { + /// The selected rows (items and folders). + pub sel: Vec, + /// Where a Shift-click range starts. + anchor: Option, + pub expanded: HashSet, + pub sort: Sort, + pub descending: bool, + pub filter: String, + /// The row being renamed and the text so far; `true` until the field has taken focus. + pub renaming: Option<(LibraryEntry, String, bool)>, + /// The list was clicked last: F2 and Delete act on it (not on the stage). + pub keys: bool, + /// Where the list was drawn last frame (`None` before the first). + list_rect: Option, + uses: Option<(StateId, HashMap, HashSet)>, + preview: Option, +} + +/// The current item's preview picture, and what it was made from. +struct Preview { + key: (LibraryItem, StateId), + texture: Option, +} + +/// The first item in the Library: its first symbol, else its first bitmap, else sound. +pub fn first_item(doc: &Document) -> Option { + doc.library_items().next() +} + +/// One visible row. +struct Row { + entry: LibraryEntry, + depth: usize, + name: String, + /// What it is, for the tooltip and screen readers (“Movie clip · 24 frames”). + detail: String, + uses: Option, + open: bool, +} + +impl LibraryView { + /// Use counts and unused items, worked out once per document state. + fn counts(&mut self, s: &anicraft_engine::Session) -> (HashMap, HashSet) { + match &self.uses { + Some((st, u, n)) if *st == s.state => (u.clone(), n.clone()), + _ => { + let (u, n): (HashMap, HashSet) = (s.doc.library_uses(), s.doc.unused_items().into_iter().collect()); + self.uses = Some((s.state, u.clone(), n.clone())); + (u, n) + } + } + } + + /// Only one row selected: `e`. + fn select_only(&mut self, e: LibraryEntry) { + self.sel = vec![e]; + self.anchor = Some(e); + } +} + +fn kind_rank(doc: &Document, e: LibraryEntry) -> u8 { + match e { + LibraryEntry::Folder(_) => 0, + LibraryEntry::Item(LibraryItem::Symbol(id)) => match doc.symbol(id).map(|s| s.kind) { + Some(SymbolKind::Graphic) => 1, + Some(SymbolKind::MovieClip) => 2, + _ => 3, + }, + LibraryEntry::Item(LibraryItem::Bitmap(_)) => 4, + LibraryEntry::Item(LibraryItem::Sound(_)) => 5, + } +} + +fn raw_id(e: LibraryEntry) -> u64 { + match e { + LibraryEntry::Item(i) => i.raw(), + LibraryEntry::Folder(f) => f.0, + } +} + +fn detail(doc: &Document, e: LibraryEntry) -> String { + match e { + LibraryEntry::Folder(f) => { + let n = doc.library_children(Some(f)).len(); + trn!("Folder · {n} item", "Folder · {n} items", n) + } + LibraryEntry::Item(LibraryItem::Symbol(id)) => doc.symbol(id).map_or_else(String::new, |s| { + let n = s.timeline.frame_count(); + let frames = trn!("{n} frame", "{n} frames", n); + tr!("{kind} · {frames}", kind = crate::panels::symbol_kind_label(s.kind), frames = frames) + }), + LibraryEntry::Item(LibraryItem::Bitmap(id)) => doc.bitmap(id).map_or_else(String::new, |b| tr!("Bitmap · {width}×{height}", width = b.width, height = b.height)), + LibraryEntry::Item(LibraryItem::Sound(id)) => doc.sound(id).map_or_else(String::new, |x| tr!("Sound · {seconds} s", seconds = format!("{:.1}", x.seconds()))), + } +} + +/// The visible rows: folders (open ones with what they hold), then items, ordered by `sort`. +/// With a search, only matching items show, inside every folder that leads to one. +fn rows(doc: &Document, v: &LibraryView, uses: &HashMap) -> Vec { + let query = v.filter.trim().to_lowercase(); + let matches = |e: LibraryEntry| query.is_empty() || doc.entry_name(e).is_some_and(|n| n.to_lowercase().contains(&query)); + // Folders that lead to a match (searching opens them all). + let mut leads: HashSet = HashSet::new(); + if !query.is_empty() { + for e in doc.library_items().map(LibraryEntry::Item).chain(doc.library_tree.folders.iter().map(|f| LibraryEntry::Folder(f.id))) { + if matches(e) + && let Some(p) = doc.parent_of(e) + { + leads.extend(doc.folder_chain(p)); + } + } + } + let count = |e: LibraryEntry| match e { + LibraryEntry::Item(i) => uses.get(&i).copied().unwrap_or(0), + LibraryEntry::Folder(_) => 0, + }; + let mut out = Vec::new(); + // Depth-first, in order: each level is sorted, then pushed in reverse. + let mut pending: Vec<(LibraryEntry, usize)> = level(doc, v, None, &count).into_iter().rev().map(|e| (e, 0)).collect(); + while let Some((e, depth)) = pending.pop() { + if out.len() > 100_000 { + break; + } + let shown = match e { + LibraryEntry::Folder(f) => query.is_empty() || leads.contains(&f) || matches(e), + LibraryEntry::Item(_) => matches(e), + }; + if !shown { + continue; + } + let open = match e { + LibraryEntry::Folder(f) => (!query.is_empty() && leads.contains(&f)) || (query.is_empty() && v.expanded.contains(&f)), + LibraryEntry::Item(_) => false, + }; + out.push(Row { entry: e, depth, name: doc.entry_name(e).unwrap_or("").to_string(), detail: detail(doc, e), uses: matches!(e, LibraryEntry::Item(_)).then(|| count(e)), open }); + if let LibraryEntry::Folder(f) = e + && open + && depth + 1 < MAX_FOLDER_DEPTH + { + pending.extend(level(doc, v, Some(f), &count).into_iter().rev().map(|c| (c, depth + 1))); + } + } + out +} + +/// What folder `parent` holds, folders first (by name), then items in the chosen order. +fn level(doc: &Document, v: &LibraryView, parent: Option, count: &dyn Fn(LibraryEntry) -> usize) -> Vec { + let mut all = doc.library_children(parent); + let name = |e: &LibraryEntry| doc.entry_name(*e).unwrap_or("").to_lowercase(); + all.sort_by(|a, b| { + let folders = matches!(b, LibraryEntry::Folder(_)).cmp(&matches!(a, LibraryEntry::Folder(_))); + let by = match v.sort { + Sort::Name => std::cmp::Ordering::Equal, + Sort::Type => kind_rank(doc, *a).cmp(&kind_rank(doc, *b)), + Sort::Uses => count(*a).cmp(&count(*b)), + Sort::Added => raw_id(*a).cmp(&raw_id(*b)), + }; + let by = by.then_with(|| name(a).cmp(&name(b))); + folders.then(if v.descending && !matches!(a, LibraryEntry::Folder(_)) { by.reverse() } else { by }) + }); + all +} + +/// F2 renames the selected row and Delete deletes the selection, while the list has the +/// keyboard (it was clicked last). Called before the global shortcuts. +pub fn consume_keys(app: &mut App, ctx: &egui::Context) { + let clicked_elsewhere = ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !app.library.list_rect.is_some_and(|r| r.contains(p)))); + if clicked_elsewhere { + app.library.keys = false; + } + if !app.library.keys || app.library.renaming.is_some() { + return; + } + let (rename, delete) = ctx.input_mut(|i| (i.consume_key(Modifiers::NONE, Key::F2), i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace))); + if rename && let [one] = app.library.sel.as_slice() { + let e = *one; + start_rename(app, e); + } + if delete { + delete_selection(app); + } +} + +fn start_rename(app: &mut App, e: LibraryEntry) { + let name = app.s.doc.entry_name(e).unwrap_or("").to_string(); + app.library.renaming = Some((e, name, true)); +} + +fn delete_selection(app: &mut App) { + let items: Vec = app.library.sel.iter().filter(|e| app.s.doc.has_entry(**e)).map(|e| entry_json(*e)).collect(); + if !items.is_empty() { + app.request("library.delete", json!({"items": items})); + } +} + +/// Places an item: a symbol or bitmap at the stage centre, a sound on the active layer's +/// keyframe at the playhead (its span grown to fit). +fn place(app: &mut App, item: LibraryItem) { + match item { + LibraryItem::Symbol(id) => app.run("library.place", json!({"symbol": id.0})), + LibraryItem::Bitmap(id) => app.run("library.place", json!({"bitmap": id.0})), + LibraryItem::Sound(id) => app.run("sound.place", json!({"sound": id.0, "extend": true})), + }; +} + +/// A new folder in the selected row's folder (or the selected folder), opened, selected and +/// ready to be named. +fn new_folder(app: &mut App) { + let parent = match app.library.sel.as_slice() { + [LibraryEntry::Folder(f)] => Some(*f), + [one] => app.s.doc.parent_of(*one), + _ => None, + }; + if let Some(p) = parent { + app.library.expanded.insert(p); + } + if let Some(v) = app.run("library.new_folder", json!({"parent": parent.map(|f| f.0)})) + && let Some(id) = v["folder"].as_u64() + { + let e = LibraryEntry::Folder(FolderId(id)); + app.library.select_only(e); + start_rename(app, e); + } +} + +/// Moves `what` into `to` (`None`: the top level), opening the folder so they stay in view. +fn move_into(app: &mut App, what: &[LibraryEntry], to: Option) { + let items: Vec = what.iter().filter(|e| app.s.doc.parent_of(**e) != to && **e != to.map_or(**e, LibraryEntry::Folder)).map(|e| entry_json(*e)).collect(); + if items.is_empty() { + return; + } + if app.run("library.move", json!({"items": items, "to": to.map(|f| f.0)})).is_some() + && let Some(f) = to + { + app.library.expanded.insert(f); + } +} + +pub fn panel(app: &mut App, ui: &mut egui::Ui) { + // Rows that are gone (an undo, a deletion) leave the selection. + let doc = &app.s.doc; + app.library.sel.retain(|e| doc.has_entry(*e)); + if app.library.renaming.as_ref().is_some_and(|(e, _, _)| !doc.has_entry(*e)) { + app.library.renaming = None; + } + if doc.library_items().next().is_none() && doc.library_tree.folders.is_empty() { + let key = |id: &str| app.keymap.primary(id).map(crate::platform::shortcut_label).unwrap_or_default(); + ui.label(text(Type::Caption, tr!("No symbols, images or sounds yet. Select artwork and press {convert} to make a symbol, or import an image or a sound with {import}.", convert = key("modify.convert_to_symbol"), import = key("file.import")))); + if ui.button(tr!("New Folder")).clicked() { + new_folder(app); + } + return; + } + toolbar(app, ui); + ui.add_space(4.0); + let (uses, unused) = app.library.counts(&app.s); + let list = rows(&app.s.doc, &app.library, &uses); + let total = app.s.doc.library_items().count(); + let summary = if app.library.filter.trim().is_empty() { + trn!("{n} item", "{n} items", total) + } else { + tr!("{shown} of {total}", shown = list.iter().filter(|r| matches!(r.entry, LibraryEntry::Item(_))).count(), total = total) + }; + ui.horizontal(|ui| { + ui.label(text(Type::Caption, summary)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(text(Type::Caption, tr!("Uses")))); + }); + list_ui(app, ui, &list, &unused); + ui.add_space(4.0); + actions_row(app, ui); + ui.add_space(6.0); + preview(app, ui); + properties(app, ui); +} + +/// Search, sort, and the panel's menu. +fn toolbar(app: &mut App, ui: &mut egui::Ui) { + let search = ui.add(egui::TextEdit::singleline(&mut app.library.filter).hint_text(tr!("Search")).desired_width(ui.available_width())); + search.set_name(tr!("Search the Library")); + ui.horizontal(|ui| { + ui.label(text(Type::Label, tr!("Sort"))); + egui::ComboBox::from_id_salt("lib_sort") + .width(110.0) + .selected_text(app.library.sort.label()) + .show_ui(ui, |ui| { + for s in Sort::ALL { + if ui.selectable_label(app.library.sort == s, s.label()).clicked() { + app.library.sort = s; + } + } + }) + .response + .set_name(tr!("Sort by")); + let (icon, tip) = if app.library.descending { (Icon::ChevronDown, tr!("Descending: click for ascending")) } else { (Icon::ChevronUp, tr!("Ascending: click for descending")) }; + if crate::timeline::icon_button(ui, tip, None, icon).clicked() { + app.library.descending = !app.library.descending; + } + let menu = ui.menu_button(tr!("More"), |ui| { + let n_unused = app.library.counts(&app.s).1.len(); + if ui.add_enabled(n_unused > 0, egui::Button::new(tr!("Select Unused Items"))).clicked() { + ui.close(); + select_unused(app); + } + if ui.add_enabled(n_unused > 0, egui::Button::new(tr!("Delete Unused Items…"))).clicked() { + ui.close(); + app.request("library.delete_unused", json!({})); + } + ui.separator(); + if ui.button(tr!("Expand All Folders")).clicked() { + ui.close(); + app.library.expanded = app.s.doc.library_tree.folders.iter().map(|f| f.id).collect(); + } + if ui.button(tr!("Collapse All Folders")).clicked() { + ui.close(); + app.library.expanded.clear(); + } + }); + menu.response.on_hover_text(tr!("Library options")).set_name(tr!("Library options")); + }); +} + +/// Selects every unused item, opening the folders they are in. +pub fn select_unused(app: &mut App) { + let unused = app.s.doc.unused_items(); + for i in &unused { + if let Some(p) = app.s.doc.parent_of(LibraryEntry::Item(*i)) { + app.library.expanded.extend(app.s.doc.folder_chain(p)); + } + } + app.library.sel = unused.iter().map(|i| LibraryEntry::Item(*i)).collect(); + app.library.keys = true; + app.status_ok(trn!("{n} unused item selected", "{n} unused items selected", unused.len())); +} + +fn list_ui(app: &mut App, ui: &mut egui::Ui, list: &[Row], unused: &HashSet) { + let mut toggle: Option = None; + let mut clicked: Option<(LibraryEntry, Modifiers)> = None; + let mut activate: Option = None; + let mut rename: Option = None; + let mut dropped: Option<(Vec, Option)> = None; + let scroll = egui::ScrollArea::vertical().id_salt("lib").max_height(200.0).auto_shrink([false, true]).show(ui, |ui| { + for row in list { + let selected = app.library.sel.contains(&row.entry); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), TARGET), Sense::click_and_drag()); + let p = ui.painter(); + if selected || resp.hovered() { + p.rect_filled(r, T.rc(), if selected { T.accent_dim } else { T.hover }); + } + if selected { + p.rect_filled(Rect::from_min_size(r.left_top(), vec2(3.0, r.height())), 0.0, T.accent); + } + let indent = 6.0 + row.depth as f32 * 14.0; + let chevron = Rect::from_center_size(pos2(r.left() + indent + 6.0, r.center().y), vec2(12.0, 12.0)); + let icon = Rect::from_center_size(pos2(r.left() + indent + 22.0, r.center().y), vec2(14.0, 14.0)); + match row.entry { + LibraryEntry::Folder(_) => { + icons::paint(p, chevron, if row.open { Icon::ChevronDown } else { Icon::ChevronRight }, T.icon); + icons::paint(p, icon.expand(1.0), if row.open { Icon::FolderOpen } else { Icon::Folder }, color(Type::Body)); + } + LibraryEntry::Item(LibraryItem::Symbol(id)) => { + let kind_color = match app.s.doc.symbol(id).map(|s| s.kind) { + Some(SymbolKind::Graphic) | None => T.kind_graphic, + Some(SymbolKind::MovieClip) => T.kind_movie_clip, + Some(SymbolKind::Button) => T.kind_button, + }; + p.rect_stroke(icon, 2.0, Stroke::new(1.5, kind_color), StrokeKind::Inside); + p.circle_filled(icon.center(), 2.5, kind_color); + } + LibraryEntry::Item(LibraryItem::Sound(_)) => icons::paint(p, icon.expand(1.0), Icon::Sound, color(Type::Body)), + LibraryEntry::Item(LibraryItem::Bitmap(_)) => icons::paint(p, icon.expand(1.0), Icon::Image, color(Type::Body)), + } + let name_rect = Rect::from_min_max(pos2(icon.right() + 8.0, r.top()), pos2(r.right() - 40.0, r.bottom())); + let uses_text = row.uses.map(|n| n.to_string()).unwrap_or_default(); + let is_unused = matches!(row.entry, LibraryEntry::Item(i) if unused.contains(&i)); + if let Some(n) = row.uses { + p.text(r.right_center() - vec2(8.0, 0.0), Align2::RIGHT_CENTER, &uses_text, font(Type::Data), if n == 0 { T.text_faint } else { color(Type::Caption) }); + } + // Renaming: a field over the name; Enter or clicking away keeps it, Esc doesn't. + let editing = app.library.renaming.as_ref().is_some_and(|(e, _, _)| *e == row.entry); + if editing { + let mut commit = None; + if let Some((e, buf, focus)) = &mut app.library.renaming { + let edit = ui.put(name_rect.shrink2(vec2(0.0, 3.0)), egui::TextEdit::singleline(buf).font(font(Type::Body))); + edit.set_name(tr!("Library name")); + if *focus { + edit.request_focus(); + *focus = false; + } + let esc = ui.input(|i| i.key_pressed(Key::Escape)); + if edit.lost_focus() { + commit = Some((*e, buf.clone(), !esc)); + } + } + if let Some((e, name, keep)) = commit { + app.library.renaming = None; + if keep && app.s.doc.entry_name(e) != Some(name.as_str()) { + let mut params = entry_json(e); + params["name"] = json!(name); + app.run("library.rename", params); + } + } + } else { + let c = if is_unused { T.text_dim } else { color(Type::Body) }; + let galley = ui.painter().layout_no_wrap(row.name.clone(), font(Type::Body), c); + let clip = ui.painter().with_clip_rect(name_rect.intersect(ui.clip_rect())); + clip.galley(pos2(name_rect.left(), r.center().y - galley.size().y / 2.0), galley, c); + } + let used_note = match row.uses { + Some(0) => tr!("not used").to_string(), + Some(n) => trn!("used {n} time", "used {n} times", n), + None => String::new(), + }; + let name = if used_note.is_empty() { format!("{} · {}", row.name, row.detail) } else { format!("{} · {} · {}", row.name, row.detail, used_note) }; + a11y::control(ui, &resp, WidgetType::SelectableLabel, &name, Some(selected)); + let resp = resp.on_hover_text(&name); + // Dragging rows: the selection if the row is in it, else just the row. + if resp.drag_started() { + let what = if selected { app.library.sel.clone() } else { vec![row.entry] }; + resp.dnd_set_drag_payload(what); + } + let target = match row.entry { + LibraryEntry::Folder(f) => Some(f), + e => app.s.doc.parent_of(e), + }; + if let Some(payload) = resp.dnd_hover_payload::>() + && !payload.contains(&row.entry) + { + let hl = if let LibraryEntry::Folder(_) = row.entry { r } else { Rect::from_min_size(pos2(r.left(), r.top()), vec2(r.width(), 2.0)) }; + ui.painter().rect_stroke(hl, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside); + } + if let Some(payload) = resp.dnd_release_payload::>() { + dropped = Some(((*payload).clone(), target)); + } + if let LibraryEntry::Folder(f) = row.entry + && resp.clicked() + && ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| p.x < icon.right() + 2.0) + { + toggle = Some(f); + } else if resp.clicked() { + clicked = Some((row.entry, ui.input(|i| i.modifiers))); + } + if resp.double_clicked() { + let on_name = ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| p.x >= name_rect.left()); + if on_name { + rename = Some(row.entry); + } else { + activate = Some(row.entry); + } + } + resp.context_menu(|ui| row_menu(app, ui, row.entry)); + } + // Below the rows: dropping there moves to the top level. + let rest = ui.available_rect_before_wrap(); + let (r, resp) = ui.allocate_exact_size(vec2(rest.width(), (rest.height()).max(TARGET)), Sense::click() - Sense::FOCUSABLE); + a11y::surface(ui, &resp, tr!("Library: drop here for the top level")); + if resp.dnd_hover_payload::>().is_some() { + ui.painter().rect_stroke(r, T.rc(), Stroke::new(1.5, T.accent), StrokeKind::Inside); + } + if let Some(payload) = resp.dnd_release_payload::>() { + dropped = Some(((*payload).clone(), None)); + } + if resp.clicked() { + app.library.sel.clear(); + app.library.keys = true; + } + resp.context_menu(|ui| { + if ui.button(tr!("New Folder")).clicked() { + ui.close(); + app.library.sel.clear(); + new_folder(app); + } + }); + }); + app.library.list_rect = Some(scroll.inner_rect); + if let Some(f) = toggle { + if !app.library.expanded.remove(&f) { + app.library.expanded.insert(f); + } + app.library.select_only(LibraryEntry::Folder(f)); + app.library.keys = true; + } + if let Some((e, m)) = clicked { + app.library.keys = true; + if m.command { + if let Some(i) = app.library.sel.iter().position(|x| *x == e) { + app.library.sel.remove(i); + } else { + app.library.sel.push(e); + } + app.library.anchor = Some(e); + } else if m.shift + && let Some(a) = app.library.anchor + && let (Some(i), Some(j)) = (list.iter().position(|r| r.entry == a), list.iter().position(|r| r.entry == e)) + { + let (lo, hi) = (i.min(j), i.max(j)); + app.library.sel = list.get(lo..=hi).map(|rs| rs.iter().map(|r| r.entry).collect()).unwrap_or_default(); + } else { + app.library.select_only(e); + } + if let LibraryEntry::Item(i) = e { + app.library_sel = Some(i); + } + } + if let Some(e) = rename { + app.library.select_only(e); + start_rename(app, e); + } else if let Some(e) = activate { + match e { + // A symbol opens for editing, as in Animate (ADR 0045); images and sounds are placed. + LibraryEntry::Item(LibraryItem::Symbol(id)) => { + app.run("symbol.edit", json!({"symbol": id.0})); + } + LibraryEntry::Item(i) => place(app, i), + LibraryEntry::Folder(f) => { + if !app.library.expanded.remove(&f) { + app.library.expanded.insert(f); + } + } + } + } + if let Some((what, to)) = dropped { + move_into(app, &what, to); + } +} + +/// A row's right-click menu. +fn row_menu(app: &mut App, ui: &mut egui::Ui, e: LibraryEntry) { + if !app.library.sel.contains(&e) { + app.library.select_only(e); + if let LibraryEntry::Item(i) = e { + app.library_sel = Some(i); + } + } + let many = app.library.sel.len() > 1; + if let LibraryEntry::Item(LibraryItem::Symbol(id)) = e + && !many + { + if ui.button(tr!("Edit Symbol")).clicked() { + ui.close(); + app.run("symbol.edit", json!({"symbol": id.0})); + } + if ui.button(tr!("Duplicate Symbol")).clicked() { + ui.close(); + if let Some(v) = app.run("library.duplicate", json!({"symbol": id.0})) + && let Some(n) = v["symbol"].as_u64() + { + let copy = LibraryEntry::Item(LibraryItem::Symbol(anicraft_engine::doc::SymbolId(n))); + app.library.select_only(copy); + start_rename(app, copy); + } + } + } + if let LibraryEntry::Item(i) = e + && !many + { + let label = if matches!(i, LibraryItem::Sound(_)) { tr!("Place on Timeline") } else { tr!("Place on Stage") }; + if ui.button(label).clicked() { + ui.close(); + place(app, i); + } + } + if !many && ui.button(tr!("Rename")).clicked() { + ui.close(); + start_rename(app, e); + } + if ui.button(tr!("New Folder")).clicked() { + ui.close(); + new_folder(app); + } + let folders: Vec<(FolderId, String)> = app.s.doc.library_tree.folders.iter().map(|f| (f.id, app.s.doc.entry_path(LibraryEntry::Folder(f.id)))).collect(); + ui.menu_button(tr!("Move to"), |ui| { + let what = app.library.sel.clone(); + if ui.button(tr!("Library (top level)")).clicked() { + ui.close(); + move_into(app, &what, None); + } + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + for (f, path) in &folders { + let inside_moved = what.iter().any(|w| matches!(w, LibraryEntry::Folder(m) if app.s.doc.folder_within(*f, *m))); + if ui.add_enabled(!inside_moved, egui::Button::new(path.as_str())).clicked() { + ui.close(); + move_into(app, &what, Some(*f)); + } + } + }); + }); + ui.separator(); + if ui.button(tr!("Delete")).clicked() { + ui.close(); + delete_selection(app); + } +} + +/// New Folder and Delete, and placing the current item. +fn actions_row(app: &mut App, ui: &mut egui::Ui) { + ui.horizontal(|ui| { + if crate::timeline::icon_button(ui, tr!("New Folder"), None, Icon::FolderPlus).clicked() { + new_folder(app); + } + let can_delete = !app.library.sel.is_empty(); + let del = ui.add_enabled(can_delete, egui::Button::new(tr!("Delete"))).on_hover_text(tr!("Deletes the selected items and folders (Delete)")); + if del.clicked() { + delete_selection(app); + } + let current = app.library_sel.filter(|i| app.s.doc.has_item(*i)); + match current { + Some(LibraryItem::Sound(id)) => { + if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (or double-click its icon)")).clicked() { + place(app, LibraryItem::Sound(id)); + } + } + other => { + if ui.add_enabled(other.is_some(), egui::Button::new(tr!("Place on stage"))).on_hover_text(tr!("Adds it at the stage centre")).clicked() + && let Some(item) = other + { + place(app, item); + } + } + } + }); +} + +/// The current item's settings: a symbol's type and linkage class, a bitmap's smoothing. +fn properties(app: &mut App, ui: &mut egui::Ui) { + let Some(item) = app.library_sel.filter(|i| app.s.doc.has_item(*i)) else { return }; + ui.add_space(6.0); + match item { + LibraryItem::Symbol(id) => { + let Some((kind, linkage)) = app.s.doc.symbol(id).map(|s| (s.kind, s.linkage.clone())) else { return }; + crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, tr!("Type"), |ui| { + egui::ComboBox::from_id_salt("lib_symkind") + .width(150.0) + .selected_text(crate::panels::symbol_kind_label(kind)) + .show_ui(ui, |ui| { + for (k, key) in [(SymbolKind::Graphic, "graphic"), (SymbolKind::MovieClip, "movie_clip"), (SymbolKind::Button, "button")] { + if ui.selectable_label(kind == k, crate::panels::symbol_kind_label(k)).clicked() && kind != k { + app.run("symbol.set_kind", json!({"symbol": id.0, "kind": key})); + } + } + }) + .response + .set_name(tr!("Symbol type")); + }); + // The class scripts create it by (ADR 0013 tier 1: kept, not run). + let (class, base) = linkage.map_or((String::new(), String::new()), |l| (l.class, l.base)); + crate::theme::form_row(ui, crate::theme::FORM_LABEL_DOCK, tr!("Class"), |ui| { + if let Some(v) = crate::actions_panel::class_field(ui, "lib_symclass", &class, tr!("Linkage class"), tr!("The class scripts create this symbol by (its linkage). Kept with the document; scripts don't run yet")) { + let base = if v.is_empty() { String::new() } else { base.clone() }; + app.run("script.set_class", json!({"symbol": id.0, "class": v, "base": base})); + } + }); + } + LibraryItem::Bitmap(id) => { + let Some(mut on) = app.s.doc.bitmap(id).map(|b| b.smoothing) else { return }; + if crate::theme::checkbox(ui, &mut on, tr!("Allow smoothing")).on_hover_text(tr!("Smooth when scaled or turned; off keeps hard pixel edges, for pixel art")).changed() { + app.run("library.set_smoothing", json!({"bitmap": id.0, "on": on})); + } + } + LibraryItem::Sound(id) => { + if let Some(x) = app.s.doc.sound(id) { + let info = format!("{} · {} Hz · {}", x.format.label(), x.rate, if x.channels > 1 { tr!("Stereo") } else { tr!("Mono") }); + with_type(ui, Type::Data, |ui| ui.label(text(Type::Caption, info))); + } + } + } +} + +// ----- preview -------------------------------------------------------------------------------- + +const PREVIEW_H: f32 = 72.0; + +/// The current item's picture: a symbol's first frame, a bitmap, or a sound's waveform with a +/// play button. +fn preview(app: &mut App, ui: &mut egui::Ui) { + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), PREVIEW_H), Sense::hover()); + ui.painter().rect_filled(r, T.rc(), T.field); + let Some(item) = app.library_sel.filter(|i| app.s.doc.has_item(*i)) else { + ui.painter().text(r.center(), Align2::CENTER_CENTER, tr!("Select an item to preview it"), font(Type::Caption), color(Type::Caption)); + return; + }; + let inner = r.shrink(6.0); + match item { + LibraryItem::Sound(id) => { + waveform(app, ui, inner, id); + let play = Rect::from_min_size(pos2(r.right() - TARGET - 4.0, r.top() + 4.0), vec2(TARGET, TARGET)); + let resp = ui.put(play, egui::Button::new("▶").min_size(vec2(TARGET, TARGET))); + a11y::control(ui, &resp, WidgetType::Button, tr!("Play the sound"), None); + if resp.on_hover_text(tr!("Plays the sound on its own")).clicked() + && let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded()) + { + app.playing = false; + app.sound.preview(dec.pcm.clone()); + if let Some(e) = app.sound.error.take() { + app.status_err(tr!("No sound: {error}", error = crate::i18n::t_dyn(&e.to_string()))); + } + } + } + _ => { + let key = (item, app.s.state); + if app.library.preview.as_ref().is_none_or(|p| p.key != key) { + let texture = picture(ui.ctx(), &app.s.doc, item, inner); + app.library.preview = Some(Preview { key, texture }); + } + if let Some(tex) = app.library.preview.as_ref().and_then(|p| p.texture.as_ref()) { + let size = tex.size_vec2() / ui.ctx().pixels_per_point(); + let fit = (inner.width() / size.x.max(1.0)).min(inner.height() / size.y.max(1.0)).min(1.0); + let at = Rect::from_center_size(inner.center(), size * fit); + ui.painter().image(tex.id(), at, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + } + } +} + +/// A texture of `item` fitting `area` (in points): a symbol's first frame rendered by the +/// oracle, or the bitmap, drawn with or without smoothing as it will be on the stage. +fn picture(ctx: &egui::Context, doc: &Document, item: LibraryItem, area: Rect) -> Option { + let ppp = ctx.pixels_per_point().clamp(0.5, 4.0); + let (w, h) = ((area.width() * ppp).round().max(1.0) as u32, (area.height() * ppp).round().max(1.0) as u32); + match item { + LibraryItem::Symbol(id) => { + let dl = symbol_frame(doc, id); + let b = dl.items.iter().filter(|i| !i.guide && i.masks.is_none()).fold(anicraft_engine::geom::Rect::EMPTY, |acc, i| { + let reach = i.stroke.as_ref().map_or(0.0, |s| s.reach()); + acc.union(&i.path.bounds().inflate(reach).transformed(&i.transform)) + }); + if b.is_empty() || !(b.width().is_finite() && b.height().is_finite()) { + return None; + } + let s = ((w as f32 - 4.0) / b.width().max(1e-3)).min((h as f32 - 4.0) / b.height().max(1e-3)).min(4.0 * ppp); + let c = b.center(); + let transform = anicraft_engine::geom::Affine::translate(w as f32 / 2.0, h as f32 / 2.0).mul(&anicraft_engine::geom::Affine::scale(s, s)).mul(&anicraft_engine::geom::Affine::translate(-c.x, -c.y)); + let view = anicraft_engine::render::View { transform, width: w, height: h, background: None }; + let (px, _) = anicraft_engine::render::render(&dl, &view).ok()?; + let image = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &px.to_premul_rgba8()); + Some(ctx.load_texture("library-preview", image, egui::TextureOptions::LINEAR)) + } + LibraryItem::Bitmap(id) => { + let b = doc.bitmap(id)?; + let px = b.pixels()?; + // At most the area's size in pixels (nearest pixel), so a huge image costs little. + let k = (w as f32 / px.width.max(1) as f32).min(h as f32 / px.height.max(1) as f32).min(1.0); + let (tw, th) = (((px.width as f32 * k).round() as u32).max(1), ((px.height as f32 * k).round() as u32).max(1)); + let mut rgba = Vec::with_capacity((tw * th * 4) as usize); + for y in 0..th { + for x in 0..tw { + let c = px.at((x as f32 / k) as i64, (y as f32 / k) as i64); + rgba.extend(c.iter().map(|v| (v * 255.0 + 0.5) as u8)); + } + } + let image = egui::ColorImage::from_rgba_unmultiplied([tw as usize, th as usize], &rgba); + let options = if b.smoothing { egui::TextureOptions::LINEAR } else { egui::TextureOptions::NEAREST }; + Some(ctx.load_texture("library-preview", image, options)) + } + LibraryItem::Sound(_) => None, + } +} + +/// Symbol `id`'s first frame on its own, its registration point at the origin. +fn symbol_frame(doc: &Document, id: anicraft_engine::doc::SymbolId) -> anicraft_engine::doc::DisplayList { + use anicraft_engine::doc::{Element, ElementId, ElementKind, Layer, LayerId, LoopMode, Scene}; + use std::sync::Arc; + let mut d = doc.clone(); + let mut layer = Layer::new(LayerId(u64::MAX - 1), ""); + if let Some(k) = layer.keyframe_mut(0) { + k.elements = vec![Arc::new(Element { + id: ElementId(u64::MAX - 2), + name: String::new(), + transform: Default::default(), + color: Default::default(), + kind: ElementKind::Symbol { symbol: id, loop_mode: LoopMode::SingleFrame, first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new() }, + })]; + } + let mut scene = Scene::new(""); + scene.timeline.layers.push(Arc::new(layer)); + d.scenes = vec![Arc::new(scene)]; + anicraft_engine::doc::evaluate_scene(&d, 0, 0) +} + +/// A sound's waveform across `r`: one line per point column, lowest to highest sample. +fn waveform(app: &App, ui: &egui::Ui, r: Rect, id: anicraft_engine::doc::SoundId) { + let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded_if_ready()) else { + ui.painter().text(r.center(), Align2::CENTER_CENTER, tr!("Reading the sound…"), font(Type::Caption), color(Type::Caption)); + return; + }; + let len = dec.peaks.frames(); + let cols = r.width().floor().max(1.0) as usize; + if len == 0 { + return; + } + let (cy, half) = (r.center().y, r.height() / 2.0); + let stroke = Stroke::new(1.0, T.waveform); + for c in 0..cols { + let a = c * len / cols; + let b = ((c + 1) * len / cols).max(a + 1).min(len); + if let Some((lo, hi)) = dec.peaks.range(a, b) { + let x = r.left() + c as f32 + 0.5; + ui.painter().line_segment([pos2(x, cy - hi.clamp(-1.0, 1.0) * half), pos2(x, cy - lo.clamp(-1.0, 1.0) * half)], stroke); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn session() -> (anicraft_engine::Session, u64, u64) { + let mut s = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let ball = s.doc.library.iter().find(|x| x.name == "Ball").map(|x| x.id.0).unwrap(); + let f = s.execute("library.new_folder", &json!({"name": "Characters"})).unwrap()["folder"].as_u64().unwrap(); + s.execute("library.duplicate", &json!({"symbol": ball})).unwrap(); + s.execute("library.move", &json!({"items": [{"symbol": ball}], "to": f})).unwrap(); + (s, ball, f) + } + + fn names(s: &anicraft_engine::Session, v: &mut LibraryView) -> Vec<(usize, String)> { + let (uses, _) = v.counts(s); + rows(&s.doc, v, &uses).into_iter().map(|r| (r.depth, r.name)).collect() + } + + #[test] + fn folders_come_first_and_open_ones_show_what_they_hold() { + let (s, _, f) = session(); + let mut v = LibraryView::default(); + let n = |d: usize, x: &str| (d, x.to_string()); + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(0, "Ball copy"), n(0, "Star")]); + v.expanded.insert(FolderId(f)); + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(1, "Ball"), n(0, "Ball copy"), n(0, "Star")]); + // By use count, most used first when descending; folders stay on top. + v.sort = Sort::Uses; + v.descending = true; + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(1, "Ball"), n(0, "Star"), n(0, "Ball copy")]); + // Date added: the copy is newest. + v.sort = Sort::Added; + v.descending = false; + assert_eq!(names(&s, &mut v)[2..], [n(0, "Star"), n(0, "Ball copy")]); + } + + #[test] + fn a_search_shows_matches_inside_closed_folders() { + let (s, _, _) = session(); + let mut v = LibraryView { filter: "BALL".into(), ..Default::default() }; + let n = |d: usize, x: &str| (d, x.to_string()); + assert_eq!(names(&s, &mut v), [n(0, "Characters"), n(1, "Ball"), n(0, "Ball copy")]); + v.filter = "nothing like it".into(); + assert!(names(&s, &mut v).is_empty()); + } +} diff --git a/src/main.rs b/src/main.rs index 37e70968..38f7fe49 100644 --- a/src/main.rs +++ b/src/main.rs @@ -34,6 +34,7 @@ mod dialogs; mod gpu_stage; mod icons; mod keymap; +mod library; mod menus; mod motion_editor; mod panels; @@ -176,7 +177,7 @@ fn main() -> eframe::Result { } "--help" | "-h" => { println!( // i18n-exempt: the --help console text - "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|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|testscript|exporthtml|sound|envelope]\n\ + "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--lang |auto|pseudo] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testscript|exporthtml|sound|envelope|library|librarymenu]\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/panels.rs b/src/panels.rs index 4f65e630..a22c3809 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -1,11 +1,11 @@ //! Tools bar, edit bar, status bar, Properties and Library panels. -use crate::app::{App, LibraryItem, Tool}; +use crate::app::{App, Tool}; use crate::icons::{self, Icon}; -use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, font, section, text, to_color32, with_type}; -use anicraft_engine::doc::{ElementKind, Paint, Rgba, SymbolKind, evaluate_layer_elements}; +use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, section, text, to_color32, with_type}; +use anicraft_engine::doc::{ElementKind, LibraryItem, Paint, Rgba, SymbolKind, evaluate_layer_elements}; use crate::a11y::{self, Named}; -use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; +use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2}; use serde_json::{Value, json}; // ----- tools -------------------------------------------------------------------------------- @@ -302,7 +302,12 @@ pub fn right(app: &mut App, ui: &mut egui::Ui) { // next one (Align goes with Properties, History with the Library). let split = ui.cursor().top(); let (library_header, _) = crate::theme::section_with_header(ui, "dock_library", Section::Band, tr!("Library"), None, |ui| { - egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| library(app, ui)); + // The Library scrolls on its own, so a short window still reaches every row (History's + // header stays below it). + let room = (ui.available_height() - 48.0).max(120.0); + egui::ScrollArea::vertical().id_salt("library_dock").max_height(room).auto_shrink([false, true]).show(ui, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| library(app, ui)); + }); }); section(ui, "dock_history", Section::Band, tr!("History"), None, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| history(app, ui)); @@ -439,7 +444,7 @@ fn properties(app: &mut App, ui: &mut egui::Ui) { } /// A symbol type's name, as the Properties panel shows it. -fn symbol_kind_label(kind: SymbolKind) -> &'static str { +pub(crate) fn symbol_kind_label(kind: SymbolKind) -> &'static str { match kind { SymbolKind::Graphic => tr!("Graphic"), SymbolKind::MovieClip => tr!("Movie clip"), @@ -579,6 +584,30 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E .response .set_name(tr!("Symbol type")); }); + // Swap Symbol (ADR 0050): another symbol in this instance's place, keeping its + // transform, colour effect, filters and name. + let current = *symbol; + let mut choices: Vec<(anicraft_engine::doc::SymbolId, String)> = app.s.doc.library.iter().map(|x| (x.id, app.s.doc.entry_path(anicraft_engine::doc::LibraryEntry::Item(LibraryItem::Symbol(x.id))))).collect(); + choices.sort_by_key(|(_, p)| p.to_lowercase()); + let name = app.s.doc.symbol(current).map(|x| x.name.clone()).unwrap_or_default(); + row_prose(ui, tr!("Symbol"), |ui| { + ui.label(text(Type::Body, name)); + ui.menu_button(tr!("Swap…"), |ui| { + egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { + for (id, path) in &choices { + if ui.selectable_label(*id == current, path.as_str()).clicked() { + ui.close(); + if *id != current { + app.run("element.swap_symbol", json!({"symbol": id.0})); + } + } + } + }); + }) + .response + .on_hover_text(tr!("Show another symbol here, keeping position, colour effect, filters and name")) + .set_name(tr!("Swap Symbol")); + }); // The class scripts know the symbol by (kept, not run; ADR 0013), in documents // that use scripts. let linkage = app.s.doc.symbol(*symbol).and_then(|s| s.linkage.clone()); @@ -1926,124 +1955,5 @@ fn ease_curve(ui: &mut egui::Ui, e: anicraft_engine::doc::Easing) { } fn library(app: &mut App, ui: &mut egui::Ui) { - let doc = &app.s.doc; - let rows: Vec = doc - .library - .iter() - .map(|sym| LibraryRow { - item: LibraryItem::Symbol(sym.id), - name: sym.name.clone(), - detail: tr!("{kind} · {frames}f", kind = symbol_kind_label(sym.kind), frames = sym.timeline.frame_count()), - kind: Some(sym.kind), - }) - .chain(doc.bitmaps.iter().map(|b| LibraryRow { item: LibraryItem::Bitmap(b.id), name: b.name.clone(), detail: tr!("Bitmap · {width}×{height}", width = b.width, height = b.height), kind: None })) - .chain(doc.sounds.iter().map(|x| LibraryRow { item: LibraryItem::Sound(x.id), name: x.name.clone(), detail: tr!("Sound · {seconds} s", seconds = format!("{:.1}", x.seconds())), kind: None })) - .collect(); - if rows.is_empty() { - let key = |id: &str| app.keymap.primary(id).map(crate::platform::shortcut_label).unwrap_or_default(); - ui.label(text(Type::Caption, tr!("No symbols, images or sounds yet. Select artwork and press {convert} to make a symbol, or import an image or a sound with {import}.", convert = key("modify.convert_to_symbol"), import = key("file.import")))); - return; - } - ui.label(text(Type::Caption, trn!("{n} item", "{n} items", rows.len()))); - // Sounds go on the active layer's keyframe at the playhead, their span grown to fit. - let place = |app: &mut App, item: LibraryItem| match item { - LibraryItem::Symbol(id) => app.run("library.place", json!({"symbol": id.0})), - LibraryItem::Bitmap(id) => app.run("library.place", json!({"bitmap": id.0})), - LibraryItem::Sound(id) => app.run("sound.place", json!({"sound": id.0, "extend": true})), - }; - egui::ScrollArea::vertical().id_salt("lib").max_height(140.0).auto_shrink([false, true]).show(ui, |ui| { - for row in &rows { - let selected = app.library_sel == Some(row.item); - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), TARGET), Sense::click()); - if selected || resp.hovered() { - ui.painter().rect_filled(r, T.rc(), if selected { T.accent_dim } else { T.hover }); - } - if selected { - ui.painter().rect_filled(Rect::from_min_size(r.left_top(), vec2(3.0, r.height())), 0.0, T.accent); - } - let icon = Rect::from_center_size(r.left_center() + vec2(14.0, 0.0), vec2(14.0, 14.0)); - match (row.kind, row.item) { - (Some(kind), _) => { - let kind_color = match kind { - SymbolKind::Graphic => T.kind_graphic, - SymbolKind::MovieClip => T.kind_movie_clip, - SymbolKind::Button => T.kind_button, - }; - ui.painter().rect_stroke(icon, 2.0, Stroke::new(1.5, kind_color), StrokeKind::Inside); - ui.painter().circle_filled(icon.center(), 2.5, kind_color); - } - (None, LibraryItem::Sound(_)) => icons::paint(ui.painter(), icon.expand(1.0), Icon::Sound, color(Type::Body)), - (None, _) => icons::paint(ui.painter(), icon.expand(1.0), Icon::Image, color(Type::Body)), - } - ui.painter().text(r.left_center() + vec2(30.0, 0.0), Align2::LEFT_CENTER, &row.name, font(Type::Body), color(Type::Body)); - ui.painter().text(r.right_center() - vec2(8.0, 0.0), Align2::RIGHT_CENTER, &row.detail, font(Type::Caption), color(Type::Caption)); - a11y::control(ui, &resp, WidgetType::SelectableLabel, &format!("{} · {}", row.name, row.detail), Some(selected)); - if resp.clicked() { - app.library_sel = Some(row.item); - } - // A symbol opens for editing, as in Animate (ADR 0045); images and sounds go on the - // stage. Place on stage (below) places a symbol. - if resp.double_clicked() { - match row.item { - LibraryItem::Symbol(id) => { - app.run("symbol.edit", json!({"symbol": id.0})); - } - other => { - place(app, other); - } - } - } - // Opens it alone, its registration point at the stage's centre (ADR 0045). - if let LibraryItem::Symbol(id) = row.item { - resp.context_menu(|ui| { - if ui.button(tr!("Edit Symbol")).clicked() { - ui.close(); - app.run("symbol.edit", json!({"symbol": id.0})); - } - }); - } - if let LibraryItem::Sound(id) = row.item { - resp.context_menu(|ui| { - if ui.button(tr!("Delete Sound")).clicked() { - ui.close(); - app.request("sound.delete", json!({"sound": id.0})); - } - }); - } - } - }); - ui.add_space(4.0); - let can_place = app.library_sel.filter(|sel| rows.iter().any(|r| r.item == *sel)); - match can_place { - Some(LibraryItem::Sound(id)) => { - ui.horizontal(|ui| { - if ui.button(tr!("Preview")).on_hover_text(tr!("Plays the sound on its own")).clicked() - && let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded()) - { - app.playing = false; - app.sound.preview(dec.pcm.clone()); - if let Some(e) = app.sound.error.take() { - app.status_err(tr!("No sound: {error}", error = crate::i18n::t_dyn(&e.to_string()))); - } - } - if ui.button(tr!("Place on timeline")).on_hover_text(tr!("Puts it on the active layer's keyframe at the playhead (or double-click it)")).clicked() { - place(app, LibraryItem::Sound(id)); - } - }); - } - _ => { - if ui.add_enabled(can_place.is_some(), egui::Button::new(tr!("Place on stage"))).on_hover_text(tr!("Adds it at the stage centre (or double-click an item)")).clicked() - && let Some(item) = can_place { - place(app, item); - } - } - } -} - -/// One Library row: a symbol (with its kind), a bitmap or a sound. -struct LibraryRow { - item: LibraryItem, - name: String, - detail: String, - kind: Option, + crate::library::panel(app, ui); } From 41b55241fdd4af51220bed31afd4c03cca463174 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:55:55 -0700 Subject: [PATCH 18/19] perf(engine): measure Library use counts and unused items on a large document (M2) 200,000 element keys (stress 100x100x240) plus 1,000 symbols in 50 folders, release build: use counts 1.5 ms, unused items 1.7 ms, library.items 5.0 ms. --- crates/engine/src/library_tests.rs | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/engine/src/library_tests.rs b/crates/engine/src/library_tests.rs index cc350a87..318b460d 100644 --- a/crates/engine/src/library_tests.rs +++ b/crates/engine/src/library_tests.rs @@ -283,3 +283,37 @@ fn inside_an_open_symbol_swap_never_nests_and_deleting_it_closes_it() { run(&mut s, "library.delete", json!({"items": [{"symbol": outer}], "confirm": true})); assert!(s.editing.is_empty() && s.doc.symbol(SymbolId(outer)).is_none()); } + +#[test] +fn library_counts_stay_quick_on_a_large_document() { + // 100 layers × 100 shapes keyed every 12 frames over 240 frames (200,000 element keys), + // plus 1,000 symbols in 50 folders, each placed once. Measured, loosely bounded (CI varies); + // the shell works these out once per document change, not per frame. + let mut s = Session::new(anicraft_doc::sample::stress(100, 100, 240)); + // A new layer, so the symbol holds only the new rectangle (drawing selects it). + run(&mut s, "layer.new", json!({})); + run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 5, "h": 5})); + let sym = run(&mut s, "modify.convert_to_symbol", json!({}))["symbol"].as_u64().unwrap(); + for i in 0..50 { + run(&mut s, "library.new_folder", json!({"name": format!("F{i}")})); + } + let folders: Vec = s.doc.library_tree.folders.iter().map(|f| f.id.0).collect(); + for i in 0..999 { + let c = run(&mut s, "library.duplicate", json!({"symbol": sym, "name": format!("S{i}")}))["symbol"].as_u64().unwrap(); + run(&mut s, "library.move", json!({"items": [{"symbol": c}], "to": folders[i % folders.len()]})); + } + let t = std::time::Instant::now(); + let uses = s.doc.library_uses(); + let counted = t.elapsed(); + let t = std::time::Instant::now(); + let unused = s.doc.unused_items(); + let reach = t.elapsed(); + let t = std::time::Instant::now(); + let listed = run(&mut s, "library.items", json!({})); + let listing = t.elapsed(); + println!("library of {} items, {} folders: use counts {counted:?}, unused {reach:?} ({} unused), library.items {listing:?}", s.doc.library.len(), folders.len(), unused.len()); + assert_eq!(listed["items"].as_array().map(Vec::len), Some(1000)); + assert_eq!(unused.len(), 999); + assert!(uses.values().sum::() >= 1); + assert!(counted.as_millis() < 500 && reach.as_millis() < 500, "counted {counted:?}, unused {reach:?}"); +} From dfca6610f8f280f87024539b5e71aa3c1c175740 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 10 Nov 2026 23:56:53 -0700 Subject: [PATCH 19/19] docs: ADR 0050 library management, roadmap and changelog (M2) --- CHANGELOG.md | 25 ++++++ docs/adr/0050-library-management.md | 126 ++++++++++++++++++++++++++++ docs/adr/README.md | 1 - docs/roadmap.md | 3 +- 4 files changed, 153 insertions(+), 2 deletions(-) create mode 100644 docs/adr/0050-library-management.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 11ee8d59..a6b3e715 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ ## Unreleased +* **Library management** (ADR 0050, M2). + * **Folders**: New Folder (the folder icon under the list, or right-click), nested as deep as + you like (32 levels). Drag items and folders onto a folder to move them in, onto an item to + join its folder, or below the list for the top level; right-click › Move to does the same. + Deleting a folder that holds items asks first, and its items go with it. + * **Rename in place** with F2 or a double-click on the name; Enter keeps it, Esc cancels. + Names are unique within a folder (case aside), as in Animate. Convert to Symbol picks the next + free “Symbol n”. + * **Duplicate Symbol** (right-click): “Ball copy” in the same folder, ready to rename. + * **Swap Symbol** in Properties › Symbol: pick another symbol for the selected instances. + Position, colour effect, blending, filters, looping and instance name stay. + * A **use count** for every item, **Select Unused Items** and **Delete Unused Items…** (in + More). Unused means nothing in any scene reaches it, so one pass clears a whole unused + branch; symbols with a linkage class count as used. Deleting an item the movie uses asks, + and its instances go with it. + * **Sort** by name, type, use count or date added, ascending or descending, and **search** + by name; folders that hold a match open. + * A **preview** of the current item (a symbol's first frame, the bitmap, or a sound's + waveform with a play button) and its **properties**: a symbol's type and linkage class, a + bitmap's **Allow Smoothing**. Smoothing off keeps hard pixel edges on the stage, in + renders, in SVG and in the HTML page. + * Animate files keep their library folders and Allow Smoothing. + * Headless: `library.items`, `library.new_folder`, `library.rename`, `library.move`, + `library.duplicate`, `library.delete`, `library.unused`, `library.delete_unused`, + `library.set_smoothing`, `element.swap_symbol`. * **Raw points, snapping while drawing, and symbols edited in place** (ADR 0045, issue #42, M1). * **Add a point** on a merged drawing's line or fill edge with the Pen's Alt-click or a Subselection double-click: every shape on that edge gets it, and the curve keeps its shape. diff --git a/docs/adr/0050-library-management.md b/docs/adr/0050-library-management.md new file mode 100644 index 00000000..56c82456 --- /dev/null +++ b/docs/adr/0050-library-management.md @@ -0,0 +1,126 @@ +# ADR 0050: Library folders, item management and Swap Symbol + +* Status: accepted (2026-11-10) +* Relates to: ADR 0003 (file format), ADR 0004 (destructive actions), ADR 0009 (XFL import), + ADR 0013 (scripts and linkage), ADR 0019/0032 (GPU stage), ADR 0028 (HTML canvas export), + ADR 0045 (symbols edited in place), roadmap M2 + +## Context + +The Library listed symbols, bitmaps and sounds in one flat list. It could place an item, delete +a sound and (since ADR 0045) open a symbol for editing. Animate users keep hundreds of items in +nested folders, rename them in place, duplicate symbols to make variants, swap one symbol for +another on the stage, clean out what the movie no longer uses, and set per-item options such as +a bitmap's smoothing. We learned how Animate does this from its public help pages and from +watching the program. Nothing was copied. + +## Decision + +1. **The organisation is a side table, not a field on each item.** + `Document.library_tree: Arc` (`crates/doc/src/library.rs`) holds the folders + (`LibraryFolder { id, name, parent }`) and a map from each item (`LibraryItem::Symbol | + Bitmap | Sound`) to its folder. An item that isn't in the map is at the top level. We chose + this over a `folder` field on `Symbol`, `Bitmap` and `Sound`: + * Moving or renaming folders touches one small table, never a symbol (so undo snapshots stay + O(changed) and symbol timelines keep their `Arc`s). + * The three item structs, which many places build, are unchanged. + * Older files have no `library_tree` and open with everything at the top level. A Library + without folders writes nothing new (`skip_serializing_if`), so files stay the same until + a folder is made. + + Folder ids come from the document's id counter, like every other id. On load, + `sanitize_library_tree` repairs a damaged tree: duplicate ids, missing parents, cycles and + nesting deeper than 32 levels are fixed, and placements of items that aren't there are + dropped. It touches nothing when the tree is sound. The fuzz checks that no command leaves a + tree that a load would have to repair. + +2. **Names are unique within a folder, ignoring case,** across items and folders, as in Animate. + They can't be empty, can't be longer than 256 characters, and can't contain `/`, which joins + a path (`Characters/Hero/Ball`). The engine checks this in `library.new_folder`, + `library.rename`, `library.move` and `library.duplicate`. A move whose name is already in + the target folder fails with a message naming it, and nothing moves (commands are atomic). + We chose refusing over Animate's "replace existing items?" prompt: replacing destroys + content, and a rename is one keystroke away. Older documents with duplicate names open as + they are. Convert to Symbol now picks the next free "Symbol n". + +3. **Commands** (`crates/engine/src/cmds_library.rs`), all in the existing `library` and + `element` plug-in namespaces. Entries are named `{"symbol"|"bitmap"|"sound"|"folder": id}`. + * `library.items`: every folder and item with path, kind, use count and whether it is unused. + * `library.new_folder`, `library.rename`, `library.move`. A folder can't go inside itself, + and nesting is limited to 32 levels. + * `library.duplicate`: a copy right after the original, in the same folder, named + " copy" (then "copy 2", …). It gets fresh layer and element ids, with layer parents, + motion tween targets and bone ends following them (`library::fresh_ids`). It has no + linkage class, because a class names one symbol. + * `library.delete`: deletes items and folders together with what they hold. What uses them + goes too, as in Animate: instances of deleted symbols, shapes filled with deleted bitmaps, + and deleted sounds on keyframes, on every timeline. Only the layers and keyframes that had + a use are copied. Deleting the symbol that is open for editing closes it (ADR 0045). + * `library.unused` (Select Unused Items) and `library.delete_unused`. + * `library.set_smoothing`; `element.swap_symbol`. Linkage stays `script.set_class` + (ADR 0013). + +4. **Use count and unused have different meanings, on purpose.** Use count is the number of + references on every timeline (scenes and symbols), counted once per keyframe: instances, + bitmap fills and keyframe sounds. *Unused* means **not reachable from any scene**. A symbol + used only inside a symbol that nothing places is unused, even though its count is above + zero. One Delete Unused Items then clears a whole dead branch in one undo step, instead of + peeling off one layer per run. Symbols with a linkage class count as reached, because scripts + create them by name (ADR 0013). The row's tooltip and screen-reader name give both. + +5. **Confirmations follow ADR 0004** (undoable tier, `crates/engine/src/confirm.rs`). Deleting + asks only when something deleted is in use ("used 4 times in the movie; those uses go too") + or when a folder holds items ("holds 5 items, deleted with it"). Deleting an unused item or + an empty folder is routine and doesn't ask. Delete Unused Items always asks and names the + first few items. + +6. **Swap Symbol** replaces only the symbol an instance shows. Transform, colour effect, + blending, filters, looping, actions and instance name stay, as in Animate. It is a button in + Properties › Symbol ("Swap…", listing symbols by path). Inside a symbol open for editing, it + refuses a symbol that would contain itself (`editing::would_nest`). + +7. **Allow Smoothing** is a property of the bitmap (`Bitmap.smoothing`, on by default; only + `false` is written). It reaches the renderers through `DisplayItem.smooth`. The CPU oracle + samples the nearest pixel instead of bilinear (`Shader::smoothed`). The GPU stage uses bit 1 + of the bitmap's flag word in `fine.wgsl` and does the same, so oracle parity still holds. + SVG export marks the image `image-rendering="pixelated"`, and the HTML page turns + `imageSmoothingEnabled` off for that fill. XFL import reads `allowSmoothing`. + +8. **XFL import keeps folders.** `` creates folders, empty + ones included. Symbols and bitmaps go into the folder their library name's path names + (`Characters/Ball` → `Ball` in `Characters`). The report lists "library folders" as kept. + +9. **The panel (`src/library.rs`) holds only view state**: selection (Ctrl-click and + Shift-click ranges), open folders, sort (Name, Type, Use count, Date added, ascending or + descending; folders first), the search text, and the item being renamed. Everything that + changes the document is a command. + * "Date added" is the item's id order: ids only grow, so no clock is stored. + * Searching opens every folder that leads to a match. + * F2, or a double-click on the name, renames in place. Enter or clicking away keeps the new + name; Esc cancels. A double-click on the icon edits a symbol (ADR 0045) or places an image + or sound. + * Rows drag onto a folder (into it), onto an item (into that item's folder) or below the + list (to the top level). + * F2 and Delete act on the Library only while the list was the last thing clicked, so + Delete on the stage still clears artwork. + * The preview shows a symbol's first frame rendered by the CPU oracle, a bitmap drawn with or + without smoothing as on the stage, or a sound's waveform with a play button. Below it are + the item's properties: a symbol's type and linkage class, a bitmap's Allow Smoothing, a + sound's format. + * Use counts are worked out once per document state. + +## Consequences + +* Measured on 200,000 element keys plus 1,000 symbols in 50 folders, release build: use counts + 1.5 ms, unused items 1.7 ms, the whole `library.items` listing 5.0 ms (`library_tests.rs`). +* Duplicates share no ids with their originals. Bone ids inside an armature are kept: they are + scoped to their layer. +* One XFL corpus golden changed: its checker bitmap says `allowSmoothing="false"` and is now + drawn with hard edges, as Animate shows it. + +## Not yet + +Dragging Library items onto the stage, Animate's Properties dialog (the properties are inline), +linkage on bitmaps and sounds, bitmap compression settings, Update and Import of library items +from another document (shared libraries), folder expansion saved in the file, sorting by size, +choosing a folder in Convert to Symbol, and Swap Bitmap. diff --git a/docs/adr/README.md b/docs/adr/README.md index 0390bd99..8a35fed1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,4 +23,3 @@ has to renumber because another PR merged first. | Number | Pull request | Topic | |---|---|---| | 0037 | #38 (outside contribution) | Interface languages | -| 0050 | m2/library-management | Library folders, item management and Swap Symbol | diff --git a/docs/roadmap.md b/docs/roadmap.md index 780d3774..dcb99ce2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -17,6 +17,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | 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. | | 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`. Not yet: sounds on button frames, sound panning beyond the envelope, sounds from XFL (Animate keeps sound data in an undocumented binary form, so neither sounds nor their envelopes come across), 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): 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). Brightness colour effects (as a tint towards white or black), 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, advanced colour effects, 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). | +| 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`. Not yet: dragging items onto the stage, shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, a folder choice in Convert to Symbol, Swap Bitmap. | | 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. | | Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. | | Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Web editor, first slice** (ADR 0036, `docs/web.md`): the same program built for `wasm32-unknown-unknown` runs in a browser (WebGL2), built by `scripts/build-web.sh`/`.ps1` with the wasm-bindgen CLI into `web/` (8973 KB, 3278 KB gzipped). Open and import with the browser's file picker; save and export as downloads (the engine reads and writes through `engine::vfs`, memory in the browser). Autosave and preferences in browser storage, with Web Locks so only closed or crashed tabs' work is offered. Leaving with unsaved work asks first. Every crate builds for wasm32 in CI, and the engine's tests run inside WebAssembly in Node. Not yet: a browser-verified run, sound (Web Audio), the GPU stage on WebGPU, video export, plug-in installs, PNG sequence as one zip, IndexedDB for large autosaves, threads, hosting. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. | @@ -32,7 +33,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a |---|---|---| | **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. | | **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅. | -| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | +| **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); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); GPU binning deferred (not the bottleneck as tiles); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: shared filtered layers across tiles, an image atlas, GPU exports. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); not yet: `.fla` variants of the corpus, sound and video items; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | | **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 XFL sounds later); ~~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. |