From 307e496d55ef7c668694e72f4eb0e1a586de8523 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:28:08 +0000 Subject: [PATCH 01/23] Fix Vec2::length overflow for large vectors Found while testing crates/geom/src/lib.rs:46-52 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/lib.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index e0b75dd1..bfaf9db7 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -44,7 +44,7 @@ impl Vec2 { self.x * o.y - self.y * o.x } pub fn length(self) -> f32 { - self.dot(self).sqrt() + self.x.hypot(self.y) } pub fn normalized(self) -> Vec2 { let l = self.length(); @@ -197,4 +197,12 @@ mod tests { assert_eq!(v.perp().dot(v), 0.0); assert_eq!(Vec2::ZERO.normalized(), Vec2::ZERO); } + + #[test] + fn length_and_normalized_survive_huge_components() { + let v = Vec2::new(3e19, 4e19); + assert!((v.length() / 5e19 - 1.0).abs() < 1e-5, "len {}", v.length()); + let n = v.normalized(); + assert!((n.x - 0.6).abs() < 1e-5 && (n.y - 0.8).abs() < 1e-5, "{n:?}"); + } } From 22aef692a35f6ea1d994b1d25e28531f4b3e9ecf Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 14:41:08 +0000 Subject: [PATCH 02/23] fix(tween): morph a shape's stroke with its fill when the side counts differ Merge Drawing stores a shape's line as one element per piece, cut at every corner, and a shape tween paired elements one to one by position. A triangle (3 pieces) into a hexagon (6) left sides bare or pieces standing in between. A shape tween now joins each stroke style's pieces end to end into the outlines they make, on both keyframes, and morphs those as it morphs the fill. Fixes #119 --- crates/doc/src/eval.rs | 71 ++++++++++++++++++++++++++++++++++++-- crates/engine/src/tests.rs | 62 +++++++++++++++++++++++++++++++++ crates/geom/src/morph.rs | 70 +++++++++++++++++++++++++++++++++++++ 3 files changed, 201 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index a17dcd6f..e17783dc 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -242,18 +242,85 @@ fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk>) let morph = tween.kind == TweenKind::Shape; let path = guide.map(|g| (g, tween.orient)); let pairs = if morph && !kf.hints.is_empty() { crate::hints::hint_pairs(kf, next) } else { Vec::new() }; + let lines = if morph { tween_lines(kf, next, t) } else { Vec::new() }; let els = kf .elements .iter() .enumerate() - .map(|(i, a)| { + .filter_map(|(i, a)| { + // A line tweened whole stands in for its first piece; its other pieces go. + if let Some((pieces, line)) = lines.iter().find(|l| l.0.contains(&i)) { + return (pieces.first() == Some(&i)).then(|| line.clone()); + } let hints: Vec<_> = pairs.iter().filter(|h| h.0 == i).map(|h| (h.1, h.2)).collect(); - next.elements.get(i).and_then(|b| interpolate(a, b, t, morph, &hints, path)).map_or_else(|| a.clone(), Arc::new) + Some(next.elements.get(i).and_then(|b| interpolate(a, b, t, morph, &hints, path)).map_or_else(|| a.clone(), Arc::new)) }) .collect(); Some((kf.start, Cow::Owned(els))) } +/// The stroke of a raw line piece: what Merge Drawing makes of a drawing's lines, cut at every +/// corner, one element per piece (placed with a plain translation). +fn raw_line(e: &Element) -> Option<&Stroke> { + let [a, b, c, d, ..] = e.transform.m; + match &e.kind { + ElementKind::Shape(s) if s.merge && s.fill.is_none() && [a - 1.0, b, c, d - 1.0].iter().all(|v| v.abs() <= 1e-6) => s.stroke.as_ref(), + _ => None, + } +} + +/// The raw line pieces of `els`, by stroke style (and colour effect) in the order the styles +/// first appear: each style's element indices. +fn line_styles(els: &[Arc]) -> Vec> { + let mut styles: Vec<(&Stroke, crate::ColorEffect, Vec)> = Vec::new(); + for (i, e) in els.iter().enumerate() { + let Some(st) = raw_line(e) else { continue }; + match styles.iter_mut().find(|s| s.0 == st && s.1 == e.color) { + Some(s) => s.2.push(i), + None => styles.push((st, e.color, vec![i])), + } + } + styles.into_iter().map(|s| s.2).collect() +} + +/// A shape tween's raw lines (issue #119): on each keyframe the pieces of one style are joined +/// end to end into the outlines they make, and those morph as the fill does, so the line +/// follows the fill whatever its number of sides (paired piece by piece, sides went bare or +/// pieces were left standing). Styles pair in the order they first appear; each comes out as +/// one element, with the indices of the start keyframe's pieces it replaces. +fn tween_lines(kf: &crate::Keyframe, next: &crate::Keyframe, t: f32) -> Vec<(Vec, Arc)> { + let (sa, sb) = (line_styles(&kf.elements), line_styles(&next.elements)); + sa.into_iter().zip(sb).filter_map(|(ia, ib)| Some((ia.clone(), Arc::new(tween_line(&kf.elements, &ia, &next.elements, &ib, &kf.hints, t)?)))).collect() +} + +/// The pieces `ia` of `a` morphed `t` of the way to the pieces `ib` of `b`, as one line. +fn tween_line(a: &[Arc], ia: &[usize], b: &[Arc], ib: &[usize], hints: &[crate::ShapeHint], t: f32) -> Option { + use anicraft_geom::morph; + let outline = |els: &[Arc], idx: &[usize]| { + let pieces: Vec = idx + .iter() + .filter_map(|&i| match &els.get(i)?.kind { + ElementKind::Shape(s) => Some(s.path.transformed(&els.get(i)?.transform)), + _ => None, + }) + .collect(); + morph::chain(&pieces, anicraft_geom::planar::SNAP) + }; + let (first, other) = (a.get(*ia.first()?)?, b.get(*ib.first()?)?); + let (sa, sb) = (raw_line(first)?, raw_line(other)?); + let (pa, pb) = (outline(a, ia), outline(b, ib)); + // Hints placed on these lines on both keyframes steer them as they steer the fill they edge. + let on = |p: &Path, q| morph::nearest_point(p, q).is_some_and(|(_, d)| d <= crate::hints::HINT_TOLERANCE); + let hints: Vec<_> = hints.iter().take(crate::hints::MAX_SHAPE_HINTS).filter(|h| on(&pa, h.start) && on(&pb, h.end)).map(|h| (h.start, h.end)).collect(); + let path = morph::morph_hinted(&pa, &pb, &hints, t)?; + let c = path.bounds().center(); + if !c.is_finite() { + return None; + } + let shape = Shape { path: Arc::new(path.transformed(&Affine::translate(-c.x, -c.y))), fill: None, stroke: Some(sa.lerp(sb, t)), fill_rule: FillRule::default(), merge: true }; + Some(Element { id: first.id, name: first.name.clone(), transform: Affine::translate(c.x, c.y), color: first.color.lerp(&other.color, t), kind: ElementKind::Shape(shape) }) +} + /// Interpolates two elements; `None` when they cannot tween. With `morph` (a shape tween), /// shapes of different structure blend through [`anicraft_geom::morph`], steered by `hints` /// (shape hints in each element's own space, ADR 0023); otherwise a shape changes only when diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 96a3bf36..ad6fc34d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1598,6 +1598,68 @@ fn create_shape_tween_morphs_and_keeps_the_easing() { assert_eq!(s.active_layer().unwrap().keyframes[0].tween.unwrap().kind, anicraft_doc::TweenKind::Classic); } +/// The flattened outlines of `items` (stage space), as line segments. +fn outline_segments<'a>(items: impl Iterator) -> Vec<(Vec2, Vec2)> { + let mut segs = Vec::new(); + for it in items { + for pl in it.path.flatten(&it.transform, 0.05) { + segs.extend(pl.points.windows(2).map(|w| (w[0], w[1]))); + if let (true, Some(&a), Some(&b)) = (pl.closed, pl.points.last(), pl.points.first()) { + segs.push((a, b)); + } + } + } + segs +} + +/// How far `p` is from the nearest of `segs`. +fn distance_to(segs: &[(Vec2, Vec2)], p: Vec2) -> f32 { + segs.iter() + .map(|&(a, b)| { + let ab = b - a; + let t = if ab.dot(ab) > 0.0 { ((p - a).dot(ab) / ab.dot(ab)).clamp(0.0, 1.0) } else { 0.0 }; + p.distance(a + ab * t) + }) + .fold(f32::INFINITY, f32::min) +} + +#[test] +fn shape_tweens_carry_the_stroke_round_shapes_with_more_or_fewer_sides() { + // Issue #119. A stroked triangle into a stroked hexagon and back (raw shapes: Merge Drawing + // makes one stroke piece per side, 3 and 6 of them). In between, the stroke must follow the + // whole morphing fill outline: no side left bare, no line left standing off it. + let mut s = Session::default(); + let polygon = |s: &mut Session, sides: u32| { + let inner = 60.0 * (std::f32::consts::PI / sides as f32).cos(); // on the edges: a polygon + run(s, "draw.star", json!({"cx": 100, "cy": 100, "outer": 60, "inner": inner, "points": sides, "fill": "#ff0000", "stroke": "#000000", "stroke_width": 2, "object": false})); + }; + polygon(&mut s, 3); + let strokes = |s: &Session| s.active_layer().unwrap().keyframes.last().unwrap().elements.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_none())).count(); + assert_eq!(strokes(&s), 3, "one stroke piece per side"); + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "timeline.insert_blank_keyframe", json!({})); + polygon(&mut s, 6); + assert_eq!(strokes(&s), 6); + run(&mut s, "timeline.goto", json!({"frame": 20})); + run(&mut s, "timeline.insert_blank_keyframe", json!({})); + polygon(&mut s, 3); + for frame in [0, 10] { + run(&mut s, "timeline.create_shape_tween", json!({"frame": frame})); + } + for frame in [3, 5, 8, 13, 15, 18] { + let list = anicraft_doc::evaluate(&s.doc, frame); + let fill = outline_segments(list.items.iter().filter(|i| i.fill.is_some())); + let stroke = outline_segments(list.items.iter().filter(|i| i.stroke.is_some())); + assert!(!fill.is_empty() && !stroke.is_empty(), "frame {frame}"); + // Every point of the fill's outline has the stroke on it, and every point of the stroke + // lies on the outline. + let bare = fill.iter().flat_map(|&(a, b)| (0..=8).map(move |k| a.lerp(b, k as f32 / 8.0))).map(|p| distance_to(&stroke, p)).fold(0.0, f32::max); + let stray = stroke.iter().flat_map(|&(a, b)| (0..=8).map(move |k| a.lerp(b, k as f32 / 8.0))).map(|p| distance_to(&fill, p)).fold(0.0, f32::max); + assert!(bare < 0.5, "frame {frame}: part of the outline is {bare} from the stroke"); + assert!(stray < 0.5, "frame {frame}: a stroke is {stray} off the outline"); + } +} + #[test] fn scenes_play_in_order_edit_separately_and_survive_save_and_undo() { let mut s = Session::default(); diff --git a/crates/geom/src/morph.rs b/crates/geom/src/morph.rs index 1f95e61c..0b875d61 100644 --- a/crates/geom/src/morph.rs +++ b/crates/geom/src/morph.rs @@ -540,6 +540,49 @@ fn to_path(subs: &[Sub]) -> Path { p } +/// Most open subpaths [`chain`] joins (the search is quadratic); past it they stay as they are. +const MAX_CHAIN: usize = 1024; + +/// Joins the open subpaths of `paths` that meet end to end (within `tol`, turning one round +/// where needed) into longer ones, closing a chain that comes back to its start. Merge +/// Drawing cuts a shape's line at every corner; chained, the pieces are its outline again, so +/// a shape tween morphs them as it morphs the fill. Closed subpaths pass through as they are. +pub fn chain(paths: &[Path], tol: f32) -> Path { + let (mut out, mut open): (Vec, Vec) = paths.iter().flat_map(subpaths).partition(|s| s.closed); + if open.len() > MAX_CHAIN { + out.append(&mut open); + return to_path(&out); + } + let end = |s: &Sub| s.segs.last().map_or(s.start, |g| g[2]); + let near = |a: Vec2, b: Vec2| a.distance(b) <= tol; + open.reverse(); // taken from the back, so in drawing order + while let Some(mut cur) = open.pop() { + // A chain that has come back to its start is done (other pieces may meet it there). + while !near(end(&cur), cur.start) { + let e = end(&cur); + if let Some(i) = open.iter().rposition(|s| near(s.start, e) || near(end(s), e)) { + let s = open.remove(i); + cur.segs.extend(if near(s.start, e) { s.segs } else { reverse(&s).segs }); + } else if let Some(i) = open.iter().rposition(|s| near(end(s), cur.start) || near(s.start, cur.start)) { + let s = open.remove(i); + let mut s = if near(end(&s), cur.start) { s } else { reverse(&s) }; + s.segs.append(&mut cur.segs); + cur = s; + } else { + break; + } + } + if near(end(&cur), cur.start) { + if let Some(g) = cur.segs.last_mut() { + g[2] = cur.start; + } + cur.closed = true; + } + out.push(cur); + } + to_path(&out) +} + /// Most shape hints a morph honours (Animate's a to z). pub const MAX_HINTS: usize = 26; @@ -841,6 +884,33 @@ mod tests { assert!(close(anchors_of(&y)[k], Vec2::new(50.0, 80.0))); } + #[test] + fn chain_joins_pieces_that_meet_into_outlines() { + // A triangle's sides, out of order, one drawn backwards and one a hair off its corner, + // plus a stray line and a closed square: the sides become one closed outline. + let (p, q, r) = (Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(5.0, 8.0)); + let sides = [Path::line(q, r), Path::line(Vec2::new(0.05, 0.0), q), Path::line(p, r)]; + let stray = Path::line(Vec2::new(50.0, 50.0), Vec2::new(60.0, 50.0)); + let square = Path::rect(100.0, 0.0, 5.0, 5.0); + let mut all = sides.to_vec(); + all.extend([stray.clone(), square.clone()]); + let joined = chain(&all, 0.2); + let subs = subpaths(&joined); + assert_eq!(subs.len(), 3, "{subs:?}"); + let tri = subs.iter().find(|s| s.segs.len() == 3).unwrap(); + assert!(tri.closed); + let corners: Vec = anchors(tri).collect(); + for c in [q, r] { + assert!(corners.iter().any(|a| close(*a, c)), "{c:?} in {corners:?}"); + } + assert!(corners.iter().any(|a| a.distance(p) < 0.1)); + assert!(subs.iter().any(|s| !s.closed && s.segs.len() == 1), "the stray line stays open"); + assert!(subs.iter().any(|s| s.closed && s.segs.len() == 4), "the square passes through"); + // The joined triangle morphs like the filled one. + assert!(morph(&joined, &Path::ellipse(0.0, 0.0, 5.0, 5.0), 0.5).is_some()); + assert!(chain(&[], 0.2).cmds.is_empty()); + } + #[test] fn nearest_point_snaps_to_the_outline() { let sq = Path::rect(0.0, 0.0, 100.0, 100.0); From 1f58af08e7a3261ef988ae2118de04f967a2d15f Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:51:19 +0100 Subject: [PATCH 03/23] Keep alpha in Rgba::to_hex so the hex round trip is lossless Found while testing crates/doc/src/lib.rs:77-81 (Rgba::to_hex) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/lib.rs | 13 ++++++++++++- crates/render/src/html.rs | 4 ++-- crates/render/src/lottie.rs | 2 +- crates/render/src/svg.rs | 3 ++- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index b6cde82e..a74fd096 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -85,7 +85,11 @@ impl Rgba { pub fn to_hex(self) -> String { let s = self.sanitized(); let b = |v: f32| (v * 255.0).round() as u8; - format!("#{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b)) + if s.a < 1.0 { + format!("#{:02x}{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b), b(s.a)) + } else { + format!("#{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b)) + } } /// Parses `#rrggbb`, `rrggbb` or `#rrggbbaa`. pub fn parse_hex(s: &str) -> Option { @@ -1687,6 +1691,13 @@ mod tests { assert_eq!(LoopMode::Loop.local_frame(u32::MAX, u32::MAX, 0), 0); } + #[test] + fn hex_roundtrip_keeps_alpha() { + let c = Rgba::parse_hex("#ff000080").unwrap(); + assert_eq!(c.to_hex(), "#ff000080"); + assert_eq!(Rgba::parse_hex(&c.to_hex()).unwrap(), c); + } + #[test] fn hex_roundtrip() { let c = Rgba::parse_hex("#ff8000").unwrap(); diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 3b070ec9..01446842 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -863,7 +863,7 @@ pub fn movie(doc: &Document, opts: &HtmlOptions) -> Movie { let json = json!({ "v": FORMAT_VERSION, "generator": format!("AniCraft {}", env!("CARGO_PKG_VERSION")), - "stage": {"w": stage.width.max(1), "h": stage.height.max(1), "fps": num(fps, 1000.0), "bg": stage.background.to_hex()}, + "stage": {"w": stage.width.max(1), "h": stage.height.max(1), "fps": num(fps, 1000.0), "bg": stage.background.with_alpha(1.0).to_hex()}, "fit": opts.fit, "scenes": doc.scenes.iter().enumerate().map(|(i, s)| json!({"name": s.name, "tl": i})).collect::>(), "symbols": symbols, @@ -913,7 +913,7 @@ pub fn to_html(doc: &Document, opts: &HtmlOptions) -> Result // the JSON is inside a string, where `<` reads the same. let data = m.json.to_string().replace('<', "\\u003c"); let title = escape_html(&opts.title); - let bg = doc.stage.background.to_hex(); + let bg = doc.stage.background.with_alpha(1.0).to_hex(); let (w, h) = (doc.stage.width.max(1), doc.stage.height.max(1)); let mut html = String::with_capacity(data.len() + PLAYER_JS.len() + FILTERS_JS.len() + CANVAS_JS.len() + 1024); html.push_str("\n\n\n\n\n"); diff --git a/crates/render/src/lottie.rs b/crates/render/src/lottie.rs index 5f04704a..5b1b216d 100644 --- a/crates/render/src/lottie.rs +++ b/crates/render/src/lottie.rs @@ -531,7 +531,7 @@ pub fn to_lottie(doc: &Document, name: &str, from: u32, to: u32, background: boo if background { let bg = doc.stage.background.sanitized(); layers.push(json!({"ddd": 0, "ind": shape_layers + mattes + 1, "ty": 1, "nm": "Stage", "sr": 1, "ks": static_ks(), "ao": 0, "ip": 0, "op": frames, "st": 0, "bm": 0, - "sc": bg.to_hex(), "sw": doc.stage.width, "sh": doc.stage.height})); + "sc": bg.with_alpha(1.0).to_hex(), "sw": doc.stage.width, "sh": doc.stage.height})); } let root = json!({ "v": "5.7.0", diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index f0f55234..02bb7b87 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -210,8 +210,9 @@ fn style_attrs(st: &anicraft_doc::Stroke, k: f32) -> String { out } +/// Opaque `#rrggbb`: SVG carries alpha in separate opacity attributes. fn hex(c: Rgba) -> String { - c.sanitized().to_hex() + c.sanitized().with_alpha(1.0).to_hex() } /// `fill="#rrggbb"` (or `stroke=…`), plus the opacity when not opaque. From 3e5b08d97c86723f66955a6fbd1f08a49657fa39 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Wed, 18 Nov 2026 21:11:31 +0000 Subject: [PATCH 04/23] fix(geom): leave stroke runs unjoined where three or more meet, and stop a chain once it closes --- crates/geom/src/morph.rs | 72 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 70 insertions(+), 2 deletions(-) diff --git a/crates/geom/src/morph.rs b/crates/geom/src/morph.rs index 18635361..e254d561 100644 --- a/crates/geom/src/morph.rs +++ b/crates/geom/src/morph.rs @@ -695,6 +695,27 @@ fn chain_find(grid: &mut HashMap<(i64, i64), Vec>, slots: &[Option], best } +/// Whether exactly two run ends of `ends` lie within `tol` of `at`: a plain corner, where the +/// line can only go on one way. Where three or more meet (a crossing, a spur), which run +/// continues the line is a guess, so [`chain`] joins nothing there. A cell crowded beyond +/// [`CHAIN_SCAN`] ends counts as a junction. +fn plain_corner(ends: &HashMap<(i64, i64), Vec>, at: Vec2, tol: f32, cell: f32, steps: &mut usize) -> bool { + let key = |v: Vec2| ((v.x / cell).floor() as i64, (v.y / cell).floor() as i64); + let (kx, ky) = key(at); + let mut n = 0; + for dx in -1..=1_i64 { + for dy in -1..=1_i64 { + let Some(list) = ends.get(&(kx.saturating_add(dx), ky.saturating_add(dy))) else { continue }; + if list.len() > CHAIN_SCAN { + return false; + } + *steps += list.len(); + n += list.iter().filter(|e| e.distance(at) <= tol).count(); + } + } + n == 2 +} + /// [`chain`], and the work it took: endpoint lookup steps plus segments moved. pub fn chain_counted(p: &Path, tol: f32) -> (Path, usize) { let (mut out, mut open): (Vec, Vec) = subpaths(p).into_iter().partition(|s| s.closed); @@ -704,12 +725,15 @@ pub fn chain_counted(p: &Path, tol: f32) -> (Path, usize) { let cell = if tol.is_finite() && tol > 0.0 { tol } else { 1.0 }; let key = |v: Vec2| ((v.x / cell).floor() as i64, (v.y / cell).floor() as i64); let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); + let mut ends: HashMap<(i64, i64), Vec> = HashMap::new(); for (i, s) in open.iter().enumerate() { let (a, b) = (key(s.start), key(end(s))); grid.entry(a).or_default().push(i); if b != a { grid.entry(b).or_default().push(i); } + ends.entry(a).or_default().push(s.start); + ends.entry(b).or_default().push(end(s)); } let mut slots: Vec> = open.into_iter().map(Some).collect(); let mut steps = 0; @@ -724,13 +748,21 @@ pub fn chain_counted(p: &Path, tol: f32) -> (Path, usize) { steps += segs.len(); loop { let tail = segs.back().map_or(cur.start, |g| g[2]); - if let Some(next) = chain_find(&mut grid, &slots, tail, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take()) { + // Back at its start: the outline is closed, whatever else touches it there. + if segs.len() > 1 && tail.distance(cur.start) <= tol { + break; + } + if plain_corner(&ends, tail, tol, cell, &mut steps) + && let Some(next) = chain_find(&mut grid, &slots, tail, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take()) + { let next = if next.start.distance(tail) <= tol { next } else { reverse(&next) }; steps += next.segs.len(); segs.extend(next.segs); continue; } - if let Some(prev) = chain_find(&mut grid, &slots, cur.start, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take()) { + if plain_corner(&ends, cur.start, tol, cell, &mut steps) + && let Some(prev) = chain_find(&mut grid, &slots, cur.start, tol, cell, &mut steps).and_then(|j| slots.get_mut(j)?.take()) + { let prev = if end(&prev).distance(cur.start) <= tol { prev } else { reverse(&prev) }; steps += prev.segs.len(); for g in prev.segs.into_iter().rev() { @@ -981,6 +1013,42 @@ mod tests { assert!(chain(&Path::default(), 0.2).cmds.is_empty()); } + #[test] + fn chain_leaves_a_junction_of_three_or_more_runs_unjoined() { + // A square ABCD with a diagonal BD of the same style, in the order AB, BD, BC, CD, DA. + // Three runs meet at B and at D: which one continues the line there is a guess, and a + // wrong guess (AB → BD) folds the square's sides into an open zigzag. Nothing is joined + // through B or D; the corners where just two runs meet (A, C) still join. + let (a, b, c, d) = (Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)); + let runs = [(a, b), (b, d), (b, c), (c, d), (d, a)]; + let mut p = Path::default(); + for (s, e) in runs { + p.move_to(s).line_to(e); + } + let subs = subpaths(&chain(&p, 0.01)); + assert_eq!(subs.iter().map(|s| s.segs.len()).sum::(), 5, "no segment is lost"); + // DA + AB, BC + CD, and the diagonal alone. + let mut lens: Vec = subs.iter().map(|s| s.segs.len()).collect(); + lens.sort_unstable(); + assert_eq!(lens, [1, 2, 2], "{subs:?}"); + for s in &subs { + let pts: Vec = anchors(s).collect(); + // No run passes through B or D: they are only ever an end. + for q in pts.iter().skip(1).take(pts.len().saturating_sub(2)) { + assert!(!close(*q, b) && !close(*q, d), "joined through a junction: {pts:?}"); + } + } + // A triangle with a spur at A: the triangle still closes, the spur stays apart. + let mut p = Path::default(); + for (s, e) in [(a, b), (b, c), (c, a), (a, d)] { + p.move_to(s).line_to(e); + } + let subs = subpaths(&chain(&p, 0.01)); + assert_eq!(subs.len(), 2, "{subs:?}"); + assert!(subs.iter().any(|s| s.closed && s.segs.len() == 3), "the triangle closes: {subs:?}"); + assert!(subs.iter().any(|s| !s.closed && s.segs.len() == 1), "the spur stays apart: {subs:?}"); + } + #[test] fn nearest_point_snaps_to_the_outline() { let sq = Path::rect(0.0, 0.0, 100.0, 100.0); From 9e2e788ce8e3b2a4d5dcf03867d1f0092910a29b Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Wed, 18 Nov 2026 21:22:04 +0000 Subject: [PATCH 05/23] fix(doc): shape-tween stroke runs keep their identities, stay apart when dashed or profiled, and ride a motion guide with their fill --- crates/doc/src/eval.rs | 64 ++++++++++++++++++++++++++-- crates/doc/src/eval_tests.rs | 72 ++++++++++++++++++++++++++++++++ crates/engine/src/merge_tests.rs | 29 +++++++++++++ 3 files changed, 161 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index c7c34ee6..b360c8ae 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -374,13 +374,46 @@ fn joined_runs(els: &[Arc]) -> Vec { } } for j in &mut out { - if let ElementKind::Shape(s) = &mut j.el.kind { + // A dash pattern restarts, and a width profile is measured, on each run; chained, the + // pattern and widths would jump on the first frame after the key. Such runs stay apart. + if let ElementKind::Shape(s) = &mut j.el.kind + && s.stroke.as_ref().is_some_and(|st| st.style.dash.is_none() && st.profile.is_none()) + { s.path = Arc::new(anicraft_geom::morph::chain(&s.path, anicraft_geom::planar::SNAP)); } } out } +/// `e` with its origin moved to `origin` (in its parent's space) and its path moved back, so +/// it looks the same. +fn rebase(e: &mut Element, origin: anicraft_geom::Vec2) { + let mut moved = e.transform; + moved.m[4] = origin.x; + moved.m[5] = origin.y; + let (Some(inv), ElementKind::Shape(s)) = (moved.inverse(), &mut e.kind) else { return }; + let d = inv.apply(e.transform.translation()); + if !d.is_finite() { + return; + } + s.path = Arc::new(s.path.transformed(&Affine::translate(d.x, d.y))); + e.transform = moved; +} + +/// What stands, in an in-between frame, for a run `x` joined into the outline `el`: nothing +/// drawn (no fill, no stroke) but the run's identity over the outline, so a run selected on a +/// key stays selected through the tween, with the outline's bounds. +fn joined_member(x: &Element, el: &Element) -> Element { + let mut e = el.clone(); + e.id = x.id; + e.name.clone_from(&x.name); + if let ElementKind::Shape(s) = &mut e.kind { + s.stroke = None; + s.fill = None; + } + e +} + /// The partner on `b` of each joined outline of `a`: one with the same stroke and colour first, then the /// rest in order. fn pair_joined(a: &[Joined], b: &[Joined]) -> Vec> { @@ -422,7 +455,19 @@ fn collapsed(e: &Element) -> Element { /// pairs in order, as in a plain shape tween. fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, guide: Option<(&PathWalk, bool)>) -> Vec> { let (a, b) = (&kf.elements, &next.elements); - let (runs_a, runs_b) = (joined_runs(a), joined_runs(b)); + let (mut runs_a, mut runs_b) = (joined_runs(a), joined_runs(b)); + if guide.is_some() { + // A guide places each element by its own origin, so outlines with origins of their own + // would take other paths than the fill they edge. Each key's outlines share the origin + // of its raw fill (or of its first outline) and travel with it. + for (els, runs) in [(a, &mut runs_a), (b, &mut runs_b)] { + let fill = els.iter().find(|e| matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some())); + let Some(origin) = fill.map(|e| e.transform.translation()).or_else(|| runs.first().map(|r| r.el.transform.translation())) else { continue }; + for r in runs.iter_mut() { + rebase(&mut r.el, origin); + } + } + } let partner = pair_joined(&runs_a, &runs_b); let placed = if kf.hints.is_empty() { Vec::new() } else { crate::hints::placed_hints(kf, next) }; // The hints placed on what `on_a` and `on_b` pick, in the spaces of `x` and `y`. @@ -433,6 +478,8 @@ fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, }; let mut rest_b = b.iter().enumerate().filter(|(_, e)| raw_stroke(e).is_none()); let mut out = Vec::with_capacity(a.len()); + // Each joined outline of the start key, tweened; it stands in for its first run. + let mut tweened: Vec>> = vec![None; runs_a.len()]; for (i, x) in a.iter().enumerate() { if raw_stroke(x).is_none() { let y = rest_b.next(); @@ -441,7 +488,12 @@ fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, ); continue; } - let Some((k, ra)) = runs_a.iter().enumerate().find(|(_, r)| r.members.first() == Some(&i)) else { continue }; + let Some((k, ra)) = runs_a.iter().enumerate().find(|(_, r)| r.members.contains(&i)) else { continue }; + if let Some(el) = tweened.get(k).and_then(Option::as_ref) { + // A later run of the outline keeps its identity, drawn by the first. + out.push(Arc::new(joined_member(x, el))); + continue; + } let el = match partner.get(k).copied().flatten().and_then(|m| runs_b.get(m)) { Some(rb) => { interpolate(&ra.el, &rb.el, t, true, &hints(&|h| ra.members.contains(&h), &|h| rb.members.contains(&h), &ra.el, &rb.el), guide) @@ -449,7 +501,11 @@ fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, // No partner on the end keyframe: it shrinks away. None => interpolate(&ra.el, &collapsed(&ra.el), t, false, &[], guide), }; - out.push(Arc::new(el.unwrap_or_else(|| ra.el.clone()))); + let el = Arc::new(el.unwrap_or_else(|| ra.el.clone())); + if let Some(slot) = tweened.get_mut(k) { + *slot = Some(el.clone()); + } + out.push(el); } // Outlines only on the end keyframe grow in. for (_, rb) in runs_b.iter().enumerate().filter(|(m, _)| !partner.contains(&Some(*m))) { diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index 304840d3..e51675c1 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -739,6 +739,78 @@ fn raw_stroke_runs_with_different_colour_effects_keep_them_in_a_shape_tween() { assert_eq!(by(1).color, ColorEffect::None.transform(), "the first run took the later run's colour"); } +/// A plain black stroke 2 wide. +fn solid_stroke() -> crate::Stroke { + Shape::filled(Path::new(), Paint::Solid(Rgba::BLACK)).with_stroke(Rgba::BLACK, 2.0).stroke.unwrap() +} + +/// A shape tween from a triangle's raw stroke runs (ids 1-3) to a square's (ids 11-14), all in +/// `stroke`: different run counts, so the runs are joined into outlines that morph. +fn polygon_runs_doc(stroke: &crate::Stroke) -> Document { + let v = anicraft_geom::Vec2::new; + let runs = |first: u64, pts: &[anicraft_geom::Vec2]| -> Vec> { + (0..pts.len()) + .map(|k| { + let mut p = Path::new(); + p.move_to(pts[k]).line_to(pts[(k + 1) % pts.len()]); + let mut s = Shape::filled(p, Paint::Solid(Rgba::BLACK)); + s.fill = None; + s.stroke = Some(stroke.clone()); + s.merge = true; + Arc::new(Element { id: ElementId(first + k as u64), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::Shape(s) }) + }) + .collect() + }; + let mut d = Document::default(); + let mut k0 = Keyframe::new(0, 10); + k0.elements = runs(1, &[v(50.0, 0.0), v(100.0, 90.0), v(0.0, 90.0)]); + k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() }); + let mut k1 = Keyframe::new(10, 1); + k1.elements = runs(11, &[v(0.0, 0.0), v(100.0, 0.0), v(100.0, 100.0), v(0.0, 100.0)]); + layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)]; + d +} + +/// Runs joined into one outline in a shape tween all keep their identities in between: the +/// first draws the outline, the others stand over it undrawn, so a selection of any of them +/// survives the tween and has bounds (a selection of a run missing from the frame is dropped). +#[test] +fn joined_stroke_runs_keep_their_identities_in_a_shape_tween() { + let d = polygon_runs_doc(&solid_stroke()); + let els = crate::evaluate_layer_elements(&d.timeline(0).layers[0], 5).unwrap().1; + let ids: Vec = els.iter().map(|e| e.id.0).collect(); + assert_eq!(ids, [1, 2, 3], "every run of the start key is there"); + let stroked: Vec<_> = els.iter().filter(|e| matches!(&e.kind, ElementKind::Shape(s) if s.stroke.is_some())).collect(); + assert_eq!(stroked.len(), 1, "one outline is drawn, once"); + assert_eq!(stroked[0].id, ElementId(1)); + for e in els.iter() { + assert!(!e.bounds(&d).is_empty(), "{:?} has bounds", e.id); + } + let list = evaluate(&d, 5); + assert_eq!(list.items.iter().filter(|i| i.stroke.is_some() || i.fill.is_some()).count(), 1, "nothing is drawn twice"); +} + +/// A dash pattern restarts on each run and a width profile is measured along each, so dashed or +/// profiled runs are not chained into one outline: right after the key they look as they did. +#[test] +fn dashed_or_profiled_stroke_runs_stay_apart_in_a_shape_tween() { + let subpaths = |d: &Document| { + let list = evaluate(d, 1); + list.items.iter().filter(|i| i.stroke.is_some()).map(|i| i.path.cmds.iter().filter(|c| matches!(c, anicraft_geom::PathCmd::MoveTo(_))).count()).sum::() + }; + let solid = solid_stroke(); + assert_eq!(subpaths(&polygon_runs_doc(&solid)), 1, "solid runs join into one outline"); + let mut dashed = solid.clone(); + dashed.style.dash = crate::Dash::dashed(6.0, 3.0); + assert!(dashed.style.dash.is_some()); + // Three runs on the start key: three pieces still, the square's fourth side growing in. + assert!(subpaths(&polygon_runs_doc(&dashed)) >= 3, "a dashed outline keeps its runs"); + let mut tapered = solid; + tapered.profile = crate::ProfilePreset::ALL.into_iter().find_map(crate::ProfilePreset::profile); + assert!(tapered.profile.is_some()); + assert!(subpaths(&polygon_runs_doc(&tapered)) >= 3, "a profiled outline keeps its runs"); +} + /// A classic tween from scale `a` to scale `b` (with a turn and a skew at the end), eased. fn squash_doc(a: (f32, f32), b: (f32, f32), easing: Easing, keep_area: bool) -> Document { let at = |s: (f32, f32), rot: f32, skew: f32, x: f32| { diff --git a/crates/engine/src/merge_tests.rs b/crates/engine/src/merge_tests.rs index d23e730e..664efabf 100644 --- a/crates/engine/src/merge_tests.rs +++ b/crates/engine/src/merge_tests.rs @@ -217,6 +217,35 @@ fn a_stroke_on_one_keyframe_only_shrinks_away_or_grows_in() { assert!(n5 > 0 && (w5 - w10 * 0.5).abs() < w10 * 0.1, "halfway: {w5} of {w10}"); } +/// A filled, stroked raw shape tween that follows a curved motion guide: the joined stroke +/// travels the guide with its fill, oriented to the path or not (#119). +#[test] +fn a_guided_shape_tween_carries_the_stroke_along_the_guide_with_the_fill() { + let mut s = polygon_tween((3, json!("#ff0000"), json!("#000000")), (5, json!("#ff0000"), json!("#000000"))); + let art = s.layer; + run(&mut s, "timeline.goto", json!({"frame": 10})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 200, "dy": 0})); + run(&mut s, "layer.add_motion_guide", json!({"layer": art.0})); + run(&mut s, "draw.path", json!({"d": "M0 0 C0 -300 200 -300 200 0"})); + let bounds = |items: &[&anicraft_doc::DisplayItem]| items.iter().fold(anicraft_geom::Rect::EMPTY, |r, i| r.union(&i.path.transformed(&i.transform).bounds())); + for (frame, orient) in [3u32, 5, 7].into_iter().flat_map(|f| [(f, false), (f, true)]) { + run(&mut s, "layer.select", json!({"layer": art.0})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + assert_eq!(run(&mut s, "timeline.set_orient", json!({"orient": orient}))["orient"], orient); + let list = anicraft_doc::evaluate(&s.doc, frame); + let on = |want_fill: bool| -> Vec<&anicraft_doc::DisplayItem> { + list.items.iter().filter(|i| i.layer == art && if want_fill { i.fill.is_some() } else { i.stroke.is_some() }).collect() + }; + let (fill, stroke) = (bounds(&on(true)), bounds(&on(false))); + assert!(!fill.is_empty() && !stroke.is_empty(), "frame {frame}"); + assert!(fill.center().y < -60.0, "frame {frame}: the fill rides up the arch: {fill:?}"); + for (a, b) in [(fill.min, stroke.min), (fill.max, stroke.max)] { + assert!(a.distance(b) < 1.0, "frame {frame} (orient {orient}): the stroke left its fill: {fill:?} vs {stroke:?}"); + } + } +} + /// A shape hint placed on a raw outline's stroke steers the stroke's morph when the keyframes' /// outlines have different numbers of runs (#119). #[test] From f06a4b4f656d9408e55b64e48205ada15c34386a Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 19 Nov 2026 19:23:51 +0000 Subject: [PATCH 06/23] fix(doc): shape-tween strokes take their own fill's origin and the fill's correspondence A solid stroke outline against a dashed or profiled one on the other key: only one of the two is chained, so a whole outline morphed against the other key's loose runs and the stroke followed a different correspondence than the fill. Both keys' outlines are chained for the morph now; the keys keep their own runs. On a guided tween, each joined outline took the first raw fill's origin, so in a keyframe with several merged fill regions the second region's stroke followed the first region's guide path. Each outline now takes the origin of the fill nearest it. Tests: a_solid_outline_morphs_against_a_dashed_one (fill edge 17.8 off the stroke before the fix) and a_guided_shape_tween_keeps_each_stroke_with_its_own_fill (the second region's stroke 273 off its fill before the fix). --- crates/doc/src/eval.rs | 53 ++++++++++++--- crates/doc/src/eval_tests.rs | 122 +++++++++++++++++++++++++++++++++++ 2 files changed, 165 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index b360c8ae..fd2c70e7 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -354,6 +354,13 @@ struct Joined { el: Element, } +/// Whether an outline's runs are chained into whole outlines by [`joined_runs`]: a stroke with +/// no dash pattern and no width profile. A dash pattern restarts, and a profile is measured, on +/// each run, so those runs stay apart. +fn chained(el: &Element) -> bool { + raw_stroke(el).is_some_and(|st| st.style.dash.is_none() && st.profile.is_none()) +} + /// The raw stroke runs of `els` joined into one element per stroke style (and scale, rotation /// and skew, which the stroke's width follows, and colour effect), each in the space of its first run. fn joined_runs(els: &[Arc]) -> Vec { @@ -376,9 +383,7 @@ fn joined_runs(els: &[Arc]) -> Vec { for j in &mut out { // A dash pattern restarts, and a width profile is measured, on each run; chained, the // pattern and widths would jump on the first frame after the key. Such runs stay apart. - if let ElementKind::Shape(s) = &mut j.el.kind - && s.stroke.as_ref().is_some_and(|st| st.style.dash.is_none() && st.profile.is_none()) - { + if chained(&j.el) && let ElementKind::Shape(s) = &mut j.el.kind { s.path = Arc::new(anicraft_geom::morph::chain(&s.path, anicraft_geom::planar::SNAP)); } } @@ -437,6 +442,17 @@ fn pair_joined(a: &[Joined], b: &[Joined]) -> Vec> { out } +/// `el` with its runs chained into whole outlines, for a morph against an outline that is +/// chained: both ends then correspond along the whole outline, the way the fill's do. Only the +/// in-between frames see this; the keys keep their own runs. +fn chained_for_morph(el: &Element) -> Element { + let mut e = el.clone(); + if let ElementKind::Shape(s) = &mut e.kind { + s.path = Arc::new(anicraft_geom::morph::chain(&s.path, anicraft_geom::planar::SNAP)); + } + e +} + /// `e` shrunk to the centre of its path: where an outline without a partner grows from or /// shrinks to. fn collapsed(e: &Element) -> Element { @@ -457,14 +473,22 @@ fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, let (a, b) = (&kf.elements, &next.elements); let (mut runs_a, mut runs_b) = (joined_runs(a), joined_runs(b)); if guide.is_some() { - // A guide places each element by its own origin, so outlines with origins of their own - // would take other paths than the fill they edge. Each key's outlines share the origin - // of its raw fill (or of its first outline) and travel with it. + // A guide places each element by its own origin, so an outline with an origin of its own + // would take another path than the fill it edges. Each outline takes the origin of the + // fill nearest it, so it travels with that fill; with no fill, of the first outline. for (els, runs) in [(a, &mut runs_a), (b, &mut runs_b)] { - let fill = els.iter().find(|e| matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some())); - let Some(origin) = fill.map(|e| e.transform.translation()).or_else(|| runs.first().map(|r| r.el.transform.translation())) else { continue }; + let fills: Vec = els + .iter() + .filter(|e| matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some())) + .map(|e| e.transform.translation()) + .collect(); + let first = runs.first().map(|r| r.el.transform.translation()); for r in runs.iter_mut() { - rebase(&mut r.el, origin); + let own = r.el.transform.translation(); + let origin = fills.iter().copied().min_by(|x, y| own.distance(*x).total_cmp(&own.distance(*y))).or(first); + if let Some(origin) = origin { + rebase(&mut r.el, origin); + } } } } @@ -496,7 +520,16 @@ fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, } let el = match partner.get(k).copied().flatten().and_then(|m| runs_b.get(m)) { Some(rb) => { - interpolate(&ra.el, &rb.el, t, true, &hints(&|h| ra.members.contains(&h), &|h| rb.members.contains(&h), &ra.el, &rb.el), guide) + // A solid outline against a dashed or profiled one: only one of the two is + // chained, so a whole outline would morph against the other key's loose runs and + // the stroke would follow a different correspondence than the fill. Both are + // chained for the morph. + let (x, y) = if chained(&ra.el) == chained(&rb.el) { + (Cow::Borrowed(&ra.el), Cow::Borrowed(&rb.el)) + } else { + (Cow::Owned(chained_for_morph(&ra.el)), Cow::Owned(chained_for_morph(&rb.el))) + }; + interpolate(&x, &y, t, true, &hints(&|h| ra.members.contains(&h), &|h| rb.members.contains(&h), &x, &y), guide) } // No partner on the end keyframe: it shrinks away. None => interpolate(&ra.el, &collapsed(&ra.el), t, false, &[], guide), diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index e51675c1..e93a524a 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -811,6 +811,128 @@ fn dashed_or_profiled_stroke_runs_stay_apart_in_a_shape_tween() { assert!(subpaths(&polygon_runs_doc(&tapered)) >= 3, "a profiled outline keeps its runs"); } +/// A raw regular polygon centred on `at` as the merge stores it: its fill element (id `first`), +/// then one stroke run per side (ids `first + 1`…), each with its own origin. +fn polygon_at(first: u64, at: anicraft_geom::Vec2, radius: f32, sides: usize, stroke: &crate::Stroke) -> Vec> { + use std::f32::consts::{PI, TAU}; + let pts: Vec = (0..sides) + .map(|k| { + let a = -PI / 2.0 + k as f32 * TAU / sides as f32; + at + anicraft_geom::Vec2::new(radius * a.cos(), radius * a.sin()) + }) + .collect(); + let mut outline = Path::new(); + if let Some(&p) = pts.first() { + outline.move_to(p); + } + for &p in pts.iter().skip(1) { + outline.line_to(p); + } + outline.close(); + let piece = |id: u64, path: &Path, centre: anicraft_geom::Vec2, fill: bool| { + let mut s = Shape::filled(path.transformed(&Affine::translate(-centre.x, -centre.y)), Paint::Solid(Rgba::BLACK)); + s.fill = fill.then_some(Paint::Solid(Rgba::BLACK)); + s.stroke = (!fill).then(|| stroke.clone()); + s.merge = true; + Arc::new(Element { + id: ElementId(id), + name: String::new(), + transform: Affine::translate(centre.x, centre.y), + color: ColorEffect::None, + kind: ElementKind::Shape(s), + }) + }; + let mut out = vec![piece(first, &outline, at, true)]; + for (k, &a) in pts.iter().enumerate() { + let b = pts[(k + 1) % sides]; + let mut side = Path::new(); + side.move_to(a).line_to(b); + out.push(piece(first + 1 + k as u64, &side, (a + b) * 0.5, false)); + } + out +} + +/// A solid outline on one key against a dashed one on the other: the keys' outlines correspond +/// as the fill's do, so the stroke stays on the morphed fill instead of pairing a whole outline +/// with the other key's loose runs. +#[test] +fn a_solid_outline_morphs_against_a_dashed_one() { + let v = anicraft_geom::Vec2::new; + let solid = solid_stroke(); + let mut dashed = solid.clone(); + dashed.style.dash = crate::Dash::dashed(6.0, 3.0); + let mut d = Document::default(); + let mut k0 = Keyframe::new(0, 10); + k0.elements = polygon_at(1, v(50.0, 45.0), 50.0, 3, &solid); + k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() }); + let mut k1 = Keyframe::new(10, 1); + k1.elements = polygon_at(11, v(50.0, 50.0), 55.0, 4, &dashed); + layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)]; + for frame in [3u32, 5, 7] { + let list = evaluate(&d, frame); + let fill = list.items.iter().find(|i| i.fill.is_some()).expect("the fill"); + let strokes: Vec<_> = list.items.iter().filter(|i| i.stroke.is_some()).collect(); + assert!(!strokes.is_empty(), "frame {frame}: the stroke is drawn"); + for pl in fill.path.flatten(&fill.transform, 0.25) { + for &p in &pl.points { + let d = strokes.iter().map(|st| st.path.distance_to_edge(p, &st.transform)).fold(f32::INFINITY, f32::min); + assert!(d < 1.5, "frame {frame}: fill edge point {p:?} is {d} from the stroke"); + } + } + for st in &strokes { + for pl in st.path.flatten(&st.transform, 0.25) { + for &p in &pl.points { + let d = fill.path.distance_to_edge(p, &fill.transform); + assert!(d < 1.5, "frame {frame}: stroke point {p:?} is {d} off the fill's edge"); + } + } + } + } +} + +/// A guide places each element by its own origin, so each joined stroke outline takes the origin +/// of the fill it edges: with two merged fill regions, each stroke travels with its own fill +/// rather than following the first region's guide path. +#[test] +fn a_guided_shape_tween_keeps_each_stroke_with_its_own_fill() { + let v = anicraft_geom::Vec2::new; + let black = solid_stroke(); + let mut blue = black.clone(); + blue.color = Rgba::hex(0x0000ff); + let mut d = Document::default(); + let mut k0 = Keyframe::new(0, 10); + k0.elements = polygon_at(1, v(0.0, 0.0), 40.0, 3, &black); + k0.elements.extend(polygon_at(10, v(300.0, 0.0), 40.0, 4, &blue)); + k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() }); + let mut k1 = Keyframe::new(10, 1); + k1.elements = polygon_at(20, v(0.0, 100.0), 40.0, 5, &black); + k1.elements.extend(polygon_at(30, v(300.0, 100.0), 40.0, 5, &blue)); + layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)]; + // A straight guide from the first region's start to the second's end: each element travels + // the stretch of it between its own start and end origins. + let pts: Vec = (0..=20).map(|k| v(300.0 * k as f32 / 20.0, 100.0 * k as f32 / 20.0)).collect(); + let walk = anicraft_geom::walk::PathWalk::new(&pts).expect("the guide"); + let layer = d.timeline(0).layers[0].clone(); + let of = |els: &[Arc], id: u64| els.iter().find(|e| e.id == ElementId(id)).cloned(); + for frame in [1u32, 3, 5, 7, 9] { + let (_, els) = crate::evaluate_guided(&layer, frame, Some(&walk)).expect("an in-between frame"); + // The outline standing for a region's first run takes that region's fill's origin, so it + // travels the same stretch of the guide as the fill it edges. + for (run, fill) in [(2u64, 1u64), (11, 10)] { + let (Some(r), Some(f)) = (of(&els, run), of(&els, fill)) else { panic!("frame {frame}: run {run} and fill {fill}") }; + let (a, b) = (r.transform.translation(), f.transform.translation()); + assert!(a.distance(b) < 0.01, "frame {frame}: run {run} at {a:?} left its fill at {b:?}"); + } + // The regions travel different stretches: a stroke on the first region's path would be + // far from the second region's fill. + let (Some(first), Some(second)) = (of(&els, 1), of(&els, 10)) else { panic!("both fills") }; + assert!(first.transform.translation().distance(second.transform.translation()) > 100.0, "frame {frame}: the regions are apart"); + let (Some(run), Some(fill)) = (of(&els, 11), of(&els, 10)) else { panic!("the second region") }; + let off = run.bounds(&d).center().distance(fill.bounds(&d).center()); + assert!(off < 20.0, "frame {frame}: the second region's stroke is {off} from its fill"); + } +} + /// A classic tween from scale `a` to scale `b` (with a turn and a skew at the end), eased. fn squash_doc(a: (f32, f32), b: (f32, f32), easing: Easing, keep_area: bool) -> Document { let at = |s: (f32, f32), rot: f32, skew: f32, x: f32| { From dde8caeca678d699f062b10e9920f05a14159713 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 19 Nov 2026 19:27:00 +0000 Subject: [PATCH 07/23] perf(doc): index shape-tween stroke runs to their outline once a frame Each start-key element searched the joined outlines for the one holding it, so an outline of n runs cost n(n+1)/2 comparisons a frame. The runs of each outline are indexed once per call and looked up in constant time. --- crates/doc/src/eval.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index fd2c70e7..9a45c5e1 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -502,6 +502,16 @@ fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, }; let mut rest_b = b.iter().enumerate().filter(|(_, e)| raw_stroke(e).is_none()); let mut out = Vec::with_capacity(a.len()); + // Which outline of the start key draws each of its runs, worked out once: searching the + // outlines for every run would cost n(n+1)/2 comparisons for an outline of n runs. + let mut outline_of: Vec> = vec![None; a.len()]; + for (k, r) in runs_a.iter().enumerate() { + for &m in &r.members { + if let Some(slot) = outline_of.get_mut(m) { + *slot = Some(k); + } + } + } // Each joined outline of the start key, tweened; it stands in for its first run. let mut tweened: Vec>> = vec![None; runs_a.len()]; for (i, x) in a.iter().enumerate() { @@ -512,7 +522,7 @@ fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, ); continue; } - let Some((k, ra)) = runs_a.iter().enumerate().find(|(_, r)| r.members.contains(&i)) else { continue }; + let Some((k, ra)) = outline_of.get(i).copied().flatten().and_then(|k| runs_a.get(k).map(|r| (k, r))) else { continue }; if let Some(el) = tweened.get(k).and_then(Option::as_ref) { // A later run of the outline keeps its identity, drawn by the first. out.push(Arc::new(joined_member(x, el))); From 6b2f21f047a1e9a644507c2e25c91542ffefa427 Mon Sep 17 00:00:00 2001 From: HagaiBA Date: Thu, 19 Nov 2026 23:39:38 +0200 Subject: [PATCH 08/23] fix(i18n): return false for private-use-only x-* tags in is_rtl_code --- src/i18n/mod.rs | 3 +++ src/i18n/tests.rs | 2 ++ 2 files changed, 5 insertions(+) diff --git a/src/i18n/mod.rs b/src/i18n/mod.rs index b991836d..6268b860 100644 --- a/src/i18n/mod.rs +++ b/src/i18n/mod.rs @@ -68,6 +68,9 @@ pub fn is_rtl_code(code: &str) -> bool { let normalized = Languages::normalize_code(code.split(['.', '@']).next().unwrap_or(code)); let mut parts = normalized.split('-').filter(|p| !p.is_empty()); let Some(base) = parts.next() else { return false }; + if base == "x" { + return false; + } let next = parts.find(|p| !(p.len() == 3 && p.chars().all(|c| c.is_ascii_alphabetic()))); if let Some(script) = next.filter(|p| p.len() == 4 && p.chars().all(|c| c.is_ascii_alphabetic())) { return matches!(script, "arab" | "hebr" | "thaa" | "syrc" | "nkoo" | "adlm" | "mand" | "samr" | "rohg"); diff --git a/src/i18n/tests.rs b/src/i18n/tests.rs index 7f9ded80..7c64216c 100644 --- a/src/i18n/tests.rs +++ b/src/i18n/tests.rs @@ -429,6 +429,8 @@ fn rtl_helper_recognizes_hebrew_and_legacy_iw() { assert!(!is_rtl_code("ku-Latn-TR")); assert!(!is_rtl_code("sd-Deva-IN")); assert!(!is_rtl_code("en-x-arab")); + assert!(!is_rtl_code("x-Arab")); + assert!(!is_rtl_code("x-Hebr")); assert!(!is_rtl_code("en")); assert!(!is_rtl_code("ka")); assert!(!is_rtl()); From 257d7ef5e544366d6918d465b7c0f271ac2c1733 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 19 Nov 2026 21:48:09 +0000 Subject: [PATCH 09/23] fix(doc): group guided shape-tween strokes by fill and keep flat member bounds --- crates/doc/src/eval.rs | 50 +++++++++++++------ crates/doc/src/eval_tests.rs | 93 ++++++++++++++++++++++++------------ 2 files changed, 99 insertions(+), 44 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 9a45c5e1..555dd812 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -347,10 +347,29 @@ fn raw_stroke(e: &Element) -> Option<&Stroke> { } } +/// The raw fill of `els` that `path` (in `xf` space) edges: the one whose edge is within two +/// snaps of a point on `path`, or that contains it, or the one whose origin is nearest `xf`'s. +fn fill_of(els: &[Arc], path: &Path, xf: &Affine) -> Option { + if let Some(p) = path.flatten(xf, 0.25).into_iter().next().and_then(|pl| pl.points.get(pl.points.len() / 2).copied()) + && let Some((k, _)) = els.iter().enumerate().find(|(_, e)| { + matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some() && (s.path.contains(p, &e.transform, s.fill_rule) || s.path.distance_to_edge(p, &e.transform) <= 2.0 * anicraft_geom::planar::SNAP)) + }) + { + return Some(k); + } + let own = xf.translation(); + els.iter() + .enumerate() + .filter(|(_, e)| matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some())) + .min_by(|(_, a), (_, b)| own.distance(a.transform.translation()).total_cmp(&own.distance(b.transform.translation()))) + .map(|(k, _)| k) +} + /// Raw stroke runs joined into one outline: the indices of the runs (the first one's space is -/// the outline's) and the joined element. +/// the outline's), the fill they edge, and the joined element. struct Joined { members: Vec, + fill: Option, el: Element, } @@ -362,22 +381,25 @@ fn chained(el: &Element) -> bool { } /// The raw stroke runs of `els` joined into one element per stroke style (and scale, rotation -/// and skew, which the stroke's width follows, and colour effect), each in the space of its first run. -fn joined_runs(els: &[Arc]) -> Vec { +/// and skew, which the stroke's width follows, and colour effect), each in the space of its first run; +/// when `by_fill`, runs that edge different fills stay in separate outlines so each outline can +/// follow its own fill along a motion guide. +fn joined_runs(els: &[Arc], by_fill: bool) -> Vec { let mut out: Vec = Vec::new(); for (i, e) in els.iter().enumerate() { let (Some(st), ElementKind::Shape(s)) = (raw_stroke(e), &e.kind) else { continue }; + let fill = by_fill.then(|| fill_of(els, &s.path, &e.transform)).flatten(); let slot = out.iter_mut().find_map(|j| { let ElementKind::Shape(js) = &mut j.el.kind else { return None }; let into = j.el.transform.inverse()?.mul(&e.transform); - (j.el.transform.m[..4] == e.transform.m[..4] && js.stroke.as_ref() == Some(st) && j.el.color == e.color).then_some((&mut j.members, js, into)) + (j.fill == fill && j.el.transform.m[..4] == e.transform.m[..4] && js.stroke.as_ref() == Some(st) && j.el.color == e.color).then_some((&mut j.members, js, into)) }); match slot { Some((members, js, into)) => { members.push(i); Arc::make_mut(&mut js.path).cmds.extend(s.path.transformed(&into).cmds); } - None => out.push(Joined { members: vec![i], el: (**e).clone() }), + None => out.push(Joined { members: vec![i], fill, el: (**e).clone() }), } } for j in &mut out { @@ -413,6 +435,12 @@ fn joined_member(x: &Element, el: &Element) -> Element { e.id = x.id; e.name.clone_from(&x.name); if let ElementKind::Shape(s) = &mut e.kind { + let pad = s.stroke.as_ref().map_or(0.0, Stroke::reach); + let b = s.path.bounds(); + if (b.width() == 0.0 || b.height() == 0.0) && pad > 0.0 { + let r = b.inflate(pad); + s.path = Arc::new(Path::rect(r.min.x, r.min.y, r.width(), r.height())); + } s.stroke = None; s.fill = None; } @@ -471,21 +499,15 @@ fn collapsed(e: &Element) -> Element { /// pairs in order, as in a plain shape tween. fn morph_raw_strokes(kf: &crate::Keyframe, next: &crate::Keyframe, t: Progress, guide: Option<(&PathWalk, bool)>) -> Vec> { let (a, b) = (&kf.elements, &next.elements); - let (mut runs_a, mut runs_b) = (joined_runs(a), joined_runs(b)); + let (mut runs_a, mut runs_b) = (joined_runs(a, guide.is_some()), joined_runs(b, guide.is_some())); if guide.is_some() { // A guide places each element by its own origin, so an outline with an origin of its own // would take another path than the fill it edges. Each outline takes the origin of the - // fill nearest it, so it travels with that fill; with no fill, of the first outline. + // fill it edges, so it travels with that fill; with no fill, of the first outline. for (els, runs) in [(a, &mut runs_a), (b, &mut runs_b)] { - let fills: Vec = els - .iter() - .filter(|e| matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some())) - .map(|e| e.transform.translation()) - .collect(); let first = runs.first().map(|r| r.el.transform.translation()); for r in runs.iter_mut() { - let own = r.el.transform.translation(); - let origin = fills.iter().copied().min_by(|x, y| own.distance(*x).total_cmp(&own.distance(*y))).or(first); + let origin = r.fill.and_then(|k| els.get(k)).map(|e| e.transform.translation()).or(first); if let Some(origin) = origin { rebase(&mut r.el, origin); } diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index e93a524a..3e6a7fd3 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -788,6 +788,35 @@ fn joined_stroke_runs_keep_their_identities_in_a_shape_tween() { } let list = evaluate(&d, 5); assert_eq!(list.items.iter().filter(|i| i.stroke.is_some() || i.fill.is_some()).count(), 1, "nothing is drawn twice"); + // Horizontal and vertical outlines have zero height or width before stroke padding: undrawn + // members still keep non-empty bounds. + let v = anicraft_geom::Vec2::new; + let seg = |id: u64, a, b| { + let mut p = Path::new(); + p.move_to(a).line_to(b); + let mut s = Shape::filled(p, Paint::Solid(Rgba::BLACK)); + s.fill = None; + s.stroke = Some(solid_stroke()); + s.merge = true; + Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::None, kind: ElementKind::Shape(s) }) + }; + for (a0, a1, a2, b0, b1, b2, b3) in [ + (v(0.0, 20.0), v(40.0, 20.0), v(80.0, 20.0), v(0.0, 20.0), v(30.0, 20.0), v(60.0, 20.0), v(90.0, 20.0)), + (v(20.0, 0.0), v(20.0, 40.0), v(20.0, 80.0), v(20.0, 0.0), v(20.0, 30.0), v(20.0, 60.0), v(20.0, 90.0)), + ] { + let mut d = Document::default(); + let mut k0 = Keyframe::new(0, 10); + k0.elements = vec![seg(1, a0, a1), seg(2, a1, a2)]; + k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() }); + let mut k1 = Keyframe::new(10, 1); + k1.elements = vec![seg(11, b0, b1), seg(12, b1, b2), seg(13, b2, b3)]; + layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)]; + let els = crate::evaluate_layer_elements(&d.timeline(0).layers[0], 5).unwrap().1; + assert_eq!(els.len(), 2); + for e in els.iter() { + assert!(!e.bounds(&d).is_empty(), "axis-aligned run {:?} has bounds", e.id); + } + } } /// A dash pattern restarts on each run and a width profile is measured along each, so dashed or @@ -899,37 +928,41 @@ fn a_guided_shape_tween_keeps_each_stroke_with_its_own_fill() { let black = solid_stroke(); let mut blue = black.clone(); blue.color = Rgba::hex(0x0000ff); - let mut d = Document::default(); - let mut k0 = Keyframe::new(0, 10); - k0.elements = polygon_at(1, v(0.0, 0.0), 40.0, 3, &black); - k0.elements.extend(polygon_at(10, v(300.0, 0.0), 40.0, 4, &blue)); - k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() }); - let mut k1 = Keyframe::new(10, 1); - k1.elements = polygon_at(20, v(0.0, 100.0), 40.0, 5, &black); - k1.elements.extend(polygon_at(30, v(300.0, 100.0), 40.0, 5, &blue)); - layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)]; - // A straight guide from the first region's start to the second's end: each element travels - // the stretch of it between its own start and end origins. - let pts: Vec = (0..=20).map(|k| v(300.0 * k as f32 / 20.0, 100.0 * k as f32 / 20.0)).collect(); - let walk = anicraft_geom::walk::PathWalk::new(&pts).expect("the guide"); - let layer = d.timeline(0).layers[0].clone(); - let of = |els: &[Arc], id: u64| els.iter().find(|e| e.id == ElementId(id)).cloned(); - for frame in [1u32, 3, 5, 7, 9] { - let (_, els) = crate::evaluate_guided(&layer, frame, Some(&walk)).expect("an in-between frame"); - // The outline standing for a region's first run takes that region's fill's origin, so it - // travels the same stretch of the guide as the fill it edges. - for (run, fill) in [(2u64, 1u64), (11, 10)] { - let (Some(r), Some(f)) = (of(&els, run), of(&els, fill)) else { panic!("frame {frame}: run {run} and fill {fill}") }; - let (a, b) = (r.transform.translation(), f.transform.translation()); - assert!(a.distance(b) < 0.01, "frame {frame}: run {run} at {a:?} left its fill at {b:?}"); + // Both different stroke styles and the same stroke style across the two regions: runs that + // edge different fills stay in separate outlines and each travels its own fill's stretch. + for second_stroke in [&blue, &black] { + let mut d = Document::default(); + let mut k0 = Keyframe::new(0, 10); + k0.elements = polygon_at(1, v(0.0, 0.0), 40.0, 3, &black); + k0.elements.extend(polygon_at(10, v(300.0, 0.0), 40.0, 4, second_stroke)); + k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() }); + let mut k1 = Keyframe::new(10, 1); + k1.elements = polygon_at(20, v(0.0, 100.0), 40.0, 5, &black); + k1.elements.extend(polygon_at(30, v(300.0, 100.0), 40.0, 5, second_stroke)); + layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)]; + // A straight guide from the first region's start to the second's end: each element travels + // the stretch of it between its own start and end origins. + let pts: Vec = (0..=20).map(|k| v(300.0 * k as f32 / 20.0, 100.0 * k as f32 / 20.0)).collect(); + let walk = anicraft_geom::walk::PathWalk::new(&pts).expect("the guide"); + let layer = d.timeline(0).layers[0].clone(); + let of = |els: &[Arc], id: u64| els.iter().find(|e| e.id == ElementId(id)).cloned(); + for frame in [1u32, 3, 5, 7, 9] { + let (_, els) = crate::evaluate_guided(&layer, frame, Some(&walk)).expect("an in-between frame"); + // The outline standing for a region's first run takes that region's fill's origin, so it + // travels the same stretch of the guide as the fill it edges. + for (run, fill) in [(2u64, 1u64), (11, 10)] { + let (Some(r), Some(f)) = (of(&els, run), of(&els, fill)) else { panic!("frame {frame}: run {run} and fill {fill}") }; + let (a, b) = (r.transform.translation(), f.transform.translation()); + assert!(a.distance(b) < 0.01, "frame {frame}: run {run} at {a:?} left its fill at {b:?}"); + } + // The regions travel different stretches: a stroke on the first region's path would be + // far from the second region's fill. + let (Some(first), Some(second)) = (of(&els, 1), of(&els, 10)) else { panic!("both fills") }; + assert!(first.transform.translation().distance(second.transform.translation()) > 100.0, "frame {frame}: the regions are apart"); + let (Some(run), Some(fill)) = (of(&els, 11), of(&els, 10)) else { panic!("the second region") }; + let off = run.bounds(&d).center().distance(fill.bounds(&d).center()); + assert!(off < 20.0, "frame {frame}: the second region's stroke is {off} from its fill"); } - // The regions travel different stretches: a stroke on the first region's path would be - // far from the second region's fill. - let (Some(first), Some(second)) = (of(&els, 1), of(&els, 10)) else { panic!("both fills") }; - assert!(first.transform.translation().distance(second.transform.translation()) > 100.0, "frame {frame}: the regions are apart"); - let (Some(run), Some(fill)) = (of(&els, 11), of(&els, 10)) else { panic!("the second region") }; - let off = run.bounds(&d).center().distance(fill.bounds(&d).center()); - assert!(off < 20.0, "frame {frame}: the second region's stroke is {off} from its fill"); } } From 2cd16209af7ed9a59b635c7ffce703d461040e03 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:07:43 +0100 Subject: [PATCH 10/23] test(engine): verify SVG link export and rendered reimport parity --- Cargo.lock | 1 + crates/engine/Cargo.toml | 1 + crates/engine/src/rich_text_tests.rs | 44 ++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index d64cc2b4..05ca03b6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -317,6 +317,7 @@ dependencies = [ "anicraft-svg", "anicraft-text", "anicraft-xfl", + "anicraft-xml", "craft-anicraft-format", "craft-csv", "craft-gif", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index fdd67e24..726e1984 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -30,6 +30,7 @@ regex.workspace = true craft-csv.workspace = true [dev-dependencies] +anicraft-xml.workspace = true # Packs the XFL corpus into .fla archives in tests (ADR 0054; already in the tree through xfl). miniz_oxide = "0.8" # Plug-in test fixtures written in WebAssembly text (Apache-2.0 WITH LLVM-exception). diff --git a/crates/engine/src/rich_text_tests.rs b/crates/engine/src/rich_text_tests.rs index a7b8f03c..db351740 100644 --- a/crates/engine/src/rich_text_tests.rs +++ b/crates/engine/src/rich_text_tests.rs @@ -227,3 +227,47 @@ fn every_export_draws_each_colour_and_svg_keeps_the_link() { let html = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap().html; assert!(html.contains("\"pp\":"), "field pieces"); } + +#[test] +fn svg_links_are_sanitized_and_round_trip_without_changing_the_drawing() { + // Exercise the export boundary without installed fonts or text shaping. + let mut doc = anicraft_doc::Document::default(); + doc.stage.width = 32; + doc.stage.height = 24; + let mut s = Session::new(doc); + run(&mut s, "draw.rect", json!({"x": 4, "y": 4, "w": 12, "h": 8, "fill": "#336699", "stroke": null})); + let expected = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().to_rgba8(); + assert!(expected.as_chunks::<4>().0.iter().any(|p| p == &[0x33, 0x66, 0x99, 0xff]), "the fixture draws a coloured rectangle"); + let mut dl = anicraft_doc::evaluate(&s.doc, 0); + assert_eq!(dl.items.len(), 1); + for (index, (url, href)) in [ + (" \thttps://example.org/?a=1&b=\"<>'\r\n\u{7f}ok ", Some("https://example.org/?a=1&b=\"<>'ok")), + ("java\tscript:alert(1)", None), + ("vb\rscript:msgbox(1)", None), + ("da\nta:text/plain,hello", None), + ] + .into_iter() + .enumerate() { + dl.links = vec![(0, url.into())]; + let svg = anicraft_render::svg::to_svg(&dl, &s.doc.stage); + let root = anicraft_xml::parse(svg.as_bytes()).unwrap(); + let anchors: Vec<_> = root.children.iter().filter(|el| el.name == "a").collect(); + assert_eq!(anchors.len(), usize::from(href.is_some()), "{url:?}: {svg}"); + assert_eq!(anchors.first().and_then(|el| el.attr("href")), href, "decoded href for {url:?}"); + if let Some(anchor) = anchors.first() { + assert!(anchor.child("path").is_some(), "the anchor wraps the artwork"); + } + + // Use the real file-import command rather than duplicating its document mapping. + let path = std::env::temp_dir().join(format!("anicraft-svg-link-roundtrip-{}-{index}.svg", std::process::id())); + std::fs::write(&path, svg.as_bytes()).unwrap(); + let mut back = anicraft_doc::Document::default(); + back.stage = s.doc.stage; + let mut imported = Session::new(back); + let result = imported.execute("file.import", &json!({"path": path.display().to_string(), "x": 0, "y": 0})); + std::fs::remove_file(&path).unwrap(); + result.unwrap_or_else(|e| panic!("file.import for {url:?}: {e}")); + let actual = anicraft_render::render_frame(&imported.doc, 0, 1.0).unwrap().to_rgba8(); + assert_eq!(actual, expected, "link handling must preserve rendered geometry for {url:?}"); + } +} From 0cdf704bdf97506312ec497fa19cba0b2db5723e Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:15:03 +0100 Subject: [PATCH 11/23] style: format SVG acceptance test source --- crates/engine/src/rich_text_tests.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/rich_text_tests.rs b/crates/engine/src/rich_text_tests.rs index db351740..bd5f5b8b 100644 --- a/crates/engine/src/rich_text_tests.rs +++ b/crates/engine/src/rich_text_tests.rs @@ -108,7 +108,11 @@ fn a_superscript_sits_above_the_line_and_runs_wrap_across() { assert!(t.box_width < before.box_width - 5.0, "{} vs {}", t.box_width, before.box_width); assert!(t.outline.bounds().min.y <= before.outline.bounds().min.y + 0.5); // Wrapping across runs: a width that fits two words per line. - run(&mut s, "text.edit", json!({"text": "one two three four five", "width": 180, "runs": [{"chars": 8, "size": 30}, {"chars": 15, "size": 60, "color": "#0000ff"}]})); + run( + &mut s, + "text.edit", + json!({"text": "one two three four five", "width": 180, "runs": [{"chars": 8, "size": 30}, {"chars": 15, "size": 60, "color": "#0000ff"}]}), + ); let w = text_of(&s, id); assert!(w.box_height > 150.0, "several lines: {}", w.box_height); assert!(w.outline.bounds().max.x <= 182.0, "{:?}", w.outline.bounds()); @@ -121,7 +125,9 @@ fn paragraphs_take_their_own_alignment_indent_and_margins() { return; } let mut s = Session::default(); - let id = ElementId(run(&mut s, "text.create", json!({"text": "Title\nbody text", "x": 0, "y": 0, "size": 30, "width": 400}))["element"].as_u64().unwrap()); + let id = ElementId( + run(&mut s, "text.create", json!({"text": "Title\nbody text", "x": 0, "y": 0, "size": 30, "width": 400}))["element"].as_u64().unwrap(), + ); run(&mut s, "text.paragraph", json!({"start": 0, "end": 0, "align": "center"})); let t = text_of(&s, id); assert_eq!(t.paragraphs.iter().map(|p| p.align).collect::>(), vec![TextAlign::Center, TextAlign::Left]); @@ -247,7 +253,8 @@ fn svg_links_are_sanitized_and_round_trip_without_changing_the_drawing() { ("da\nta:text/plain,hello", None), ] .into_iter() - .enumerate() { + .enumerate() + { dl.links = vec![(0, url.into())]; let svg = anicraft_render::svg::to_svg(&dl, &s.doc.stage); let root = anicraft_xml::parse(svg.as_bytes()).unwrap(); From 50cfd2f321b73c422b6108eef18349035f148096 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:27:30 +0100 Subject: [PATCH 12/23] test: initialize SVG roundtrip document without reassignment --- crates/engine/src/rich_text_tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/engine/src/rich_text_tests.rs b/crates/engine/src/rich_text_tests.rs index bd5f5b8b..bcb83dd1 100644 --- a/crates/engine/src/rich_text_tests.rs +++ b/crates/engine/src/rich_text_tests.rs @@ -268,8 +268,7 @@ fn svg_links_are_sanitized_and_round_trip_without_changing_the_drawing() { // Use the real file-import command rather than duplicating its document mapping. let path = std::env::temp_dir().join(format!("anicraft-svg-link-roundtrip-{}-{index}.svg", std::process::id())); std::fs::write(&path, svg.as_bytes()).unwrap(); - let mut back = anicraft_doc::Document::default(); - back.stage = s.doc.stage; + let back = anicraft_doc::Document { stage: s.doc.stage, ..Default::default() }; let mut imported = Session::new(back); let result = imported.execute("file.import", &json!({"path": path.display().to_string(), "x": 0, "y": 0})); std::fs::remove_file(&path).unwrap(); From 7872255e665d8fed76d7757ff7ed7c030c0decb0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:53:46 +0100 Subject: [PATCH 13/23] chore: publish SVG acceptance for draft review [skip ci] Identical source tree to 50cfd2f, validated on Linux and Windows by diagnostic44654845961. Production checks remain outstanding. From 8a729b2bdbf10d315b4fcc9c79f099e14bf27111 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 11 Nov 2026 07:01:23 +0100 Subject: [PATCH 14/23] Reject SVG path coordinates that overflow f32 Found while testing crates/geom/src/svg.rs:~66 (Cursor::number) and P::v at ~88 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/svg/src/path_data.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/svg/src/path_data.rs b/crates/svg/src/path_data.rs index 8e155c71..ccc07223 100644 --- a/crates/svg/src/path_data.rs +++ b/crates/svg/src/path_data.rs @@ -141,6 +141,13 @@ mod tests { assert_eq!(ends(&lock).last().copied(), Some(Vec2::new(17.0, 11.0))); } + #[test] + fn numbers_overflowing_f32_are_errors() { + for bad in ["M0 0 L1e39 0", "M0 0 v , 3.4028236692e38 z", "M0 0 l3e38 0 3e38 0"] { + assert!(parse_path_data(bad).is_err(), "{bad}"); + } + } + #[test] fn bad_input_is_an_error() { assert!(parse_path_data("").unwrap().is_empty()); From f21016222cfe819e20b12ef60ab46d9b76a63458 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:01:43 -0700 Subject: [PATCH 15/23] perf(geom): Vec2::length takes hypot only where the squares leave f32 (M8) --- crates/geom/src/lib.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index f67bb9a4..5b5abd45 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -48,8 +48,13 @@ impl Vec2 { pub fn cross(self, o: Vec2) -> f32 { self.x * o.y - self.y * o.x } + /// Exact wherever the true length is a finite `f32`. The squares leave `f32` for components + /// past about 1.8e19 (or below 1e-19), so only then is the slower `hypot` taken: in range + /// the result is the multiply's, bit for bit, at its cost (0.85 ns against 0.83 ns; `hypot` + /// alone is 1.9 ns, and this is on the flattening and stroking paths). pub fn length(self) -> f32 { - self.x.hypot(self.y) + let sq = self.dot(self); + if sq.is_normal() { sq.sqrt() } else { self.x.hypot(self.y) } } pub fn normalized(self) -> Vec2 { let l = self.length(); @@ -251,5 +256,10 @@ mod tests { assert!((v.length() / 5e19 - 1.0).abs() < 1e-5, "len {}", v.length()); let n = v.normalized(); assert!((n.x - 0.6).abs() < 1e-5 && (n.y - 0.8).abs() < 1e-5, "{n:?}"); + // Squares too small for `f32` no longer read as no length at all. + let tiny = Vec2::new(3e-30, 4e-30).length(); + assert!((tiny / 5e-30 - 1.0).abs() < 1e-5, "len {tiny}"); + assert_eq!(Vec2::ZERO.length(), 0.0); + assert!(Vec2::new(f32::NAN, 1.0).length().is_nan()); } } From 0000ba2c4b19d8af0d0d59281e537b9266702c6c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:08:39 -0700 Subject: [PATCH 16/23] fix(doc): Rgba::to_hex stays opaque; to_hex_alpha is the form that reads back (M8) --- crates/doc/src/lib.rs | 24 +++++++++++++++++------- crates/engine/src/cmds_paint.rs | 11 +++++------ crates/engine/src/cmds_swatch.rs | 3 +-- crates/engine/src/cmds_view.rs | 3 +-- crates/engine/src/eyedropper_tests.rs | 5 +++++ crates/render/src/html.rs | 4 ++-- crates/render/src/svg.rs | 3 +-- src/colour_panel.rs | 3 +-- 8 files changed, 33 insertions(+), 23 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 91e3dbf1..58b429fa 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -97,14 +97,20 @@ impl Rgba { let c = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; Rgba::new(c(self.r), c(self.g), c(self.b), c(self.a)) } + /// Always the opaque `#rrggbb`, alpha left out: what the SVG, HTML and Lottie writers and + /// the layer colours put where six digits are expected (they carry opacity themselves). + /// [`Rgba::to_hex_alpha`] is the form that reads back as the same colour. pub fn to_hex(self) -> String { let s = self.sanitized(); let b = |v: f32| (v * 255.0).round() as u8; - if s.a < 1.0 { - format!("#{:02x}{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b), b(s.a)) - } else { - format!("#{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b)) - } + format!("#{:02x}{:02x}{:02x}", b(s.r), b(s.g), b(s.b)) + } + /// `#rrggbb`, or `#rrggbbaa` when not opaque: [`Rgba::parse_hex`] reads it back as the + /// same colour, to the 8 bits a channel is written in. + pub fn to_hex_alpha(self) -> String { + let s = self.sanitized(); + let a = (s.a * 255.0).round() as u8; + if a == u8::MAX { s.to_hex() } else { format!("{}{a:02x}", s.to_hex()) } } /// Parses `#rrggbb`, `rrggbb` or `#rrggbbaa`. pub fn parse_hex(s: &str) -> Option { @@ -2518,8 +2524,12 @@ mod tests { #[test] fn hex_roundtrip_keeps_alpha() { let c = Rgba::parse_hex("#ff000080").unwrap(); - assert_eq!(c.to_hex(), "#ff000080"); - assert_eq!(Rgba::parse_hex(&c.to_hex()).unwrap(), c); + assert_eq!(c.to_hex_alpha(), "#ff000080"); + assert_eq!(Rgba::parse_hex(&c.to_hex_alpha()).unwrap(), c); + // Six digits where six are expected, whatever the alpha: the exporters' contract. + assert_eq!(c.to_hex(), "#ff0000"); + // An alpha that rounds to opaque is written as opaque, so both forms agree. + assert_eq!(Rgba::new(1.0, 0.0, 0.0, 0.999).to_hex_alpha(), "#ff0000"); } #[test] diff --git a/crates/engine/src/cmds_paint.rs b/crates/engine/src/cmds_paint.rs index 320d3ff6..effe5bc4 100644 --- a/crates/engine/src/cmds_paint.rs +++ b/crates/engine/src/cmds_paint.rs @@ -414,7 +414,7 @@ fn pick_style(s: &mut Session, p: &Value) -> Result { if other { st.stroke = color; st.use_stroke = true; - return Ok(json!({"picked": "fill", "into": "stroke", "paint": paint_kind(&paint), "color": color.to_hex()})); + return Ok(json!({"picked": "fill", "into": "stroke", "paint": paint_kind(&paint), "color": hex_alpha(color)})); } st.fill = color; st.fill_paint = (!matches!(paint, Paint::Solid(_))).then(|| paint.clone()); @@ -423,13 +423,13 @@ fn pick_style(s: &mut Session, p: &Value) -> Result { st.lock_fill = true; } st.use_fill = true; - Ok(json!({"picked": "fill", "into": "fill", "paint": paint_kind(&paint), "color": color.to_hex()})) + Ok(json!({"picked": "fill", "into": "fill", "paint": paint_kind(&paint), "color": hex_alpha(color)})) } Some(Picked::Line(stroke, scale)) => { if other { st.set_fill_color(stroke.color); st.use_fill = true; - return Ok(json!({"picked": "line", "into": "fill", "paint": "solid", "color": stroke.color.to_hex()})); + return Ok(json!({"picked": "line", "into": "fill", "paint": "solid", "color": hex_alpha(stroke.color)})); } st.stroke = stroke.color; st.stroke_width = (stroke.width * scale).clamp(0.1, 1000.0); @@ -447,7 +447,7 @@ fn pick_style(s: &mut Session, p: &Value) -> Result { "custom" } }; - Ok(json!({"picked": "line", "into": "stroke", "color": stroke.color.to_hex(), "width": st.stroke_width, "profile": profile, "cap": st.line.cap.key(), "join": st.line.join.key(), "style": st.line.dash_kind().key()})) + Ok(json!({"picked": "line", "into": "stroke", "color": hex_alpha(stroke.color), "width": st.stroke_width, "profile": profile, "cap": st.line.cap.key(), "join": st.line.join.key(), "style": st.line.dash_kind().key()})) } None => Err(EngineError::State("click a fill or a line to pick its colour".into())), } @@ -598,8 +598,7 @@ impl FillSpec { /// `#rrggbb`, or `#rrggbbaa` when not opaque. fn hex_alpha(c: Rgba) -> String { - let c = c.sanitized(); - if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } + c.to_hex_alpha() } /// A fill as `paint.set_fill` reports it (in its own params' terms). diff --git a/crates/engine/src/cmds_swatch.rs b/crates/engine/src/cmds_swatch.rs index 7c0d3afe..3ef78d25 100644 --- a/crates/engine/src/cmds_swatch.rs +++ b/crates/engine/src/cmds_swatch.rs @@ -48,8 +48,7 @@ pub fn specs() -> Vec { /// `#rrggbb`, or `#rrggbbaa` when not opaque. pub fn hex(c: Rgba) -> String { - let c = c.sanitized(); - if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } + c.to_hex_alpha() } fn stops_json(stops: &[GradientStop]) -> Value { diff --git a/crates/engine/src/cmds_view.rs b/crates/engine/src/cmds_view.rs index 1e088563..c3b9aa42 100644 --- a/crates/engine/src/cmds_view.rs +++ b/crates/engine/src/cmds_view.rs @@ -67,8 +67,7 @@ pub(crate) fn aids_json(s: &Session) -> Value { } fn color_hex(c: anicraft_doc::Rgba) -> String { - let c = c.sanitized(); - if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } + c.to_hex_alpha() } fn guides_json(s: &Session) -> Value { diff --git a/crates/engine/src/eyedropper_tests.rs b/crates/engine/src/eyedropper_tests.rs index 7b99125b..6fde660e 100644 --- a/crates/engine/src/eyedropper_tests.rs +++ b/crates/engine/src/eyedropper_tests.rs @@ -45,6 +45,11 @@ fn picking_a_solid_fill_sets_the_fill_colour_and_records_no_step() { let r = run(&mut s, "paint.pick", json!({"x": 150, "y": 150, "other": true})); assert_eq!(r["into"], "stroke"); assert_eq!((s.style.stroke, s.style.fill), (Rgba::hex(0xff0000), Rgba::hex(0x00ff00))); + // The report names the colour that was picked, its opacity included. + rect(&mut s, 300.0, "#0000ff80"); + let r = run(&mut s, "paint.pick", json!({"x": 350, "y": 150})); + assert_eq!(Rgba::parse_hex(r["color"].as_str().unwrap()), Some(s.style.fill)); + assert!(s.style.fill.a < 0.6); } #[test] diff --git a/crates/render/src/html.rs b/crates/render/src/html.rs index 64c7b9ce..5a62dfdc 100644 --- a/crates/render/src/html.rs +++ b/crates/render/src/html.rs @@ -1071,7 +1071,7 @@ pub fn movie(doc: &Document, opts: &HtmlOptions) -> Movie { let json = json!({ "v": FORMAT_VERSION, "generator": format!("AniCraft {}", env!("CARGO_PKG_VERSION")), - "stage": {"w": stage.width.max(1), "h": stage.height.max(1), "fps": num(fps, 1000.0), "bg": stage.background.with_alpha(1.0).to_hex()}, + "stage": {"w": stage.width.max(1), "h": stage.height.max(1), "fps": num(fps, 1000.0), "bg": stage.background.to_hex()}, "fit": opts.fit, "scenes": doc.scenes.iter().enumerate().map(|(i, s)| json!({"name": s.name, "tl": i})).collect::>(), "symbols": symbols, @@ -1139,7 +1139,7 @@ pub fn to_html(doc: &Document, opts: &HtmlOptions) -> Result // the JSON is inside a string, where `<` reads the same. let data = m.json.to_string().replace('<', "\\u003c"); let title = escape_html(&opts.title); - let bg = doc.stage.background.with_alpha(1.0).to_hex(); + let bg = doc.stage.background.to_hex(); let (w, h) = (doc.stage.width.max(1), doc.stage.height.max(1)); let mut html = String::with_capacity(data.len() + PLAYER_JS.len() + FILTERS_JS.len() + CANVAS_JS.len() + 1024); html.push_str("\n\n\n\n\n"); diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index d785d4ca..d796a1dc 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -257,9 +257,8 @@ fn style_attrs(st: &anicraft_doc::Stroke, k: f32) -> String { out } -/// Opaque `#rrggbb`: SVG carries alpha in separate opacity attributes. fn hex(c: Rgba) -> String { - c.sanitized().with_alpha(1.0).to_hex() + c.sanitized().to_hex() } /// `fill="#rrggbb"` (or `stroke=…`), plus the opacity when not opaque. diff --git a/src/colour_panel.rs b/src/colour_panel.rs index 6c622124..b7782a10 100644 --- a/src/colour_panel.rs +++ b/src/colour_panel.rs @@ -71,8 +71,7 @@ pub fn apply_set(app: &mut App, edit: &FillEdit, selection: bool) { /// `#rrggbb`, or `#rrggbbaa` when not opaque. fn hex(c: Rgba) -> String { - let c = c.sanitized(); - if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } + c.to_hex_alpha() } fn stops_json(stops: &[GradientStop]) -> Value { From eae761cacb4f37cb925ae4fe921cc5c829437813 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:10:59 -0700 Subject: [PATCH 17/23] test(engine): keep #500's link test to the lines it adds (M8) --- crates/engine/src/rich_text_tests.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/rich_text_tests.rs b/crates/engine/src/rich_text_tests.rs index bcb83dd1..074c02c7 100644 --- a/crates/engine/src/rich_text_tests.rs +++ b/crates/engine/src/rich_text_tests.rs @@ -108,11 +108,7 @@ fn a_superscript_sits_above_the_line_and_runs_wrap_across() { assert!(t.box_width < before.box_width - 5.0, "{} vs {}", t.box_width, before.box_width); assert!(t.outline.bounds().min.y <= before.outline.bounds().min.y + 0.5); // Wrapping across runs: a width that fits two words per line. - run( - &mut s, - "text.edit", - json!({"text": "one two three four five", "width": 180, "runs": [{"chars": 8, "size": 30}, {"chars": 15, "size": 60, "color": "#0000ff"}]}), - ); + run(&mut s, "text.edit", json!({"text": "one two three four five", "width": 180, "runs": [{"chars": 8, "size": 30}, {"chars": 15, "size": 60, "color": "#0000ff"}]})); let w = text_of(&s, id); assert!(w.box_height > 150.0, "several lines: {}", w.box_height); assert!(w.outline.bounds().max.x <= 182.0, "{:?}", w.outline.bounds()); @@ -125,9 +121,7 @@ fn paragraphs_take_their_own_alignment_indent_and_margins() { return; } let mut s = Session::default(); - let id = ElementId( - run(&mut s, "text.create", json!({"text": "Title\nbody text", "x": 0, "y": 0, "size": 30, "width": 400}))["element"].as_u64().unwrap(), - ); + let id = ElementId(run(&mut s, "text.create", json!({"text": "Title\nbody text", "x": 0, "y": 0, "size": 30, "width": 400}))["element"].as_u64().unwrap()); run(&mut s, "text.paragraph", json!({"start": 0, "end": 0, "align": "center"})); let t = text_of(&s, id); assert_eq!(t.paragraphs.iter().map(|p| p.align).collect::>(), vec![TextAlign::Center, TextAlign::Left]); From 1a9b44da8fc5f7085df24e32668b6347c6ee9eab Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:16:44 -0700 Subject: [PATCH 18/23] fix(doc): one work allowance for layers, outlines, lookups and the player's step, and frames that say when artwork is left out (M8) --- crates/doc/src/eval.rs | 126 ++++++++++++++++++++++++++------- crates/doc/src/eval_tests.rs | 62 +++++++++++++++- crates/doc/src/lib.rs | 17 +++-- crates/doc/src/player.rs | 77 +++++++++++++++----- crates/doc/src/player_tests.rs | 33 +++++++++ 5 files changed, 262 insertions(+), 53 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 53e3e748..801a71ca 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -13,21 +13,74 @@ use std::sync::Arc; /// Symbols nested deeper than this are not drawn (guards cyclic libraries). pub const MAX_SYMBOL_DEPTH: usize = 32; -/// Most elements one evaluation (or one bounds query) visits, nested symbols and groups -/// included. The depth cap alone leaves a symbol holding two instances of the next, 32 deep, +/// The work one evaluation (or one bounds query) may do, nested symbols and groups included +/// (ADR 0128). The depth cap alone leaves a symbol holding two instances of the next, 32 deep, /// to expand 2^32 times, which no file may make AniCraft do: past the allowance the rest is /// left out, so a hostile or damaged document draws in part instead of hanging or running -/// out of memory. Real scenes stay far below it (the heaviest benchmark has 50,000 shapes). +/// out of memory, and the result says so ([`DisplayList::left_out`]). Real scenes stay far +/// below it (the heaviest benchmark has 50,000 shapes). +/// +/// A unit is one element or one layer visited. A shape costs one more for every +/// [`PATH_COMMANDS_PER_UNIT`] commands of its outline, and finding a symbol one more for every +/// [`LIBRARY_ENTRIES_PER_UNIT`] library entries passed, so neither a huge outline nor a huge +/// library, repeated by nesting, multiplies the work past what the allowance stands for. pub const MAX_EVAL_ELEMENTS: u32 = 1_000_000; -/// Takes one visit from `work`; `false` once the allowance is spent. -pub(crate) fn spend(work: &Cell) -> bool { - match work.get().checked_sub(1) { - Some(left) => { - work.set(left); - true +/// A shape's outline costs one unit of work for each this many path commands. +pub const PATH_COMMANDS_PER_UNIT: usize = 256; + +/// Finding a symbol costs one unit of work for each this many library entries looked at. +pub const LIBRARY_ENTRIES_PER_UNIT: usize = 1024; + +/// An allowance of work (see [`MAX_EVAL_ELEMENTS`]) shared by everything one query visits, that +/// remembers whether it ran out. +pub(crate) struct Work { + left: Cell, + ran_out: Cell, +} + +impl Work { + pub(crate) fn new(units: u32) -> Work { + Work { left: Cell::new(units), ran_out: Cell::new(false) } + } + + /// Takes `units`; `false` once the allowance is spent (and from then on). + pub(crate) fn spend(&self, units: u32) -> bool { + match self.left.get().checked_sub(units) { + Some(left) if !self.ran_out.get() => { + self.left.set(left); + true + } + _ => { + self.left.set(0); + self.ran_out.set(true); + false + } } - None => false, + } + + /// Something was left out because the allowance was spent. + pub(crate) fn ran_out(&self) -> bool { + self.ran_out.get() + } + + /// Takes what visiting `el` costs. + pub(crate) fn visit(&self, el: &Element) -> bool { + let outline = match &el.kind { + ElementKind::Shape(s) => s.path.cmds.len() / PATH_COMMANDS_PER_UNIT, + _ => 0, + }; + self.spend(u32::try_from(outline).unwrap_or(u32::MAX).saturating_add(1)) + } + + /// The library symbol `id`, paid for by how far into the library it is. + pub(crate) fn symbol<'d>(&self, doc: &'d Document, id: SymbolId) -> Option<&'d crate::Symbol> { + let at = doc.library.iter().position(|s| s.id == id); + let passed = at.unwrap_or(doc.library.len()) / LIBRARY_ENTRIES_PER_UNIT; + if passed > 0 && !self.spend(u32::try_from(passed).unwrap_or(u32::MAX)) { + return None; + } + at.and_then(|i| doc.library.get(i)).map(|s| &**s) } } @@ -87,6 +140,10 @@ pub struct DisplayList { /// Links on text (ADR 0085): `(item, url)` for each item drawing characters that link /// somewhere, in item order. Sparse: most lists have none. pub links: Vec<(u32, Arc)>, + /// The frame's allowance of work ([`MAX_EVAL_ELEMENTS`]) ran out, so artwork is missing + /// from this list: whoever shows or exports it says so instead of passing it off as the + /// whole frame (ADR 0128). + pub left_out: bool, } /// A group that fades as one (see [`DisplayList::groups`]). @@ -160,6 +217,7 @@ impl DisplayList { self.set_clip_mode(base + i as u32, m); } self.groups.extend(other.groups.into_iter().map(|g| Group { parent: gshift(g.parent), alpha: g.alpha, blend: g.blend, filters: g.filters, clip: shift(g.clip) })); + self.left_out |= other.left_out; let ibase = self.items.len() as u32; self.links.extend(other.links.into_iter().map(|(i, u)| (i + ibase, u))); self.items.extend(other.items.into_iter().map(|mut i| { @@ -182,8 +240,9 @@ pub fn evaluate(doc: &Document, frame: u32) -> DisplayList { /// applied: what the stage shows while editing (and what picking and bounds use). pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList { let mut out = DisplayList::default(); - let work = Cell::new(MAX_EVAL_ELEMENTS); + let work = Work::new(MAX_EVAL_ELEMENTS); eval_timeline(doc, doc.timeline(scene), frame, &Ctx::top(Affine::IDENTITY, &work), &mut out, None); + out.left_out = work.ran_out(); out } @@ -192,8 +251,9 @@ pub fn evaluate_scene(doc: &Document, scene: usize, frame: u32) -> DisplayList { /// top-level ones, as a scene's are in [`evaluate_scene`]. pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayList { let mut out = DisplayList::default(); - let work = Cell::new(MAX_EVAL_ELEMENTS); + let work = Work::new(MAX_EVAL_ELEMENTS); eval_timeline(doc, tl, frame, &Ctx::top(Affine::IDENTITY, &work), &mut out, None); + out.left_out = work.ran_out(); out } @@ -203,8 +263,9 @@ pub fn evaluate_timeline(doc: &Document, tl: &Timeline, frame: u32) -> DisplayLi /// skin or Edit Multiple Frames composes its frames (ADR 0051). pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affine) -> DisplayList { let mut out = DisplayList::default(); - let work = Cell::new(MAX_EVAL_ELEMENTS); + let work = Work::new(MAX_EVAL_ELEMENTS); eval_timeline(doc, tl, frame, &Ctx::top(xf, &work), &mut out, None); + out.left_out = work.ran_out(); out } @@ -214,8 +275,9 @@ pub fn evaluate_timeline_at(doc: &Document, tl: &Timeline, frame: u32, xf: Affin pub fn evaluate_scene_camera(doc: &Document, scene: usize, frame: u32) -> DisplayList { let tl = doc.timeline(scene); let mut out = DisplayList::default(); - let work = Cell::new(MAX_EVAL_ELEMENTS); + let work = Work::new(MAX_EVAL_ELEMENTS); eval_timeline(doc, tl, frame, &Ctx::through(tl.camera_at(frame, &doc.stage), &work), &mut out, None); + out.left_out = work.ran_out(); out } @@ -224,22 +286,26 @@ pub fn evaluate_scene_camera(doc: &Document, scene: usize, frame: u32) -> Displa /// through the scene's camera. pub fn evaluate_player(doc: &Document, state: &PlayerState) -> DisplayList { let mut out = DisplayList::default(); - let work = Cell::new(MAX_EVAL_ELEMENTS); + let work = Work::new(MAX_EVAL_ELEMENTS); let play = Play { state, path: Vec::new() }; let tl = doc.timeline(state.scene); eval_timeline(doc, tl, state.root.frame, &Ctx::through(tl.camera_at(state.root.frame, &doc.stage), &work), &mut out, Some(&play)); + out.left_out = work.ran_out(); out } /// A symbol's timeline at `frame`, drawn at `xf` (stage space): a button's hit area, or a movie /// clip's artwork, as the player sees it when `play` is given. -pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Affine, play: Option<&Play<'_>>) -> DisplayList { +/// +/// `work` is the caller's allowance, so a player step that looks at many instances pays for +/// all of them from one. +pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Affine, play: Option<&Play<'_>>, work: &Work) -> DisplayList { let mut out = DisplayList::default(); - let work = Cell::new(MAX_EVAL_ELEMENTS); - let mut cx = Ctx::top(xf, &work); + let mut cx = Ctx::top(xf, work); cx.depth = 1; cx.stage = false; eval_timeline(doc, tl, frame, &cx, &mut out, play); + out.left_out = work.ran_out(); out } @@ -602,9 +668,9 @@ fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(an /// What a timeline is evaluated inside of. #[derive(Clone, Copy)] struct Ctx<'a> { - /// The evaluation's allowance of element visits ([`MAX_EVAL_ELEMENTS`]), shared by everything - /// nested in it. - work: &'a Cell, + /// The evaluation's allowance of work ([`MAX_EVAL_ELEMENTS`]), shared by everything nested + /// in it. + work: &'a Work, /// Local → stage transform and colour effect of the enclosing instance. xf: Affine, color: ColorTransform, @@ -632,12 +698,12 @@ struct Ctx<'a> { } impl<'a> Ctx<'a> { - fn top(xf: Affine, work: &'a Cell) -> Ctx<'a> { + fn top(xf: Affine, work: &'a Work) -> Ctx<'a> { Ctx { work, xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, stage: true, clip: None, masks: None, guide: false, group: None, camera: None, slice: None } } /// A main timeline seen through `camera`: its tint colours everything. - fn through(camera: Option, work: &'a Cell) -> Ctx<'a> { + fn through(camera: Option, work: &'a Work) -> Ctx<'a> { let mut cx = Ctx::top(Affine::IDENTITY, work); cx.stage = false; if let Some(c) = camera { @@ -777,6 +843,11 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx<'_>, out: & for k in 0..n { let index = sorted.as_ref().map_or(n - 1 - k, |o| o.get(k).copied().unwrap_or(n)); let Some(layer) = tl.layers.get(index) else { continue }; + // A layer looked at counts as an element does, so a timeline of empty layers, repeated + // by nesting, is bounded too. + if !cx.work.spend(1) { + return; + } // Guide artwork is listed (marked, for editing) but never drawn; inside mask artwork // it plays no part at all. let is_guide = layer.kind == LayerKind::Guide; @@ -872,8 +943,9 @@ struct LayerCtx<'a> { } fn eval_element(doc: &Document, cx: &Ctx<'_>, lc: &LayerCtx<'_>, el: &Element, out: &mut DisplayList, play: Option<&Play<'_>>) { - // Every element drawn counts, however deep: see MAX_EVAL_ELEMENTS. - if !spend(cx.work) { + // Every element drawn counts, however deep, and a shape by the size of its outline: see + // MAX_EVAL_ELEMENTS. + if !cx.work.visit(el) { return; } let LayerCtx { layer, frame, kf_start, clip, masks, guide, outline: layer_outline, xf: layer_xf } = *lc; @@ -1002,7 +1074,7 @@ fn eval_element(doc: &Document, cx: &Ctx<'_>, lc: &LayerCtx<'_>, el: &Element, o } } ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, .. } => { - let Some(sym) = doc.symbol(*symbol) else { return }; + let Some(sym) = cx.work.symbol(doc, *symbol) else { return }; let len = sym.timeline.frame_count(); let local = match (sym.kind, &child) { // A graphic keeps step with this timeline: loop mode and first frame apply. @@ -1149,7 +1221,7 @@ fn sliced_shape(s: &Shape, own: &Affine, sl: &Slicing) -> (Arc, Affine, Op #[cfg(test)] #[path = "eval_tests.rs"] -mod tests; +pub(crate) mod tests; #[cfg(test)] #[path = "pivot_tests.rs"] diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index 987ffc60..da46fc19 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -835,7 +835,7 @@ fn keep_area_off_is_bit_exact_with_a_tween_that_never_had_it_and_files_stay_smal /// A chain of symbols, each holding two instances of the next and the last one a square: 2^depth /// squares from `depth` symbols, with no cycle anywhere and no nesting deeper than the cap. -fn doubling_doc(depth: u64) -> Document { +pub(crate) fn doubling_doc(depth: u64) -> Document { let mut d = Document::default(); let instance = |id: u64, symbol: u64, x: f32| Element { id: ElementId(id), @@ -878,3 +878,63 @@ fn symbols_that_double_at_each_level_stay_within_the_allowance() { assert!(!bounds.is_empty(), "what was reached still counts"); assert!(started.elapsed() < std::time::Duration::from_secs(30), "{:?}", started.elapsed()); } + +/// ADR 0128: a frame that ran out of work says so, and one that did not, does not. +#[test] +fn a_frame_cut_short_by_the_allowance_says_artwork_is_left_out() { + let small = evaluate(&doubling_doc(11), 0); + assert!(!small.left_out); + let cut = evaluate(&doubling_doc(31), 0); + assert!(cut.left_out); + // Whoever composes lists (onion skin, the hit overlay) keeps the mark. + let mut both = small.clone(); + both.append(cut); + assert!(both.left_out); + assert!(evaluate_scene(&doubling_doc(31), 0, 0).left_out && evaluate_scene_camera(&doubling_doc(31), 0, 0).left_out); +} + +/// ADR 0128: what takes more work is counted as more, so nesting can multiply none of it past +/// the allowance: layers with nothing on them, an outline of many commands, a symbol far into +/// a long library. +#[test] +fn layers_long_outlines_and_long_libraries_count_as_work() { + let plain = evaluate(&doubling_doc(31), 0).items.len(); + // 200 empty layers in every symbol: each visit of a symbol looks at all of them. + let mut layered = doubling_doc(31); + for sym in &mut layered.library { + let tl = &mut Arc::make_mut(sym).timeline; + for i in 0..200 { + tl.layers.push(Arc::new(Layer::new(LayerId(9000 + i), "empty"))); + } + } + let dl = evaluate(&layered, 0); + assert!(dl.left_out && dl.items.len() * 20 < plain, "{} of {plain}", dl.items.len()); + assert!(!layered.timeline(0).layers[0].keyframes[0].elements[0].bounds(&layered).is_empty()); + // The one shape at the bottom has an outline of several units of work. + let mut heavy = doubling_doc(31); + let last = heavy.library.len() - 1; + let mut path = Path::new(); + path.move_to(Vec2::ZERO); + for i in 0..(8 * crate::eval::PATH_COMMANDS_PER_UNIT) { + path.line_to(Vec2::new(i as f32, (i % 7) as f32)); + } + let shape = Arc::make_mut(&mut Arc::make_mut(&mut Arc::make_mut(&mut Arc::make_mut(&mut heavy.library[last]).timeline.layers[0]).keyframes[0]).elements[0]); + shape.kind = ElementKind::Shape(Shape::filled(path, Paint::Solid(Rgba::BLACK))); + let dl = evaluate(&heavy, 0); + assert!(dl.left_out && dl.items.len() * 2 < plain, "{} of {plain}", dl.items.len()); + // The same symbols behind several thousand others: every lookup walks past them. + let mut far = doubling_doc(31); + let mut library: Vec> = (0..8 * crate::eval::LIBRARY_ENTRIES_PER_UNIT as u64).map(|i| Arc::new(Symbol { id: SymbolId(1_000_000 + i), name: String::new(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline::default() })).collect(); + library.append(&mut far.library); + far.library = library; + let dl = evaluate(&far, 0); + assert!(dl.left_out && dl.items.len() * 2 < plain, "{} of {plain}", dl.items.len()); + // A library that long is no cost to a scene of ordinary size. + let mut modest = doubling_doc(11); + let mut library = far.library.clone(); + library.truncate(8 * crate::eval::LIBRARY_ENTRIES_PER_UNIT); + library.append(&mut modest.library); + modest.library = library; + let dl = evaluate(&modest, 0); + assert!(!dl.left_out && dl.items.len() == 1 << 10); +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 58b429fa..db40a5d1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1113,18 +1113,18 @@ impl Element { } /// Local-space bounds (control-point bounds for shapes, `None` for symbols). pub fn local_bounds(&self, doc: &Document) -> Rect { - element_bounds(doc, self, &Affine::IDENTITY, 0, &std::cell::Cell::new(MAX_EVAL_ELEMENTS)) + element_bounds(doc, self, &Affine::IDENTITY, 0, &eval::Work::new(MAX_EVAL_ELEMENTS)) } /// Bounds in the parent's space. pub fn bounds(&self, doc: &Document) -> Rect { - element_bounds(doc, self, &self.transform, 0, &std::cell::Cell::new(MAX_EVAL_ELEMENTS)) + element_bounds(doc, self, &self.transform, 0, &eval::Work::new(MAX_EVAL_ELEMENTS)) } } -/// `work` is the query's allowance of element visits ([`MAX_EVAL_ELEMENTS`]): past it the rest -/// adds nothing, as in evaluation. -fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize, work: &std::cell::Cell) -> Rect { - if depth > MAX_SYMBOL_DEPTH || !eval::spend(work) { +/// `work` is the query's allowance ([`MAX_EVAL_ELEMENTS`]): past it the rest adds nothing, as in +/// evaluation. A shape pays for the outline measured here, and a symbol for each of its layers. +fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize, work: &eval::Work) -> Rect { + if depth > MAX_SYMBOL_DEPTH || !work.visit(el) { return Rect::EMPTY; } match &el.kind { @@ -1142,9 +1142,12 @@ fn element_bounds(doc: &Document, el: &Element, xf: &Affine, depth: usize, work: r } ElementKind::Symbol { symbol, .. } => { - let Some(sym) = doc.symbol(*symbol) else { return Rect::EMPTY }; + let Some(sym) = work.symbol(doc, *symbol) else { return Rect::EMPTY }; let mut r = Rect::EMPTY; for layer in &sym.timeline.layers { + if !work.spend(1) { + return r; + } if let Some(kf) = layer.keyframes.first() { for child in &kf.elements { let m = xf.mul(&child.transform); diff --git a/crates/doc/src/player.rs b/crates/doc/src/player.rs index a6dba851..3ccdb8bd 100644 --- a/crates/doc/src/player.rs +++ b/crates/doc/src/player.rs @@ -18,7 +18,7 @@ use crate::actions::as3::ir::{Base, Function, ListenEvent, Place, Prop, Value}; use crate::actions::as3::run::{self, Stop, World}; use crate::actions::as3::{Compiled, Decls, Problem}; use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, PluginScript, Property, Seg, Target}; -use crate::eval::{Play, evaluate_shown, evaluate_symbol, guide_walk}; +use crate::eval::{Play, Work, evaluate_shown, evaluate_symbol, guide_walk}; use crate::field::{Changed, Edit, Editor, FieldLook, FieldState, chars, fit, scroll_to_caret}; use crate::html_text::{self, RichStyles}; use crate::sound::Started; @@ -38,6 +38,11 @@ pub const MAX_ACTIONS_PER_STEP: usize = 10_000; pub const MAX_ENTERS_PER_STEP: usize = 1_000; /// Most symbol instances the player follows. pub const MAX_NODES: usize = 10_000; +/// The work one step may do looking at the movie (ADR 0128): every rebuild of the instance tree +/// after a change and every pointer hit test in the step share it, in the units of +/// [`crate::MAX_EVAL_ELEMENTS`]. Four full frames' worth: a movie that needs more in one step +/// is one no machine plays in time, and a hostile one stops here instead of hanging. +pub const MAX_WORK_PER_STEP: u32 = 4 * crate::MAX_EVAL_ELEMENTS; /// Most output lines one step keeps (more are counted). pub const MAX_OUTPUT_PER_STEP: usize = 1_000; /// Most pointer events one step handles. @@ -456,18 +461,24 @@ pub fn input(doc: &Document, state: &PlayerState, events: &[Event], host: &mut d /// The instance tree at `state`: the main timeline (index 0), then every symbol instance in /// drawing order (parents before their contents). pub fn tree(doc: &Document, st: &PlayerState) -> Vec { + tree_in(doc, st, &Work::new(crate::MAX_EVAL_ELEMENTS)) +} + +/// [`tree`], paid for from `work`: once it is spent the rest of the movie is left out. +fn tree_in(doc: &Document, st: &PlayerState, work: &Work) -> Vec { let tl = doc.timeline(st.scene); let mut out = vec![Node { path: Vec::new(), parent: None, owner: 0, name: String::new(), symbol: None, kind: NodeKind::Root, frame: st.root.frame, frames: tl.frame_count(), xf: Affine::IDENTITY, local: Affine::IDENTITY, alpha: 1.0, hittable: true, events: Vec::new(), gain: 1.0, text: None }]; // The main timeline is seen through its camera (ADR 0027): instances are where the pointer // sees them. let camera = tl.camera_at(st.root.frame, &doc.stage); - walk(doc, st, tl, st.root.frame, 0, 0, Affine::IDENTITY, 1, true, camera, &mut out); + walk(doc, st, tl, st.root.frame, 0, 0, Affine::IDENTITY, 1, true, camera, work, &mut out); out } /// The button (or movie clip with event handlers) at stage point `p`, topmost first. pub fn hit(doc: &Document, st: &PlayerState, p: Vec2) -> Option { - hit_in(doc, st, &tree(doc, st), p) + let work = Work::new(crate::MAX_EVAL_ELEMENTS); + hit_in(doc, st, &tree_in(doc, st, &work), p, &work) } /// The text field at stage point `p` the viewer can click into, topmost first (ADR 0066): what @@ -505,7 +516,11 @@ pub fn hit_frame(len: u32) -> u32 { /// shapes count however faint they are drawn). The hit test and Test Movie's hit-area overlay /// both use it. pub fn hit_area(doc: &Document, tl: &Timeline, xf: Affine) -> DisplayList { - let mut dl = evaluate_symbol(doc, tl, hit_frame(tl.frame_count()), xf, None); + hit_area_in(doc, tl, xf, &Work::new(crate::MAX_EVAL_ELEMENTS)) +} + +fn hit_area_in(doc: &Document, tl: &Timeline, xf: Affine, work: &Work) -> DisplayList { + let mut dl = evaluate_symbol(doc, tl, hit_frame(tl.frame_count()), xf, None, work); dl.items.retain(|i| !i.guide && i.masks.is_none()); dl.links.clear(); for i in &mut dl.items { @@ -543,11 +558,14 @@ pub fn tinted(dl: DisplayList, tint: Rgba, alpha: f32) -> DisplayList { /// Areas): where the pointer finds the buttons, drawn over the movie. pub fn hit_overlay(doc: &Document, st: &PlayerState, tint: Rgba, alpha: f32) -> DisplayList { let mut out = DisplayList::default(); - for n in tree(doc, st).iter().filter(|n| n.kind == NodeKind::Button && n.hittable) { - if let Some(sym) = n.symbol.and_then(|s| doc.symbol(s)) { - out.append(tinted(hit_area(doc, &sym.timeline, n.xf), tint, alpha)); + // One allowance for the tree and every button's area, however many buttons there are. + let work = Work::new(crate::MAX_EVAL_ELEMENTS); + for n in tree_in(doc, st, &work).iter().filter(|n| n.kind == NodeKind::Button && n.hittable) { + if let Some(sym) = n.symbol.and_then(|s| work.symbol(doc, s)) { + out.append(tinted(hit_area_in(doc, &sym.timeline, n.xf, &work), tint, alpha)); } } + out.left_out = work.ran_out(); out } @@ -558,7 +576,7 @@ fn plays(tl: &Timeline, index: usize) -> bool { } #[allow(clippy::too_many_arguments)] -fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usize, owner: usize, xf: Affine, depth: usize, hittable: bool, camera: Option, out: &mut Vec) { +fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usize, owner: usize, xf: Affine, depth: usize, hittable: bool, camera: Option, work: &Work, out: &mut Vec) { if depth > MAX_SYMBOL_DEPTH { return; } @@ -576,6 +594,11 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi if !plays(tl, index) { continue; } + // Layers and elements are paid for as the evaluator pays for them, so a timeline of + // plain artwork, looked at once for every instance of it, is bounded too. + if !work.spend(1) { + return; + } let gain = parent_gain * layer.sound_gain(); let hit = hittable && layer.kind != LayerKind::Mask; let path_walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame)); @@ -594,7 +617,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi // Instances inside a group belong to the group's timeline (ADR 0073). let els = crate::expand_groups(&els).into_owned(); for el in els.iter() { - if out.len() >= MAX_NODES { + if out.len() >= MAX_NODES || !work.spend(1) { return; } // Dynamic and input text fields are instances scripts can name (static text isn't). @@ -611,7 +634,7 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi continue; } let ElementKind::Symbol { symbol, loop_mode, first_frame, events, .. } = &el.kind else { continue }; - let Some(sym) = doc.symbol(*symbol) else { continue }; + let Some(sym) = work.symbol(doc, *symbol) else { continue }; let mut path = base.clone(); path.push(el.id); let ov = st.props.get(&path); @@ -630,22 +653,27 @@ fn walk(doc: &Document, st: &PlayerState, tl: &Timeline, frame: u32, parent: usi // Names inside a movie clip (or a button's states) are its own; a graphic's // contents belong to the timeline the graphic is on. let inner_owner = if kind == NodeKind::Graphic { owner } else { idx }; - walk(doc, st, &sym.timeline, local, idx, inner_owner, node_xf, depth + 1, hit && shown, None, out); + walk(doc, st, &sym.timeline, local, idx, inner_owner, node_xf, depth + 1, hit && shown, None, work, out); } } } -fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2) -> Option { +/// `work` pays for every area looked at: each interactive instance is evaluated to find the one +/// under the pointer, and they share one allowance instead of having a whole frame's each. +fn hit_in(doc: &Document, st: &PlayerState, nodes: &[Node], p: Vec2, work: &Work) -> Option { for n in nodes.iter().rev() { let interactive = n.kind == NodeKind::Button || (n.kind == NodeKind::MovieClip && (!n.events.is_empty() || st.listeners.contains_key(&n.path))); if !n.hittable || !interactive { continue; } - let Some(sym) = n.symbol.and_then(|s| doc.symbol(s)) else { continue }; + if work.ran_out() { + return None; + } + let Some(sym) = n.symbol.and_then(|s| work.symbol(doc, s)) else { continue }; let dl = if n.kind == NodeKind::Button { - hit_area(doc, &sym.timeline, n.xf) + hit_area_in(doc, &sym.timeline, n.xf, work) } else { - evaluate_symbol(doc, &sym.timeline, n.frame, n.xf, Some(&Play { state: st, path: n.path.clone() })) + evaluate_symbol(doc, &sym.timeline, n.frame, n.xf, Some(&Play { state: st, path: n.path.clone() }), work) }; let inside = dl.items.iter().filter(|i| !i.guide && i.masks.is_none()).any(|i| { let fill = i.fill.is_some() && i.path.contains(p, &i.transform, i.fill_rule); @@ -694,11 +722,13 @@ struct Run<'a, 'h> { decls: BTreeMap>, /// Script fuel left this step. fuel: u64, + /// What is left of [`MAX_WORK_PER_STEP`]. + work: Work, } impl<'a, 'h> Run<'a, 'h> { fn new(doc: &'a Document, st: PlayerState, host: &'h mut dyn ScriptHost) -> Self { - Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new(), decls: BTreeMap::new(), fuel: MAX_FUEL_PER_STEP } + Run { doc, st, host, nodes: Vec::new(), dirty: true, pending: VecDeque::new(), actions: 0, enters: 0, halted: false, output: Vec::new(), dropped: 0, sounds: Vec::new(), graphics: BTreeMap::new(), decls: BTreeMap::new(), fuel: MAX_FUEL_PER_STEP, work: Work::new(MAX_WORK_PER_STEP) } } fn remember_graphics(&mut self) { @@ -776,6 +806,15 @@ impl<'a, 'h> Run<'a, 'h> { } } + /// The step's allowance of work ran out ([`MAX_WORK_PER_STEP`]): nothing more runs this + /// step, and the Output panel says why, once. + fn overworked(&mut self) { + if self.work.ran_out() && !self.halted { + self.halted = true; + self.out("Stopped this frame early: the movie holds more than one frame may look at, so some instances and buttons were left out (symbols nested in themselves?)"); + } + } + /// Rebuilds the instance tree after a change, starting movie clips that appeared (they /// enter their first frame) and forgetting those that left. fn refresh(&mut self) { @@ -788,7 +827,8 @@ impl<'a, 'h> Run<'a, 'h> { } let n = self.doc.timeline(self.st.scene).frame_count(); self.st.root.frame = self.st.root.frame.min(n.saturating_sub(1)); - self.nodes = tree(self.doc, &self.st); + self.nodes = tree_in(self.doc, &self.st, &self.work); + self.overworked(); let live: std::collections::BTreeSet<&InstancePath> = self.nodes.iter().filter(|n| n.kind == NodeKind::MovieClip).map(|n| &n.path).collect(); self.st.clips.retain(|p, _| live.contains(p)); for p in live { @@ -1590,7 +1630,8 @@ impl<'a, 'h> Run<'a, 'h> { if let Some(p) = p { self.st.mouse = p; } - let now = p.and_then(|p| hit_in(self.doc, &self.st, &self.nodes, p)); + let now = p.and_then(|p| hit_in(self.doc, &self.st, &self.nodes, p, &self.work)); + self.overworked(); if now != self.st.hover { let before = self.pointer_now(); let old = std::mem::replace(&mut self.st.hover, now.clone()); diff --git a/crates/doc/src/player_tests.rs b/crates/doc/src/player_tests.rs index 9ec48d2e..1964f3bd 100644 --- a/crates/doc/src/player_tests.rs +++ b/crates/doc/src/player_tests.rs @@ -929,3 +929,36 @@ fn max_chars_and_restrict_limit_what_the_viewer_types() { assert_eq!(text_of(&type_into_name(&d, &s.state, "ok").state, 6).as_deref(), Some("ok")); } + +/// ADR 0128: a step looks at the movie many times (the instance tree after every change, a hit +/// test for every pointer event), and all of it comes out of one allowance. Movie clips that +/// double at each level, each over a thousand plain shapes, stop the step with a line in the +/// Output panel instead of holding the window; the next step is bounded the same way. +#[test] +fn a_step_over_a_movie_too_large_to_look_at_stops_and_says_so() { + let mut d = crate::eval::tests::doubling_doc(31); + for sym in &mut d.library { + let sym = Arc::make_mut(sym); + sym.kind = SymbolKind::MovieClip; + let mut artwork = Layer::new(LayerId(7000), "artwork"); + artwork.keyframes = vec![kf(0, 1, (0..1000).map(|i| rect(50_000 + i, 0.0, 0.0, 4.0, 4.0)).collect(), vec![], "")]; + sym.timeline.layers.push(Arc::new(artwork)); + } + let first = start(&d, &mut NoScripts); + assert!(first.output.iter().any(|l| l.contains("left out")), "{:?}", first.output); + let next = step(&d, &first.state, &[Event::Move(Vec2::new(1.0, 1.0)), Event::Down(Vec2::new(1.0, 1.0))], &mut NoScripts); + assert_eq!(next.output.iter().filter(|l| l.contains("left out")).count(), 1, "said once a step: {:?}", next.output); + // What draws the movie and its hit areas marks the same. + assert!(evaluate_player(&d, &next.state).left_out); + // Buttons instead: every button's hit area is a frame's worth of artwork, and the overlay + // shows them all from one allowance. + for sym in &mut d.library { + Arc::make_mut(sym).kind = SymbolKind::Button; + } + assert!(hit_overlay(&d, &PlayerState::default(), Rgba::WHITE, 0.4).left_out); + assert_eq!(hit(&d, &PlayerState::default(), Vec2::new(-500.0, -500.0)), None); + // An ordinary movie is not marked. + let small = sample::interactive(); + let s = run(&small, 3); + assert!(!s.output.iter().any(|l| l.contains("left out")) && !evaluate_player(&small, &s.state).left_out); +} From d9b8bcadd176692297037636ba419ed7780db2e3 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:28:27 -0700 Subject: [PATCH 19/23] feat(engine): exports, info and the MCP render say when a frame's artwork was left out (M8) --- crates/cli/src/mcp.rs | 13 ++++++-- crates/doc/src/eval_tests.rs | 29 ++---------------- crates/doc/src/sample.rs | 30 ++++++++++++++++++ crates/engine/src/anim.rs | 7 +++-- crates/engine/src/cmds_draw.rs | 2 +- crates/engine/src/cmds_file.rs | 54 ++++++++++++++++++++++----------- crates/engine/src/left_out.rs | 50 ++++++++++++++++++++++++++++++ crates/engine/src/lib.rs | 8 +++-- crates/engine/src/tests.rs | 35 +++++++++++++++++++++ crates/gpu/src/tests.rs | 34 ++++++++++----------- crates/render/src/html_tests.rs | 2 +- crates/render/src/lib.rs | 23 +++++++------- crates/render/src/stroke.rs | 4 +-- crates/render/src/svg.rs | 14 ++++----- 14 files changed, 216 insertions(+), 89 deletions(-) create mode 100644 crates/engine/src/left_out.rs diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 13aa801b..14d6af39 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -211,11 +211,20 @@ pub fn call_tool_in(h: &mut H, name: &str, args: &Value, roots }; let scale = scale.min(MAX_PICTURE_EDGE / largest); let movie_frame = s.doc.scene_start(s.scene).saturating_add(frame); - let png = anicraft_render::render_frame(&s.doc, movie_frame, scale).and_then(|p| p.encode_png()).map_err(|e| e.to_string())?; + // A frame cut short by its allowance of work is said to be (ADR 0128). + let cut = anicraft_engine::left_out::LeftOut::default(); + let dl = cut.evaluate(&s.doc, movie_frame); + let png = anicraft_render::render(&dl, &anicraft_render::View::stage(&s.doc, scale)).and_then(|(p, _)| p.encode_png()).map_err(|e| e.to_string())?; + let mut caption = format!("Frame {frame} of scene {} at {:.0}% ({}×{} stage).", s.scene, scale * 100.0, stage.width, stage.height); + if cut.any() { + caption.push_str(" Not the whole frame: "); + caption.push_str(anicraft_engine::left_out::WARNING); + caption.push('.'); + } json!({ "content": [ {"type": "image", "data": anicraft_doc::base64_encode(&png), "mimeType": "image/png"}, - {"type": "text", "text": format!("Frame {frame} of scene {} at {:.0}% ({}×{} stage).", s.scene, scale * 100.0, stage.width, stage.height)} + {"type": "text", "text": caption} ], "isError": false }) diff --git a/crates/doc/src/eval_tests.rs b/crates/doc/src/eval_tests.rs index da46fc19..489d0b82 100644 --- a/crates/doc/src/eval_tests.rs +++ b/crates/doc/src/eval_tests.rs @@ -833,32 +833,9 @@ fn keep_area_off_is_bit_exact_with_a_tween_that_never_had_it_and_files_stay_smal assert!(back.scenes[0].timeline.layers[0].keyframes[0].tween.as_ref().unwrap().keep_area); } -/// A chain of symbols, each holding two instances of the next and the last one a square: 2^depth -/// squares from `depth` symbols, with no cycle anywhere and no nesting deeper than the cap. -pub(crate) fn doubling_doc(depth: u64) -> Document { - let mut d = Document::default(); - let instance = |id: u64, symbol: u64, x: f32| Element { - id: ElementId(id), - name: String::new(), - transform: Affine::translate(x, 0.0), - color: ColorEffect::default(), - kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters: Vec::new(), events: Vec::new(), pivot: None }, - }; - for level in 0..depth { - let mut layer = Layer::new(LayerId(1000 + level), "l"); - layer.keyframes = vec![Arc::new(Keyframe::new(0, 1))]; - if level + 1 == depth { - push(&mut layer, 0, shape_el(5000, 0.0)); - } else { - push(&mut layer, 0, instance(2000 + level, 101 + level, 0.0)); - push(&mut layer, 0, instance(3000 + level, 101 + level, 1.0)); - } - let timeline = Timeline { layers: vec![Arc::new(layer)] }; - d.library.push(Arc::new(Symbol { id: SymbolId(100 + level), name: format!("s{level}"), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline })); - } - layer0(&mut d).keyframes = vec![Arc::new(Keyframe::new(0, 1))]; - push(layer0(&mut d), 0, instance(1, 100, 0.0)); - d +/// [`crate::sample::doubling`]: 2^(depth - 1) squares from `depth` symbols. +pub(crate) fn doubling_doc(depth: u32) -> Document { + crate::sample::doubling(depth) } /// #13: the depth cap alone lets symbols that double at each level expand without end. One diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 06a0992b..fb1b22aa 100644 --- a/crates/doc/src/sample.rs +++ b/crates/doc/src/sample.rs @@ -242,6 +242,36 @@ pub fn interactive() -> Document { d } +/// A document whose symbols double at every level: `levels` symbols in a chain, each holding +/// two instances of the next and the last one a square, so the one instance on the stage is +/// 2^(`levels` - 1) squares, with no cycle anywhere and nothing nested deeper than +/// [`crate::MAX_SYMBOL_DEPTH`]. Past twenty levels it is more than a frame's allowance of work +/// ([`crate::MAX_EVAL_ELEMENTS`], ADR 0128): what tests and benchmarks use for a document too +/// large to draw. +pub fn doubling(levels: u32) -> Document { + let levels = u64::from(levels.clamp(1, 31)); + let mut d = Document::default(); + let at = |id: u64, x: f32, kind: ElementKind| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 0.0), color: ColorEffect::default(), kind }); + let on_one_layer = |id: u64, elements: Vec>| { + let mut l = Layer::new(LayerId(id), "l"); + l.keyframes = vec![Arc::new(key(0, 1, elements, None))]; + Timeline { layers: vec![Arc::new(l)] } + }; + for level in 0..levels { + let elements = if level + 1 == levels { + vec![at(5000, 0.0, ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK))))] + } else { + vec![at(2000 + level, 0.0, instance(SymbolId(101 + level))), at(3000 + level, 1.0, instance(SymbolId(101 + level)))] + }; + let timeline = on_one_layer(1000 + level, elements); + d.library.push(Arc::new(Symbol { id: SymbolId(100 + level), name: format!("s{level}"), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline })); + } + let root = on_one_layer(1, vec![at(1, 0.0, instance(SymbolId(100)))]); + d.timeline_mut(0).layers = root.layers; + d.next_id = 10_000; + d +} + /// Deterministic stress document for benchmarks and scaling tests: `layers` layers with /// `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. diff --git a/crates/engine/src/anim.rs b/crates/engine/src/anim.rs index 60d0cce5..75bada70 100644 --- a/crates/engine/src/anim.rs +++ b/crates/engine/src/anim.rs @@ -371,12 +371,13 @@ pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result { let mut shown: Vec<(u64, u64)> = Vec::new(); let mut encoded: Vec = Vec::new(); let mut prev: Option> = None; + let cut = crate::left_out::LeftOut::default(); let frames: Vec = (from..=to).collect(); for (b, chunk) in frames.chunks(batch).enumerate() { let images: Vec> = chunk .par_iter() .map(|&f| { - let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + let (pm, _) = render(&cut.evaluate(doc, f), &view)?; crate::publish::tick(job, 1)?; Ok(pm.to_rgba8()) }) @@ -437,7 +438,7 @@ pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result { } }; crate::vfs::write(&path, &bytes)?; - Ok(json!({ + Ok(cut.noted(json!({ "written": path.display().to_string(), "frames": n, "stored_frames": encoded.len(), @@ -446,7 +447,7 @@ pub fn export(s: &mut Session, p: &Value, kind: Kind) -> Result { "height": h, "loop": plays, "ms": started.elapsed().as_millis() as u64, - })) + }))) } #[cfg(test)] diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index eb279b83..71db4ef3 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -1073,7 +1073,7 @@ fn selection_list(s: &Session) -> anicraft_doc::DisplayList { i }) .collect(); - anicraft_doc::DisplayList { items, clip_parents, clip_modes: full.clip_modes.clone(), groups, links: Vec::new() } + anicraft_doc::DisplayList { items, clip_parents, clip_modes: full.clip_modes.clone(), groups, links: Vec::new(), left_out: full.left_out } } /// Convert to Bitmap (#463): the selection, drawn by the CPU renderer on whole pixels of the diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 5b834a0c..789aa5e8 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -1,5 +1,6 @@ //! File, edit-history and document commands. +use crate::left_out::LeftOut; use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session, format}; use anicraft_doc::{Document, MAX_STAGE_EDGE, Stage, sample}; @@ -261,7 +262,12 @@ pub(crate) fn scale_param(p: &Value) -> Result { /// Renders movie frame `frame` (scenes in order) of `doc` to PNG bytes. pub fn render_png(doc: &Document, frame: u32, scale: f32) -> Result> { - let dl = anicraft_doc::evaluate(doc, frame); + render_png_noting(doc, frame, scale, &LeftOut::default()) +} + +/// [`render_png`], noting in `cut` a frame whose artwork was left out (ADR 0128). +pub fn render_png_noting(doc: &Document, frame: u32, scale: f32, cut: &LeftOut) -> Result> { + let dl = cut.evaluate(doc, frame); let (pm, _) = render(&dl, &View::stage(doc, scale))?; Ok(pm.encode_png()?) } @@ -270,9 +276,10 @@ fn export_png(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); let frame = opt_u32(p, "frame")?.unwrap_or(s.frame); // `frame` is within the current scene; the renderer takes movie frames. - let bytes = render_png(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), scale_param(p)?)?; + let cut = LeftOut::default(); + let bytes = render_png_noting(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), scale_param(p)?, &cut)?; crate::vfs::write(&path, &bytes)?; - Ok(json!({"written": path.display().to_string(), "bytes": bytes.len(), "frame": frame})) + Ok(cut.noted(json!({"written": path.display().to_string(), "bytes": bytes.len(), "frame": frame}))) } /// Largest file Import to Stage reads. @@ -524,9 +531,16 @@ fn import_image(s: &mut Session, path: &std::path::Path, bytes: Vec) -> Resu Ok(anicraft_svg::SvgImport::single(w, h, vec![anicraft_svg::ImportedElement { name, transform: anicraft_geom::Affine::IDENTITY, alpha: 1.0, kind: anicraft_doc::ElementKind::Shape(shape) }])) } -/// Movie frame `frame` as a standalone SVG document (vectors, gradients and masks kept). +/// [`frame_svg_noting`] for a frame known to be whole: what tests compare a written file with. +#[cfg(test)] pub fn frame_svg(doc: &Document, frame: u32) -> String { - anicraft_render::svg::to_svg(&anicraft_doc::evaluate(doc, frame), &doc.stage) + frame_svg_noting(doc, frame, &LeftOut::default()) +} + +/// Movie frame `frame` as a standalone SVG document (vectors, gradients and masks kept), +/// noting in `cut` a frame whose artwork was left out (ADR 0128). +pub fn frame_svg_noting(doc: &Document, frame: u32, cut: &LeftOut) -> String { + anicraft_render::svg::to_svg(&cut.evaluate(doc, frame), &doc.stage) } fn export_svg(s: &mut Session, p: &Value) -> Result { @@ -535,9 +549,10 @@ fn export_svg(s: &mut Session, p: &Value) -> Result { if frame >= s.frame_count() { return Err(EngineError::Param(format!("frame {} is past the end (the timeline has {} frames)", u64::from(frame) + 1, s.frame_count()))); } - let svg = frame_svg(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame)); + let cut = LeftOut::default(); + let svg = frame_svg_noting(&s.doc, s.doc.scene_start(s.scene).saturating_add(frame), &cut); crate::vfs::write(&path, svg.as_bytes())?; - Ok(json!({"written": path.display().to_string(), "bytes": svg.len(), "frame": frame})) + Ok(cut.noted(json!({"written": path.display().to_string(), "bytes": svg.len(), "frame": frame}))) } /// Export Sprite Sheet: movie frames in a grid on one PNG (transparent unless `background`), @@ -578,10 +593,11 @@ fn export_sprite_sheet(s: &mut Session, p: &Value) -> Result { let doc = &s.doc; // A publish counts the frames, and stops between them when cancelled (ADR 0060). let job = s.job.as_deref(); + let cut = LeftOut::default(); let frames: Vec = (from..=to) .into_par_iter() .map(|f| { - let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + let (pm, _) = render(&cut.evaluate(doc, f), &view)?; crate::publish::tick(job, 1)?; Ok(pm) }) @@ -631,7 +647,7 @@ fn export_sprite_sheet(s: &mut Session, p: &Value) -> Result { let text = serde_json::to_string_pretty(&atlas).map_err(|e| EngineError::Format(e.to_string()))?; crate::vfs::write(&path, &png)?; crate::vfs::write(&json_path, text)?; - Ok(json!({"written": path.display().to_string(), "map": json_path.display().to_string(), "frames": n, "columns": cols, "rows": rows, "width": sheet_w, "height": sheet_h})) + Ok(cut.noted(json!({"written": path.display().to_string(), "map": json_path.display().to_string(), "frames": n, "columns": cols, "rows": rows, "width": sheet_w, "height": sheet_h}))) } /// The ffmpeg to run: `ffmpeg` param, else `ANICRAFT_FFMPEG`, else `ffmpeg` on the PATH. @@ -714,11 +730,12 @@ fn export_video(s: &mut Session, p: &Value) -> Result { let doc = &s.doc; let job = s.job.as_deref(); let mut written = 0u32; + let cut = LeftOut::default(); let mut failure: Option = None; if let Some(mut stdin) = child.stdin.take() { let frames: Vec = (from..=to).collect(); 'batches: for batch in frames.chunks(8) { - let images: Vec> = match batch.par_iter().map(|&f| render(&anicraft_doc::evaluate(doc, f), &view).map(|(pm, _)| pm.to_rgba8())).collect::>() { + let images: Vec> = match batch.par_iter().map(|&f| render(&cut.evaluate(doc, f), &view).map(|(pm, _)| pm.to_rgba8())).collect::>() { Ok(v) => v, Err(e) => { failure = Some(e.into()); @@ -754,7 +771,7 @@ fn export_video(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Format(format!("ffmpeg could not make the video ({status}): {}", if tail.is_empty() { "no message".to_string() } else { tail.join(" | ") }))); } let bytes = crate::vfs::len(&path).unwrap_or(0); - Ok(json!({"written": path.display().to_string(), "frames": written, "bytes": bytes, "width": w, "height": h, "fps": fps, "audio": track.is_some()})) + Ok(cut.noted(json!({"written": path.display().to_string(), "frames": written, "bytes": bytes, "width": w, "height": h, "fps": fps, "audio": track.is_some()}))) } fn export_sequence(s: &mut Session, p: &Value) -> Result { @@ -775,16 +792,17 @@ fn export_sequence(s: &mut Session, p: &Value) -> Result { let doc = &s.doc; let job = s.job.as_deref(); let mut files = 0usize; + let cut = LeftOut::default(); let frames: Vec = (from..=to).collect(); for batch in frames.chunks(64) { - let pngs = batch.par_iter().map(|&f| render_png(doc, f, scale)).collect::>>()?; + let pngs = batch.par_iter().map(|&f| render_png_noting(doc, f, scale, &cut)).collect::>>()?; for (f, png) in batch.iter().zip(pngs) { crate::vfs::write(&dir.join(format!("frame_{:05}.png", f + 1)), png)?; files += 1; } crate::publish::tick(job, batch.len() as u64)?; } - Ok(json!({"frames": files, "dir": dir.display().to_string()})) + Ok(cut.noted(json!({"frames": files, "dir": dir.display().to_string()}))) } /// Export SVG Sequence (#504): every movie frame as its own SVG file, named like the PNG @@ -804,9 +822,10 @@ fn export_svg_sequence(s: &mut Session, p: &Value) -> Result { let doc = &s.doc; let job = s.job.as_deref(); let (mut files, mut bytes) = (0usize, 0u64); + let cut = LeftOut::default(); let frames: Vec = (from..=to).collect(); for batch in frames.chunks(16) { - let svgs: Vec = batch.par_iter().map(|&f| frame_svg(doc, f)).collect(); + let svgs: Vec = batch.par_iter().map(|&f| frame_svg_noting(doc, f, &cut)).collect(); for (f, svg) in batch.iter().zip(svgs) { bytes = bytes.saturating_add(svg.len() as u64); crate::vfs::write(&dir.join(format!("frame_{:05}.svg", f + 1)), svg.as_bytes())?; @@ -814,7 +833,7 @@ fn export_svg_sequence(s: &mut Session, p: &Value) -> Result { } crate::publish::tick(job, batch.len() as u64)?; } - Ok(json!({"frames": files, "bytes": bytes, "dir": dir.display().to_string()})) + Ok(cut.noted(json!({"frames": files, "bytes": bytes, "dir": dir.display().to_string()}))) } /// Largest GIF we produce (frames × pixels), keeping memory and time bounded. @@ -921,11 +940,12 @@ fn export_gif(s: &mut Session, p: &Value) -> Result { let doc = &s.doc; let job = s.job.as_deref(); let delays = gif_delays(n as usize, doc.stage.fps); + let cut = LeftOut::default(); let frames: Vec<(craft_gif::write::PreparedFrame, u16)> = (from..to.saturating_add(1)) .into_par_iter() .zip(delays.into_par_iter()) .map(|(f, delay)| { - let (pm, _) = render(&anicraft_doc::evaluate(doc, f), &view)?; + let (pm, _) = render(&cut.evaluate(doc, f), &view)?; let rgba = pm.to_rgba8(); let frame = craft_gif::write::prepare_frame(u32::from(w), u32::from(h), rgba, 10) .map_err(|e| EngineError::Format(e.to_string()))?; @@ -943,7 +963,7 @@ fn export_gif(s: &mut Session, p: &Value) -> Result { } } crate::vfs::write(&path, &bytes)?; - Ok(json!({"written": path.display().to_string(), "frames": n, "bytes": bytes.len(), "width": w, "height": h})) + Ok(cut.noted(json!({"written": path.display().to_string(), "frames": n, "bytes": bytes.len(), "width": w, "height": h}))) } fn set_stage(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/left_out.rs b/crates/engine/src/left_out.rs new file mode 100644 index 00000000..7c3e99ea --- /dev/null +++ b/crates/engine/src/left_out.rs @@ -0,0 +1,50 @@ +//! Saying when artwork was left out of a frame (ADR 0128). +//! +//! A frame's evaluation has an allowance of work (`anicraft_doc::MAX_EVAL_ELEMENTS`), so that no +//! document, however its symbols nest, hangs AniCraft or runs it out of memory. A frame cut +//! short draws in part. A command that writes such a frame still writes it, and says so in its +//! result, so a partial picture is never passed off as the whole one. + +use anicraft_doc::{DisplayList, Document}; +use serde_json::{Value, json}; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// What a result says when artwork was left out. +pub const WARNING: &str = "the document holds more artwork than AniCraft draws in one frame, so some of it was left out (symbols nested many times over?)"; + +/// Whether any frame one command evaluated was cut short. Shared by the threads that render a +/// sequence's frames. +#[derive(Default)] +pub struct LeftOut(AtomicBool); + +impl LeftOut { + /// Movie frame `frame`, as `anicraft_doc::evaluate` gives it, noted when it was cut short. + pub fn evaluate(&self, doc: &Document, frame: u32) -> DisplayList { + let dl = anicraft_doc::evaluate(doc, frame); + self.note(&dl); + dl + } + + /// Notes `dl` when it was cut short. + pub fn note(&self, dl: &DisplayList) { + if dl.left_out { + self.0.store(true, Ordering::Relaxed); + } + } + + pub fn any(&self) -> bool { + self.0.load(Ordering::Relaxed) + } + + /// `result` as it is when every frame was whole; with `left_out: true` and a `warning` + /// when one was not. + pub fn noted(&self, mut result: Value) -> Value { + if self.any() + && let Some(o) = result.as_object_mut() + { + o.insert("left_out".into(), json!(true)); + o.insert("warning".into(), json!(WARNING)); + } + result + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index de144ad9..95193297 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -7,6 +7,7 @@ pub mod access; mod anim; +pub mod left_out; mod cmds_actions; mod cmds_bone; mod cmds_warp; @@ -1305,8 +1306,11 @@ impl Session { }) .collect(); let symbols: Vec = self.doc.library.iter().map(|s| json!({"id": s.id.0, "name": s.name, "kind": format!("{:?}", s.kind), "frames": s.timeline.frame_count()})).collect(); + // The frame shown, when its artwork is not all there (ADR 0128). + let cut = left_out::LeftOut::default(); + cut.note(&self.display_list()); let sounds: Vec = self.doc.sounds.iter().map(|x| json!({"id": x.id.0, "name": x.name, "format": x.format.label(), "rate": x.rate, "channels": x.channels, "seconds": x.seconds()})).collect(); - json!({ + cut.noted(json!({ "stage": {"width": self.doc.stage.width, "height": self.doc.stage.height, "fps": self.doc.stage.fps, "background": self.doc.stage.background.to_hex()}, "frames": self.frame_count(), "frame": self.frame, @@ -1325,7 +1329,7 @@ impl Session { "dirty": self.is_dirty(), "history": {"undo": self.history.undo_len(), "redo": self.history.redo_len(), "bytes": self.history.bytes(), "evicted": self.history.evicted}, "state": self.state, - }) + })) } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4b791968..7fc86139 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2743,3 +2743,38 @@ fn a_motion_guide_with_sharp_corners_is_followed_to_its_end() { prev = p; } } + +/// ADR 0128: a frame cut short by its allowance of work is still written, and every command +/// that writes it says so; a whole frame's results are as they always were. (The symbols hold +/// thousands of empty layers, so the allowance goes on looking at them and little is drawn.) +#[test] +fn exports_of_a_frame_too_large_to_draw_say_artwork_was_left_out() { + let dir = std::env::temp_dir().join(format!("anicraft-left-out-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut large = anicraft_doc::sample::doubling(31); + for sym in &mut large.library { + let tl = &mut std::sync::Arc::make_mut(sym).timeline; + for i in 0..5_000 { + tl.layers.push(std::sync::Arc::new(anicraft_doc::Layer::new(anicraft_doc::LayerId(9_000 + i), "empty"))); + } + } + for (doc, cut) in [(large, true), (anicraft_doc::sample::doubling(6), false)] { + let mut s = Session::new(doc); + let at = |name: &str| dir.join(format!("{cut}-{name}")).display().to_string(); + let results = [ + s.info(), + run(&mut s, "file.export_png", json!({"path": at("f.png"), "scale": 0.1})), + run(&mut s, "file.export_svg", json!({"path": at("f.svg")})), + run(&mut s, "file.export_png_sequence", json!({"dir": at("png"), "scale": 0.1})), + run(&mut s, "file.export_svg_sequence", json!({"dir": at("svg")})), + run(&mut s, "file.export_sprite_sheet", json!({"path": at("sheet.png"), "scale": 0.1})), + run(&mut s, "file.export_gif", json!({"path": at("f.gif"), "scale": 0.1})), + run(&mut s, "file.export_apng", json!({"path": at("a.png"), "scale": 0.1})), + ]; + for v in &results { + assert_eq!(v.get("left_out").and_then(Value::as_bool).unwrap_or(false), cut, "{v}"); + assert_eq!(v.get("warning").is_some(), cut, "{v}"); + } + } + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 5c06c962..f0904d97 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -212,7 +212,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { let grad = || Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(120.0, 40.0), stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)])); let mut out = Vec::new(); // A mask: a gradient seen through a circle, an unclipped shape over it, and one under it. - let dl = DisplayList { links: Vec::new(), + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![item(Path::rect(70.0, 0.0, 50.0, 100.0), Paint::Solid(green)), clipped(item(Path::rect(0.0, 0.0, 120.0, 100.0), grad()), 0), mask(Path::ellipse(50.0, 50.0, 37.3, 33.1), 0), item(Path::rect(10.0, 60.0, 30.0, 30.0), Paint::Solid(blue))], clip_parents: vec![None], @@ -235,10 +235,10 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { } let mut items = stripes; items.extend([eo, mask(Path::ellipse(95.0, 20.0, 30.0, 18.0), 0), star]); - out.push(("nested masks", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); + out.push(("nested masks", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0))))); // Group alpha: overlapping shapes fade as one; nested groups multiply; a group spans tiles // and the render bands; a top-level shape between two groups. - let dl = DisplayList { links: Vec::new(), + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(5.0, 5.0, 60.0, 50.0), Paint::Solid(red)), 0), @@ -266,9 +266,9 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { items.push(in_group(item(Path::ellipse(x + 12.0, 30.0, 11.0, 28.0), grad()), g)); items.push(in_group(item(Path::rect(x + 2.0, 60.0, 20.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.5, 0.2, 0.7))), g)); } - out.push(("blend modes", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); + out.push(("blend modes", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8))))); // Masks inside groups and groups inside masks, with a blend mode, on transparent. - let dl = DisplayList { links: Vec::new(), + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![ in_group(clipped(item(Path::rect(0.0, 0.0, 100.0, 60.0), grad()), 0), 0), @@ -284,7 +284,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> { out.push(("masks and groups", dl, view(110, 90, None))); // Malformed links, as the oracle treats them: a clip whose parent is later (empty, hides // what it clips), a group whose parent is later (top-level), a clip index past the list. - let dl = DisplayList { links: Vec::new(), + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![ clipped(item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(red)), 0), @@ -670,7 +670,7 @@ fn binning_shapes_the_scene_into_tiles() { assert!(b.index.iter().all(|&v| v == 0)); // A group in one tile: open, the fill, close; a clipped fill: the clip's level first. In // the middle tile the mask has no artwork, so the clipped fill is left out there. - let dl = DisplayList { links: Vec::new(), + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![ in_group(item(Path::rect(1.0, 1.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)), 0), @@ -699,7 +699,7 @@ fn binning_shapes_the_scene_into_tiles() { #[test] fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { - let deep = |n: usize| DisplayList { links: Vec::new(), + let deep = |n: usize| DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)], clip_parents: Vec::new(), @@ -712,7 +712,7 @@ fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() { let masks = |n: usize| { let mut items: Vec = (0..n).map(|c| mask(Path::rect(0.0, 0.0, 8.0, 8.0), c as u32)).collect(); items.push(clipped(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)); - DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } + DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() } }; assert!(bin(&masks(bn::MAX_CLIP_DEPTH)).is_ok()); assert_eq!(bin(&masks(bn::MAX_CLIP_DEPTH + 1)).err(), Some(NeedsFull::Clips)); @@ -883,7 +883,7 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() { .collect(); let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1); it.color = ColorTransform::alpha(0.5); - DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups } + DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups } }; let deep = nested(MAX_FILTER_DEPTH + 1); assert!(matches!(g.render(&deep, &view(12, 12, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Filters)))); @@ -994,7 +994,7 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> { // Inside a mask and a faded group, over a gradient. let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(80.0, 60.0), stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))]))); 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 { links: Vec::new(), clip_modes: Vec::new(), 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)] }; + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), 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); @@ -1087,7 +1087,7 @@ fn gpu_matches_the_oracle_on_every_filter() { for (name, f) in filters_to_test() { let mut items = vec![backdrop.clone()]; items.extend(symbol_items(0)); - let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] }; // At 1:1; zoomed, so sizes scale; and panned so the layer reaches past the surface. for v in [view(70, 60, Some(Rgba::WHITE)), View { transform: Affine::scale(1.5, 1.5), width: 105, height: 90, background: None }, View { transform: Affine::translate(-20.0, -15.0), width: 40, height: 33, background: Some(Rgba::WHITE) }] { let d = assert_parity(g, name, &dl, &v); @@ -1112,7 +1112,7 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { (grp.alpha, grp.blend) = (0.7, BlendMode::Multiply); let mut items = vec![bg.clone()]; items.extend(symbol_items(0)); - scenes.push(("filters in a row, faded and multiplied", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] })); + scenes.push(("filters in a row, faded and multiplied", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] })); // A filtered symbol inside a filtered symbol, inside a faded one. let mut outer = filtered_group(vec![shadow.clone()]); outer.parent = Some(0); @@ -1120,22 +1120,22 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() { inner.parent = Some(1); let mut items = vec![bg.clone(), in_group(item(Path::rect(4.0, 40.0, 30.0, 16.0), Paint::Solid(Rgba::new(0.9, 0.6, 0.0, 1.0))), 1)]; items.extend(symbol_items(2)); - scenes.push(("nested filtered symbols", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); + scenes.push(("nested filtered symbols", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] })); // Masked from outside (after filtering) and inside (before). let mut clipped_grp = filtered_group(vec![glow.clone()]); clipped_grp.clip = Some(0); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(mask(Path::ellipse(36.0, 30.0, 24.0, 20.0), 0)); - scenes.push(("masked after filtering", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] })); + scenes.push(("masked after filtering", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] })); let mut items = vec![bg.clone()]; items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0))); items.push(in_group(mask(Path::rect(20.0, 10.0, 16.0, 40.0), 0), 0)); - scenes.push(("masked inside the symbol", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); + scenes.push(("masked inside the symbol", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] })); // A bitmap inside a filtered symbol. let px = pixels(9, 7, 4); let items = vec![bg.clone(), in_group(bitmap_item(Path::ellipse(40.0, 32.0, 26.0, 20.0), &px, true, Affine::scale(4.0, 4.0)), 0)]; - scenes.push(("filtered bitmap", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); + scenes.push(("filtered bitmap", DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] })); for (name, dl) in scenes { for v in [view(80, 64, white), View { transform: Affine::translate(-37.0, -5.0).mul(&Affine::scale(1.3, 1.3)), width: 48, height: 48, background: white }] { let d = assert_parity(g, name, &dl, &v); diff --git a/crates/render/src/html_tests.rs b/crates/render/src/html_tests.rs index bb618965..0490fb91 100644 --- a/crates/render/src/html_tests.rs +++ b/crates/render/src/html_tests.rs @@ -1477,7 +1477,7 @@ fn filters_and_soft_masks_compose_in_the_page_as_in_the_renderer() { // A mask over the symbol: its artwork drawn as it looks on its own, read as the // page reads it (canvas.js `maskEnd`). let reveal: Option> = (!inside).then(|| { - let art = anicraft_doc::DisplayList { links: Vec::new(), items: dl.items.iter().filter(|i| i.masks.is_some()).map(|i| anicraft_doc::DisplayItem { masks: None, clip: None, group: None, ..i.clone() }).collect(), clip_parents: Vec::new(), clip_modes: Vec::new(), groups: Vec::new() }; + let art = anicraft_doc::DisplayList { left_out: false, links: Vec::new(), items: dl.items.iter().filter(|i| i.masks.is_some()).map(|i| anicraft_doc::DisplayItem { masks: None, clip: None, group: None, ..i.clone() }).collect(), clip_parents: Vec::new(), clip_modes: Vec::new(), groups: Vec::new() }; let (mp, _) = crate::render(&art, &crate::View { background: None, ..view }).unwrap(); mp.data.iter().map(|p| mode.reveal(*p)).collect() }); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4de35a98..6e7b0d34 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -532,6 +532,7 @@ fn filter_setup(dl: &DisplayList, run: &FilteredRun, view: &View, surface: IRect clip_modes: dl.clip_modes.clone(), groups, links: Vec::new(), + left_out: dl.left_out, }; let sub_view = View { transform: Affine::translate(-b.x0 as f32, -b.y0 as f32).mul(&view.transform), width: b.width() as u32, height: b.height() as u32, background: None }; let filters = group.filters.iter().map(|f| filters::resolve(f, scale)).collect(); @@ -983,7 +984,7 @@ mod tests { } fn list(items: Vec) -> DisplayList { - DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() } + DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() } } /// A 40 × 40 opaque blue square masked by `art` in `mode`, on transparent. @@ -1078,7 +1079,7 @@ mod tests { let mut mask = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.2))); mask.masks = Some(0); mask.stroke = Some(anicraft_doc::Stroke::new(Rgba::BLACK, 8.0)); - let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() }; + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() }; let (pm, _) = render(&dl, &view(40, 40)).unwrap(); // Pixel for pixel, the same as the circle drawn in the square's colour. let circle = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); @@ -1146,7 +1147,7 @@ mod tests { let mut blue = item(Path::rect(4.0, 0.0, 8.0, 4.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0))); red.group = Some(0); blue.group = Some(0); - let grouped = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] }; + let grouped = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] }; let (pm, _) = render(&grouped, &white).unwrap(); let near = |p: Premul, q: [f32; 4]| p.iter().zip(q).all(|(a, b)| (a - b).abs() < 1e-4); // In the overlap only the top square shows through: half blue, half white, no red. @@ -1162,7 +1163,7 @@ mod tests { // Nested groups multiply; a group with a bad parent link is a top-level group. let mut inner = item(Path::rect(0.0, 0.0, 12.0, 4.0), Paint::Solid(Rgba::BLACK)); inner.group = Some(1); - let nested = DisplayList { links: Vec::new(), + let nested = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![inner], clip_parents: vec![], @@ -1177,7 +1178,7 @@ mod tests { // Spanning several render bands changes nothing. let mut tall = item(Path::rect(0.0, 0.0, 4.0, 100.0), Paint::Solid(Rgba::BLACK)); tall.group = Some(0); - let (t, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap(); + let (t, _) = render(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap(); assert!((0..100).all(|y| near(t.pixel(1, y).unwrap(), [0.75, 0.75, 0.75, 1.0]))); } @@ -1207,7 +1208,7 @@ mod tests { inner.masks = Some(1); let mut lost = clipped.clone(); lost.clip = Some(2); - let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() }; + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() }; let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap(); let (_, rst) = render(&dl, &view(16, 16)).unwrap(); assert_eq!((st.drawn, st.edges, st.pixels_touched), (rst.drawn, rst.edges, rst.pixels_touched)); @@ -1220,7 +1221,7 @@ mod tests { let mut grouped = sq.clone(); grouped.group = Some(1); let g = |parent, alpha| anicraft_doc::Group { parent, alpha, blend: BlendMode::Multiply, filters: Default::default(), clip: None }; - let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] }; + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] }; let (scene, _) = prepare_scene(&dl, &view(16, 16)).unwrap(); assert!(scene.fills.iter().all(|f| f.group == Some(1))); assert_eq!((scene.groups[1].chain.clone(), scene.groups[0].alpha, scene.groups[1].alpha, scene.groups[1].blend), (vec![0, 1], 1.0, 1.0, BlendMode::Multiply)); @@ -1262,7 +1263,7 @@ mod tests { let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)); clipped.clip = Some(0); let free = item(Path::rect(0.0, 0.0, 2.0, 2.0), Paint::Solid(Rgba::BLACK)); - let (pm, st) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap(); + let (pm, st) = render(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap(); assert_eq!(st.drawn, 1); assert_eq!(pm, render(&list(vec![free]), &view(8, 8)).unwrap().0); } @@ -1277,11 +1278,11 @@ mod tests { inner.masks = Some(1); let items = vec![fill, outer, inner]; // Clip 1 lies inside clip 0: a 32 × 32 square across two render bands survives. - let (pm, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap(); + let (pm, _) = render(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap(); assert!((alpha_sum(&pm) - 32.0 * 32.0).abs() < 1e-2, "{}", alpha_sum(&pm)); // A parent link pointing forward (malformed) or out of range masks everything out. for parents in [vec![Some(1), Some(1)], vec![None, Some(9)]] { - let (pm, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap(); + let (pm, _) = render(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap(); assert_eq!(alpha_sum(&pm), 0.0); } } @@ -1503,7 +1504,7 @@ mod tests { let bg = item(Path::rect(0.0, 0.0, 20.0, 10.0), Paint::Solid(Rgba::new(0.5, 0.5, 1.0, 1.0))); let mut top = item(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0))); top.group = Some(0); - let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] }; + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] }; let (pm, _) = render(&dl, &View { background: Some(Rgba::WHITE), ..view(20, 10) }).unwrap(); let p = pm.pixel(5, 5).unwrap(); assert!((p[0] - 0.5).abs() < 1e-3 && p[1].abs() < 1e-3 && p[2].abs() < 1e-3, "red × lavender: {p:?}"); diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index 5b6c9c6e..453fa089 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -703,7 +703,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa items.push(DisplayItem { path: std::sync::Arc::new(outline), transform: Affine::IDENTITY, fill: Some(anicraft_doc::Paint::Solid(st.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, image: None, ..it.clone() }); } } - std::borrow::Cow::Owned(DisplayList { links: Vec::new(), clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() }) + std::borrow::Cow::Owned(DisplayList { links: Vec::new(), clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone(), left_out: dl.left_out }) } #[cfg(test)] @@ -974,7 +974,7 @@ mod tests { smooth: true, warp: None, }; - let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![item], clip_parents: Vec::new(), groups: Vec::new() }; + let dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![item], clip_parents: Vec::new(), groups: Vec::new() }; let view = crate::View { transform: Affine::IDENTITY, width: 400, height: 300, background: Some(anicraft_doc::Rgba::WHITE) }; let (pm, _) = crate::render(&dl, &view).unwrap(); pm.data.iter().map(|p| 1.0 - p[0]).collect() diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index d796a1dc..029488a5 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -601,7 +601,7 @@ mod tests { *spread = anicraft_doc::Spread::Reflect; } let items = vec![item(Path::rect(0.0, 0.0, 60.0, 60.0), Some(rad)), item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(lin))]; - let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![], groups: Vec::new() }, &stage()); assert!(svg.contains("spreadMethod=\"repeat\"") && svg.contains("spreadMethod=\"reflect\""), "{svg}"); assert!(svg.contains("color-interpolation=\"linearRGB\""), "{svg}"); assert!(svg.contains("fx=\"40\" fy=\"30\""), "focal point half way along the ring's x axis: {svg}"); @@ -630,7 +630,7 @@ mod tests { a.stroke = Some(Stroke::new(Rgba::BLACK, 3.0)); a.color = ColorTransform::alpha(0.5); a.fill_rule = FillRule::EvenOdd; - let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); assert!(svg.starts_with("")); assert!(svg.contains(""), "background"); assert!(svg.contains("d=\"M5 7L25 7L25 27L5 27Z\" fill=\"#ff0000\" fill-opacity=\"0.5\" fill-rule=\"evenodd\""), "{svg}"); @@ -645,7 +645,7 @@ mod tests { let mut a = item(Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), None); a.transform = Affine::scale(2.0, 2.0); a.stroke = Some(st); - to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()) + to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()) }; // The default style is written as before: round, no dashes. let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0)); @@ -665,7 +665,7 @@ mod tests { fn variable_width_strokes_are_written_as_filled_outlines() { let mut a = item(Path::line(Vec2::new(0.0, 10.0), Vec2::new(80.0, 10.0)), Some(Paint::Solid(Rgba::hex(0xff0000)))); a.stroke = Some(Stroke::new(Rgba::hex(0x0000ff), 6.0).with_profile(anicraft_doc::ProfilePreset::TaperBoth.profile())); - let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage()); assert!(!svg.contains("stroke-width"), "no SVG stroke: {svg}"); assert!(svg.contains("fill=\"#0000ff\""), "the outline is filled in the stroke colour"); assert!(svg.contains("fill=\"#ff0000\""), "the shape's own fill stays"); @@ -682,7 +682,7 @@ mod tests { outer.masks = Some(0); let mut inner = item(Path::ellipse(25.0, 25.0, 10.0, 10.0), Some(Paint::Solid(Rgba::BLACK))); inner.masks = Some(1); - let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage()); assert!(svg.contains("gradientTransform=\"matrix(1 0 0 1 20 0)\" x1=\"0\" y1=\"0\" x2=\"10\" y2=\"0\""), "{svg}"); assert!(svg.contains("")); assert!(svg.contains(""), "nested clip"); @@ -735,7 +735,7 @@ mod tests { let clear = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::TRANSPARENT))); let mut lost = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::BLACK))); lost.clip = Some(7); - let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage()); + let svg = to_svg(&DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage()); assert_eq!(svg.matches(""), "a malformed clip clips everything"); assert!(!svg.contains("NaN") && !svg.contains("inf")); @@ -769,7 +769,7 @@ mod group_tests { smooth: true, warp: None, }; - let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), 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 dl = DisplayList { left_out: false, links: Vec::new(), clip_modes: Vec::new(), 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 }); assert!(svg.contains("") && svg.contains(""), "{svg}"); assert_eq!(svg.matches("").count(), "balanced"); From c7d2fdb6d510dca016fe526974d60bf2b3290d68 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:32:05 -0700 Subject: [PATCH 20/23] feat(stage): the status bar says when the frame shown has artwork left out (M8) --- src/app.rs | 4 ++++ src/rulers_tests.rs | 28 ++++++++++++++++++++++++++++ src/stage.rs | 16 ++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/src/app.rs b/src/app.rs index 687524a8..142e441e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -376,6 +376,9 @@ pub struct App { /// The tool in hand last frame (picking the Camera tool adds a camera). pub last_tool: Tool, pub status: Option, + /// The frame shown was not all drawn when the stage last looked (ADR 0128): the status bar + /// has said so, and says it again only after a frame that was whole. + pub left_out_said: bool, pub prompt: Option, /// The Convert to Symbol dialog, and what it chose last (ADR 0053). pub convert: Option, @@ -802,6 +805,7 @@ impl App { camera_preview: false, last_tool: Tool::Select, status: None, + left_out_said: false, prompt: None, convert: None, layer_props: None, diff --git a/src/rulers_tests.rs b/src/rulers_tests.rs index 154eeaf4..1b2911e0 100644 --- a/src/rulers_tests.rs +++ b/src/rulers_tests.rs @@ -24,6 +24,34 @@ fn app() -> (egui::Context, App) { (ctx, app) } +/// ADR 0128: a frame too large to draw in full is drawn in part, and the status bar says so +/// once, as an error that stays; going to a frame that is whole and back says it again. +#[test] +fn a_frame_with_artwork_left_out_says_so_in_the_status_bar() { + let mut large = sample::doubling(31); + // Thousands of empty layers in every symbol: the allowance goes on looking at them, so + // the frame is cut short with little to draw. + for sym in &mut large.library { + let tl = &mut std::sync::Arc::make_mut(sym).timeline; + for i in 0..5_000 { + tl.layers.push(std::sync::Arc::new(anicraft_engine::doc::Layer::new(anicraft_engine::doc::LayerId(9_000 + i), "empty"))); + } + } + let ctx = egui::Context::default(); + let mut big = App::with_context(&ctx, Session::new(large), Some(std::path::PathBuf::from("unused.png"))); + frame(&ctx, &mut big, vec![]); + let said = big.status.as_ref().map(|s| (s.text.clone(), s.error)); + assert!(said.as_ref().is_some_and(|(text, error)| *error && text.contains("left out")), "{said:?}"); + // Said once: a later message is not written over while the frame stays as it is. + big.status_ok("something else"); + frame(&ctx, &mut big, vec![]); + assert_eq!(big.status.as_ref().map(|s| s.text.as_str()), Some("something else")); + // An ordinary document says nothing. + let (ctx, mut app) = app(); + frame(&ctx, &mut app, vec![]); + assert!(!app.status.as_ref().is_some_and(|s| s.text.contains("left out"))); +} + fn press(p: Pos2, pressed: bool) -> Event { Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } } diff --git a/src/stage.rs b/src/stage.rs index 704c8ca8..fb36b654 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -230,6 +230,21 @@ fn to_v(p: Pos2) -> Vec2 { Vec2::new(p.x, p.y) } +/// Says in the status bar, once each time it starts, that the frame shown is not all there: its +/// artwork took more than a frame's allowance of work, so the rest was left out (ADR 0128). A +/// picture with parts missing and nothing said would read as lost work. Not asked while +/// playing, where it would cost an evaluation every frame; the frame playback stops on is. +fn note_left_out(app: &mut App) { + if app.playing { + return; + } + let cut = app.s.display_list().left_out; + if cut && !app.left_out_said { + app.status_err(tr!("This frame holds more artwork than AniCraft draws at once, so some of it is left out. Nothing is lost: look for symbols nested many times over.")); + } + app.left_out_said = cut; +} + pub fn show(app: &mut App, ui: &mut egui::Ui) { // View › Rulers along the top and the left (ADR 0076); the stage view in what is left. let (canvas, bars) = crate::rulers::layout(app, ui.max_rect()); @@ -237,6 +252,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { crate::camera_tool::on_tool_change(app); crate::shape_envelope::settle(app); crate::camera_tool::tick(app, ui.ctx(), now); + note_left_out(app); let canvas_was = std::mem::replace(&mut app.stage_cache.canvas, canvas); let laid_out = std::mem::replace(&mut app.stage_cache.laid_out, true); // While a colour picker popup is open the stage is its eyedropper (ADR 0109): a click From 80508758dd9c51b849e1a4b29951acedf15184a8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:43:52 -0700 Subject: [PATCH 21/23] fix(doc): on a guided shape tween every raw outline rides with the fill it edges (M5) --- crates/doc/src/eval.rs | 20 +++++++++++++++++--- crates/engine/src/tests.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index d23bb53f..56e8e6a1 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -381,7 +381,10 @@ pub(crate) fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<& let morph = tween.kind == TweenKind::Shape; let path = guide.map(|g| (g, tween.orient)); let runs = |els: &[Arc]| els.iter().filter(|e| raw_stroke(e).is_some()).count(); - if morph && runs(&kf.elements) != runs(&next.elements) { + // Along a motion guide the runs are joined even when both keys have as many: a guide places + // each element by its own origin, so runs left to pair one by one would each take their own + // way along it and leave the fill they edge. + if morph && (runs(&kf.elements) != runs(&next.elements) || (path.is_some() && runs(&kf.elements) > 0)) { return Some((kf.start, Cow::Owned(morph_raw_strokes(kf, next, t, path)))); } let pairs = if morph && !kf.hints.is_empty() { crate::hints::hint_pairs(kf, next) } else { Vec::new() }; @@ -439,9 +442,20 @@ fn raw_stroke(e: &Element) -> Option<&Stroke> { } /// The raw fill of `els` that `path` (in `xf` space) edges: the one whose edge is within two -/// snaps of a point on `path`, or that contains it, or the one whose origin is nearest `xf`'s. +/// snaps of the middle of `path`, or that contains it, or the one whose origin is nearest `xf`'s. +/// The middle, not an end: a run ends at a corner, where the runs of the fill next door end +/// too, so an end says nothing about whose edge the run is. An edge two fills share (their +/// outlines joined there) goes with the lower of the two, the first in the stack. fn fill_of(els: &[Arc], path: &Path, xf: &Affine) -> Option { - if let Some(p) = path.flatten(xf, 0.25).into_iter().next().and_then(|pl| pl.points.get(pl.points.len() / 2).copied()) + let middle = |pl: anicraft_geom::Polyline| { + let k = pl.points.len() / 2; + match (pl.points.get(k.wrapping_sub(1)), pl.points.get(k)) { + (Some(a), Some(b)) => Some(a.lerp(*b, 0.5)), + (None, b) => b.copied(), + (a, None) => a.copied(), + } + }; + if let Some(p) = path.flatten(xf, 0.25).into_iter().next().and_then(middle) && let Some((k, _)) = els.iter().enumerate().find(|(_, e)| { matches!(&e.kind, ElementKind::Shape(s) if s.merge && s.fill.is_some() && (s.path.contains(p, &e.transform, s.fill_rule) || s.path.distance_to_edge(p, &e.transform) <= 2.0 * anicraft_geom::planar::SNAP)) }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e967276a..0d5d6c4a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2840,3 +2840,36 @@ fn exports_of_a_frame_too_large_to_draw_say_artwork_was_left_out() { } std::fs::remove_dir_all(&dir).unwrap(); } + +/// P-011: two raw fills side by side, their outlines joined along the edge they share, on a +/// shape tween that follows a motion guide. A guide places every element by its own origin, so +/// the stroke runs used to leave the fills and cross them. Each run rides with the fill it +/// edges, the same number of runs on both keys or not; the shared edge goes with the lower fill. +#[test] +fn guided_shape_tweens_keep_each_raw_outline_on_its_fill() { + let mut s = Session::default(); + for (x, fill) in [(100, "#e63946"), (180, "#457b9d")] { + run(&mut s, "draw.rect", json!({"x": x, "y": 240, "w": 80, "h": 80, "fill": fill, "stroke": "#000000", "stroke_width": 4, "object": false})); + } + let art = s.active_layer().unwrap().id; + run(&mut s, "timeline.goto", json!({"frame": 20})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "element.translate", json!({"dx": 440, "dy": 0})); + run(&mut s, "timeline.goto", json!({"frame": 0})); + run(&mut s, "timeline.create_shape_tween", json!({})); + run(&mut s, "layer.add_motion_guide", json!({"layer": art.0})); + for (a, b) in [((140, 280), (400, 80)), ((400, 80), (660, 280))] { + run(&mut s, "draw.line", json!({"x0": a.0, "y0": a.1, "x1": b.0, "y1": b.1, "object": false})); + } + let length = |segs: &[(Vec2, Vec2)]| segs.iter().map(|(a, b)| a.distance(*b)).sum::(); + let on_art = |list: &anicraft_doc::DisplayList| (outline_segments(list.items.iter().filter(|i| i.layer == art && i.fill.is_some())), outline_segments(list.items.iter().filter(|i| i.layer == art && i.stroke.is_some()))); + let drawn = length(&on_art(&anicraft_doc::evaluate_scene(&s.doc, s.scene, 0)).1); + assert!(drawn > 500.0, "seven sides of 80: {drawn}"); + for frame in [3, 5, 10, 15, 18] { + let (fill, stroke) = on_art(&anicraft_doc::evaluate_scene(&s.doc, s.scene, frame)); + let stray = stroke.iter().flat_map(|&(a, b)| (0..=8).map(move |k| a.lerp(b, k as f32 / 8.0))).map(|p| distance_to(&fill, p)).fold(0.0, f32::max); + assert!(stray < 0.5, "frame {frame}: a stroke is {stray} off the fills' outlines"); + assert!((length(&stroke) - drawn).abs() < 1.0, "frame {frame}: every run is still drawn: {} of {drawn}", length(&stroke)); + } +} From d6bb4dfd6064a24fa2bfa5aa5dba0f8a595cd215 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:51:26 -0700 Subject: [PATCH 22/23] docs(adr): ADR 0128, the work allowance and frames that say what they left out; roadmap, parity, changelog and credits for P-002, P-011 and P-012 (M8) --- AUTHORS.md | 9 +- CHANGELOG.md | 30 +++++ ...-and-frames-that-say-what-they-left-out.md | 119 ++++++++++++++++++ docs/mcp.md | 9 ++ docs/parity.md | 2 +- docs/roadmap.md | 19 ++- 6 files changed, 172 insertions(+), 16 deletions(-) create mode 100644 docs/adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md diff --git a/AUTHORS.md b/AUTHORS.md index c14cf24f..844f3861 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -9,10 +9,10 @@ People who have contributed to AniCraft. The repository starts from one initial * mypenc: skew in Free Transform (#176). * Davit Matchakhelidze (devius): Georgian in the interface, with Noto Sans Georgian (#160). * Mex (MMexicann): SVG path data, `Math.round` and `Math.min`/`max` signed zeros, affine inverses, documentation; preset files with a byte-order mark, oversized indices, CLI numbers, guide anchors and the Windows build scripts. -* NetterSilver (Silvertree2010): shape tweens that morph a raw shape's line with its fill, dash patterns, colour, easing and script-string parsing; an XFL nested-group regression test; eight-point ovals, smooth anchors that stay smooth when a segment is bent, and non-finite numbers in transforms, paths, scripts and saved files. +* NetterSilver (Silvertree2010): shape tweens that morph a raw shape's line with its fill, dash patterns, colour, easing and script-string parsing; an XFL nested-group regression test; eight-point ovals, smooth anchors that stay smooth when a segment is bent, and non-finite numbers in transforms, paths, scripts and saved files; the length of very large vectors, a hex colour form that keeps alpha, and a test for SVG path numbers past `f32` (#142, #233, #130). * Mex (MMexicann): SVG path data, `Math.round` and `Math.min`/`max` signed zeros, affine inverses, documentation. * NetterSilver (Silvertree2010): shape tweens that morph a raw shape's line with its fill, dash patterns, colour, easing and script-string parsing; an XFL nested-group regression test; Trace Bitmap and Convert to Bitmap (#489). -* jayzed80: flipped scales in Properties, CLI subcommand help and frame numbering; copy, cut and paste keys on the stage. +* jayzed80: flipped scales in Properties, CLI subcommand help and frame numbering; copy, cut and paste keys on the stage; shape-tween outlines at junctions, with dashes and width profiles, and along a motion guide (#238). * Efe Şahinbaş (MacallanTheRoot): the MCP render caption. * nocturney: localisation tests (Hebrew plurals, the product name). * Vincent Agerbech (va-moviestarplanet): XFL group placement. @@ -24,6 +24,7 @@ People who have contributed to AniCraft. The repository starts from one initial * Oskar Raszkiewicz (oskarraszkiewicz): the macOS menu row. * Wilder Ccasa (Call4han): fitting the stage by double-clicking the Hand tool (#457). * Dylan M. Taylor (dylanmtaylor): no caller-chosen ffmpeg over serve and MCP, bounded request lines, safer XFL folder reads. -* Agapenor (Agapenordev): XFL folder paths with backslashes, the frame limit on loaded documents, the report behind the evaluation allowance. +* Agapenor (Agapenordev): XFL folder paths with backslashes, the frame limit on loaded documents, the report behind the evaluation allowance and what it counts as work (#13). * rcoenen: Animate's shape hints (`morphHintsList`), default text line spacing and default dash gap, from files Animate saved. -* Hagai Baram (hrb9): the Hebrew fallback face, `iw` read as Hebrew, and right-to-left language detection (#486). +* Hagai Baram (hrb9): the Hebrew fallback face, `iw` read as Hebrew, and right-to-left language detection, private-use tags included (#486). +* FredApps: a test that linked artwork survives SVG export and re-import (#500). diff --git a/CHANGELOG.md b/CHANGELOG.md index b416e0e2..9f3c7437 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,36 @@ ## Unreleased +* **Documents too large to draw, shape-tween outlines on a guide, and small fixes from outside** + (M8, backlog P-002, P-011 and P-012; ADR 0128). + * **Security: no nesting of symbols hangs AniCraft.** The allowance of work one frame has + (a million elements) now also counts the layers looked at, the size of each outline and + how far into a long library a symbol is, so a file can multiply none of them by nesting. + **Test Movie** has an allowance for each step: it used to look at every element of up to + 10,000 instances after every change, and give every button a whole frame's allowance at + every move of the pointer (ideas from Agapenor's #13). + * **A frame with artwork left out says so.** The status bar tells you once ("This frame + holds more artwork than AniCraft draws at once…"), Test Movie's Output panel says why a + step stopped, and the commands that write frames (PNG, SVG, sequences, sprite sheet, GIF, + animated PNG and WebP, video) add `"left_out": true` and a `"warning"` to their result + instead of passing a partial picture off as the whole one. `anicraft-cli info` and the MCP + `anicraft_render` caption say it too. + * **Shape tweens along a motion guide keep their outlines** (jayzed80, #238). A raw shape's + line pieces used to follow the guide one by one and cross the fill. Each piece now rides + with the fill it edges, also when both keyframes have as many pieces; an edge two fills + share goes with the lower fill. Outlines are no longer joined through a point where three + or more lines meet, dashed and variable-width outlines keep their pieces, and a piece + selected on a keyframe stays selected through the tween. + * **Colours:** the Eyedropper's result names the colour it picked with its opacity + (`#rrggbbaa`); `Rgba::to_hex_alpha` is the hex form that reads back as the same colour, + and `to_hex` stays six digits for the exporters (NetterSilver, #233). + * **Never crash:** the length of a vector with components past 1.8e19 is no longer infinite, + so its direction is no longer lost (NetterSilver, #142; taken only out of range, so drawing + costs the same); a private-use language tag such as `x-Arab` is not read as right-to-left + (Hagai Baram, #486). + * **Tests:** SVG path numbers past `f32` are refused (NetterSilver, #130); linked artwork + survives SVG export and re-import with its link sanitised (FredApps, #500). + * **Reliability fixes from the November principal-engineer review** (M8, `docs/reviews/2026-11-principal-review.md`). * **Save is flushed to the disk** before the new file replaces the old one, as the diff --git a/docs/adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md b/docs/adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md new file mode 100644 index 00000000..14265d37 --- /dev/null +++ b/docs/adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md @@ -0,0 +1,119 @@ +# ADR 0128: One allowance of work for a frame and for a player step, and frames that say what they left out + +* Status: accepted (2026-11-21) +* Relates to: `docs/roadmap.md` (P-002), ADR 0024 (the player), ADR 0125 (the backlog), outside + pull request #13, AGENTS.md rule 15 + +## Context + +A symbol may hold instances of other symbols, 32 deep (`MAX_SYMBOL_DEPTH`). That cap stops a +library that refers to itself in a cycle. It does not stop one that doubles: 32 symbols, each +holding two instances of the next, are 2^32 shapes. The editor can't build that by accident, but +a damaged or hostile `.anicraft` or `.fla` can hold it, and "never crash" covers such files. + +Pull request #497 gave one evaluation, and one bounds query, an allowance of 1,000,000 element +visits (`MAX_EVAL_ELEMENTS`). Outside pull request #13 had proposed a budget first and went +further in what it counted. Looking at `main` after #497, four things were still open. + +1. **Work that is not an element visit.** A timeline's layers are looked at on every visit of + its symbol and cost nothing, so a symbol with thousands of empty layers multiplied by + nesting. An outline of a million commands is measured once per bounds query of each instance. + A symbol is found by walking the library, so a library of a hundred thousand symbols + multiplied every lookup. +2. **The player's step.** Test Movie rebuilds the instance tree after every change in a step + (up to 10,000 actions) and evaluates every interactive instance for every pointer event (up + to 256), each with a whole frame's allowance of its own. The tree was capped at 10,000 + instances but looked at every plain element of every one of them for nothing. +3. **Nobody was told.** A frame cut short drew in part and looked like lost artwork. An export + wrote the partial picture and reported success. +4. **Outside PR #13** conflicted with all of it and needed a decision. + +## Decision + +### 1. One unit of work, and what costs more than one + +The allowance stays 1,000,000 units for one evaluation or one bounds query. A unit is one +element or one layer looked at. Two things cost more: + +* a shape costs one more unit for every 256 commands of its outline + (`PATH_COMMANDS_PER_UNIT`), where it is drawn and where it is measured; +* finding a symbol costs one more unit for every 1,024 library entries passed on the way + (`LIBRARY_ENTRIES_PER_UNIT`). + +An ordinary document pays nothing extra: outlines are tens of commands and libraries hundreds of +symbols, and the heaviest benchmark scene (50,000 shapes) uses a twentieth of the allowance. +Once the allowance is spent nothing more is taken from it, so the cut is clean: what was reached +is drawn, the rest is not. + +#13 charged one unit for every library entry passed. That bounds the same hostile case, but an +honest document with 2,000 symbols and 5,000 instances would spend ten times the allowance on +lookups alone and lose artwork. Dividing by 1,024 keeps the bound (a lookup in a library of +100,000 symbols costs about 100 units, so at most 10,000 of them happen) and leaves honest +documents whole. A map from id to symbol would remove the cost altogether; it is a larger change +to the document model and is not needed for the bound. + +### 2. A player step has an allowance of its own + +`MAX_WORK_PER_STEP` is four frames' worth (4,000,000 units). Every rebuild of the instance +tree and every hit test in one `step`, `start` or `input` takes from it, in the same units: the +tree pays for each layer and each element it looks at, and hit tests evaluate from the step's +allowance instead of a fresh one each. When it is spent the step stops as it does when its +action or fuel budget is spent, with one line in the Output panel: + +> Stopped this frame early: the movie holds more than one frame may look at, so some instances +> and buttons were left out (symbols nested in themselves?) + +The queries the shell makes between steps (`tree`, `hit`, `field_at`, `hit_overlay`) each have +one frame's allowance for everything they do; `hit_overlay` used to give every button its own. + +Four frames, not one, because an honest step does look at the movie several times: after a +`gotoAndPlay`, after a button changes state, for a pointer that moved. A movie that needs more +than four full passes in one step is one no machine plays in time. + +### 3. A list that was cut short says so, and so does whoever shows or writes it + +`DisplayList::left_out` is set by every evaluation whose allowance ran out, and kept when lists +are appended (onion skins, the hit-area overlay). It is a plain field of the result: +`evaluate` stays a pure function of the document and the frame. + +* **The stage** says once, in the status bar, as an error that stays: "This frame holds more + artwork than AniCraft draws at once, so some of it is left out. Nothing is lost: look for + symbols nested many times over." It says it again only after a frame that was whole. The + check is skipped while playing, where it would cost an evaluation every frame; the frame + playback stops on is checked. +* **Commands** that write frames still write them, and add `"left_out": true` and a + `"warning"` to their result: `file.export_png`, `file.export_svg`, + `file.export_png_sequence`, `file.export_svg_sequence`, `file.export_sprite_sheet`, + `file.export_gif`, `file.export_apng`, `file.export_webp`, `file.export_video`. A result + without the keys is a whole frame, so nothing that reads results today changes. + `anicraft-cli info` reports it for the frame shown, and the MCP `render` tool says it in the + picture's caption. +* An export is not refused. A partial picture with a warning is more use to someone repairing a + damaged file than no picture, and the warning is in the result an agent or a script reads. + +### 4. What was taken from #13, and what was not + +Taken, as ideas, into the allowance `main` already had: counting layers, symbol lookups and +outline commands, and making exhaustion something a caller can see. Its author is credited in +`AUTHORS.md` and the changelog. + +Not taken: its commits (they rewrite the same functions #497 rewrote, from a base two hundred +commits old); the per-entry lookup charge (above); a public budget type that callers pass in +(no caller outside `anicraft-doc` needs to share one, and the player does it inside the crate); +charging both keyframes of a tween before interpolating (the tweened elements are charged when +they are visited, outline included, which bounds how often the work repeats); and refusing +**Paste** at a point when the clipboard's bounds were cut short (the paste still lands, offset by +the bounds of what was reached, which is the same partial answer every other bounds query gives). + +## Consequences + +* A hostile document costs a bounded amount everywhere it is looked at: about 0.1 s for a frame + or a bounds query and under 0.3 s for a whole player step in a debug build on the development + machine (the tests that build such documents run in 0.07 s to 0.31 s). +* Ordinary documents are unchanged. Evaluating the 50,000-shape stress scene takes 11.7 ms a + frame with the change and 11.9 ms without (release build, best of three; the machine's noise + is larger than the difference). +* `DisplayList` has one more public field. Code that builds one field by field names it. +* Not yet: the same note from the Lottie and HTML exporters and from exporter plug-ins (they + walk the document their own way), a notice inside the Test Movie window when the picture + (and not the step) is cut short, and a count of how much was left out. diff --git a/docs/mcp.md b/docs/mcp.md index c0ddb6fe..256febe9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -117,6 +117,15 @@ saved command's file) or `{"steps": [{"cmd", "params"}]}` runs the steps as one unlike `anicraft_run_script` a failing step leaves the document as it was. `macro.history` and `macro.save` turn the session's undo steps into a saved command. +## A frame with artwork left out + +A document can hold more than AniCraft draws in one frame (symbols nested many times over, as +in a damaged file): the frame is then drawn in part +([ADR 0128](adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md)). The commands +that write frames still write it, and their result has `"left_out": true` and a `"warning"`; +`anicraft_render` says so in the picture's caption, and the document's state has the two keys +for the frame shown. A result without them is a whole frame. + ## Safety * Everything runs through the engine's commands, so params are checked and every edit can be diff --git a/docs/parity.md b/docs/parity.md index 3c898ae4..4580d7df 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -276,7 +276,7 @@ not this table, says what matters most. | Motion presets: save a tween, apply it elsewhere | **missing** | P-041. | | Copy and paste motion; paste properties | **missing** | P-041. | | 3D properties in a motion tween | **missing** | With the 3D tools (P-044). | -| Shape tweens | **done** | Open: strokes that should follow their fills (outside PR [#238](https://github.com/storytold/anicraft/issues/238), P-011). | +| Shape tweens | **done** | A raw shape's outline morphs with its fill, whatever the number of sides, and rides a motion guide with the fill it edges (an edge two fills share goes with the lower one). | | Shape hints | **done** | [ADR 0023](adr/0023-shape-hints.md). [#82](https://github.com/storytold/anicraft/issues/82) can close. Missing: hints inside a symbol edited in place. | | Shape tween blend (distributive, angular) | **partial** | One blend; no choice?. | | Keep area while tweening | **ours** | [ADR 0115](adr/0115-pen-parity-and-keep-area-tweens.md). | diff --git a/docs/roadmap.md b/docs/roadmap.md index 427deb4a..d4ae6fad 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -44,7 +44,6 @@ the changelog. | Id | Goal | Parity area | Size | Needs | Lane | |---|---|---|---|---|---| | P-001 | AniCraft starts on every supported machine: the launch failures on Windows and Linux graphics drivers ([#164](https://github.com/storytold/anicraft/issues/164), [#158](https://github.com/storytold/anicraft/issues/158), [#207](https://github.com/storytold/anicraft/issues/207), [#268](https://github.com/storytold/anicraft/issues/268), [#421](https://github.com/storytold/anicraft/issues/421), [#342](https://github.com/storytold/anicraft/issues/342); duplicates [#488](https://github.com/storytold/anicraft/issues/488), [#448](https://github.com/storytold/anicraft/issues/448), [#412](https://github.com/storytold/anicraft/issues/412), [#313](https://github.com/storytold/anicraft/issues/313), [#286](https://github.com/storytold/anicraft/issues/286), [#285](https://github.com/storytold/anicraft/issues/285)) each end in a window or a message that says what to do | Preferences, platforms | M | reports' logs | platform | -| P-002 | Nested symbols can't exhaust memory or hang: a work budget on evaluation and bounds (outside PR [#13](https://github.com/storytold/anicraft/issues/13)) | Symbols | S | | doc | | P-003 | A long Brush stroke never freezes the app ([#519](https://github.com/storytold/anicraft/issues/519)): bound the trace and fit, keep the stage responsive while it merges | Tools | M | | stage | | P-004 | Memory and frame time stay flat: 900 MB for a 24-frame move in the web build ([#314](https://github.com/storytold/anicraft/issues/314)), stutter when zoomed in ([#477](https://github.com/storytold/anicraft/issues/477)); a budget test for each | Workspace | M | | render | | P-005 | Free Transform works everywhere: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117)); decide [#193](https://github.com/storytold/anicraft/issues/193) (see outside PR [#218](https://github.com/storytold/anicraft/issues/218)) and write the rule in the guide | Tools | M | | stage | @@ -53,8 +52,6 @@ the changelog. | P-008 | Text reads right: mixed directions (outside PR [#39](https://github.com/storytold/anicraft/issues/39)), then letters from a fallback face (outside PR [#40](https://github.com/storytold/anicraft/issues/40)) | Text | M | [#39](https://github.com/storytold/anicraft/issues/39) before [#40](https://github.com/storytold/anicraft/issues/40) | text | | P-009 | Timeline bugs: a click on the playhead acts on every layer ([#195](https://github.com/storytold/anicraft/issues/195), outside PR [#222](https://github.com/storytold/anicraft/issues/222)), several layers selected with Ctrl and Shift ([#512](https://github.com/storytold/anicraft/issues/512)), the layer count over the header icons ([#523](https://github.com/storytold/anicraft/issues/523)), the mask edge drawn in the layer colour ([#429](https://github.com/storytold/anicraft/issues/429)) | Timeline, layers | S each | | timeline | | P-010 | Panel bugs: empty space in the Movie Explorer ([#513](https://github.com/storytold/anicraft/issues/513)), a side dock that grows under the pointer ([#159](https://github.com/storytold/anicraft/issues/159)), fill and stroke squares that don't answer ([#246](https://github.com/storytold/anicraft/issues/246)), the flicker in [#255](https://github.com/storytold/anicraft/issues/255) | Workspace | S each | | shell | -| P-011 | Shape tweens morph a raw shape's outline with its fill (outside PR [#238](https://github.com/storytold/anicraft/issues/238)) | Tweens | S | | doc | -| P-012 | Small hardening fixes from outside: overflow in `Vec2::length` ([#142](https://github.com/storytold/anicraft/issues/142)), alpha kept by `Rgba::to_hex` ([#233](https://github.com/storytold/anicraft/issues/233)), a test for path numbers past `f32` ([#130](https://github.com/storytold/anicraft/issues/130)), private-use language tags ([#486](https://github.com/storytold/anicraft/issues/486)), a test of SVG link sanitising ([#500](https://github.com/storytold/anicraft/issues/500)) | (robustness) | S each | | several | | P-013 | No hairline between merged curved fills ([#182](https://github.com/storytold/anicraft/issues/182)) | Drawing model | M | | geom | | P-014 | Pen pressure on every desktop: Linux Wayland (outside PR [#320](https://github.com/storytold/anicraft/issues/320)), reports from tablets ([#290](https://github.com/storytold/anicraft/issues/290)) | Tools | M | a tablet to test with | platform | | P-015 | Verified by hand on real machines: the Mac checklist of [ADR 0062](adr/0062-test-movie-window-and-macos-document-opening.md), a hybrid-GPU laptop, passes with Narrator, VoiceOver and Orca ([ADR 0064](adr/0064-accessibility-second-pass.md)), launcher icons on Fedora ([#348](https://github.com/storytold/anicraft/issues/348)) | Accessibility, platforms | M | the machines; the person | platform | @@ -142,16 +139,16 @@ As of 2026-11-20 (27 open): | PR | What | Id | State | What it still needs, or what happened | |---|---|---|---|---| -| [#13](https://github.com/storytold/anicraft/issues/13) | Bound the work of evaluating nested symbols | P-002 | **planned** | Its two review findings are answered. Needs a rebase (it conflicts), its roadmap edit dropped for a changelog entry, and the principal-engineer review. First in line. | +| [#13](https://github.com/storytold/anicraft/issues/13) | Bound the work of evaluating nested symbols | (done) | **superseded by** | The P-002 change ([ADR 0128](adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md)), which took its ideas into the allowance `main` already had: layers, symbol lookups and outline sizes count as work, and a frame that ran out says so. Its commits were not merged: they rewrite what [#497](https://github.com/storytold/anicraft/issues/497) rewrote, and its charge of one unit per library entry would cut honest documents with large libraries. Credited in `AUTHORS.md`. | | [#39](https://github.com/storytold/anicraft/issues/39) | Text that mixes directions | P-008 | **planned** | Re-reviewed clean; changes were requested earlier, so it needs a fresh review at the rebased head, and the licence of any new crate checked against `standards/licences.md`. Before [#40](https://github.com/storytold/anicraft/issues/40). | | [#40](https://github.com/storytold/anicraft/issues/40) | Letters from a fallback face | P-008 | **planned** | Builds on [#39](https://github.com/storytold/anicraft/issues/39); rebase onto it once [#39](https://github.com/storytold/anicraft/issues/39) is in. | | [#222](https://github.com/storytold/anicraft/issues/222) | A click on the playhead makes the frame keys act on every layer | P-009 | **planned** | Mergeable and green. Needs a check by hand of the ruler click with a screenshot, since no reviewer ran it. | -| [#238](https://github.com/storytold/anicraft/issues/238) | Morph a shape's stroke with its fill | P-011 | **planned** | Its first fix is on `main`; the rest handles guided tweens and dashed outlines. Needs the open design question answered with pictures: which fill an outline belongs to when outlines join. | -| [#142](https://github.com/storytold/anicraft/issues/142) | `Vec2::length` overflow | P-012 | **planned** | Needs a measured cost: `hypot` is slower than the multiply and `length` is on hot paths. If it shows, scale only inside `normalized`. | -| [#233](https://github.com/storytold/anicraft/issues/233) | Keep alpha in `Rgba::to_hex` | P-012 | **planned** | Needs a rebase and an audit of every caller: SVG, HTML and Lottie writers expect six digits and carry alpha themselves. | -| [#130](https://github.com/storytold/anicraft/issues/130) | Reject SVG path numbers past `f32` | P-012 | **planned** | Now a test only; ready after a rebase check. | -| [#486](https://github.com/storytold/anicraft/issues/486) | Hebrew font, `iw`, right-to-left preparation | P-012, P-034 | **planned** | Most of it came in with [#496](https://github.com/storytold/anicraft/issues/496). What is left (private-use tags are not right-to-left) is small and ready. | -| [#500](https://github.com/storytold/anicraft/issues/500) | A test of SVG link sanitising and re-import | P-012 | **planned** | A draft. Ready when its author marks it so. | +| [#238](https://github.com/storytold/anicraft/issues/238) | Morph a shape's stroke with its fill | (done) | **superseded by** | Merged with its commits in the P-011 change. The design question is answered with pictures there: a stroke run belongs to the fill whose edge its middle lies on, and an edge two fills share goes with the lower one. On top of it, a guided shape tween now joins the runs even when both keys have as many. | +| [#142](https://github.com/storytold/anicraft/issues/142) | `Vec2::length` overflow | (done) | **superseded by** | Merged with its commit in the P-012 change, then narrowed after measuring: `hypot` alone cost 1.9 ns against 0.83 ns a call, so it is taken only where the squares leave `f32` (0.85 ns, the same results in range). | +| [#233](https://github.com/storytold/anicraft/issues/233) | Keep alpha in `Rgba::to_hex` | (done) | **superseded by** | Merged with its commit in the P-012 change, as a function of its own: `to_hex` keeps its six digits for the SVG, HTML and Lottie writers (as merged, the four callers that add their own alpha digits would have written ten), and `to_hex_alpha` is the form that reads back. The Eyedropper's result uses it. | +| [#130](https://github.com/storytold/anicraft/issues/130) | Reject SVG path numbers past `f32` | (done) | **superseded by** | Merged with its commit in the P-012 change (the test). | +| [#486](https://github.com/storytold/anicraft/issues/486) | Hebrew font, `iw`, right-to-left preparation | (done) | **superseded by** | The rest (private-use tags are not right-to-left) is merged with its commits in the P-012 change; the Hebrew face and `iw` came in with [#496](https://github.com/storytold/anicraft/issues/496). P-034 stays open for laying out right to left. | +| [#500](https://github.com/storytold/anicraft/issues/500) | A test of SVG link sanitising and re-import | (done) | **superseded by** | Merged with its commits in the P-012 change, without the two lines it only reformatted. It is the one test that linked artwork survives export and re-import. | | [#320](https://github.com/storytold/anicraft/issues/320) | Pen pressure on Linux Wayland | P-014 | **planned** | Needs a rebase, platform code kept in `src/platform.rs` with no `unsafe`, the licences of its X11 crates checked, and a test by hand with a tablet. | | [#336](https://github.com/storytold/anicraft/issues/336) | Raw pressure-sensitive ink | P-028 | **planned** | After P-003, so a long stroke is bounded first. Needs a rebase and a new ADR number (0096 is taken; ask for one to be reserved). | | [#394](https://github.com/storytold/anicraft/issues/394) | Studio theme, canvas turn, Ctrl+Space zoom | P-029, P-046 | **planned, in parts** | Three things in one PR, 75 files. Needs to be split: the view turn and the zoom key each as their own PR (P-029), and the palette as a theme file for [ADR 0117](adr/0117-user-themes-from-a-folder.md) instead of a built-in theme (P-046). | @@ -253,7 +250,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va | Data-driven animation | **Data tables that drive animation, first slice** (ADR 0118, #416, #417, #418): numeric **tables kept in the document** as Library items, imported from **CSV, TSV or JSON** (File › Import › Import Data Table; through craft-csv; named columns, gaps, text-only columns left out and reported, a row per frame or a **key column** for a row per keyed time; 256 tables, 100 000 rows, 1 000 000 cells, files up to 32 MB; hostile input refused or cut to the limits), a **table viewer**, **Import Again** that keeps every binding; **bindings** that let a column drive a symbol instance's **X, Y, Scale X, Scale Y, Rotation, Alpha** or **the frame a graphic shows** over a span of frames, with scale, offset, linear or step interpolation and reversed key ranges, edited live in Properties › Data and evaluated purely in `evaluate` (stage, oracle, GPU stage, Test Movie and every export that draws frames agree); **Bake to Keyframes** (every frame looks as it did); `data.*` commands headless, over the CLI and MCP, and for plug-ins (all but reading a file). Not yet: bindings that follow copy, paste and duplicate; baking inside a motion tween and a Lottie export warning for live bindings; editing cells in the viewer, adding and renaming columns; text columns for captions; binding skew, tint, filter values, shapes, text and group members; expressions; audio amplitude into a table. | | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. | | Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. | -| 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. | +| 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. **Documents too large to draw** ([ADR 0128](adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md)): a frame, a bounds query and a Test Movie step each have an allowance of work that no nesting of symbols gets past; a frame cut short says so in the status bar, in the results of the commands that write frames, in `info` and in the MCP picture's caption. Not yet: the same note from the Lottie and HTML exporters and exporter plug-ins, a notice inside the Test Movie window when its picture is cut short, how much was left out. | | 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 (Follow system, Dark (Graphite), Light or High contrast; ADR 0077), 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). **CI on macOS and Windows** (ADR 0067): every code PR builds, tests and lints the workspace on macOS (arm64) and Windows (x64) runners besides Linux. Not yet: native macOS NSMenu, Linux arm64 and Windows ARM64 test legs on PRs, a GPU runner. Verified by hand on Windows only so far. **Robust start-up** (#207): the window opens through a list of ways (the one chosen in Preferences › Stage › Window graphics or `--renderer gl|wgpu|vulkan|dx12|metal`, then wgpu automatic, DirectX 12 on the low-power GPU on Windows, OpenGL), falling through on an error or a panic; a start that died inside a driver tries that way last for the next five starts, then 25 and 100 if it dies again (#335, ADR 0105); stage work on the window's device is submitted only inside a frame, which removes the `Surface::configure` "Failed to wait for GPU to come idle" error behind 0.2.1 closing at start-up and on resizing (#264, #309; ADR 0105); a start-up log (`Logs/anicraft.log` in the settings folder, the previous run's kept) records each way, the adapter and driver, panics and slow starts; a system message names it when nothing works. Not yet: verified on a hybrid-GPU laptop, the log from the Help menu, restarting by itself when a driver hangs at start-up. | | Installers & release | **Packaging** (ADR 0026, `docs/release.md`): the Craft family's `packaging/` layout behind the shared release workflow. Windows MSI (x64, arm64; per-user by default, everyone on request, upgrades in place), portable and symbols zips; macOS universal DMG with a laid-out window and CLI zip; Linux AppImage, deb, rpm, tar.gz, Flatpak and Arch (x86_64, aarch64; riscv64 deb/rpm/tar). `.anicraft` opens AniCraft by default; `.fla`/`.xfl` offered under Open with. Signed and notarized on the `release` branch (missing secrets fail it), unsigned elsewhere; ends in a draft release. Packaging lint and a fixture WiX build guard PRs; `src/packaging_tests.rs` keeps ids and types in step. **Opening documents on macOS** (ADR 0062): a double-click in Finder, a drop on the Dock icon or Open With opens the document, at launch or while running (the open-documents Apple Event through `platform.rs`, by `fmv-macos-events`, so no `unsafe` of ours), through the unsaved-changes guard; the Dock's Quit asks to save too; Windows and Linux command-line hand-over covered by a test. **Portable mode and AppImage desktop integration** (ADR 0094): an `anicraft-portable` marker (shipped in the Windows zip and the Linux tar.gz; also honoured beside `AniCraft.app` and an `.AppImage`) keeps preferences, autosave, logs, plug-ins, templates, recent files, brushes, filter presets and workspaces in `data/` beside the app, through one switch in `platform.rs`, falling back visibly when that folder can't be written; Preferences › About shows the mode and every folder; on first start from an AppImage a non-modal card offers once to add AniCraft to the applications menu (`desktop.integrate/remove/status`: desktop entry with a quoted `Exec`, MIME types and icons under `$XDG_DATA_HOME` only, idempotent, removable from About, following a moved or updated AppImage); a store-readiness job checks the Flatpak manifests, AppStream (`appstreamcli validate`), the desktop entry and any winget/MSIX manifests. Not yet: verified on a Mac (the checklist is in ADR 0062), a single running AniCraft taking a second document on Windows and Linux, store submissions and winget/MSIX manifests, self-update inside a portable copy, video export inside the Flatpak. | | Documentation | **User guide, first slice** (ADR 0069, `docs/guide/`): eighteen chapters for artists (getting started to troubleshooting, and Coming from Animate), a command reference and a shortcut reference (Windows/Linux and macOS) generated from the registry and checked for freshness by tests, every link, anchor and picture checked, eight screenshots from `scripts/guide-shots.sh`. Help › User Guide opens the book bundled in the app, offline, in the browser; the web build serves it beside the editor; `anicraft-cli guide --out ` writes it. Not yet: translated guides, search, a PDF edition, context help from panels, macOS and Linux screenshots. | From 6b24865995b91bb0ef2ef4730c0656cdf13fb42a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 14:07:29 -0700 Subject: [PATCH 23/23] fix(stage): the left-out notice leads with what happened (M8) --- CHANGELOG.md | 4 ++-- ...e-work-allowance-and-frames-that-say-what-they-left-out.md | 4 ++-- src/stage.rs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f3c7437..32e57220 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,8 @@ **Test Movie** has an allowance for each step: it used to look at every element of up to 10,000 instances after every change, and give every button a whole frame's allowance at every move of the pointer (ideas from Agapenor's #13). - * **A frame with artwork left out says so.** The status bar tells you once ("This frame - holds more artwork than AniCraft draws at once…"), Test Movie's Output panel says why a + * **A frame with artwork left out says so.** The status bar tells you once ("Some artwork + on this frame is left out…"), Test Movie's Output panel says why a step stopped, and the commands that write frames (PNG, SVG, sequences, sprite sheet, GIF, animated PNG and WebP, video) add `"left_out": true` and a `"warning"` to their result instead of passing a partial picture off as the whole one. `anicraft-cli info` and the MCP diff --git a/docs/adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md b/docs/adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md index 14265d37..367e728e 100644 --- a/docs/adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md +++ b/docs/adr/0128-one-work-allowance-and-frames-that-say-what-they-left-out.md @@ -76,8 +76,8 @@ than four full passes in one step is one no machine plays in time. are appended (onion skins, the hit-area overlay). It is a plain field of the result: `evaluate` stays a pure function of the document and the frame. -* **The stage** says once, in the status bar, as an error that stays: "This frame holds more - artwork than AniCraft draws at once, so some of it is left out. Nothing is lost: look for +* **The stage** says once, in the status bar, as an error that stays: "Some artwork on this + frame is left out: it holds more than AniCraft draws at once. Nothing is lost. Look for symbols nested many times over." It says it again only after a frame that was whole. The check is skipped while playing, where it would cost an evaluation every frame; the frame playback stops on is checked. diff --git a/src/stage.rs b/src/stage.rs index fb36b654..4b9ea541 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -240,7 +240,7 @@ fn note_left_out(app: &mut App) { } let cut = app.s.display_list().left_out; if cut && !app.left_out_said { - app.status_err(tr!("This frame holds more artwork than AniCraft draws at once, so some of it is left out. Nothing is lost: look for symbols nested many times over.")); + app.status_err(tr!("Some artwork on this frame is left out: it holds more than AniCraft draws at once. Nothing is lost. Look for symbols nested many times over.")); } app.left_out_said = cut; }