From d3b46e7cabefebd04ce18f1d8ad3031e23359e1d Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sat, 7 Nov 2026 10:31:35 +0300 Subject: [PATCH 01/44] fix(text): text that mixes directions reads the right way round A paragraph was shaped as one run in the direction of its first letter, so a number or a Latin word inside Arabic came out reversed ("2026" as "6202", "AniCraft" as "tfarCinA"), and a wrapped Arabic paragraph was broken from its visual left, which put its last words on the first line. Layout now follows the Unicode bidi algorithm (UAX #9, the unicode-bidi crate, MIT OR Apache-2.0): each paragraph's level runs are shaped in their own direction to measure it, lines are found in reading order, and each line's runs are shaped and placed in visual order. Text that reads one way is laid out as before. A test pins the line breaks and, where the font has Arabic letters, the number's order and the wrapped paragraph's first line. --- Cargo.lock | 7 ++ crates/text/Cargo.toml | 2 + crates/text/src/lib.rs | 156 +++++++++++++++++++++++++++-------------- docs/adr/0012-text.md | 4 ++ docs/roadmap.md | 2 +- 5 files changed, 119 insertions(+), 52 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d7b4d91a..77042232 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -268,6 +268,7 @@ dependencies = [ "fontdb", "harfrust", "skrifa", + "unicode-bidi", ] [[package]] @@ -3147,6 +3148,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-general-category" version = "1.1.0" diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 6214daf1..79dfffa5 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -14,6 +14,8 @@ fontdb.workspace = true # Shaping (a HarfBuzz port) and outlines/metrics: both already in the tree through egui. harfrust = "0.12" skrifa = { version = "0.44", default-features = false, features = ["std"] } +# The Unicode bidi algorithm (UAX #9), for text that mixes right-to-left and left-to-right runs. +unicode-bidi = "0.3" [lints] workspace = true diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 950dfa6d..530030cf 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -199,64 +199,45 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let charmap = font.charmap(); let missing = text.chars().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(*c).is_none()).count(); - // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. + // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. Text + // that mixes directions follows the Unicode bidi algorithm (UAX #9): a paragraph's lines are + // found in reading order, then each line's runs are shaped in their own direction and placed + // in visual order, so a number or a Latin word inside Arabic reads the right way round, and a + // wrapped Arabic paragraph starts on the first line. let mut lines: Vec<(f32, Vec<(Glyph, f32)>)> = Vec::new(); for para in text.split('\n') { let para = para.strip_suffix('\r').unwrap_or(para); - let mut buffer = harfrust::UnicodeBuffer::new(); - buffer.push_str(para); - buffer.guess_segment_properties(); - let shaped = shaper.shape(buffer, harfrust::ShapeOptions::new()); - let run: Vec = shaped - .glyph_infos() - .iter() - .zip(shaped.glyph_positions()) - .map(|(info, pos)| Glyph { - id: skrifa::GlyphId::new(info.glyph_id), - cluster: info.cluster as usize, - x_offset: pos.x_offset as f32 * scale, - y_offset: pos.y_offset as f32 * scale, - advance: pos.x_advance as f32 * scale + style.letter_spacing, - }) - .collect(); - let is_space = |g: &Glyph| para.get(g.cluster..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace); - let mut line: Vec<(Glyph, f32)> = Vec::new(); - let mut x = 0.0f32; - // Where the current line could break: after its last space. - let mut break_at: Option = None; - for g in run { - let space = is_space(&g); - if let Some(w) = style.width - && !space - && x + g.advance > w - && !line.is_empty() - { - // Wrap: at the last space if there is one (dropping trailing spaces), else here. - let rest = match break_at { - Some(b) => line.split_off(b), - None => Vec::new(), - }; - while line.last().is_some_and(|(g, _)| is_space(g)) { - line.pop(); + let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); + let shape_run = |run: std::ops::Range, rtl: bool| para.get(run).map_or_else(Vec::new, |s| shape(&shaper, s, rtl, scale, style.letter_spacing)); + // Each byte's share of the width (a cluster's advance on its first byte), run by run. + let mut advance = vec![0.0f32; para.len()]; + let mut start = 0; + while start < para.len() { + let level = bidi.levels.get(start).copied(); + let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); + for g in shape_run(start..end, level.is_some_and(|l| l.is_rtl())) { + if let Some(a) = advance.get_mut(start + g.cluster) { + *a += g.advance; } - let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push((width, std::mem::take(&mut line))); - let shift = rest.first().map_or(0.0, |(_, gx)| *gx); - line = rest.into_iter().map(|(g, gx)| (g, gx - shift)).collect(); - x = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - break_at = None; } - line.push((g, x)); - x += line.last().map_or(0.0, |(g, _)| g.advance); - if space { - break_at = Some(line.len()); + start = end; + } + for range in break_lines(para, &advance, style.width) { + let mut line: Vec<(Glyph, f32)> = Vec::new(); + let mut x = 0.0f32; + if !range.is_empty() { + let (levels, runs) = bidi.visual_runs(range); + for run in runs { + let rtl = levels.get(run.start).is_some_and(|l| l.is_rtl()); + for g in shape_run(run, rtl) { + let a = g.advance; + line.push((g, x)); + x += a; + } + } } + lines.push((x, line)); } - while line.last().is_some_and(|(g, _)| is_space(g)) { - line.pop(); - } - let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push((width, line)); } let box_width = style.width.unwrap_or_else(|| lines.iter().map(|(w, _)| *w).fold(0.0, f32::max)); @@ -279,6 +260,58 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing }) } +/// Shapes `text` in one direction. Glyphs come back in visual order (left to right), clusters +/// counted in bytes from the start of `text`. +fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, letter_spacing: f32) -> Vec { + let mut buffer = harfrust::UnicodeBuffer::new(); + buffer.push_str(text); + buffer.set_direction(if rtl { harfrust::Direction::RightToLeft } else { harfrust::Direction::LeftToRight }); + buffer.guess_segment_properties(); + let shaped = shaper.shape(buffer, harfrust::ShapeOptions::new()); + shaped + .glyph_infos() + .iter() + .zip(shaped.glyph_positions()) + .map(|(info, pos)| Glyph { + id: skrifa::GlyphId::new(info.glyph_id), + cluster: info.cluster as usize, + x_offset: pos.x_offset as f32 * scale, + y_offset: pos.y_offset as f32 * scale, + advance: pos.x_advance as f32 * scale + letter_spacing, + }) + .collect() +} + +/// A paragraph's lines as byte ranges in reading order, given each byte's share of the width: +/// wrapped after the last space before `width` is passed (or within a word wider than the line), +/// with the spaces at a line's end left out. +fn break_lines(para: &str, advance: &[f32], width: Option) -> Vec> { + let trimmed = |start: usize, end: usize| start..para.get(start..end).map_or(start, |s| start + s.trim_end().len()); + let mut lines = Vec::new(); + let (mut start, mut x, mut break_at) = (0usize, 0.0f32, None::); + for (i, c) in para.char_indices() { + let a = advance.get(i).copied().unwrap_or(0.0); + let space = c.is_whitespace(); + if let Some(w) = width + && !space + && x + a > w + && i > start + { + let end = break_at.unwrap_or(i); + lines.push(trimmed(start, end)); + start = end; + x = advance.get(start..i).map_or(0.0, |s| s.iter().sum()); + break_at = None; + } + x += a; + if space { + break_at = Some(i + c.len_utf8()); + } + } + lines.push(trimmed(start, para.len())); + lines +} + /// Draws glyph outlines (font space, y up) into a path (pixels, y down) at a pen position. struct Pen<'a> { cmds: &'a mut Vec, @@ -371,6 +404,27 @@ mod tests { assert!(boxed(Align::Right).min.x > 280.0); } + #[test] + fn mixed_directions_read_the_right_way_round() { + // Lines are found in reading order: after the last space that fits, or within a word. + assert_eq!(break_lines("ab cd ef", &[1.0; 8], Some(5.0)), vec![0..5, 6..8]); + assert_eq!(break_lines("abcdefgh", &[1.0; 8], Some(3.0)), vec![0..3, 3..6, 6..8]); + let Some(fonts) = fonts() else { return }; + let lay = |t: &str, width| fonts.layout(t, &Style { width, ..style(40.0) }).unwrap(); + let arabic = lay("مرحبا 2026", None); + if arabic.missing > 0 { + eprintln!("{} has no Arabic letters: right-to-left layout test skipped", arabic.family); + return; + } + // A number inside Arabic keeps its digits in order, at the line's left end ... + assert!(arabic.outline.cmds.starts_with(&lay("2026", None).outline.cmds)); + // ... and a wrapped Arabic paragraph starts with its first word, on the first line. + let first = lay("بيت", None); + let wrapped = lay("بيت جديد", Some(first.width + 1.0)); + assert!(wrapped.height > first.height * 1.8, "two lines: {}", wrapped.height); + assert!(wrapped.outline.cmds.starts_with(&first.outline.cmds)); + } + #[test] fn families_resolve_and_styles_are_clamped() { let Some(fonts) = fonts() else { return }; diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index 751dfa77..ff42d48c 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -34,6 +34,10 @@ so neither may depend on which fonts happen to be installed. embedded Inter), shapes with `harfrust` (a HarfBuzz port), reads outlines and metrics with `skrifa`, and breaks lines (paragraphs at line breaks; with a width, greedily at spaces). These crates are already in the dependency tree through egui, so no new licences. + Text that mixes directions (Arabic or Hebrew with numbers or Latin words) follows the + Unicode bidi algorithm through `unicode-bidi` (MIT OR Apache-2.0): lines are found in + reading order, then each line's runs are shaped in their own direction and placed in + visual order. Bold and italic pick the matching face of the family; there is no synthetic styling. 5. **Break Apart** turns a text element into a shape with the same outlines, as Animate's second Break Apart does. diff --git a/docs/roadmap.md b/docs/roadmap.md index f3a35188..3d3a9c7d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,7 +29,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | -| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | +| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters); frame scripts on the same sandbox; HTML canvas runtime export; button states in test-movie preview; command macros. | | **M7** | Advanced animation | Bone/IK tool; camera layer with depth; variable-width strokes and brush library; asset warp; graph-based easing presets library. | | **M8** | Release quality | Installers and signing for Windows/macOS/Linux; web build (wasm) of the editor; localisation; accessibility audit; crash-recovery autosave; documentation book. | From e90f3854a4e3fc2a88959e08df9d4a76b04e7342 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sat, 7 Nov 2026 10:41:40 +0300 Subject: [PATCH 02/44] fix(text): letters the chosen font lacks come from a fallback face Text was drawn with one face, so letters it doesn't have showed as boxes, and nothing said so: Arabic in Inter, the default family where the app embeds it, or in Consolas. Now each character the chosen face lacks comes from the first of FALLBACK_FAMILIES that has it (faces with wide coverage that come with Windows, macOS and common Linux desktops, then Noto's script families), character by character: the rest of the block keeps its face, and a letter's marks stay with it. The block's line metrics still come from the chosen face. Characters no face has are counted, and text.create and text.edit now say they show as boxes. --- crates/engine/src/cmds_text.rs | 12 ++- crates/text/src/lib.rs | 140 ++++++++++++++++++++++++++++----- docs/adr/0012-text.md | 4 +- docs/roadmap.md | 2 +- 4 files changed, 136 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 354e3c97..c46e5f45 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -105,7 +105,17 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu }, ) .map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; - let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); + let mut notes = Vec::new(); + if !style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim()) { + notes.push(format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); + } + // Letters no installed font has (after the fallbacks) would otherwise show as boxes unsaid. + match layout.missing { + 0 => {} + 1 => notes.push("1 character isn't in any font on this computer and shows as a box".to_string()), + n => notes.push(format!("{n} characters aren't in any font on this computer and show as boxes")), + } + let note = (!notes.is_empty()).then(|| notes.join("; ")); let block = TextBlock { text: text.to_string(), font: layout.family, diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 530030cf..0c9b8814 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -158,11 +158,55 @@ impl Fonts { style: if style.italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, }; let id = self.db.query(&q).ok_or(TextError::NoFonts)?; - let laid = self.db.with_face_data(id, |data, index| lay_out(data, index, text, style)).flatten().ok_or(TextError::NoFonts)?; + let face = |id| self.db.with_face_data(id, |data, index| (data.to_vec(), index)); + let mut faces = vec![face(id).ok_or(TextError::NoFonts)?]; + // Characters the face doesn't have (Arabic in Inter, say) come from the first fallback + // family that has them; everything else stays in the chosen face. + let charmap_lacks = |f: &(Vec, u32), c: char| skrifa::FontRef::from_index(&f.0, f.1).ok().is_none_or(|font| font.charmap().map(c).is_none()); + let mut missing: Vec = text.chars().filter(|c| needs_glyph(*c)).collect(); + missing.sort_unstable(); + missing.dedup(); + missing.retain(|c| faces.first().is_none_or(|f| charmap_lacks(f, *c))); + for fallback in FALLBACK_FAMILIES { + if missing.is_empty() || faces.len() >= MAX_FACES { + break; + } + let Some(fid) = self.db.query(&fontdb::Query { families: &[fontdb::Family::Name(fallback)], ..q }).filter(|f| *f != id) else { continue }; + let Some(f) = face(fid) else { continue }; + let before = missing.len(); + missing.retain(|c| charmap_lacks(&f, *c)); + if missing.len() < before { + faces.push(f); + } + } + let laid = lay_out(&faces, text, style).ok_or(TextError::NoFonts)?; Ok(Layout { family, ..laid }) } } +/// Families tried, in order, for characters the chosen face doesn't have: faces with wide +/// coverage that come with Windows, macOS and common Linux desktops, then Noto's script families. +pub const FALLBACK_FAMILIES: &[&str] = &[ + "Segoe UI", + "Arial", + "Tahoma", + "Geeza Pro", + "Arial Unicode MS", + "DejaVu Sans", + "Noto Sans", + "Noto Sans Arabic", + "Noto Naskh Arabic", + "Noto Sans Hebrew", +]; + +/// Most faces one text block draws with (the chosen face and its fallbacks). +const MAX_FACES: usize = 6; + +/// A character that is drawn (not a space, a line break or another control). +fn needs_glyph(c: char) -> bool { + !c.is_control() && !c.is_whitespace() +} + /// Clamps a style to sane ranges (sizes from 1 to 2000 px, spacing within ±1000 px). pub fn sanitize(style: &Style) -> Style { let fin = |v: f32, d: f32| if v.is_finite() { v } else { d }; @@ -175,8 +219,10 @@ pub fn sanitize(style: &Style) -> Style { } } -/// One shaped glyph: id, where its pen position starts, its offsets and advance (pixels). +/// One shaped glyph: the face it comes from, its id, the byte it starts at in its paragraph, its +/// offsets and advance (pixels). struct Glyph { + face: usize, id: skrifa::GlyphId, cluster: usize, x_offset: f32, @@ -184,20 +230,22 @@ struct Glyph { advance: f32, } -fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option { +/// Lays `text` out with `faces`: the chosen face first (its metrics set the lines), then the +/// fallbacks for characters it doesn't have. +fn lay_out(faces: &[(Vec, u32)], text: &str, style: &Style) -> Option { let style = sanitize(style); - let font = skrifa::FontRef::from_index(data, index).ok()?; + let fonts: Vec = faces.iter().filter_map(|(data, index)| skrifa::FontRef::from_index(data, *index).ok()).collect(); let size = skrifa::instance::Size::new(style.size); - let metrics = font.metrics(size, skrifa::instance::LocationRef::default()); - let upem = f32::from(metrics.units_per_em.max(1)); - let scale = style.size / upem; + let metrics = fonts.first()?.metrics(size, skrifa::instance::LocationRef::default()); let ascent = metrics.ascent; let line_height = (metrics.ascent - metrics.descent + metrics.leading).max(style.size * 0.5) + style.line_spacing; - let shaper_data = harfrust::ShaperData::new(&font); - let shaper = shaper_data.shaper(&font).build(); - let glyphs = font.outline_glyphs(); - let charmap = font.charmap(); - let missing = text.chars().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(*c).is_none()).count(); + let shaper_data: Vec = fonts.iter().map(harfrust::ShaperData::new).collect(); + let shapers: Vec = fonts.iter().zip(&shaper_data).map(|(f, d)| d.shaper(f).build()).collect(); + let scales: Vec = fonts.iter().map(|f| style.size / f32::from(f.metrics(size, skrifa::instance::LocationRef::default()).units_per_em.max(1))).collect(); + let outlines: Vec<_> = fonts.iter().map(|f| f.outline_glyphs()).collect(); + let charmaps: Vec<_> = fonts.iter().map(|f| f.charmap()).collect(); + let has = |face: usize, c: char| charmaps.get(face).is_some_and(|m| m.map(c).is_some()); + let missing = text.chars().filter(|c| needs_glyph(*c) && !(0..fonts.len()).any(|f| has(f, *c))).count(); // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. Text // that mixes directions follows the Unicode bidi algorithm (UAX #9): a paragraph's lines are @@ -208,7 +256,35 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option for para in text.split('\n') { let para = para.strip_suffix('\r').unwrap_or(para); let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); - let shape_run = |run: std::ops::Range, rtl: bool| para.get(run).map_or_else(Vec::new, |s| shape(&shaper, s, rtl, scale, style.letter_spacing)); + // The face drawing each byte: the chosen one where it has the character, else the first + // fallback that does. Spaces and marks stay with what comes before them, so a letter and + // its harakat are shaped together. + let mut face_of = vec![0usize; para.len()]; + let mut current = 0; + for (i, c) in para.char_indices() { + let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); + if !joins || !has(current, c) { + current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(if joins { current } else { 0 }); + } + face_of.iter_mut().skip(i).take(c.len_utf8()).for_each(|f| *f = current); + } + // A run shaped in one direction, split where the face changes; glyphs in visual order. + let shape_run = |run: std::ops::Range, rtl: bool| { + let mut parts: Vec> = Vec::new(); + let mut start = run.start; + while start < run.end { + let face = face_of.get(start).copied().unwrap_or(0); + let end = (start..run.end).find(|i| face_of.get(*i).copied().unwrap_or(0) != face).unwrap_or(run.end); + if let (Some(s), Some(shaper)) = (para.get(start..end), shapers.get(face)) { + parts.push(shape(shaper, face, s, start, rtl, scales.get(face).copied().unwrap_or(1.0), style.letter_spacing)); + } + start = end; + } + if rtl { + parts.reverse(); + } + parts.into_iter().flatten().collect::>() + }; // Each byte's share of the width (a cluster's advance on its first byte), run by run. let mut advance = vec![0.0f32; para.len()]; let mut start = 0; @@ -216,7 +292,7 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let level = bidi.levels.get(start).copied(); let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); for g in shape_run(start..end, level.is_some_and(|l| l.is_rtl())) { - if let Some(a) = advance.get_mut(start + g.cluster) { + if let Some(a) = advance.get_mut(g.cluster) { *a += g.advance; } } @@ -250,7 +326,7 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option }; let baseline = ascent + row as f32 * line_height; for (g, gx) in line { - let Some(glyph) = glyphs.get(g.id) else { continue }; + let Some(glyph) = outlines.get(g.face).and_then(|o| o.get(g.id)) else { continue }; let mut pen = Pen { cmds: &mut outline.cmds, x: shift + gx + g.x_offset, y: baseline - g.y_offset }; let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); let _ = glyph.draw(settings, &mut pen); @@ -260,9 +336,9 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing }) } -/// Shapes `text` in one direction. Glyphs come back in visual order (left to right), clusters -/// counted in bytes from the start of `text`. -fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, letter_spacing: f32) -> Vec { +/// Shapes `text` (which starts at byte `at` of its paragraph) with one face in one direction. +/// Glyphs come back in visual order (left to right), clusters counted from the paragraph's start. +fn shape(shaper: &harfrust::Shaper<'_>, face: usize, text: &str, at: usize, rtl: bool, scale: f32, letter_spacing: f32) -> Vec { let mut buffer = harfrust::UnicodeBuffer::new(); buffer.push_str(text); buffer.set_direction(if rtl { harfrust::Direction::RightToLeft } else { harfrust::Direction::LeftToRight }); @@ -273,8 +349,9 @@ fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, lette .iter() .zip(shaped.glyph_positions()) .map(|(info, pos)| Glyph { + face, id: skrifa::GlyphId::new(info.glyph_id), - cluster: info.cluster as usize, + cluster: at + info.cluster as usize, x_offset: pos.x_offset as f32 * scale, y_offset: pos.y_offset as f32 * scale, advance: pos.x_advance as f32 * scale + letter_spacing, @@ -425,6 +502,31 @@ mod tests { assert!(wrapped.outline.cmds.starts_with(&first.outline.cmds)); } + #[test] + fn letters_the_font_lacks_come_from_a_fallback_face() { + let Some(fonts) = fonts() else { return }; + let has = |family: &str, c: char| { + let q = fontdb::Query { families: &[fontdb::Family::Name(family)], ..fontdb::Query::default() }; + fonts.db.query(&q).and_then(|id| fonts.db.with_face_data(id, |d, i| skrifa::FontRef::from_index(d, i).is_ok_and(|f| f.charmap().map(c).is_some()))).unwrap_or(false) + }; + // A family with Latin letters and no Arabic ones, and a fallback that has Arabic. + let Some(latin) = fonts.families().iter().find(|f| has(f, 'a') && !has(f, 'ب')) else { return }; + if !FALLBACK_FAMILIES.iter().any(|f| has(f, 'ب')) { + eprintln!("no fallback family with Arabic letters here: fallback test skipped"); + return; + } + let lay = |t: &str| fonts.layout(t, &Style { family: latin.clone(), ..style(40.0) }).unwrap(); + let arabic = lay("بيت"); + assert_eq!((arabic.missing, arabic.family.as_str()), (0, latin.as_str()), "the block keeps its family"); + assert!(!arabic.outline.cmds.is_empty()); + // The Latin letters are still drawn in the chosen face, the Arabic ones after them. + let mixed = lay("ab بيت"); + assert!(mixed.outline.cmds.starts_with(&lay("ab").outline.cmds)); + assert!(mixed.outline.cmds.len() > lay("ab").outline.cmds.len()); + // A character no font has is counted, so the command can say so. + assert_eq!(lay("a\u{10FFFD}").missing, 1); + } + #[test] fn families_resolve_and_styles_are_clamped() { let Some(fonts) = fonts() else { return }; diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index ff42d48c..cc7138c7 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -37,7 +37,9 @@ so neither may depend on which fonts happen to be installed. Text that mixes directions (Arabic or Hebrew with numbers or Latin words) follows the Unicode bidi algorithm through `unicode-bidi` (MIT OR Apache-2.0): lines are found in reading order, then each line's runs are shaped in their own direction and placed in - visual order. + visual order. Characters the chosen face doesn't have (Arabic in Inter, say) come from the + first of `FALLBACK_FAMILIES` that has them, character by character, so the rest of the block + keeps its face; any that no face has are counted, and the command says they show as boxes. Bold and italic pick the matching face of the family; there is no synthetic styling. 5. **Break Apart** turns a text element into a shape with the same outlines, as Animate's second Break Apart does. diff --git a/docs/roadmap.md b/docs/roadmap.md index 3d3a9c7d..164e9328 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,7 +29,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | -| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | +| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, fallback faces for letters the chosen font lacks, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters); frame scripts on the same sandbox; HTML canvas runtime export; button states in test-movie preview; command macros. | | **M7** | Advanced animation | Bone/IK tool; camera layer with depth; variable-width strokes and brush library; asset warp; graph-based easing presets library. | | **M8** | Release quality | Installers and signing for Windows/macOS/Linux; web build (wasm) of the editor; localisation; accessibility audit; crash-recovery autosave; documentation book. | From 5fb4c75d732101bbf70b0c5ab4b74876a7bda3f1 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sun, 8 Nov 2026 07:18:28 +0300 Subject: [PATCH 03/44] perf(text): read the chosen face in place and each fallback's charmap once Fallback faces had every face copied out of the memory-mapped font on each layout, the chosen one included, and a font parsed for every character checked against it. Now the chosen face is read in place, only fallback faces the text needs are copied, and each candidate's charmap is read once. The fallback test says when it skips, and checks the Arabic letters are the fallback face's (as wide as in that family) rather than boxes from the chosen face. --- crates/text/src/lib.rs | 80 +++++++++++++++++++++++++++--------------- 1 file changed, 52 insertions(+), 28 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 0c9b8814..cb5675d8 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -158,28 +158,37 @@ impl Fonts { style: if style.italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, }; let id = self.db.query(&q).ok_or(TextError::NoFonts)?; - let face = |id| self.db.with_face_data(id, |data, index| (data.to_vec(), index)); - let mut faces = vec![face(id).ok_or(TextError::NoFonts)?]; - // Characters the face doesn't have (Arabic in Inter, say) come from the first fallback - // family that has them; everything else stays in the chosen face. - let charmap_lacks = |f: &(Vec, u32), c: char| skrifa::FontRef::from_index(&f.0, f.1).ok().is_none_or(|font| font.charmap().map(c).is_none()); - let mut missing: Vec = text.chars().filter(|c| needs_glyph(*c)).collect(); - missing.sort_unstable(); - missing.dedup(); - missing.retain(|c| faces.first().is_none_or(|f| charmap_lacks(f, *c))); - for fallback in FALLBACK_FAMILIES { - if missing.is_empty() || faces.len() >= MAX_FACES { - break; - } - let Some(fid) = self.db.query(&fontdb::Query { families: &[fontdb::Family::Name(fallback)], ..q }).filter(|f| *f != id) else { continue }; - let Some(f) = face(fid) else { continue }; - let before = missing.len(); - missing.retain(|c| charmap_lacks(&f, *c)); - if missing.len() < before { - faces.push(f); - } - } - let laid = lay_out(&faces, text, style).ok_or(TextError::NoFonts)?; + // The chosen face is read in place (memory-mapped); only fallback faces the text needs are + // copied, so text in one script costs what it did before fallbacks. + let laid = self + .db + .with_face_data(id, |data, index| { + // Characters the face doesn't have (Arabic in Inter, say) come from the first + // fallback family that has them; everything else stays in the chosen face. + let mut missing: Vec = text.chars().filter(|c| needs_glyph(*c)).collect(); + missing.sort_unstable(); + missing.dedup(); + keep_lacking(&mut missing, data, index); + let mut fallbacks: Vec<(Vec, u32)> = Vec::new(); + for fallback in FALLBACK_FAMILIES { + if missing.is_empty() || fallbacks.len() + 1 >= MAX_FACES { + break; + } + let Some(fid) = self.db.query(&fontdb::Query { families: &[fontdb::Family::Name(fallback)], ..q }).filter(|f| *f != id) else { continue }; + let helps = |d: &[u8], i: u32| { + let before = missing.len(); + keep_lacking(&mut missing, d, i); + (missing.len() < before).then(|| (d.to_vec(), i)) + }; + if let Some(face) = self.db.with_face_data(fid, helps).flatten() { + fallbacks.push(face); + } + } + let faces: Vec<(&[u8], u32)> = std::iter::once((data, index)).chain(fallbacks.iter().map(|(d, i)| (d.as_slice(), *i))).collect(); + lay_out(&faces, text, style) + }) + .flatten() + .ok_or(TextError::NoFonts)?; Ok(Layout { family, ..laid }) } } @@ -207,6 +216,14 @@ fn needs_glyph(c: char) -> bool { !c.is_control() && !c.is_whitespace() } +/// Drops from `chars` those the face in `data` has (its charmap read once). +fn keep_lacking(chars: &mut Vec, data: &[u8], index: u32) { + if let Ok(font) = skrifa::FontRef::from_index(data, index) { + let charmap = font.charmap(); + chars.retain(|c| charmap.map(*c).is_none()); + } +} + /// Clamps a style to sane ranges (sizes from 1 to 2000 px, spacing within ±1000 px). pub fn sanitize(style: &Style) -> Style { let fin = |v: f32, d: f32| if v.is_finite() { v } else { d }; @@ -232,7 +249,7 @@ struct Glyph { /// Lays `text` out with `faces`: the chosen face first (its metrics set the lines), then the /// fallbacks for characters it doesn't have. -fn lay_out(faces: &[(Vec, u32)], text: &str, style: &Style) -> Option { +fn lay_out(faces: &[(&[u8], u32)], text: &str, style: &Style) -> Option { let style = sanitize(style); let fonts: Vec = faces.iter().filter_map(|(data, index)| skrifa::FontRef::from_index(data, *index).ok()).collect(); let size = skrifa::instance::Size::new(style.size); @@ -266,7 +283,9 @@ fn lay_out(faces: &[(Vec, u32)], text: &str, style: &Style) -> Option, rtl: bool| { @@ -510,15 +529,20 @@ mod tests { fonts.db.query(&q).and_then(|id| fonts.db.with_face_data(id, |d, i| skrifa::FontRef::from_index(d, i).is_ok_and(|f| f.charmap().map(c).is_some()))).unwrap_or(false) }; // A family with Latin letters and no Arabic ones, and a fallback that has Arabic. - let Some(latin) = fonts.families().iter().find(|f| has(f, 'a') && !has(f, 'ب')) else { return }; - if !FALLBACK_FAMILIES.iter().any(|f| has(f, 'ب')) { + let Some(latin) = fonts.families().iter().find(|f| has(f, 'a') && !has(f, 'ب')) else { + eprintln!("no family with Latin letters and no Arabic ones here: fallback test skipped"); + return; + }; + let Some(fallback) = FALLBACK_FAMILIES.iter().find(|f| has(f, 'ب')) else { eprintln!("no fallback family with Arabic letters here: fallback test skipped"); return; - } + }; let lay = |t: &str| fonts.layout(t, &Style { family: latin.clone(), ..style(40.0) }).unwrap(); let arabic = lay("بيت"); assert_eq!((arabic.missing, arabic.family.as_str()), (0, latin.as_str()), "the block keeps its family"); - assert!(!arabic.outline.cmds.is_empty()); + // The letters are the fallback face's (as wide as in that family), not the chosen face's boxes. + let direct = fonts.layout("بيت", &Style { family: fallback.to_string(), ..style(40.0) }).unwrap(); + assert!((arabic.width - direct.width).abs() < 0.01, "{} vs {} in {fallback}", arabic.width, direct.width); // The Latin letters are still drawn in the chosen face, the Arabic ones after them. let mixed = lay("ab بيت"); assert!(mixed.outline.cmds.starts_with(&lay("ab").outline.cmds)); From c9dd3163d1077ce6fd9e733d5f7a7bf4d25dc471 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 10 Nov 2026 01:05:24 +0300 Subject: [PATCH 04/44] perf(text): skip bidi reordering for a paragraph with no right-to-left text (M5) --- crates/text/src/lib.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 6e4ca3fd..c4037a55 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -318,7 +318,14 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option for range in break_lines(para, &advance, style.width) { let mut line: Vec<(Glyph, f32)> = Vec::new(); let mut x = 0.0f32; - if !range.is_empty() { + if !bidi.has_rtl() { + // All left to right: nothing to reorder (visual_runs copies the paragraph's levels per line). + for g in shape_run(range, false) { + let a = g.advance; + line.push((g, x)); + x += a; + } + } else if !range.is_empty() { let (levels, runs) = bidi.visual_runs(range); for run in runs { let rtl = levels.get(run.start).is_some_and(|l| l.is_rtl()); From 912ceba1916d8c950675201983968b6fe94892a1 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 10 Nov 2026 09:26:04 +0300 Subject: [PATCH 05/44] fix(text): invisible format characters aren't missing glyphs; the notice names the fonts it checked (M5) --- crates/engine/src/cmds_text.rs | 6 +++--- crates/text/src/lib.rs | 8 +++++++- docs/adr/0012-text.md | 5 +++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 9f1396e1..ededa328 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -109,11 +109,11 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu if !style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim()) { notes.push(format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); } - // Letters no installed font has (after the fallbacks) would otherwise show as boxes unsaid. + // Letters neither the font nor the fallback fonts have would otherwise show as boxes unsaid. match layout.missing { 0 => {} - 1 => notes.push("1 character isn't in any font on this computer and shows as a box".to_string()), - n => notes.push(format!("{n} characters aren't in any font on this computer and show as boxes")), + 1 => notes.push(format!("1 character isn't in {} or the fallback fonts and shows as a box", layout.family)), + n => notes.push(format!("{n} characters aren't in {} or the fallback fonts and show as boxes", layout.family)), } let note = (!notes.is_empty()).then(|| notes.join("; ")); let block = TextBlock { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7355a31a..6e35b879 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -280,7 +280,11 @@ const MAX_FACES: usize = 6; /// A character that is drawn (not a space, a line break or another control). fn needs_glyph(c: char) -> bool { - !c.is_control() && !c.is_whitespace() + // Invisible format characters (ZWNJ, ZWJ, direction marks and embeddings, variation + // selectors, the BOM) draw as nothing, and fonts often don't map them. + let invisible = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::BN + || matches!(c, '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}'); + !c.is_control() && !c.is_whitespace() && !invisible } /// Drops from `chars` those the face in `data` has (its charmap read once). @@ -649,6 +653,8 @@ mod tests { assert!(mixed.outline.cmds.len() > lay("ab").outline.cmds.len()); // A character no font has is counted, so the command can say so. assert_eq!(lay("a\u{10FFFD}").missing, 1); + // Invisible format characters aren't boxes, so they aren't missing either. + assert_eq!(lay("a\u{200C}b\u{200D}\u{200F}\u{FE0F}").missing, 0); } #[test] diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index 7e06e2fc..1ca8e1b6 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -52,5 +52,6 @@ so neither may depend on which fonts happen to be installed. edited, and the user is told. * Text in Animate documents imports onto this model (ADR 0014). * Not yet: per-character styles in one block, vertical text, text along a path, input and - dynamic text fields (with scripting, M6), font embedding for export, glyph fallback across - fonts for missing characters (missing glyphs draw as the font's "notdef" box). + dynamic text fields (with scripting, M6), font embedding for export, fallback to installed + fonts outside the fallback list (a character none of the loaded faces has draws as the + font's "notdef" box, and the command says so). From c80f2c47e3ac4c33950caf10bf8c8f4f6bcd2898 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 10 Nov 2026 10:54:49 +0300 Subject: [PATCH 06/44] perf(text): a block without a width skips the measuring pass that only line wrapping reads (M5) --- crates/text/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 44f64a56..d5a7efa5 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -307,9 +307,10 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let para = para.strip_suffix('\r').unwrap_or(para); let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); let shape_run = |run: std::ops::Range, rtl: bool| para.get(run).map_or_else(Vec::new, |s| shape(&shaper, s, rtl, scale, style.letter_spacing)); - // Each byte's share of the width (a cluster's advance on its first byte), run by run. + // Each byte's share of the width (a cluster's advance on its first byte), run by run. Only wrapping + // reads it, so a block without a width skips this pass (it would shape every paragraph twice). let mut advance = vec![0.0f32; para.len()]; - let mut start = 0; + let mut start = if style.width.is_some() { 0 } else { para.len() }; while start < para.len() { let level = bidi.levels.get(start).copied(); let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); From a9c6fc0d3232086a8afa53332d715da7b41479ed Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Wed, 11 Nov 2026 09:23:55 +0300 Subject: [PATCH 07/44] fix(text): a combining mark the letter's face lacks takes the letter to a face with both (M5) Before, the mark alone went to the fallback face and was shaped apart from its letter, so it couldn't attach. Now the letter moves with it when one face has both; a mark no face pairs with still comes from the first face that has it. --- crates/text/src/lib.rs | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 86c3de5b..7e57000c 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -377,13 +377,26 @@ fn lay_out(faces: &[(&[u8], u32)], text: &str, style: &Style) -> Option let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); // The face drawing each byte: the chosen one where it has the character, else the first // fallback that does. Spaces and marks stay with what comes before them, so a letter and - // its harakat are shaped together. + // its harakat are shaped together; a mark its letter's face lacks takes the letter to a + // face that has both, if there is one. let mut face_of = vec![0usize; para.len()]; let mut current = 0; + let mut base = (0, '\0'); // the last letter: its byte offset and character for (i, c) in para.char_indices() { let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); - if !joins || !has(current, c) { - current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(if joins { current } else { 0 }); + if !joins { + current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(0); + base = (i, c); + } else if !has(current, c) { + let mark = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM; + if let Some(both) = (0..fonts.len()).find(|f| mark && has(*f, base.1) && has(*f, c)) { + current = both; + if let Some(bytes) = face_of.get_mut(base.0..i) { + bytes.fill(both); + } + } else if let Some(f) = (0..fonts.len()).find(|f| has(*f, c)) { + current = f; + } } if let Some(bytes) = face_of.get_mut(i..i + c.len_utf8()) { bytes.fill(current); @@ -661,6 +674,21 @@ mod tests { assert_eq!(lay("a\u{10FFFD}").missing, 1); // Invisible format characters aren't boxes, so they aren't missing either. assert_eq!(lay("a\u{200C}b\u{200D}\u{200F}\u{FE0F}").missing, 0); + // A combining mark the chosen face lacks takes its letter along to a face with both, so + // the two are shaped together (the mark attaches) instead of in two faces. + let mark = '\u{0301}'; + if let (Some(latin), Some(both)) = ( + fonts.families().iter().find(|f| has(f, 'e') && !has(f, mark)), + FALLBACK_FAMILIES.iter().find(|f| has(f, mark)).filter(|f| has(f, 'e')), + ) { + let lay_in = |family: &str| fonts.layout("e\u{0301}", &Style { family: family.to_string(), ..style(40.0) }).unwrap(); + let (mixed, direct) = (lay_in(latin), lay_in(both)); + assert_eq!(mixed.missing, 0); + assert!((mixed.width - direct.width).abs() < 0.01, "{} vs {} in {both}", mixed.width, direct.width); + assert_eq!(mixed.outline.cmds.len(), direct.outline.cmds.len()); + } else { + eprintln!("no family with e and without U+0301 here: combining mark check skipped"); + } } #[test] 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 08/44] 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 09/44] 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 10/44] 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 da342a3d11b8c4f9a002f28970865c9713d38d0e Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Fri, 13 Nov 2026 10:55:15 +0300 Subject: [PATCH 11/44] fix(text): wrap narrow lines between shaped clusters, never inside one break_lines walked every scalar, but advances sit only on a cluster's first byte, so a cluster wider than the line was split after its first scalar: a combining mark landed on the next line, away from its letter, and a ligature was reshaped in pieces. Advances are now None inside a cluster and lines break only where one starts; an overwide cluster stays whole on its own line. Regressions for a combining mark and a ligature at a narrow width. --- crates/text/src/lib.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 6afcd84f..8adcb4a8 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -510,16 +510,17 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style, want_glyphs: bool run }) }; - // Each byte's share of the width (a cluster's advance on its first byte), run by run. Only wrapping - // reads it, so a block without a width skips this pass (it would shape every paragraph twice). - let mut advance = vec![0.0f32; para.len()]; + // Each cluster's advance on its first byte, run by run (`None` inside a cluster, where a + // line can't break). Only wrapping reads it, so a block without a width skips this pass + // (it would shape every paragraph twice). + let mut advance: Vec> = vec![None; para.len()]; let mut start = if style.width.is_some() { 0 } else { para.len() }; while start < para.len() { let level = bidi.levels.get(start).copied(); let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); for g in shape_run(start..end, level.is_some_and(|l| l.is_rtl())) { if let Some(a) = advance.get_mut(g.cluster) { - *a += g.advance; + *a.get_or_insert(0.0) += g.advance; } } start = end; @@ -654,15 +655,16 @@ fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, lette .collect() } -/// A paragraph's lines as byte ranges in reading order, given each byte's share of the width: -/// wrapped after the last space before `width` is passed (or within a word wider than the line), -/// with the spaces at a line's end left out. -fn break_lines(para: &str, advance: &[f32], width: Option) -> Vec> { +/// A paragraph's lines as byte ranges in reading order, given each cluster's advance on its first +/// byte (`None` inside a cluster): wrapped after the last space before `width` is passed (or +/// between the clusters of a word wider than the line, never inside one), with the spaces at a +/// line's end left out. +fn break_lines(para: &str, advance: &[Option], width: Option) -> Vec> { let trimmed = |start: usize, end: usize| start..para.get(start..end).map_or(start, |s| start + s.trim_end().len()); let mut lines = Vec::new(); let (mut start, mut x, mut break_at) = (0usize, 0.0f32, None::); for (i, c) in para.char_indices() { - let a = advance.get(i).copied().unwrap_or(0.0); + let Some(a) = advance.get(i).copied().flatten() else { continue }; let space = c.is_whitespace(); if let Some(w) = width && !space @@ -672,7 +674,7 @@ fn break_lines(para: &str, advance: &[f32], width: Option) -> Vec Date: Fri, 13 Nov 2026 11:11:13 +0300 Subject: [PATCH 12/44] fix(text): a mark its letter's face lacks moves the whole cluster to a face with all of it (M5) Fallback looked only at the letter and the new mark, then moved the letter and every earlier mark to that face, so a mark the original face had could land in a face without it and draw as notdef while the missing count stayed zero. The face is now chosen for the whole cluster; when no face has all of it, the new mark comes from a face that has it and the rest stay where they were. Invisible joiners the face doesn't map no longer move the run to another face, which would break joining across a ZWJ. The face choice is a pure function, choose_faces, with regressions for complementary coverage. --- crates/text/src/lib.rs | 74 +++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 27 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 2ca50820..1d07fffb 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -514,6 +514,40 @@ pub fn sanitize(style: &Style) -> Style { } } +/// The face drawing each byte of a paragraph, given how many faces there are and which has which +/// character: the chosen one (0) where it has the character, else the first fallback that does. +/// Spaces and marks stay with what comes before them, so a letter and its harakat are shaped +/// together; a mark its letter's face lacks takes the whole cluster (the letter and every mark +/// after it) to a face that has all of them, if there is one, and otherwise draws from a face +/// that has the mark, leaving the letter and the earlier marks where they were. +fn choose_faces(para: &str, faces: usize, has: impl Fn(usize, char) -> bool) -> Vec { + let mut face_of = vec![0usize; para.len()]; + let mut current = 0; + let mut base = 0; // the byte offset of the last letter + for (i, c) in para.char_indices() { + let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); + if !joins { + current = (0..faces).find(|f| has(*f, c)).unwrap_or(0); + base = i; + } else if needs_glyph(c) && !has(current, c) { + let mark = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM; + let cluster = para.get(base..i + c.len_utf8()).unwrap_or_default(); + if let Some(all) = (0..faces).find(|f| mark && cluster.chars().filter(|ch| needs_glyph(*ch)).all(|ch| has(*f, ch))) { + current = all; + if let Some(bytes) = face_of.get_mut(base..i) { + bytes.fill(all); + } + } else if let Some(f) = (0..faces).find(|f| has(*f, c)) { + current = f; + } + } + if let Some(bytes) = face_of.get_mut(i..i + c.len_utf8()) { + bytes.fill(current); + } + } + face_of +} + /// One shaped glyph: the face it comes from, its id, the byte it starts at in its paragraph, its /// offsets and advance (pixels). struct Glyph { @@ -568,33 +602,7 @@ fn lay_out(faces: &[(&[u8], u32)], text: &str, style: &Style, want_glyphs: bool) let to_char = Arc::new(to_char); let lines_before = lines.len(); let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); - // The face drawing each byte: the chosen one where it has the character, else the first - // fallback that does. Spaces and marks stay with what comes before them, so a letter and - // its harakat are shaped together; a mark its letter's face lacks takes the letter to a - // face that has both, if there is one. - let mut face_of = vec![0usize; para.len()]; - let mut current = 0; - let mut base = (0, '\0'); // the last letter: its byte offset and character - for (i, c) in para.char_indices() { - let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); - if !joins { - current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(0); - base = (i, c); - } else if !has(current, c) { - let mark = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM; - if let Some(both) = (0..fonts.len()).find(|f| mark && has(*f, base.1) && has(*f, c)) { - current = both; - if let Some(bytes) = face_of.get_mut(base.0..i) { - bytes.fill(both); - } - } else if let Some(f) = (0..fonts.len()).find(|f| has(*f, c)) { - current = f; - } - } - if let Some(bytes) = face_of.get_mut(i..i + c.len_utf8()) { - bytes.fill(current); - } - } + let face_of = choose_faces(para, fonts.len(), has); // A run shaped in one direction, split where the face changes; glyphs in visual order. let shape_run = |run: std::ops::Range, rtl: bool| { let mut parts: Vec> = Vec::new(); @@ -881,6 +889,18 @@ mod tests { assert!(boxed(Align::Right).min.x > 280.0); } + #[test] + fn a_mark_takes_its_whole_cluster_to_a_face_with_all_of_it() { + let covers = |sets: &'static [&'static str]| move |f: usize, c: char| sets.get(f).is_some_and(|s| s.contains(c)); + // Face 1 has the letter and the second mark but not the first; face 2 has all three. + assert_eq!(choose_faces("e\u{0301}\u{0323}", 3, covers(&["e\u{0301}", "e\u{0323}", "e\u{0301}\u{0323}"])), vec![2; 5]); + // No face has all three: the letter and its first mark stay together, and the second + // mark comes from a face that has it. + assert_eq!(choose_faces("q\u{0301}\u{0323}", 2, covers(&["q\u{0323}", "q\u{0301}"])), vec![1, 1, 1, 0, 0]); + // An invisible joiner the face doesn't map doesn't move the run to another face. + assert_eq!(choose_faces("ب\u{200D}ب", 2, covers(&["ب", "\u{200D}"])), vec![0; 7]); + } + #[test] fn mixed_directions_read_the_right_way_round() { // Lines are found in reading order: after the last space that fits, or within a word. From 3e5b08d97c86723f66955a6fbd1f08a49657fa39 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Wed, 18 Nov 2026 21:11:31 +0000 Subject: [PATCH 13/44] 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 14/44] 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 15/44] 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 16/44] 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 17/44] 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 18/44] 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 19/44] 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 20/44] 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 21/44] 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 22/44] 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 23/44] 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 24/44] 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 25/44] 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 26/44] 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 27/44] 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 28/44] 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 29/44] 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 30/44] 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 31/44] 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 32/44] 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; } From fcef9937578ccb2d9849ad570b3cff03dbd0e964 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:31:13 -0700 Subject: [PATCH 33/44] perf(geom): a brush stroke's field sampling is bounded, and paint already laid is skipped (M8) --- crates/geom/src/brush.rs | 120 ++++++++++++++++++++++++++++++++++----- 1 file changed, 106 insertions(+), 14 deletions(-) diff --git a/crates/geom/src/brush.rs b/crates/geom/src/brush.rs index 354f8d5e..ada4ba0b 100644 --- a/crates/geom/src/brush.rs +++ b/crates/geom/src/brush.rs @@ -35,6 +35,11 @@ use crate::{Affine, Path, PathCmd, Vec2, fit_curve, trace}; pub const MAX_CELLS: usize = 4_000_000; /// Most samples one stroke may have. pub const MAX_SAMPLES: usize = 100_000; +/// Most cells the stroke's pieces may visit between them while the distance field is sampled +/// (each piece visits the cells of its own bounds). A stroke that would visit more is sampled on +/// a coarser grid, so the time one stroke takes is bounded however long it is and however often +/// it crosses itself (#519): a fast scribble of 60 000 samples visited 190 million cells. +pub const MAX_STAMP_WORK: usize = 1 << 24; /// The tip's size at zero pressure, as a fraction of its full size. pub const MIN_PRESSURE_SIZE: f32 = 0.1; @@ -442,14 +447,7 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin let fine: f64 = if shaping.texture > 0.0 { f64::min(fine, 1.0 / 18.0) } else { fine }; // In stage space the tip's narrow side is `round` radii across. let narrow = if turns { round } else { 1.0 }; - let mut c: f64 = (fmin / 2.5).min(fine) * narrow; - for _ in 0..4 { - let cells = ((hi.0 - lo.0) / c + 2.0 * MARGIN + 2.0) * ((hi.1 - lo.1) / c + 2.0 * MARGIN + 2.0); - if cells <= MAX_CELLS as f64 { - break; - } - c *= (cells / MAX_CELLS as f64).sqrt() * 1.01; - } + let c = cell_size(&q, (lo, hi), (fmin / 2.5).min(fine) * narrow, narrow, dabbed); let origin = (lo.0 - MARGIN * c, lo.1 - MARGIN * c); let w = ((hi.0 - lo.0) / c + 2.0 * MARGIN).ceil() + 1.0; let h = ((hi.1 - lo.1) / c + 2.0 * MARGIN).ceil() + 1.0; @@ -481,9 +479,16 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin }; let scale = if turn.is_some() { round } else { 1.0 }; let (ta, tb) = (to_tip(a), to_tip(b)); + let full = top as f32; for y in y0 as usize..=y1 as usize { let py = origin.1 + (y as f64 + 0.5) * c; - for x in x0 as usize..=x1 as usize { + let Some(row) = field.get_mut(y * w + x0 as usize..=y * w + x1 as usize) else { continue }; + for (x, cell) in (x0 as usize..).zip(row) { + // Deep inside paint already: nothing can raise it (a stroke that goes over + // itself again and again costs a comparison here, not a distance). + if *cell >= full { + continue; + } let px = origin.0 + (x as f64 + 0.5) * c; let tx = to_tip((px, py)); let d = match tip.shape { @@ -491,9 +496,7 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin TipShape::Square => square_dist(tx, ta, ra, tb, rb), } * scale; let v = (0.5 - d / c).clamp(OUTSIDE, top) as f32; - if let Some(cell) = field.get_mut(y * w + x) - && v > *cell - { + if v > *cell { *cell = v; } } @@ -573,6 +576,46 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin out } +/// The grid's cell size for the stroke through `q` (bounds `lo..hi`): `wanted`, or as much +/// larger as keeps the grid within [`MAX_CELLS`] and the sampling within [`MAX_STAMP_WORK`]. +fn cell_size(q: &[(P, f64, f64)], (lo, hi): (P, P), wanted: f64, narrow: f64, dabbed: bool) -> f64 { + let mut c = wanted; + for _ in 0..4 { + let cells = ((hi.0 - lo.0) / c + 2.0 * MARGIN + 2.0) * ((hi.1 - lo.1) / c + 2.0 * MARGIN + 2.0); + if cells <= MAX_CELLS as f64 { + break; + } + c *= (cells / MAX_CELLS as f64).sqrt() * 1.01; + } + for _ in 0..6 { + let work = stamp_work(&thin(q, c * 0.5), c, narrow, dabbed); + if work <= MAX_STAMP_WORK as f64 { + break; + } + c *= (work / MAX_STAMP_WORK as f64).sqrt().max(1.05); + } + c +} + +/// About how many cells of size `c` the pieces of the stroke through `q` visit between them: +/// each piece's own bounds, as the field is sampled (a long segment in pieces of [`PIECE`]). +fn stamp_work(q: &[(P, f64, f64)], c: f64, narrow: f64, dabbed: bool) -> f64 { + let cells = |len: (f64, f64), r: f64| { + let reach = 2.0 * (r.max(c / narrow) + (MARGIN - 1.0) * c); + ((len.0 + reach) / c + 1.0) * ((len.1 + reach) / c + 1.0) + }; + if dabbed || q.len() < 2 { + return q.iter().map(|(_, f, _)| cells((0.0, 0.0), *f)).sum(); + } + q.windows(2) + .map(|pair| { + let &[(a, ra, _), (b, rb, _)] = pair else { return 0.0 }; + let n = (dist(a, b) / PIECE.max(16.0 * c)).ceil().clamp(1.0, 1e6); + n * cells(((a.0 - b.0).abs() / n, (a.1 - b.1).abs() / n), ra.max(rb)) + }) + .sum() +} + /// Most loops one outline keeps (a fine paper grain on a long stroke opens many holes). pub const MAX_LOOPS: usize = 20_000; /// The paper grain's size, in tip radii. @@ -630,7 +673,9 @@ fn v64(p: Vec2) -> P { (f64::from(p.x), f64::from(p.y)) } fn dist(a: P, b: P) -> f64 { - (a.0 - b.0).hypot(a.1 - b.1) + // Not `hypot`: nothing here is near overflow, and this runs for every cell a piece visits. + let (x, y) = (a.0 - b.0, a.1 - b.1); + (x * x + y * y).sqrt() } fn lerp(a: P, b: P, t: f64) -> P { (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t) @@ -689,7 +734,7 @@ fn thin(q: &[(P, f64, f64)], gap: f64) -> Vec<(P, f64, f64)> { /// to the segment) is the minimum. fn round_dist(x: P, a: P, ra: f64, b: P, rb: f64) -> f64 { let d = (b.0 - a.0, b.1 - a.1); - let l = d.0.hypot(d.1); + let l = (d.0 * d.0 + d.1 * d.1).sqrt(); let dr = rb - ra; let ends = || (dist(x, a) - ra).min(dist(x, b) - rb); if l < 1e-12 || dr.abs() >= l { @@ -768,6 +813,53 @@ mod tests { assert!(p.anchors().len() <= 16, "{} anchors", p.anchors().len()); } + /// A fast scribble over a 1280 × 720 stage that crosses itself again and again, with the + /// pressure swelling and fading: `n` samples about 16 units apart. + fn scribble(n: usize) -> Vec { + (0..n) + .map(|i| i as f32 * 0.06) + .map(|t| Sample::new(Vec2::new(640.0 + 420.0 * (t * 0.11).sin() + 170.0 * (t * 0.83).cos(), 360.0 + 200.0 * (t * 0.07).cos() + 130.0 * (t * 0.83).sin()), 0.55 + 0.45 * (t * 0.37).sin())) + .collect() + } + + /// #519: the cells a stroke's pieces visit are bounded, however long the stroke is. A + /// scribble of 60 000 samples would visit several times the budget on the grid its size + /// asks for; the grid it gets keeps it inside, and the paint is still where the hand went. + #[test] + fn a_long_scribble_is_sampled_within_the_work_budget() { + let s = scribble(60_000); + let q: Vec<(P, f64, f64)> = centre_points(&s, 3.0, 0.08, &Shaping::default()).iter().map(|p| ((f64::from(p.at.x) / 5.0, f64::from(p.at.y) / 5.0), f64::from(p.f), 0.0)).collect(); + let (lo, hi) = q.iter().fold(((f64::MAX, f64::MAX), (f64::MIN, f64::MIN)), |(lo, hi), (p, _, _)| ((lo.0.min(p.0), lo.1.min(p.1)), (hi.0.max(p.0), hi.1.max(p.1)))); + let wanted = 0.04; + let grid_only = { + let cells = ((hi.0 - lo.0) / wanted + 8.0) * ((hi.1 - lo.1) / wanted + 8.0); + wanted * (cells / MAX_CELLS as f64).sqrt().max(1.0) + }; + let unbounded = stamp_work(&thin(&q, grid_only * 0.5), grid_only, 1.0, false); + assert!(unbounded > 2.0 * MAX_STAMP_WORK as f64, "the scenario is past the budget without the bound: {unbounded}"); + let c = cell_size(&q, (lo, hi), wanted, 1.0, false); + let work = stamp_work(&thin(&q, c * 0.5), c, 1.0, false); + assert!(work <= MAX_STAMP_WORK as f64 * 1.05, "{work}"); + assert!(c > grid_only && c < 0.5, "coarser, but still well under the tip's radius: {c}"); + // The outline it gives: paint under the hand at every sample, none far from all of them. + let p = outline(&s, &Tip::round(10.0), 3.0, 0.3); + assert!(s.iter().step_by(997).all(|x| p.contains(x.at, &Affine::IDENTITY, FillRule::EvenOdd)), "paint under the hand"); + assert!(!p.contains(Vec2::new(20.0, 20.0), &Affine::IDENTITY, FillRule::EvenOdd), "and none in the corner it never reached"); + } + + #[test] + #[ignore = "a measurement, not a check"] + fn long_stroke_cost() { + for n in [1500, 6000, 20_000, 60_000, 100_000] { + for (name, size) in [("size 10", 10.0), ("size 3", 3.0), ("size 60", 60.0)] { + let s = scribble(n); + let t = std::time::Instant::now(); + let p = outline(&s, &Tip::round(size), 3.0, 0.3); + println!("{n:6} samples, {name}: {:7.1} ms, {} segments", t.elapsed().as_secs_f64() * 1000.0, p.cmds.len()); + } + } + } + #[test] fn a_dab_is_the_tip() { let p = outline(&[Sample::new(Vec2::new(10.0, 10.0), 1.0)], &Tip::round(8.0), 1.0, 0.05); From dcb45b9301f6d473fb74a665144d7feeca9da356 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:31:14 -0700 Subject: [PATCH 34/44] feat(engine): draw.brush takes an outline traced ahead for the same stroke (M8) --- crates/engine/src/brush_tests.rs | 32 +++++++++++ crates/engine/src/cmds_brush.rs | 92 +++++++++++++++++++++++++++----- crates/engine/src/lib.rs | 4 ++ 3 files changed, 115 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/brush_tests.rs b/crates/engine/src/brush_tests.rs index bd7bcc9f..24886ab2 100644 --- a/crates/engine/src/brush_tests.rs +++ b/crates/engine/src/brush_tests.rs @@ -421,3 +421,35 @@ fn crossing_brush_strokes_keep_what_was_drawn() { } } } + +/// ADR 0129: an outline traced ahead (on the editor's other thread) is painted by the +/// `draw.brush` that asks for exactly that stroke, and by no other. Either way it is gone +/// afterwards, so it can never be painted by a later stroke. +#[test] +fn an_outline_traced_ahead_is_taken_by_its_own_stroke_only() { + let stroke = json!({"points": [[100, 100], [220, 130], [300, 90]], "size": 12, "color": "#000000"}); + let other = json!({"points": [[100, 100], [220, 130], [300, 95]], "size": 12, "color": "#000000"}); + // A marker no trace would give: a square far from the stroke. + let marker = anicraft_geom::Path::rect(600.0, 400.0, 50.0, 50.0); + let painted_at = |staged: &Value, painted: &Value| { + let mut s = blank(true); + let ahead = crate::cmds_brush::stroke_request(&s, staged).unwrap().prepare(); + s.staged_stroke = Some(ahead.with_path(marker.clone())); + run(&mut s, "draw.brush", painted.clone()); + assert!(s.staged_stroke.is_none(), "it doesn't linger"); + (top_at(&s, Vec2::new(625.0, 425.0)).is_some(), top_at(&s, Vec2::new(220.0, 130.0)).is_some()) + }; + assert_eq!(painted_at(&stroke, &stroke), (true, false), "its own stroke takes the outline as it is"); + assert_eq!(painted_at(&stroke, &other), (false, true), "another stroke traces its own"); + // Traced ahead or by the command: the same document. + let mut plain = blank(true); + run(&mut plain, "draw.brush", stroke.clone()); + let mut ahead = blank(true); + ahead.staged_stroke = Some(crate::cmds_brush::stroke_request(&ahead, &stroke).unwrap().prepare()); + run(&mut ahead, "draw.brush", stroke.clone()); + assert_eq!(shapes(&plain), shapes(&ahead)); + // A stroke that fails leaves nothing staged either. + plain.staged_stroke = Some(crate::cmds_brush::stroke_request(&plain, &stroke).unwrap().prepare()); + assert!(plain.execute("draw.brush", &json!({"points": []})).is_err()); + assert!(plain.staged_stroke.is_none()); +} diff --git a/crates/engine/src/cmds_brush.rs b/crates/engine/src/cmds_brush.rs index 0dbb2ce7..37d2f530 100644 --- a/crates/engine/src/cmds_brush.rs +++ b/crates/engine/src/cmds_brush.rs @@ -10,7 +10,7 @@ use crate::params::*; use crate::{CommandSpec, EngineError, Result, Session}; use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, MAX_WIDTH_POINTS, Paint, Rgba, Shape, Stroke, WidthPoint, WidthProfile}; use anicraft_geom::planar; -use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tilt, Tip, TipShape, centre_stroke, outline_shaped}; +use anicraft_geom::brush::{MAX_SAMPLES, Sample, Shaping, Tilt, Tip, TipShape, centre_stroke, outline_shaped}; use anicraft_geom::{Affine, FillRule, Path, PathCmd, Vec2}; use serde_json::{Value, json}; use std::sync::Arc; @@ -237,31 +237,97 @@ fn paint_stacks(p: &Paint) -> bool { } } -fn draw_brush(s: &mut Session, p: &Value) -> Result { +/// What a Brush stroke's outline is traced from: the samples (their pressure already through +/// the brush's curve), the tip, the shaping, and how closely the hand and the outline are +/// followed. Tracing is the slow part of a long stroke and depends on nothing else, so the +/// editor does it on another thread and hands the result to `draw.brush` (ADR 0129). +#[derive(Clone, Debug, PartialEq)] +pub struct StrokeRequest { + pts: Vec, + tip: Tip, + shaping: Shaping, + smoothing: f32, + tol: f32, +} + +impl StrokeRequest { + /// The filled outline (`geom::brush::outline_shaped`). Bounded for any stroke: the grid by + /// `MAX_CELLS`, the sampling by `MAX_STAMP_WORK`, the loops by `MAX_LOOPS`. + pub fn trace(&self) -> Path { + outline_shaped(&self.pts, &self.tip, &self.shaping, self.smoothing, self.tol) + } + + /// Traces the outline: what [`Session::staged_stroke`] takes. + pub fn prepare(self) -> PreparedStroke { + let path = self.trace(); + PreparedStroke { request: self, path } + } + + /// How many samples the stroke has. + pub fn samples(&self) -> usize { + self.pts.len() + } +} + +/// A stroke's outline, traced ahead of the command that paints it. +#[derive(Clone, Debug)] +pub struct PreparedStroke { + request: StrokeRequest, + path: Path, +} + +impl PreparedStroke { + /// The same request with another outline, so a test can tell a taken outline from a traced + /// one. + #[cfg(test)] + pub(crate) fn with_path(self, path: Path) -> PreparedStroke { + PreparedStroke { path, ..self } + } +} + +/// The request `draw.brush` with params `p` would trace. An error is the command's own (the +/// same params fail the same way there). +pub fn stroke_request(s: &Session, p: &Value) -> Result { + stroke_inputs(s, p).map(|x| x.0) +} + +/// [`stroke_request`], with the brush it paints with and the opacity its pressure gives it. +fn stroke_inputs(s: &Session, p: &Value) -> Result<(StrokeRequest, BrushPreset, f32)> { let pts = bounded_samples(p)?; let b = brush_param(s, p)?; let tip = b.tip(); - let size = tip.size; - let as_stroke = opt_bool(p, "as_stroke")?.unwrap_or(false); let unit = ranged(p, "unit", 0.001..=1000.0, 1.0)?; - let mode_key = opt_str(p, "mode")?.unwrap_or("normal"); - let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills, behind, selection or inside)")))?; - let color = opt_color(p, "color")?.unwrap_or(if as_stroke { s.style.stroke } else { s.style.fill }); - let color = Rgba { a: color.a * pressure_opacity(&b, &pts), ..color }; - let object = object_param(s, p)?; + let opacity = pressure_opacity(&b, &pts); // Pressure through the curve (ADR 0068) before it sizes the tip. let pts: Vec = pts.iter().map(|x| Sample { pressure: b.size_pressure(x.pressure), ..*x }).collect(); - // Smoothing and accuracy are screen distances, so a stroke looks the same at any zoom: at 50 // the centre line may wander 3.3 screen points from the hand, at 0 a third of a point. // The outline is fitted within a third of a screen point, or a hundredth of the size for // small brushes (so a small dab is still round). - let (smoothing, tol) = (unit * (0.3 + b.smoothing * 0.06), (unit * 0.35).min(size * 0.01)); + let (smoothing, tol) = (unit * (0.3 + b.smoothing * 0.06), (unit * 0.35).min(tip.size * 0.01)); + Ok((StrokeRequest { pts, tip, shaping: b.shaping(), smoothing, tol }, b, opacity)) +} + +fn draw_brush(s: &mut Session, p: &Value) -> Result { + // An outline traced ahead is this stroke's or nobody's: it never waits for a later one. + let staged = s.staged_stroke.take(); + let (request, b, opacity) = stroke_inputs(s, p)?; + let pts = &request.pts; + let (smoothing, tol) = (request.smoothing, request.tol); + let as_stroke = opt_bool(p, "as_stroke")?.unwrap_or(false); + let mode_key = opt_str(p, "mode")?.unwrap_or("normal"); + let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills, behind, selection or inside)")))?; + let color = opt_color(p, "color")?.unwrap_or(if as_stroke { s.style.stroke } else { s.style.fill }); + let color = Rgba { a: color.a * opacity, ..color }; + let object = object_param(s, p)?; if as_stroke { - return paint_stroke(s, &pts, &b, smoothing, tol, color, object); + return paint_stroke(s, pts, &b, smoothing, tol, color, object); } let start = pts.first().map_or(Vec2::ZERO, |x| x.at); - let mut path = outline_shaped(&pts, &tip, &b.shaping(), smoothing, tol); + let mut path = match staged { + Some(ahead) if ahead.request == request => ahead.path, + _ => request.trace(), + }; if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) { return Err(EngineError::Param("the stroke is too small to paint".into())); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index de144ad9..be264557 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -460,6 +460,9 @@ pub struct Session { /// An import the editor prepared on another thread (ADR 0116): `file.import_video` asked /// for the same thing takes it instead of decoding again. Never in the document. pub staged_video: Option, + /// A Brush stroke's outline the editor traced on another thread (ADR 0129): `draw.brush` + /// asked for the same stroke takes it instead of tracing again. Never in the document. + pub staged_stroke: Option, /// Files this session's publishes wrote: publishing again replaces them without asking. pub published: std::collections::BTreeSet, /// The files opened and saved last, and pinned favourites (ADR 0059). They belong to the @@ -598,6 +601,7 @@ impl Session { picture_cache: RefCell::new(None), job: None, staged_video: None, + staged_stroke: None, published: std::collections::BTreeSet::new(), recent: cmds_recent::RecentFiles::default(), brushes: brush_library::BrushLibrary::default(), From 579cd30e58f2d5746f109cdd29f7b14fbacd61dc Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:46:32 -0700 Subject: [PATCH 35/44] perf(shell): a selection's stipple is cut by the artwork in its own rows, not by every span above it (M8) --- src/stage.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/src/stage.rs b/src/stage.rs index 704c8ca8..09f48600 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -765,7 +765,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Drag::BindMarquee { start, cur } => crate::bind_tool::drag_end(app, start, cur, shift, command), Drag::BindPaint { .. } => crate::bind_tool::paint_end(app), Drag::Pencil => crate::pathtools::commit_pencil(app, xf), - Drag::Brush => crate::brushtool::commit(app, xf), + Drag::Brush => crate::brushtool::commit(app, ui.ctx(), xf), Drag::Eraser => crate::erasertool::commit(app, xf), // Raw shapes merge where they landed, in the drag's step (ADR 0051). Drag::MultiMove { .. } | Drag::MultiTransform { .. } => crate::onion::drag_end(app), @@ -820,7 +820,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { Tool::Brush if !panning => { // A click paints a dab. crate::brushtool::start(app, to_v(sp), pressure, now); - crate::brushtool::commit(app, xf); + crate::brushtool::commit(app, ui.ctx(), xf); } Tool::Eraser if !panning => { if app.eraser.faucet { @@ -1383,6 +1383,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { crate::widthtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p))); crate::gradient_tool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning)); crate::shape_envelope::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning)); + // Strokes on their way into the document (ADR 0129), under the one in hand. + crate::ink::draw(app, &painter, xf); crate::brushtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused)); crate::erasertool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused)); // After this frame's edits, so a drag on the path shows where it is now. @@ -2621,16 +2623,33 @@ fn exclude_overlying_artwork(fills: &mut Vec, above: &[anicraft_engine::do /// Remove areas covered by `occluders` from a collection of rectangles. /// Each overlapping rectangle may produce up to four smaller rectangles. +/// +/// Both lists are rows of runs, thousands of each for a long brush stroke, so a span is only +/// compared with the occluders in its own rows: they are looked up by their top edge. Comparing +/// every span with every occluder took seconds a frame on such a stroke (#519). fn subtract_spans(spans: &mut Vec, occluders: &[Rect]) { let mut remaining = Vec::new(); let mut pieces = Vec::new(); let mut next = Vec::new(); + // The occluders by top edge (their order among equals kept), and the tallest of them: one + // that reaches down into a span starts less than that above the span's top. + let mut by_top: Vec = (0..occluders.len()).collect(); + let top_of = |i: usize| occluders.get(i).map_or(f32::INFINITY, |o| o.top()); + by_top.sort_by(|&a, &b| top_of(a).total_cmp(&top_of(b))); + let tallest = occluders.iter().fold(0.0f32, |h, o| h.max(o.height())); + let mut rows: Vec = Vec::new(); for span in spans.drain(..) { pieces.clear(); pieces.push(span); + let from = by_top.partition_point(|&i| top_of(i) <= span.top() - tallest); + let to = by_top.partition_point(|&i| top_of(i) < span.bottom()); + rows.clear(); + rows.extend(by_top.get(from..to).unwrap_or(&[])); + // In the order they were given, so the pieces come out as they always did. + rows.sort_unstable(); - for &occluder in occluders { + for &occluder in rows.iter().filter_map(|&i| occluders.get(i)) { // Skip occluders that cannot touch the original span. let overlap = span.intersect(occluder); if overlap.width() <= 0.0 || overlap.height() <= 0.0 { @@ -2774,6 +2793,34 @@ mod pattern_tests { } } + /// #519: occluders are looked up by row instead of each being tried against every span. + /// What is left is the same as trying them all: every point of a span is kept exactly when + /// no occluder covers it, whatever the occluders' heights and order. + #[test] + fn spans_lose_exactly_what_the_occluders_in_their_rows_cover() { + // A fixed scatter: rows of runs, and occluders one row to many rows tall, unsorted. + let n = |i: u32, k: u32, m: u32| (i.wrapping_mul(2_654_435_761).wrapping_add(k.wrapping_mul(40_503)) >> 7) % m; + let spans: Vec = (0..300).map(|i| Rect::from_min_size(pos2(n(i, 1, 180) as f32, (n(i, 2, 50) * 4) as f32), vec2(4.0 + n(i, 3, 40) as f32, 4.0))).collect(); + let occluders: Vec = (0..400).map(|i| Rect::from_min_size(pos2(n(i, 4, 190) as f32 + 0.5, n(i, 5, 200) as f32 + 0.25), vec2(1.0 + n(i, 6, 25) as f32, if i % 7 == 0 { 30.0 } else { 1.0 }))).collect(); + let mut left = spans.clone(); + subtract_spans(&mut left, &occluders); + let inside = |rects: &[Rect], p: Pos2| rects.iter().any(|r| r.contains(p)); + let mut kept = 0; + for y in 0..420 { + for x in 0..460 { + let p = pos2(x as f32 * 0.5 + 0.13, y as f32 * 0.5 + 0.11); + let want = inside(&spans, p) && !inside(&occluders, p); + assert_eq!(inside(&left, p), want, "at {p:?}"); + kept += usize::from(want); + } + } + assert!(kept > 1000, "the scatter leaves something to compare: {kept}"); + // Nothing to take away leaves the spans as they were. + let mut same = spans.clone(); + subtract_spans(&mut same, &[]); + assert_eq!(same, spans); + } + /// A thin opaque foreground shape must hide the selection /// backing of artwork behind it, even between stipple rows. #[test] From 361decf8cc464e012a739b4427eefb1138d7f3a1 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:46:32 -0700 Subject: [PATCH 36/44] feat(shell): a long Brush stroke's outline is traced off the window's thread, the stroke shown as drawn until it is painted (M8) --- src/app.rs | 10 ++ src/brushtool.rs | 51 +++++--- src/ink.rs | 156 +++++++++++++++++++++++ src/long_stroke_tests.rs | 262 +++++++++++++++++++++++++++++++++++++++ src/main.rs | 3 + src/tabs.rs | 2 + src/updates.rs | 1 + 7 files changed, 467 insertions(+), 18 deletions(-) create mode 100644 src/ink.rs create mode 100644 src/long_stroke_tests.rs diff --git a/src/app.rs b/src/app.rs index 687524a8..e6e24e9f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -474,6 +474,9 @@ pub struct App { /// A filter preset being named in Properties (ADR 0091). pub filter_naming: crate::panels::FilterNaming, pub brush_samples: Vec<(anicraft_engine::geom::Vec2, Option)>, + /// Brush strokes drawn but not yet painted: their outlines are being traced on another + /// thread (ADR 0129). Oldest first. + pub ink: Vec, pub pen_pressure: Option, /// Whether a pointer event has carried a pen's tilt this session (ADR 0093). Until one has, /// the brushes' Tilt options stay hidden: they would do nothing. @@ -856,6 +859,7 @@ impl App { brush_lib: crate::brush_panel::BrushLibraryView::default(), filter_naming: Default::default(), brush_samples: Vec::new(), + ink: Vec::new(), pen_pressure: None, pen_tilt_seen: false, eraser: crate::erasertool::EraserOptions::default(), @@ -1031,6 +1035,9 @@ impl App { } pub fn run(&mut self, id: &str, params: Value) -> Option { + // Strokes still on their way in are painted first: commands run in the order they + // were asked for (ADR 0129). + crate::ink::flush(self); let result = self.s.execute(id, ¶ms); if platform::WEB && id.starts_with("file.") { // In a browser, what a save or an export wrote is in memory: hand it to the @@ -4759,6 +4766,9 @@ impl App { } } self.handle_screenshot(&ctx); + // Brush strokes whose outlines are traced go into the document, before this frame's + // input can edit it (ADR 0129). + crate::ink::frame(self, &ctx); // An assistant's edits (ADR 0104), before anything draws: they show in this frame. #[cfg(not(target_arch = "wasm32"))] crate::remote::poll(self, &ctx); diff --git a/src/brushtool.rs b/src/brushtool.rs index f0ef6b3a..3ed049d5 100644 --- a/src/brushtool.rs +++ b/src/brushtool.rs @@ -323,7 +323,9 @@ pub fn sample(app: &mut App, p: Vec2, pressure: Option, xf: Xf, now: f64) { } /// Sends the stroke (one command, one undo step). Smoothing and accuracy follow the screen. -pub fn commit(app: &mut App, xf: Xf) { +/// A long Brush stroke's outline is traced on another thread first, the stroke staying on the +/// stage as drawn until it is painted (ADR 0129, `crate::ink`). +pub fn commit(app: &mut App, ctx: &egui::Context, xf: Xf) { let samples = std::mem::take(&mut app.brush_samples); if samples.is_empty() { return; @@ -344,12 +346,19 @@ pub fn commit(app: &mut App, xf: Xf) { } return; } + if !crate::ink::defer(app, ctx, &samples, ¶ms, o.mode) { + paint(app, params, o.mode); + } +} + +/// Paints a Brush stroke: `draw.brush` with `params`, and what to say when nothing was painted. +pub fn paint(app: &mut App, params: serde_json::Value, mode: PaintMode) { // Paint Selection keeps the selection it paints in, for the next stroke (ADR 0080). - let v = if o.mode == PaintMode::Selection { app.run("draw.brush", params) } else { app.draw("draw.brush", params) }; + let v = if mode == PaintMode::Selection { app.run("draw.brush", params) } else { app.draw("draw.brush", params) }; if let Some(v) = v && v["elements"].as_array().is_some_and(Vec::is_empty) { - match o.mode { + match mode { PaintMode::Selection => app.status_ok(tr!("Nothing painted: Paint Selection paints only inside the selected fills. Select them with the Selection tool first.")), PaintMode::Inside => app.status_ok(tr!("Nothing painted: Paint Inside paints only inside the fill where the stroke starts.")), _ => app.status_ok(tr!("Nothing to paint behind there: Paint Behind only paints empty areas.")), @@ -394,7 +403,7 @@ const MASK_MAX: usize = 2048; /// The alpha the finished stroke will have: the fill (or the stroke colour) times, when /// pressure drives opacity, the average mapped pressure so far. That average is what the /// command stores for the whole stroke (ADR 0068). -fn intended_alpha(o: &BrushOptions, paint_a: f32, samples: &[(Vec2, Option)]) -> f32 { +pub(crate) fn intended_alpha(o: &BrushOptions, paint_a: f32, samples: &[(Vec2, Option)]) -> f32 { let paint_a = if paint_a.is_finite() { paint_a.clamp(0.0, 1.0) } else { 1.0 }; if !o.pressure_opacity || samples.is_empty() { return paint_a; @@ -430,15 +439,7 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option= 255.0 { - let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint }); - draw_sweep(painter, xf, &tip, &app.brush_samples, color); - } else { - draw_sweep_alpha(painter, xf, &tip, &app.brush_samples, paint, alpha); - } + draw_ink(painter, xf, &tip, &app.brush_samples, paint, alpha, 0); } if let Some(h) = hover { // The tip's size and shape at the pointer, as Animate shows it. @@ -446,6 +447,19 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option)], paint: anicraft_engine::doc::Rgba, alpha: f32, slot: usize) { + if (alpha * 255.0).round() >= 255.0 { + let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint }); + draw_sweep(painter, xf, tip, samples, color); + } else { + draw_sweep_alpha(painter, xf, tip, samples, paint, alpha, slot); + } +} + /// The tip swept along `samples` (shared with the Eraser, ADR 0034), filled with `color`. pub fn draw_sweep(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option)], color: egui::Color32) { if samples.is_empty() { @@ -502,7 +516,7 @@ fn sweep_hulls(xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option)]) -> Vec /// The same sweep as one coverage image, tinted at `alpha`. Overlapping pieces keep the /// greater coverage, so a crossing in one stroke stays one alpha. -fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option)], paint: anicraft_engine::doc::Rgba, alpha: f32) { +fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option)], paint: anicraft_engine::doc::Rgba, alpha: f32, slot: usize) { if alpha <= 0.0 { return; } @@ -540,14 +554,15 @@ fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: pixels.push(egui::Color32::from_white_alpha(a)); } let image = egui::ColorImage::new([w, h], pixels); - let tex = sweep_texture(painter.ctx(), image); + let tex = sweep_texture(painter.ctx(), image, slot); let tint = to_color32(anicraft_engine::doc::Rgba { a: alpha, ..paint }); painter.image(tex.id(), view, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint); } -/// One reused texture for the live wash, so a stroke does not leak a texture every frame. -fn sweep_texture(ctx: &egui::Context, image: egui::ColorImage) -> egui::TextureHandle { - let id = egui::Id::new("anicraft.brush.sweep"); +/// One reused texture for the live wash, so a stroke does not leak a texture every frame (and +/// one for each stroke that waits to be painted: a few at most). +fn sweep_texture(ctx: &egui::Context, image: egui::ColorImage, slot: usize) -> egui::TextureHandle { + let id = if slot == 0 { egui::Id::new("anicraft.brush.sweep") } else { egui::Id::new(("anicraft.brush.sweep", slot)) }; let options = egui::TextureOptions::LINEAR; if let Some(mut tex) = ctx.data(|d| d.get_temp::(id)) { tex.set(image, options); diff --git a/src/ink.rs b/src/ink.rs new file mode 100644 index 00000000..988cc49e --- /dev/null +++ b/src/ink.rs @@ -0,0 +1,156 @@ +//! Brush strokes whose outline is still being traced (ADR 0129, issue #519). +//! +//! Tracing a long stroke's outline takes longer than a frame (a tenth of a second and more for +//! a stroke drawn over many seconds), and it depends on nothing but the stroke. So when the +//! pointer lifts on a long stroke, the trace runs on another thread; the stroke stays on the +//! stage as it was drawn, and the next stroke can start at once. When the trace is done the +//! stroke is painted by the same `draw.brush` as ever, which takes the traced outline +//! (`Session::staged_stroke`) instead of tracing it again. +//! +//! Strokes are painted in the order they were drawn, and nothing else may come between a stroke +//! and its paint: before any other edit (a key, a click anywhere but a brush on the stage, a +//! command from an assistant, playback, another document), the waiting strokes are finished +//! first, on this thread ([`flush`]). The wait is bounded, since a trace is +//! (`geom::brush::MAX_STAMP_WORK`). + +use crate::app::{App, Tool}; +use crate::brushtool::{self, BrushOptions}; +use crate::pathtools::Xf; +use anicraft_engine::cmds_brush::{PaintMode, PreparedStroke, stroke_request}; +use anicraft_engine::doc::Rgba; +use anicraft_engine::geom::Vec2; +use serde_json::Value; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; + +/// Strokes with fewer samples are traced where they are: they take less than a frame. +pub const DEFER_SAMPLES: usize = 400; +/// Most strokes waiting at once; one more waits for the first. +const MAX_WAITING: usize = 8; + +/// A stroke on its way into the document. +pub struct Pending { + /// The stroke as it was drawn, for the stage. + samples: Vec<(Vec2, Option)>, + tip: BrushOptions, + paint: Rgba, + alpha: f32, + /// What `draw.brush` is run with. + params: Value, + mode: PaintMode, + done: Receiver, +} + +/// Takes a Brush stroke whose trace should not hold the window up: `false` when it is short +/// enough to paint right away (nothing waiting before it), or can't be handed over (the web +/// build has one thread; a stroke the command would refuse is left for it to refuse). +pub fn defer(app: &mut App, ctx: &egui::Context, samples: &[(Vec2, Option)], params: &Value, mode: PaintMode) -> bool { + if crate::platform::WEB || (app.ink.is_empty() && samples.len() < DEFER_SAMPLES) { + return false; + } + let Ok(request) = stroke_request(&app.s, params) else { return false }; + if app.ink.len() >= MAX_WAITING { + flush(app); + } + let (tx, done) = channel(); + let wake = ctx.clone(); + let started = std::thread::Builder::new().name("anicraft-ink".into()).spawn(move || { + let _ = tx.send(request.prepare()); + wake.request_repaint(); + }); + if started.is_err() { + return false; + } + let tip = *brushtool::options(app); + let paint = app.s.style.fill; + let alpha = brushtool::intended_alpha(&tip, paint.a, samples); + app.ink.push(Pending { samples: samples.to_vec(), tip, paint, alpha, params: params.clone(), mode, done }); + true +} + +/// Paints the waiting strokes whose traces are done, oldest first, stopping at the first that +/// is not. +pub fn poll(app: &mut App) { + if app.ink.is_empty() { + return; + } + // Out of the app while they are painted, so painting one never waits on the others. + let mut waiting = std::mem::take(&mut app.ink).into_iter(); + let mut rest = Vec::new(); + for p in waiting.by_ref() { + match p.done.try_recv() { + Ok(traced) => paint(app, &p, Some(traced)), + // The thread is gone without an outline: the command traces it. + Err(TryRecvError::Disconnected) => paint(app, &p, None), + Err(TryRecvError::Empty) => { + rest.push(p); + break; + } + } + } + rest.extend(waiting); + app.ink = rest; +} + +/// Paints every waiting stroke now, waiting for its trace: before anything else edits. +pub fn flush(app: &mut App) { + for p in std::mem::take(&mut app.ink) { + let traced = p.done.recv().ok(); + paint(app, &p, traced); + } +} + +fn paint(app: &mut App, p: &Pending, traced: Option) { + app.s.staged_stroke = traced; + brushtool::paint(app, p.params.clone(), p.mode); + app.s.staged_stroke = None; +} + +/// Whether what this frame brings may go ahead of the waiting strokes: looking around and +/// painting more. Anything that could edit (a key, text, a click that is not a brush on the +/// stage, a dropped file) may not. +fn only_painting(app: &App, ctx: &egui::Context) -> bool { + if app.playing || app.modal_open() || app.palette.is_some() { + return false; + } + // The presses this frame, unless something else came with them (the context is not asked + // about its layers while its input is being read). + let presses: Option> = ctx.input(|i| { + if !i.raw.dropped_files.is_empty() { + return None; + } + let mut presses = Vec::new(); + for e in &i.raw.events { + match e { + egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone | egui::Event::Touch { .. } | egui::Event::MouseWheel { .. } | egui::Event::Zoom(_) | egui::Event::WindowFocused(_) => {} + egui::Event::PointerButton { pressed: false, .. } => {} + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => presses.push(*pos), + _ => return None, + } + } + Some(presses) + }); + let Some(presses) = presses else { return false }; + // A press paints when the Brush is in hand and it lands on the stage itself. + let canvas = app.stage_cache.canvas; + presses.iter().all(|pos| app.tool == Tool::Brush && canvas.contains(*pos) && ctx.layer_id_at(*pos).is_none_or(|l| l.order == egui::Order::Background)) +} + +/// At the start of a frame: strokes whose traces are done are painted; if this frame's input +/// could edit, all of them are, first. +pub fn frame(app: &mut App, ctx: &egui::Context) { + if app.ink.is_empty() { + return; + } + if only_painting(app, ctx) { + poll(app); + } else { + flush(app); + } +} + +/// The waiting strokes on the stage, as they were drawn. +pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) { + for (slot, p) in app.ink.iter().enumerate() { + brushtool::draw_ink(painter, xf, &p.tip, &p.samples, p.paint, p.alpha, slot + 1); + } +} diff --git a/src/long_stroke_tests.rs b/src/long_stroke_tests.rs new file mode 100644 index 00000000..6c76b8a1 --- /dev/null +++ b/src/long_stroke_tests.rs @@ -0,0 +1,262 @@ +//! A long Brush stroke keeps the window answering (issue #519, P-003). + +use crate::app::{App, Tool}; +use anicraft_engine::geom::Vec2; +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2}; +use serde_json::json; +use std::time::Instant; + +/// The app on a document, a few frames in, with its clock and the worst frame so far. +struct Rig { + ctx: egui::Context, + app: App, + t: f64, + worst: (f64, String), + log: bool, +} + +impl Rig { + fn new(doc: anicraft_engine::doc::Document) -> Rig { + let ctx = egui::Context::default(); + let app = App::with_context(&ctx, anicraft_engine::Session::new(doc), Some(std::path::PathBuf::from("unused.png"))); + let mut rig = Rig { ctx, app, t: 0.0, worst: (0.0, String::new()), log: false }; + for _ in 0..3 { + rig.frame("start", Vec::new()); + } + rig.worst = (0.0, String::new()); + rig + } + + fn frame(&mut self, what: &str, events: Vec) -> f64 { + self.t += 0.05; + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), time: Some(self.t), events, ..Default::default() }; + let t = Instant::now(); + let mut out = self.ctx.run_ui(input, |ui| self.app.frame(ui)); + out.textures_delta.clear(); + let ms = t.elapsed().as_secs_f64() * 1000.0; + if self.log { + println!("{ms:9.1} ms {what}"); + } + if ms > self.worst.0 { + self.worst = (ms, what.to_string()); + } + ms + } + + /// Where stage point `p` is on screen. + fn at(&self, p: Vec2) -> Pos2 { + let app = &self.app; + let size = vec2(app.s.doc.stage.width as f32, app.s.doc.stage.height as f32); + let origin = app.stage_cache.canvas.center() + app.view.pan - size * app.view.zoom * 0.5; + origin + vec2(p.x, p.y) * app.view.zoom + } + + fn button(pos: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE } + } + + fn click(&mut self, what: &str, p: Vec2) { + let sp = self.at(p); + self.frame(&format!("{what}: move"), vec![Event::PointerMoved(sp)]); + self.frame(&format!("{what}: press"), vec![Rig::button(sp, true)]); + self.frame(&format!("{what}: release"), vec![Rig::button(sp, false)]); + self.frame(&format!("{what}: after"), Vec::new()); + } + + fn drag(&mut self, what: &str, from: Vec2, to: Vec2) { + let (a, b) = (self.at(from), self.at(to)); + self.frame(&format!("{what}: move"), vec![Event::PointerMoved(a)]); + self.frame(&format!("{what}: press"), vec![Rig::button(a, true)]); + for i in 1..=4 { + self.frame(&format!("{what}: drag"), vec![Event::PointerMoved(a + (b - a) * (i as f32 / 4.0))]); + } + self.frame(&format!("{what}: release"), vec![Rig::button(b, false)]); + for _ in 0..2 { + self.frame(&format!("{what}: after"), Vec::new()); + } + } + + /// A stage point on the ink, and one in a gap inside the drawing's bounds. + fn ink_and_gap(&self) -> (Vec2, Vec2) { + let b = self.app.s.display_list().items.iter().fold(anicraft_engine::geom::Rect::EMPTY, |r, i| r.union(&i.path.bounds().transformed(&i.transform))); + let grid = |hit: bool| { + (0..4000) + .map(|i| Vec2::new((i * 37 % 1280) as f32, (i * 53 % 720) as f32)) + .find(|p| b.inflate(-20.0).contains(*p) && (0..9).all(|k| self.app.s.hit_test(*p + Vec2::new((k % 3 - 1) as f32 * 2.0, (k / 3 - 1) as f32 * 2.0), 0.0).is_some() == hit)) + .unwrap_or_default() + }; + (grid(true), grid(false)) + } +} + +/// A fast scribble across the stage, as stage points with pressure: `n` samples. +fn scribble(n: usize) -> Vec<(Vec2, Option)> { + (0..n).map(|i| i as f32 * 0.06).map(|t| (Vec2::new(640.0 + 420.0 * (t * 0.11).sin() + 170.0 * (t * 0.83).cos(), 360.0 + 200.0 * (t * 0.07).cos() + 130.0 * (t * 0.83).sin()), Some(0.55 + 0.45 * (t * 0.37).sin()))).collect() +} + +impl Rig { + /// Draws `samples` with the Brush: a press, the samples, and the release. + fn brush(&mut self, samples: Vec<(Vec2, Option)>) { + self.app.tool = Tool::Brush; + let (first, last) = (samples.first().map_or(Vec2::ZERO, |s| s.0), samples.last().map_or(Vec2::ZERO, |s| s.0)); + let a = self.at(first); + self.frame("brush: move", vec![Event::PointerMoved(a)]); + self.frame("brush: press", vec![Rig::button(a, true)]); + self.frame("brush: drag", vec![Event::PointerMoved(a + vec2(20.0, 12.0))]); + self.frame("brush: drag", vec![Event::PointerMoved(a + vec2(40.0, 24.0))]); + assert_eq!(self.app.drag, crate::app::Drag::Brush, "the press began a stroke"); + self.app.brush_samples = samples; + let b = self.at(last); + self.frame("brush: release", vec![Rig::button(b, false)]); + } + + /// Frames until no stroke waits (the trace is on another thread), or a long time has passed. + fn until_painted(&mut self) { + let started = Instant::now(); + while !self.app.ink.is_empty() && started.elapsed().as_secs() < 120 { + std::thread::sleep(std::time::Duration::from_millis(2)); + self.frame("waiting", Vec::new()); + } + } + + fn shapes(&self) -> usize { + self.app.s.visible_elements().len() + } +} + +fn blank() -> Rig { + let mut rig = Rig::new(anicraft_engine::doc::Document::default()); + rig.app.s.style.object_drawing = true; + rig +} + +/// ADR 0129: when the pointer lifts on a long stroke, the frame does not wait for its outline. +/// The stroke stays on the stage as drawn, and goes into the document, as one undo step, once +/// its outline is traced. +#[test] +fn a_long_stroke_is_painted_after_the_pointer_lifts_without_holding_the_frame() { + let mut rig = blank(); + let undo_before = rig.app.s.history().undo_len(); + rig.brush(scribble(3000)); + assert_eq!(rig.app.ink.len(), 1, "the stroke waits for its outline"); + assert_eq!(rig.app.drag, crate::app::Drag::None); + // It is still drawn: the stage paints its sweep, piece by piece. + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), time: Some(rig.t + 0.01), ..Default::default() }; + let xf = crate::pathtools::Xf { origin: rig.at(Vec2::ZERO), zoom: rig.app.view.zoom }; + let mut out = rig.ctx.run_ui(input, |ui| crate::ink::draw(&rig.app, ui.painter(), xf)); + out.textures_delta.clear(); + assert!(out.shapes.len() > 100, "{} pieces", out.shapes.len()); + rig.until_painted(); + assert_eq!(rig.shapes(), 1, "painted"); + assert_eq!(rig.app.s.history().undo_len(), undo_before + 1, "one undo step"); + // A short stroke never waits. + rig.brush(scribble(40)); + assert!(rig.app.ink.is_empty()); + assert_eq!(rig.shapes(), 2); +} + +/// Nothing comes between a stroke and its paint: an edit asked for while it waits finds it in +/// the document already, strokes are painted in the order they were drawn, and a key press +/// (undo, say) acts on the stroke, not on what was there before it. +#[test] +fn edits_wait_for_the_strokes_drawn_before_them() { + let mut rig = blank(); + rig.brush(scribble(3000)); + rig.brush(scribble(60)); + assert_eq!(rig.app.ink.len(), 2, "a short stroke queues behind a waiting one"); + // A command: both strokes are in before it runs, the long one first (under the short one). + rig.app.run("edit.select_all", json!({})); + assert!(rig.app.ink.is_empty()); + assert_eq!(rig.app.s.selection.len(), 2); + let widths: Vec = rig.app.s.visible_elements().iter().map(|e| rig.app.s.element_bounds(e.id).width()).collect(); + assert!(widths.first() > widths.last(), "drawn first, painted first (the long one is under the short one): {widths:?}"); + // A key: the waiting stroke is painted before the key is handled. + let mut rig = blank(); + rig.brush(scribble(3000)); + assert_eq!(rig.app.ink.len(), 1); + rig.frame("a key", vec![Event::Key { key: egui::Key::F13, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + assert!(rig.app.ink.is_empty()); + assert_eq!(rig.shapes(), 1); + // Leaving the document: it takes its strokes with it. + let mut rig = blank(); + rig.brush(scribble(3000)); + crate::ink::flush(&mut rig.app); + assert_eq!(rig.shapes(), 1); +} + +/// The reporter's steps and every tool's gesture on the reporter's file +/// (`ANICRAFT_STROKE_FILE`), each from a fresh window: the worst frame of each. +#[test] +#[ignore = "a measurement, not a check"] +fn long_stroke_frame_cost() { + let Ok(file) = std::env::var("ANICRAFT_STROKE_FILE") else { return }; + let doc = anicraft_engine::format::load(std::path::Path::new(&file)).expect("the file loads"); + let log = std::env::var("ANICRAFT_STROKE_LOG").is_ok(); + type Scenario = (&'static str, fn(&mut Rig, Vec2, Vec2)); + let scenarios: [Scenario; 12] = [ + ("move, then click a gap", |r, ink, gap| { + r.app.tool = Tool::Select; + r.drag("move", ink, ink + Vec2::new(40.0, 24.0)); + r.click("deselect", gap + Vec2::new(40.0, 24.0)); + }), + ("click a gap", |r, _, gap| { + r.app.tool = Tool::Select; + r.click("gap", gap); + }), + ("marquee over a part", |r, _, gap| { + r.app.tool = Tool::Select; + r.drag("marquee", gap, gap + Vec2::new(260.0, 180.0)); + r.click("deselect", gap); + }), + ("double-click", |r, ink, _| { + r.app.tool = Tool::Select; + r.click("first", ink); + r.click("second", ink); + }), + ("select all, Free Transform", |r, ink, _| { + r.app.tool = Tool::Transform; + r.app.run("edit.select_all", json!({})); + r.frame("selected", Vec::new()); + r.drag("move", ink, ink + Vec2::new(30.0, 10.0)); + }), + ("Subselection click", |r, ink, _| { + r.app.tool = Tool::Subselect; + r.click("ink", ink); + r.frame("shown", Vec::new()); + }), + ("Paint Bucket in a gap", |r, _, gap| { + r.app.tool = Tool::PaintBucket; + r.click("gap", gap); + }), + ("Paint Bucket on the ink", |r, ink, _| { + r.app.tool = Tool::PaintBucket; + r.click("ink", ink); + }), + ("Eraser across", |r, ink, _| { + r.app.tool = Tool::Eraser; + r.drag("erase", ink + Vec2::new(-200.0, -80.0), ink + Vec2::new(200.0, 80.0)); + }), + ("Brush across", |r, ink, _| { + r.app.tool = Tool::Brush; + r.drag("paint", ink + Vec2::new(-200.0, 80.0), ink + Vec2::new(200.0, -80.0)); + }), + ("Pencil across", |r, ink, _| { + r.app.tool = Tool::Pencil; + r.drag("draw", ink + Vec2::new(-200.0, 60.0), ink + Vec2::new(200.0, -60.0)); + }), + ("Rectangle over", |r, ink, _| { + r.app.tool = Tool::Rect; + r.drag("draw", ink + Vec2::new(-100.0, -60.0), ink + Vec2::new(100.0, 60.0)); + r.app.tool = Tool::Select; + r.frame("select tool", Vec::new()); + }), + ]; + for (name, run) in scenarios { + let mut rig = Rig::new(doc.clone()); + rig.log = log; + let (ink, gap) = rig.ink_and_gap(); + let t = Instant::now(); + run(&mut rig, ink, gap); + println!("{:9.1} ms worst ({}), {:8.1} ms in all, {} elements <- {name}", rig.worst.0, rig.worst.1, t.elapsed().as_secs_f64() * 1000.0, rig.app.s.visible_elements().len()); + } +} diff --git a/src/main.rs b/src/main.rs index 3694fb48..119d22a5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -525,4 +525,7 @@ mod parenting_ui_tests; #[cfg(test)] mod tilt_ui_tests; #[cfg(test)] +mod long_stroke_tests; +mod ink; +#[cfg(test)] mod zoom_tests; diff --git a/src/tabs.rs b/src/tabs.rs index 9986017f..1b615bb6 100644 --- a/src/tabs.rs +++ b/src/tabs.rs @@ -272,6 +272,8 @@ fn busy(app: &App) -> Option<&'static str> { /// Finishes what is in progress on the shown document, before it is put aside or closed: text /// being typed and a pen path are kept, playback stops, an open drag ends its undo step. fn settle(app: &mut App) { + // Brush strokes on their way into this document (ADR 0129). + crate::ink::flush(app); if app.playing { app.toggle_play(); } diff --git a/src/updates.rs b/src/updates.rs index 5c06df8a..4d449999 100644 --- a/src/updates.rs +++ b/src/updates.rs @@ -25,6 +25,7 @@ pub(crate) fn safe_to_install(app: &crate::app::App) -> bool { && app.pen.is_none() && app.pencil.is_empty() && app.brush_samples.is_empty() + && app.ink.is_empty() && app.raw_touched.is_empty() && app.drag == crate::app::Drag::None && app.motion_drag.is_none() From bd127b811e3248a8d5257ebbd054e3b2942fed3e Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:46:32 -0700 Subject: [PATCH 37/44] feat(cli): bench --stroke measures a long Brush stroke, and --stroke-file a document's artwork (M8) --- crates/cli/src/bench_stroke.rs | 101 +++++++++++++++++++++++++++++++++ crates/cli/src/lib.rs | 4 ++ 2 files changed, 105 insertions(+) create mode 100644 crates/cli/src/bench_stroke.rs diff --git a/crates/cli/src/bench_stroke.rs b/crates/cli/src/bench_stroke.rs new file mode 100644 index 00000000..c2b460d7 --- /dev/null +++ b/crates/cli/src/bench_stroke.rs @@ -0,0 +1,101 @@ +//! `bench --stroke`: what one long, fast, pressured Brush stroke costs (issue #519). The stroke +//! is painted, picked, moved, floated and deselected (which merges it into the drawing, ADR +//! 0122), and each step is timed. `--stroke-file` times the same steps on the artwork of a +//! document instead, so a reported file can be measured as it is. + +use crate::{Args, avg_ms, open_session, round}; +use anicraft_engine::Session; +use serde_json::{Value, json}; +use std::time::Instant; + +/// Samples of the default scenario: about 50 seconds of drawing at a tablet's 120 reports a +/// second. +pub const DEFAULT_SAMPLES: u32 = 6000; +/// Most samples the scenario takes (the command's own limit is `geom::brush::MAX_SAMPLES`). +const MAX_SAMPLES: u32 = 100_000; + +/// A fast scribble over a 1280 × 720 stage: loops that drift across it and cross themselves +/// again and again, with the pressure swelling and fading. The same for a given `n`. +pub fn scribble(n: u32) -> Vec<[f32; 3]> { + let n = n.clamp(2, MAX_SAMPLES); + (0..n) + .map(|i| { + // About 16 stage units between samples: a fast hand. + let t = i as f32 * 0.06; + let x = 640.0 + 420.0 * (t * 0.11).sin() + 170.0 * (t * 0.83).cos(); + let y = 360.0 + 200.0 * (t * 0.07).cos() + 130.0 * (t * 0.83).sin(); + [x, y, 0.55 + 0.45 * (t * 0.37).sin()] + }) + .collect() +} + +fn ms(t: Instant) -> f64 { + round(t.elapsed().as_secs_f64() * 1000.0) +} + +/// Curve and line segments of every shape on the playhead's frame. +fn segments(s: &Session) -> usize { + s.display_list().items.iter().map(|i| i.path.cmds.len()).sum() +} + +pub fn bench_stroke(a: &Args) -> Result { + let file = a.flag("stroke-file"); + let samples = match a.flag("stroke") { + Some("yes" | "true") | None => DEFAULT_SAMPLES, + Some(v) => v.parse::().map_err(|_| "--stroke takes a number of samples (or yes)".to_string())?.clamp(2, MAX_SAMPLES), + }; + let mut out = json!({"build": if cfg!(debug_assertions) { "debug (use --release for real numbers)" } else { "release" }}); + let mut s = match file { + Some(p) => { + out["file"] = json!(p); + open_session(Some(p))? + } + None => { + let mut s = Session::default(); + let _ = s.execute("draw.object_drawing", &json!({"on": false})); + let t = Instant::now(); + let v = s.execute("draw.brush", &json!({"points": scribble(samples), "size": 10, "color": "#000000", "object": false})).map_err(|e| e.to_string())?; + out["samples"] = json!(samples); + out["draw_brush_ms"] = json!(ms(t)); + out["pieces"] = json!(v["elements"].as_array().map_or(0, Vec::len)); + out["merged"] = v["merged"].clone(); + s + } + }; + out["segments"] = json!(segments(&s)); + out["elements"] = json!(s.visible_elements().len()); + + let doc = s.doc.clone(); + let frame = s.frame; + out["evaluate_ms"] = json!(round(avg_ms(5, |_| { + let _ = anicraft_doc::evaluate(&doc, frame); + }))); + let view = anicraft_render::View::stage(&doc, 1.0); + let dl = anicraft_doc::evaluate(&doc, frame); + out["render_ms"] = json!(round(avg_ms(3, |_| { + let _ = anicraft_render::render(&dl, &view); + }))); + out["hit_test_us"] = json!(round( + avg_ms(200, |i| { + let _ = s.hit_test(anicraft_geom::Vec2::new((i * 37 % 1280) as f32, (i * 53 % 720) as f32), 2.0); + }) * 1000.0 + )); + + // The reporter's steps: select it, move it, let go of the mouse (it floats), deselect (it + // merges into the drawing). + let mut step = |s: &mut Session, key: &str, id: &str, p: Value| -> Result { + let t = Instant::now(); + let v = s.execute(id, &p).map_err(|e| format!("{id}: {e}"))?; + out[key] = json!(ms(t)); + Ok(v) + }; + step(&mut s, "select_all_ms", "edit.select_all", json!({}))?; + step(&mut s, "move_ms", "element.translate", json!({"dx": 24, "dy": 16}))?; + step(&mut s, "float_ms", "draw.float", json!({}))?; + step(&mut s, "deselect_merge_ms", "edit.deselect", json!({}))?; + let t = Instant::now(); + let _ = s.undo(); + out["undo_ms"] = json!(ms(t)); + out["segments_after"] = json!(segments(&s)); + serde_json::to_string_pretty(&out).map_err(|e| e.to_string()) +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 6c67d3e0..c941cbbb 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -3,6 +3,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #[cfg(not(target_arch = "wasm32"))] +mod bench_stroke; pub mod control; pub mod mcp; @@ -579,6 +580,9 @@ pub fn check_budgets(out: &Value) -> (Vec, Vec) { /// `cargo run --release -p anicraft-cli -- bench`. With `--check yes`, the default scenario /// is compared with [`TIME_BUDGETS`] and a missed budget is an error. pub fn bench(a: &Args) -> Result { + if a.flag("stroke").is_some() || a.flag("stroke-file").is_some() { + return bench_stroke::bench_stroke(a); + } let check = a.flag("check").is_some_and(|v| v == "yes" || v == "true"); if check { if cfg!(debug_assertions) { From 5183081863bc41fff87cf397e7bf2b49522e03c0 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 13:55:50 -0700 Subject: [PATCH 38/44] test(shell): Free Transform's handles on a skewed symbol, end to end (M8) --- src/stage.rs | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/src/stage.rs b/src/stage.rs index 09f48600..301a59df 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -5398,6 +5398,70 @@ mod pointer_tests { assert_eq!((icon, arrowheads), (CursorIcon::Move, 0), "inside the box: move"); } + /// #117: a symbol instance that is skewed still answers Free Transform on the stage. Its + /// box is the slanted one its artwork has, the handles are on that box's corners, and a + /// drag from a corner scales it, one from just outside a corner turns it, and one on an + /// edge skews it further: each changes the instance, and each is one undo step. + #[test] + fn free_transform_handles_work_on_a_skewed_symbol() { + let (mut app, ctx, at) = scene(); + app.run("edit.select_all", json!({})); + app.run("edit.delete", json!({})); + app.run("draw.rect", json!({"x": 300, "y": 200, "w": 200, "h": 100, "fill": "#3366ff", "stroke": null, "object": true})); + app.run("modify.convert_to_symbol", json!({"name": "Slanted"})); + // Slant it: the top slides right of the bottom. + app.run("modify.transform", json!({"a": 1, "b": 0, "c": -0.6, "d": 1, "e": 150, "f": 0})); + app.tool = Tool::Transform; + let mut t = 2.0; + let mut frame = |app: &mut App, events: Vec| { + t += 0.05; + run_frame(&ctx, app, t, events); + }; + frame(&mut app, Vec::new()); + let instance = |app: &App| app.s.selected_elements().first().map(|(_, e)| e.transform).expect("the instance is selected"); + let box_of = |app: &App| crate::xform::frame(app).expect("a selection has a box"); + let slanted = box_of(&app); + let [tl, tr, br, bl] = slanted.corners(); + assert!((tl.x - bl.x).abs() > 30.0 && (tl.y - tr.y).abs() < 1.0, "the box slants with the instance: {tl:?} {tr:?} {br:?} {bl:?}"); + let mut drag = |app: &mut App, from: Vec2, to: Vec2| { + let (a, b) = (at(from.x, from.y), at(to.x, to.y)); + frame(app, vec![Event::PointerMoved(a)]); + frame(app, vec![button(a, true)]); + for i in 1..=5 { + frame(app, vec![Event::PointerMoved(a + (b - a) * (i as f32 / 5.0))]); + } + frame(app, vec![button(b, false)]); + frame(app, Vec::new()); + }; + let steps = |app: &App| app.s.history().undo_len(); + // The bottom right corner, pulled away from the box: larger, and still as slanted. + let (before, undo) = (instance(&app).decompose(), steps(&app)); + let out = (br - tl).normalized() * 60.0; + drag(&mut app, br, br + out); + let after = instance(&app).decompose(); + assert!(after.sx > before.sx * 1.1 && after.sy > before.sy * 1.1, "scaled from the corner handle: {before:?} to {after:?}"); + assert_eq!(steps(&app), undo + 1, "one undo step"); + let now = box_of(&app); + assert!(now.corners()[0].distance(tl) < 1.0, "the opposite corner stays where it was"); + // Just outside the top right corner: a turn. + let (before, undo) = (instance(&app).decompose(), steps(&app)); + let [_, tr, _, _] = now.corners(); + let outside = tr + (tr - now.handle(0, 0)).normalized() * (14.0 / app.view.zoom); + drag(&mut app, outside, outside + Vec2::new(40.0, 120.0)); + let after = instance(&app).decompose(); + assert!((after.rotation - before.rotation).abs().to_degrees() > 5.0, "turned from outside the corner: {before:?} to {after:?}"); + assert_eq!(steps(&app), undo + 1); + // The top edge between its handles, slid along itself: more slant, the bottom edge kept. + let now = box_of(&app); + let (undo, bottom) = (steps(&app), now.handle(0, 1)); + let on_edge = now.handle(-1, -1).lerp(now.handle(0, -1), 0.5); + let along = (now.handle(1, -1) - now.handle(-1, -1)).normalized() * 50.0; + drag(&mut app, on_edge, on_edge + along); + let skewed = box_of(&app); + assert!(skewed.handle(0, -1).distance(now.handle(0, -1)) > 20.0 && skewed.handle(0, 1).distance(bottom) < 1.0, "the top edge slid, the bottom stayed"); + assert_eq!(steps(&app), undo + 1); + } + /// A double-click: press, release, `gap` seconds, press, release (each its own frame). fn double_click(gap: f64) -> App { let (mut app, ctx, at) = scene(); From 0454782d3cf5300af70d28ccc6a921a85b15b8be Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 14:11:17 -0700 Subject: [PATCH 39/44] docs: ADR 0129, the long-stroke numbers, and P-003 and P-005 in the roadmap and parity matrix (M8) --- CHANGELOG.md | 20 +++++ crates/cli/src/lib.rs | 4 + ...ong-brush-stroke-never-holds-the-window.md | 81 +++++++++++++++++++ docs/guide/drawing.md | 3 +- docs/parity.md | 2 +- docs/performance.md | 4 + docs/roadmap.md | 4 +- 7 files changed, 114 insertions(+), 4 deletions(-) create mode 100644 docs/adr/0129-a-long-brush-stroke-never-holds-the-window.md diff --git a/CHANGELOG.md b/CHANGELOG.md index b416e0e2..83f763dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ ## Unreleased +* **A long Brush stroke no longer freezes the window** (M8, ADR 0129, #519, backlog P-003). + * A stroke drawn for a long time, over itself again and again, took longer to turn into a + shape the longer it was, and a part of it selected over the rest cost seconds on every + frame. The outline's tracing is now bounded however long the stroke is (a fast scribble of + 60 000 samples: 1.5 s before, 0.4 s now, of which the trace is at most 0.3 s), and the + selection's stipple is cut row by row (seconds a frame before, a few milliseconds now). + * In the editor a long stroke's outline is traced off the window's thread: the stroke stays + on the stage as you drew it, you can go on painting at once, and it becomes a shape, in + one undo step, a moment later. Anything else you do waits for it first, so strokes and + edits always happen in the order you made them. + * `anicraft-cli bench --stroke ` measures a long stroke (painting, picking, moving, + the merge on deselect), and `bench --stroke-file ` a document's own artwork. + * Not yet: the Subselection tool, the Paint Bucket and the shape tools' snapping are still + slow on a single shape of ten thousand points and more. +* **Free Transform on a skewed symbol** (M8, #117, backlog P-005): scaling from a corner, + turning from outside it and skewing from an edge are now covered end to end by a test on a + slanted instance (the fix itself came with ADR 0111). The guide says what a handle scales + from (#193). Rotation on Windows and FreeBSD (#479) could not be reproduced on Windows 10 + and stays open. + * **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/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c941cbbb..27f3836a 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -47,6 +47,10 @@ USAGE: anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release) anicraft-cli bench --check yes the default scenario against the budgets in docs/performance.md; fails when one is missed + anicraft-cli bench --stroke one long Brush stroke: painting it, picking it, moving + it and the merge when it is deselected (ADR 0129) + anicraft-cli bench --stroke-file + the same steps on a document's own artwork anicraft-cli serve [file|--sample] [--automation-read-root --automation-write-root ] JSON-lines on stdin/stdout: {\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}} diff --git a/docs/adr/0129-a-long-brush-stroke-never-holds-the-window.md b/docs/adr/0129-a-long-brush-stroke-never-holds-the-window.md new file mode 100644 index 00000000..e2a10110 --- /dev/null +++ b/docs/adr/0129-a-long-brush-stroke-never-holds-the-window.md @@ -0,0 +1,81 @@ +# ADR 0129: A long Brush stroke never holds the window + +* Status: accepted (2026-11-21) +* Relates to: ADR 0033 (the Brush), ADR 0031 (merge drawing), ADR 0122 (a moved selection + merges when it is deselected), ADR 0116 (work prepared on another thread, then one command), + issue #519, backlog item P-003 + +## Context + +Issue #519: a Brush stroke drawn for 40 to 50 seconds without lifting, then moved and +deselected, left the window "Not Responding", again and again, and the saved file did the same +when it was opened. The reporter's file holds one raw fill of 11 370 curves in 1 107 loops. + +Measured on that file and on generated strokes (`anicraft-cli bench --stroke ` and +`--stroke-file `; a 32-thread desktop, so a laptop is several times slower): + +| What | Before | Why | +|---|---|---| +| `draw.brush`, 6 000 / 20 000 / 60 000 samples of fast scribble | 306 / 807 / 1 563 ms | The distance field (ADR 0033) is sampled piece by piece, each piece over its own bounds. A stroke that goes over itself visits the same cells again and again: 190 million cell visits for 60 000 samples. The cost grew with the stroke's length without limit. | +| A frame with part of the stroke selected over the rest (after a marquee) | 3.2 s **a frame** (debug build) | The stipple of a selected raw fill is cut by the artwork above it. Every span of the selection was compared with every span of every occluder: tens of thousands by tens of thousands. | +| The merge when a moved stroke is deselected | 75 to 195 ms | `planar::merge`, already bounded (`MAX_SEGMENTS`, `MAX_PAIRS`). | +| Drawing the stage with the stroke on it | 3 to 5 ms CPU, 4 to 20 ms GPU | Not a problem. | + +So there were two unbounded costs, one in the engine (the trace) and one in the shell (the +selection overlay, paid on every frame, which is the "loop" the reporter saw), and one bounded +cost that is still longer than a frame. + +## Decision + +1. **The trace is bounded.** `geom::brush` counts the cells a stroke's pieces would visit and, + past `MAX_STAMP_WORK` (2²⁴), samples on a coarser grid, as it already does past `MAX_CELLS`. + A cell that is already deep inside paint is skipped with one comparison, since nothing can + raise it. The result for a stroke under the budget is unchanged. Past it the grid is at + worst the size the brush's own tip asks for at full pressure (a sixth of its radius), so + thin parts of a very long stroke are a little less fine; the outline is still traced from a + true distance, well under a cell. + +2. **The editor traces a long stroke on another thread.** The trace depends on nothing but the + stroke, so it is a pure function of a `StrokeRequest`. When the pointer lifts on a stroke of + 400 samples or more, the shell starts the trace on a thread (`src/ink.rs`) and keeps drawing + the stroke as it was drawn. When the outline is ready, the shell runs the same `draw.brush` + as ever with the outline staged (`Session::staged_stroke`): the command takes a staged + outline only when it is for exactly the stroke it was asked to paint, and traces otherwise. + This is the pattern of ADR 0116 (`staged_video`). The command, its parameters, its undo step + and what a script or an assistant sees are unchanged; headless callers trace in the command. + +3. **Nothing comes between a stroke and its paint.** Strokes are painted in the order they + were drawn. While strokes wait, only looking around and painting more go ahead: a frame + whose input could edit (any key, text, a press that is not the Brush on the stage, a dropped + file, playback, a dialog) first finishes the waiting strokes on the window's thread, as does + any command (`App::run`, so an assistant's commands too) and leaving the document. The wait + is bounded by decision 1. At most eight strokes wait; a ninth waits for the first. + +4. **The merge stays on the window's thread**, bounded as before. A `Session` is not `Send` + and cannot be cloned (plug-ins, caches, the undo history), and a merge needs the drawing it + merges into, so moving it would mean running the command on a copy and adopting the result, + which is a second way for an edit to enter the document. It is not worth that for 75 to + 220 ms on the largest strokes the app accepts. If it turns out to be, the copy-and-adopt + route is the one to take, for every slow command at once, in its own ADR. + +5. **The selection overlay looks up occluders by row.** `subtract_spans` sorts the occluders by + their top edge and compares a span only with those in its own rows, in their original order, + so the pieces it leaves are the ones it always left. + +## Consequences + +* `draw.brush` on the three generated strokes: 218 / 461 / 383 ms, of which the trace is at + most about 300 ms whatever the stroke, and in the editor none of the trace is on the + window's thread. What is left there is the merge. +* The marquee case is 200 ms once (the cut) instead of seconds on every frame. +* A stroke can be on the stage for a moment before it is in the document. Undo, save and every + other edit see it, because they wait for it; an update is not installed while one waits. +* The web build has one thread: it traces in the command, bounded by decision 1. +* *Not done here:* the Subselection tool's click on a shape of 13 000 points (3 s once in a + debug build), the Paint Bucket in a gap of such a shape (0.8 s), and the shape tools' snapping + near it (about 100 ms a frame in a debug build). They are bounded and one-off or mild, and + are listed under P-003 in the roadmap. +* *Rejected:* a progress window ("processing strokes", as the reference app shows). With the + trace bounded and off the thread there is nothing long enough to report. +* *Rejected:* simplifying the outline to fewer curves. It changes what the artist drew, and + the curve count was not what cost the time. diff --git a/docs/guide/drawing.md b/docs/guide/drawing.md index 80147e21..60025b6b 100644 --- a/docs/guide/drawing.md +++ b/docs/guide/drawing.md @@ -422,7 +422,8 @@ Both dialogs remember what you entered. Each command is one undo step. ## Transforming artwork With the **Free Transform** tool (**Q**), drag a handle (a corner or the middle of an edge) to -**scale** (**Shift** keeps the proportions, **Alt** scales about the transformation point), +**scale** (the opposite handle stays where it is; **Shift** keeps the proportions, **Alt** +scales about the transformation point instead), the line between two handles to **skew** (the opposite edge stays where it is; **Alt** skews about the transformation point), just outside a corner to **rotate** (the pointer turns into a curved arrow there; **Shift** snaps to 15°), or inside the box to **move**. diff --git a/docs/parity.md b/docs/parity.md index 3c898ae4..9eb04e18 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -99,7 +99,7 @@ not this table, says what matters most. |---|---|---| | Selection | **partial** | Raw shapes, objects, marquee, bend an edge, move a corner ([ADR 0041](adr/0041-selection-tool-on-raw-drawings.md), [ADR 0044](adr/0044-selection-across-layers.md)). Missing: a marquee that takes instances and objects it only touches ([#522](https://github.com/storytold/anicraft/issues/522)), Hide Edges ([#298](https://github.com/storytold/anicraft/issues/298)) (P-017). | | Subselection | **done** | [ADR 0042](adr/0042-subselection-and-merging-everywhere.md), [ADR 0045](adr/0045-raw-points-and-raw-shapes-inside-symbols.md). | -| Free Transform | **partial** | Scale, skew, rotate, the transformation point, a box that turns with the object ([ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md)), Envelope ([ADR 0080](adr/0080-drawing-parity-leftovers.md)). Missing: Distort. Open bugs: 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)) (P-005). | +| Free Transform | **partial** | Scale, skew, rotate, the transformation point, a box that turns with the object ([ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md)), Envelope ([ADR 0080](adr/0080-drawing-parity-leftovers.md)). Missing: Distort. Open bug: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), not reproduced on Windows 10 (P-005). | | Gradient Transform | **done** | Gradient and bitmap fills, Lock Fill. | | Lasso | **missing** | P-018 ([#515](https://github.com/storytold/anicraft/issues/515)). | | Polygon (lasso) | **missing** | P-018. | diff --git a/docs/performance.md b/docs/performance.md index b09ec34e..e7169d6c 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -9,6 +9,8 @@ oracle; its output must stay bit-identical). ```sh cargo run --release -p anicraft-cli -- bench # 50 layers × 200 shapes × 240 frames cargo run --release -p anicraft-cli -- bench --layers 200 --shapes 500 --frames 600 +cargo run --release -p anicraft-cli -- bench --stroke 6000 # one long Brush stroke (ADR 0129) +cargo run --release -p anicraft-cli -- bench --stroke-file drawing.anicraft # the same steps on a file ``` `bench` builds a deterministic stress document (`doc::sample::stress`) and reports file size, @@ -37,6 +39,8 @@ The default `bench` scenario: 50 layers × 200 shapes × 240 frames, 200k elemen | UI frame while rendering | never blocked | worker thread ✅ | design (ADR 0002) | | Autosave: time on the editing thread | < 1 ms | 7–15 µs ✅ | `bench --check` | | Autosave of the 65 MB file, in the background | < 2 s | 183–184 ms ✅ | `bench --check` | +| A long Brush stroke: tracing its outline (ADR 0129) | bounded: `MAX_STAMP_WORK` cells visited, whatever the stroke | 45 to 310 ms for 1,500 to 100,000 samples, sizes 3 to 60 (2026-11-21; 1,500 ms and growing before) | test, every PR (the budget, not the time) | +| A long Brush stroke in the editor | the trace is never on the window's thread | worker thread ✅; the merge (75 to 220 ms at the largest) still is | test, every PR | | GPU stage, 1,000 shapes at 4K, stage tiles (M3 exit) | < 16.7 ms | 4.5–4.7 ms ✅ (2026-11-10, RTX 5090) | `gpu_bench --check` | | GPU stage, 10k shapes at 4K, stage tiles | < 16.7 ms | 10.1–10.4 ms ✅ | `gpu_bench --check` | | GPU stage, 50k shapes at 1080p, stage tiles | < 33.3 ms (30 fps) | 24.8–26.3 ms ✅ | `gpu_bench --check` | diff --git a/docs/roadmap.md b/docs/roadmap.md index 427deb4a..b9fde0ec 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -45,9 +45,9 @@ the changelog. |---|---|---|---|---|---| | 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-003 | What is left of "a long Brush stroke never freezes the app" ([#519](https://github.com/storytold/anicraft/issues/519)) after [ADR 0129](adr/0129-a-long-brush-stroke-never-holds-the-window.md) bounded the trace, took it off the window's thread and fixed the selection overlay: on one raw shape of ten thousand points and more, the Subselection tool's click (seconds, once), the Paint Bucket in a gap (about a second) and the shape tools' snapping (slow frames); and the merge of such a shape (75 to 220 ms) still runs on the window's thread | Tools | S each | | 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 | +| P-005 | Free Transform works everywhere: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), which did not reproduce on Windows 10 (the curved pointer shows outside a corner in the real window; the headless press-and-drag tests pass) and needs the reporter's build number and steps. Done: handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117), tested end to end), and [#193](https://github.com/storytold/anicraft/issues/193) decided by [ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md) with the rule in the guide | Tools | S | the reporter's answer | stage | | P-006 | Animate files open right: lines missing or filled in ([#498](https://github.com/storytold/anicraft/issues/498)), a `.fla` refused on macOS ([#347](https://github.com/storytold/anicraft/issues/347)); each fixed file joins the corpus | Import | M | the reporters' files | xfl | | P-007 | The web build is usable: import, export and save ([#55](https://github.com/storytold/anicraft/issues/55)), preferences kept ([#56](https://github.com/storytold/anicraft/issues/56)), a web asset on each release ([#316](https://github.com/storytold/anicraft/issues/316), [#210](https://github.com/storytold/anicraft/issues/210)), a run in a real browser in CI | Preferences, platforms | M | | platform | | 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 | From 96f22a2e657930423996dfce854a804b4690f130 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 21 Nov 2026 14:52:04 -0700 Subject: [PATCH 40/44] fix(cli): the stroke bench builds for the web, with a test of its steps (M8) --- crates/cli/src/lib.rs | 29 ++++++++++++++++++++++++++++- src/long_stroke_tests.rs | 8 ++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 27f3836a..bdf5e133 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -2,8 +2,8 @@ //! server (`mcp`). Every operation goes through the engine's command registry. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -#[cfg(not(target_arch = "wasm32"))] mod bench_stroke; +#[cfg(not(target_arch = "wasm32"))] pub mod control; pub mod mcp; @@ -1029,6 +1029,33 @@ pub(crate) mod tests { } } + /// `bench --stroke` walks the reporter's steps of #519 (paint, pick, move, float, deselect, + /// undo) and `--stroke-file` the same on a document: the stroke becomes one merged shape, + /// the merge on deselect keeps it, and undo puts the drawing back as it was. + #[test] + fn stroke_bench_paints_moves_and_merges_a_long_stroke() { + let out: Value = serde_json::from_str(&run(&["bench".into(), "--stroke".into(), "400".into()]).unwrap()).unwrap(); + assert_eq!(out["samples"], 400); + assert_eq!(out["merged"], true); + let segments = out["segments"].as_u64().unwrap(); + assert!(segments > 50, "a scribble has an outline of many curves: {segments}"); + assert_eq!(out["segments_after"].as_u64(), Some(segments), "undo takes the move and its merge back"); + for step in ["draw_brush_ms", "hit_test_us", "move_ms", "float_ms", "deselect_merge_ms", "undo_ms", "render_ms"] { + assert!(out[step].as_f64().is_some_and(|v| v >= 0.0), "{step} was timed: {out}"); + } + assert!(run(&["bench".into(), "--stroke".into(), "many".into()]).unwrap_err().contains("number of samples")); + // The same steps on a saved document's artwork. + let dir = std::env::temp_dir().join(format!("anicraft-cli-stroke-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("stroke.anicraft"); + let mut s = Session::default(); + s.execute("draw.brush", &json!({"points": bench_stroke::scribble(200), "size": 8, "object": false})).unwrap(); + s.execute("file.save", &json!({"path": file.display().to_string()})).unwrap(); + let out: Value = serde_json::from_str(&run(&["bench".into(), "--stroke-file".into(), file.display().to_string()]).unwrap()).unwrap(); + assert!(out["samples"].is_null() && out["elements"].as_u64() == Some(1) && out["deselect_merge_ms"].is_number(), "{out}"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn plugins_folder_flag() { let dir = std::env::temp_dir().join(format!("anicraft-cli-plugins-{}", std::process::id())); diff --git a/src/long_stroke_tests.rs b/src/long_stroke_tests.rs index 6c76b8a1..efd59fa9 100644 --- a/src/long_stroke_tests.rs +++ b/src/long_stroke_tests.rs @@ -177,6 +177,14 @@ fn edits_wait_for_the_strokes_drawn_before_them() { rig.frame("a key", vec![Event::Key { key: egui::Key::F13, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); assert!(rig.app.ink.is_empty()); assert_eq!(rig.shapes(), 1); + // Only a few strokes wait at once: one more paints the oldest first. + let mut rig = blank(); + for _ in 0..10 { + rig.brush(scribble(450)); + assert!(rig.app.ink.len() <= 8, "{} waiting", rig.app.ink.len()); + } + rig.until_painted(); + assert_eq!(rig.shapes(), 10, "every stroke was painted"); // Leaving the document: it takes its strokes with it. let mut rig = blank(); rig.brush(scribble(3000)); From 386c018421ac74708b79a0b86ba6cda48e8371eb Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 23 Nov 2026 12:42:34 -0700 Subject: [PATCH 41/44] feat(text): mixed directions follow the bidi algorithm, and letters a face lacks come from a fallback face (M5) Layout resolves embedding levels with craft-text's bidi module (UAX #9), shapes each run in stretches of one direction and one script, finds lines in reading order on shaped clusters and then puts each line in the order it is displayed. A cluster its run's face has no glyph for is shaped again, whole, in the first fallback face that has all of it: the listed families first, then any installed face. Carets carry each cluster's box and the paragraph's direction. Rebuilds outside PRs #39 and #40 (SoldierPePe) on the styled-text layout of ADR 0085: lines in reading order and never inside a cluster, the fallback family list, a cluster moving whole with its marks, invisible format characters not counted as missing. Tests run on fonts made in memory, so they are the same on every computer. --- Cargo.lock | 17 +- Cargo.toml | 3 + crates/text/Cargo.toml | 4 +- crates/text/src/fallback.rs | 186 ++++++++++++++ crates/text/src/lib.rs | 40 ++- crates/text/src/lines.rs | 236 ++++++++++++++++++ crates/text/src/rich.rs | 445 ++++++++++++++++++++++++---------- crates/text/src/rich_tests.rs | 182 ++++++++++++++ crates/text/src/testfont.rs | 152 ++++++++++++ 9 files changed, 1128 insertions(+), 137 deletions(-) create mode 100644 crates/text/src/fallback.rs create mode 100644 crates/text/src/lines.rs create mode 100644 crates/text/src/testfont.rs diff --git a/Cargo.lock b/Cargo.lock index 2a178fd0..1ffc9ba1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -412,10 +412,10 @@ name = "anicraft-text" version = "0.3.0" dependencies = [ "anicraft-geom", + "craft-text", "fontdb", "harfrust", "skrifa", - "unicode-bidi", ] [[package]] @@ -1405,6 +1405,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-text" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +dependencies = [ + "unicode-bidi", + "unicode-bidi-mirroring", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -5232,6 +5241,12 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" +[[package]] +name = "unicode-bidi-mirroring" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" + [[package]] name = "unicode-general-category" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index 19bbce44..c4fa71b9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,9 @@ craft-xfl = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c5 # bounded record parser. The same reviewed commit as craft-mime and craft-gif. craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" } +# The Unicode bidi algorithm (UAX #9) for text that mixes directions (ADR 0130): only the `bidi` +# module, which brings unicode-bidi and unicode-bidi-mirroring (both MIT OR Apache-2.0). +craft-text = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a", default-features = false, features = ["bidi"] } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 79dfffa5..0bbf377c 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -14,8 +14,8 @@ fontdb.workspace = true # Shaping (a HarfBuzz port) and outlines/metrics: both already in the tree through egui. harfrust = "0.12" skrifa = { version = "0.44", default-features = false, features = ["std"] } -# The Unicode bidi algorithm (UAX #9), for text that mixes right-to-left and left-to-right runs. -unicode-bidi = "0.3" +# The Unicode bidi algorithm (UAX #9): embedding levels, line reordering (ADR 0130). +craft-text.workspace = true [lints] workspace = true diff --git a/crates/text/src/fallback.rs b/crates/text/src/fallback.rs new file mode 100644 index 00000000..d9fc2283 --- /dev/null +++ b/crates/text/src/fallback.rs @@ -0,0 +1,186 @@ +//! Fallback faces (ADR 0130): letters a run's own face has no glyph for are drawn from another +//! face on this computer, cluster by cluster (a letter with its marks), so the rest of the block +//! keeps its face. The faces tried first are [`FALLBACK_FAMILIES`]; after them, any installed +//! face that has the character. +//! +//! The list, the rule that a cluster moves whole and the rule that invisible format characters +//! are never "missing" come from outside PR #40 (SoldierPePe), rebuilt here on shaped clusters. + +use crate::Fonts; +use skrifa::MetadataProvider as _; +use std::collections::HashMap; + +/// Families tried, in order, for characters a run's own face doesn't have: faces with wide +/// coverage that come with Windows, macOS and common Linux desktops, then the system faces for +/// Chinese, Japanese, Korean, Indic and Thai text, then symbols. +pub const FALLBACK_FAMILIES: &[&str] = &[ + "Segoe UI", + "Arial", + "Tahoma", + "Geeza Pro", + "Arial Unicode MS", + "DejaVu Sans", + "Noto Sans", + "Noto Sans Arabic", + "Noto Naskh Arabic", + "Noto Sans Hebrew", + "Yu Gothic", + "Meiryo", + "Hiragino Sans", + "Noto Sans CJK JP", + "Microsoft YaHei", + "Microsoft JhengHei", + "PingFang SC", + "Noto Sans CJK SC", + "Malgun Gothic", + "Apple SD Gothic Neo", + "Noto Sans CJK KR", + "Nirmala UI", + "Kohinoor Devanagari", + "Noto Sans Devanagari", + "Leelawadee UI", + "Thonburi", + "Noto Sans Thai", + "Segoe UI Symbol", + "Apple Symbols", + "Noto Sans Symbols", + "Noto Sans Symbols 2", + "Droid Sans Fallback", +]; + +/// Most fallback faces one block draws with; clusters past it stay in their run's face. +pub const MAX_FALLBACK_FACES: usize = 16; + +/// Most characters one layout searches every installed face for (after the list): each search +/// opens up to [`crate::MAX_FALLBACK_SEARCH`] faces once, and its answer is remembered. +pub(crate) const MAX_WIDE_SEARCHES: usize = 16; + +/// Most answers of the wide search remembered. +const MAX_REMEMBERED: usize = 4096; + +/// Whether a character is drawn: not a space, a line break or another control, and not an +/// invisible format character (joiners, direction marks and embeddings, variation selectors, +/// the byte-order mark, the soft hyphen, tags), which fonts often don't map and which draw as +/// nothing. +pub fn needs_glyph(c: char) -> bool { + let invisible = matches!(c, + '\u{00AD}' | '\u{034F}' | '\u{061C}' | '\u{180B}'..='\u{180F}' | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{206F}' | '\u{FE00}'..='\u{FE0F}' | '\u{FEFF}' | '\u{E0000}'..='\u{E0FFF}'); + !c.is_control() && !c.is_whitespace() && !invisible +} + +/// Which of `candidates` faces draws a cluster whose own face lacks part of it. `cluster` is +/// its drawn characters, `own` how many of them its own face has, and `has(f, c)` whether +/// candidate `f` has `c`. The first candidate with every character wins, so a letter and its +/// marks are shaped together; when none has them all, the one with the most, if that is more +/// than the cluster's own face has (the earliest of equals). `None`: it stays where it is. +pub(crate) fn pick_face(cluster: &[char], own: usize, candidates: usize, has: &mut dyn FnMut(usize, char) -> bool) -> Option { + let mut best: Option<(usize, usize)> = None; + for f in 0..candidates { + let n = cluster.iter().filter(|c| has(f, **c)).count(); + if n == cluster.len() && n > 0 { + return Some(f); + } + if n > own && best.is_none_or(|b| n > b.1) { + best = Some((f, n)); + } + } + best.map(|b| b.0) +} + +/// Which characters which faces have, asked once each. +pub(crate) struct Coverage<'f> { + fonts: &'f Fonts, + memo: HashMap<(fontdb::ID, char), bool>, +} + +impl<'f> Coverage<'f> { + pub(crate) fn new(fonts: &'f Fonts) -> Self { + Coverage { fonts, memo: HashMap::new() } + } + + pub(crate) fn has(&mut self, id: fontdb::ID, c: char) -> bool { + let fonts = self.fonts; + *self.memo.entry((id, c)).or_insert_with(|| fonts.db.with_face_data(id, |data, index| crate::face_has(data, index, c)).unwrap_or(false)) + } +} + +impl Fonts { + /// The faces of [`FALLBACK_FAMILIES`] on this computer in a weight and slant, in order. + pub(crate) fn fallback_list(&self, bold: bool, italic: bool) -> Vec { + let mut out: Vec = Vec::new(); + for name in FALLBACK_FAMILIES { + let q = fontdb::Query { + families: &[fontdb::Family::Name(name)], + weight: if bold { fontdb::Weight::BOLD } else { fontdb::Weight::NORMAL }, + stretch: fontdb::Stretch::Normal, + style: if italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, + }; + if let Some(id) = self.db.query(&q) + && !out.contains(&id) + { + out.push(id); + } + } + out + } + + /// Any installed face with a glyph for `c`: regular faces in family order (so the answer is + /// the same from run to run), found once and remembered. `None` when no face has it. + pub(crate) fn any_face_with(&self, c: char) -> Option { + if let Ok(known) = self.wide.lock() + && let Some(found) = known.get(&c) + { + return *found; + } + let regular = |f: &&fontdb::FaceInfo| f.style == fontdb::Style::Normal && (300..=500).contains(&f.weight.0); + let mut faces: Vec<(&str, fontdb::ID)> = self.db.faces().filter(regular).filter_map(|f| f.families.first().map(|(n, _)| (n.as_str(), f.id))).filter(|(n, _)| !n.starts_with('.')).collect(); + faces.sort_unstable_by(|a, b| a.0.cmp(b.0)); + let found = faces.into_iter().take(crate::MAX_FALLBACK_SEARCH).map(|(_, id)| id).find(|id| self.db.with_face_data(*id, |data, index| skrifa::FontRef::from_index(data, index).is_ok_and(|f| f.charmap().map(c).is_some() && f.outline_glyphs().format().is_some())).unwrap_or(false)); + if let Ok(mut known) = self.wide.lock() + && known.len() < MAX_REMEMBERED + { + known.insert(c, found); + } + found + } + + /// A face's family name. + pub(crate) fn family_of(&self, id: fontdb::ID) -> String { + self.db.face(id).and_then(|f| f.families.first().map(|(n, _)| n.clone())).unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Faces as the characters they have. + fn pick(cluster: &str, own: &str, faces: &[&str]) -> Option { + let drawn: Vec = cluster.chars().filter(|c| needs_glyph(*c)).collect(); + let had = drawn.iter().filter(|c| own.contains(**c)).count(); + pick_face(&drawn, had, faces.len(), &mut |f, c| faces.get(f).is_some_and(|s| s.contains(c))) + } + + /// From outside PR #40: a letter and its marks go together to the first face with all of + /// them, even when an earlier face has the letter. + #[test] + fn a_cluster_moves_whole_to_the_first_face_with_all_of_it() { + assert_eq!(pick("e\u{0301}\u{0323}", "e\u{0301}", &["e\u{0323}", "e\u{0301}\u{0323}"]), Some(1)); + assert_eq!(pick("\u{05D0}", "", &["abc", "\u{05D0}\u{05D1}", "\u{05D0}"]), Some(1), "the earliest face that has it"); + // No face has all three: the one with the most, when that beats the cluster's own face. + assert_eq!(pick("q\u{0301}\u{0323}", "q", &["q\u{0323}", "\u{0301}"]), Some(0)); + assert_eq!(pick("q\u{0301}\u{0323}", "q\u{0301}", &["q\u{0323}", "\u{0301}"]), None, "no better than its own face: it stays"); + assert_eq!(pick("\u{10FFFD}", "", &["abc", "def"]), None, "a character no face has"); + assert_eq!(pick("", "", &["abc"]), None); + } + + #[test] + fn invisible_format_characters_need_no_glyph() { + for c in ['\u{200C}', '\u{200D}', '\u{200F}', '\u{202B}', '\u{2067}', '\u{FE0F}', '\u{FEFF}', '\u{00AD}', ' ', '\n', '\t'] { + assert!(!needs_glyph(c), "{c:?}"); + } + for c in ['a', '\u{05D0}', '\u{0627}', '\u{0301}', '1', '-'] { + assert!(needs_glyph(c), "{c:?}"); + } + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 91f12cf9..4b768066 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -8,14 +8,22 @@ //! [`Fonts::layout_glyphs`] also hands back each glyph on its own ([`PlacedGlyph`]), for text //! placed glyph by glyph: along a path ([`on_path`], ADR 0070) or at SVG's per-character //! positions. +//! +//! Text that mixes directions (Hebrew or Arabic with Latin words and numbers) follows the +//! Unicode bidi algorithm, and letters a run's face lacks come from a fallback face (ADR 0130). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use anicraft_geom::{Path, PathCmd, Vec2}; use std::sync::{Arc, OnceLock}; mod embed; +mod fallback; +mod lines; mod rich; +#[cfg(test)] +mod testfont; pub use embed::{EMBED_EM, Embedding, GlyphTable, MAX_EMBED_CHARS, TableGlyph}; +pub use fallback::{FALLBACK_FAMILIES, MAX_FALLBACK_FACES, needs_glyph}; pub use rich::{MAX_FACES, MAX_RUNS, ParaStyle, RichText, Run, RunStyle, Shift, sanitize_para, sanitize_run}; /// Families tried, in order, when none is asked for or the one asked for isn't installed. @@ -72,7 +80,8 @@ pub struct Layout { pub height: f32, /// The family actually used (the one asked for, or the fallback). pub family: String, - /// Characters the font has no glyph for (drawn as its "notdef" box). + /// Characters no face has a glyph for, neither the run's own nor a fallback (drawn as the + /// run's face's "notdef" box). pub missing: usize, /// Lines laid out (at least one), and the distance between their baselines (pixels): a /// line that continued the block would start `lines × line_height` below its top. @@ -92,6 +101,9 @@ pub struct Layout { pub pieces: Vec<(u32, Path)>, /// The family each run was laid out in (the one asked for, or the fallback). pub families: Vec, + /// The other families letters were drawn from, because their run's face lacks them, in + /// the order they were first needed (ADR 0130). + pub fallbacks: Vec, } /// One laid-out glyph on its own. @@ -352,6 +364,19 @@ fn first_subpath_closed(path: &Path) -> bool { false } +/// Where one cluster (a letter with its marks, or a ligature) stands on its line (ADR 0130). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CaretBox { + /// The characters it covers: from `start` up to `end`. + pub start: u32, + pub end: u32, + /// Its left and right edges. + pub x0: f32, + pub x1: f32, + /// It reads right to left: `start` is at its right edge. + pub rtl: bool, +} + /// One laid-out line's characters and caret positions. Indices count `char`s of the whole text /// (line breaks included); `x` is from the box's left edge, alignment applied. #[derive(Clone, Debug, Default, PartialEq)] @@ -360,8 +385,15 @@ pub struct CaretLine { /// trailing spaces belong to it; a line break belongs to neither line). pub start: u32, pub end: u32, - /// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending. + /// `(index, x)` of the boundaries clusters start at and of the line's end, ascending by + /// index. A cluster's boundary is at the edge it is read from, so in text that mixes + /// directions `x` does not rise with the index. pub stops: Vec<(u32, f32)>, + /// The paragraph reads right to left: the line starts at its right end. + pub rtl: bool, + /// The line's clusters as they are displayed, left to right (trailing spaces left out): + /// what a selection highlights, and the order a caret moves in. + pub boxes: Vec, /// The line's top and height (to the next line's top, its line spacing included) and its /// baseline, from the box's top (pixels). pub top: f32, @@ -434,6 +466,8 @@ impl std::error::Error for TextError {} pub struct Fonts { db: fontdb::Database, families: Vec, + /// Which face, if any, has each character the fallback list didn't (`Fonts::any_face_with`). + wide: std::sync::Mutex>>, } static FONTS: OnceLock = OnceLock::new(); @@ -470,7 +504,7 @@ impl Fonts { let mut families: Vec = db.faces().filter_map(|f| f.families.first().map(|(n, _)| n.clone())).filter(|n| !n.starts_with('.')).collect(); families.sort_by_key(|f| f.to_lowercase()); families.dedup(); - Fonts { db, families } + Fonts { db, families, wide: std::sync::Mutex::default() } } /// A library of just these faces (tests, and documents carrying their own fonts). diff --git a/crates/text/src/lines.rs b/crates/text/src/lines.rs new file mode 100644 index 00000000..a8e63e8f --- /dev/null +++ b/crates/text/src/lines.rs @@ -0,0 +1,236 @@ +//! Lines of text that mixes directions (ADR 0130), on shaped clusters and independent of fonts. +//! +//! The order is the one the Unicode bidi algorithm (UAX #9) prescribes: levels are resolved for +//! the paragraph, text is shaped and broken into lines in reading order, and only then is each +//! line put in the order it is displayed ([`place`]). A cluster (a letter with its marks, or a +//! ligature) is never split, by a line break or by reordering. +//! +//! Breaking lines in reading order and never inside a cluster is from outside PR #39 +//! (SoldierPePe); the levels and the reordering are `craft_text::bidi`. + +use crate::CaretBox; +use craft_text::bidi; +use std::collections::HashMap; +use std::ops::Range; + +/// One shaped cluster of a paragraph, in reading order. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Cluster { + /// Its glyphs (a range of the paragraph's glyphs, in the order the shaper gave them). + pub glyphs: Range, + /// The characters it covers (of the whole text): from `start` up to `end`. + pub start: u32, + pub end: u32, + /// Its first character, and whether that is white space. + pub first: char, + pub space: bool, + pub advance: f32, + /// Its embedding level: odd is right to left. + pub level: u8, +} + +/// A paragraph's lines as ranges of its clusters, in reading order: wrapped after the last +/// space before the room is used up (or between the clusters of a word wider than the line), +/// with the spaces at a line's end left out. `room(first)` is the width a line may take +/// (`first`: the paragraph's first line); `None` keeps the paragraph on one line. There is +/// always at least one line. +pub(crate) fn break_lines(clusters: &[Cluster], room: &dyn Fn(bool) -> Option) -> Vec> { + let trimmed = |start: usize, mut end: usize| { + while end > start && clusters.get(end - 1).is_some_and(|c| c.space) { + end -= 1; + } + start..end + }; + let mut lines = Vec::new(); + let (mut start, mut x, mut break_at) = (0usize, 0.0f32, None::); + for (i, c) in clusters.iter().enumerate() { + if let Some(w) = room(lines.is_empty()) + && !c.space + && x + c.advance > w + && i > start + { + let end = break_at.unwrap_or(i); + lines.push(trimmed(start, end)); + start = end; + x = clusters.get(start..i).map_or(0.0, |rest| rest.iter().map(|r| r.advance).sum()); + break_at = None; + } + x += c.advance; + if c.space { + break_at = Some(i + 1); + } + } + lines.push(trimmed(start, clusters.len())); + lines +} + +/// One line's clusters in the order they are displayed, left to right (rules L1 and L2), with +/// where each one stands: `(cluster, box)`, the cluster as an index into `clusters` and the +/// box's x from the line's left end. `line` is the line's range of `clusters` and `para_level` +/// its paragraph's embedding level. +pub(crate) fn place(clusters: &[Cluster], line: Range, para_level: u8) -> Vec<(usize, CaretBox)> { + let on_line = clusters.get(line.clone()).unwrap_or(&[]); + let mixed = para_level > 0 || on_line.iter().any(|c| c.level > 0); + let (order, levels): (Vec, Vec) = if mixed { + let chars: Vec = on_line.iter().map(|c| c.first).collect(); + let resolved: Vec = on_line.iter().map(|c| c.level).collect(); + let levels = bidi::line_levels(&chars, &resolved, para_level); + (bidi::visual_order(&levels), levels) + } else { + ((0..on_line.len()).collect(), vec![0; on_line.len()]) + }; + let mut x = 0.0f32; + let mut out = Vec::with_capacity(order.len()); + for k in order { + let Some(c) = on_line.get(k) else { continue }; + let rtl = levels.get(k).is_some_and(|l| l % 2 == 1); + out.push((line.start + k, CaretBox { start: c.start, end: c.end, x0: x, x1: x + c.advance, rtl })); + x += c.advance; + } + out +} + +/// Where the caret stands on a line (see [`crate::CaretLine::stops`]): each cluster's first +/// character at the edge the cluster is read from (its left when it reads left to right, its +/// right otherwise), and the boundary after the line's last cluster at that cluster's other +/// edge. `boxes` are the line's, x from the box's left edge; `empty` is where the caret stands +/// on a line without clusters. +pub(crate) fn stops(boxes: &[CaretBox], empty: (u32, f32)) -> Vec<(u32, f32)> { + let mut stops: Vec<(u32, f32)> = boxes.iter().map(|b| (b.start, if b.rtl { b.x1 } else { b.x0 })).collect(); + stops.sort_by_key(|s| s.0); + stops.dedup_by_key(|s| s.0); + match boxes.iter().max_by_key(|b| b.start) { + Some(last) => stops.push((last.end.max(last.start + 1), if last.rtl { last.x0 } else { last.x1 })), + None => stops.push(empty), + } + stops +} + +/// The script each character is shaped in: its own, or for characters every script shares +/// (spaces, digits, punctuation, marks) the script before them (after them at the start). +/// `None` throughout when no character has a script of its own. +pub(crate) struct Scripts { + known: HashMap>, +} + +impl Scripts { + pub(crate) fn new() -> Self { + Scripts { known: HashMap::new() } + } + + /// A character's own script (`None`: common to all, inherited or unknown). + fn own(&mut self, c: char) -> Option { + if c.is_ascii() { + return c.is_ascii_alphabetic().then_some(harfrust::script::LATIN); + } + *self.known.entry(c).or_insert_with(|| { + // harfrust keeps its script table to itself: a buffer of one character says it. + let mut one = harfrust::UnicodeBuffer::new(); + one.add(c, 0); + one.guess_segment_properties(); + let s = one.script(); + (s != harfrust::script::UNKNOWN && s != harfrust::script::COMMON && s != harfrust::script::INHERITED).then_some(s) + }) + } + + /// The scripts of one paragraph's characters. + pub(crate) fn of(&mut self, chars: &[char]) -> Vec> { + let mut out: Vec> = chars.iter().map(|c| self.own(*c)).collect(); + let mut last = out.iter().flatten().next().copied(); + for s in &mut out { + match s { + Some(own) => last = Some(*own), + None => *s = last, + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Clusters of one character each, 10 wide: capitals are right to left (level 1, or the + /// level given after them in `levels`), a space is a space. + fn clusters(text: &str, levels: &[u8]) -> Vec { + text.chars().enumerate().map(|(i, c)| Cluster { glyphs: i..i + 1, start: i as u32, end: i as u32 + 1, first: c, space: c == ' ', advance: 10.0, level: levels.get(i).copied().unwrap_or(0) }).collect() + } + + fn shown(cl: &[Cluster], line: Range, para: u8) -> String { + place(cl, line, para).iter().map(|(k, _)| cl[*k].first).collect() + } + + /// From outside PR #39: lines are found in reading order, after the last space that fits + /// or between the clusters of a word wider than the line. + #[test] + fn lines_break_in_reading_order() { + let wide = |w: f32| move |_: bool| Some(w); + assert_eq!(break_lines(&clusters("ab cd ef", &[]), &wide(50.0)), vec![0..5, 6..8]); + assert_eq!(break_lines(&clusters("abcdefgh", &[]), &wide(30.0)), vec![0..3, 3..6, 6..8]); + assert_eq!(break_lines(&clusters("ab cd", &[]), &|_| None), vec![0..5]); + assert_eq!(break_lines(&[], &wide(10.0)), vec![0..0], "an empty paragraph is one empty line"); + assert_eq!(break_lines(&clusters("ab ", &[]), &wide(100.0)), vec![0..2], "spaces at the end are left out"); + // A cluster wider than the line stays whole, on a line of its own. + let mut big = clusters("abc", &[]); + big[1].advance = 500.0; + assert_eq!(break_lines(&big, &wide(15.0)), vec![0..1, 1..2, 2..3]); + // The first line's room can differ (an indent). + let lines = break_lines(&clusters("aa bb cc dd", &[]), &|first| Some(if first { 25.0 } else { 55.0 })); + assert_eq!(lines, vec![0..2, 3..8, 9..11]); + } + + #[test] + fn a_line_is_displayed_in_visual_order() { + // Left to right throughout: as written. + let ltr = clusters("abc def", &[]); + assert_eq!(shown(<r, 0..7, 0), "abc def"); + // A right-to-left word inside left-to-right text is reversed in place. + let mixed = clusters("ab CDE fg", &[0, 0, 0, 1, 1, 1, 0, 0, 0]); + assert_eq!(shown(&mixed, 0..9, 0), "ab EDC fg"); + // A number (level 2) inside a right-to-left paragraph keeps its digits in order, and the + // paragraph runs from the right: its first word is the rightmost. + let rtl = clusters("ABC 123 DEF", &[1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1]); + assert_eq!(shown(&rtl, 0..11, 1), "FED 123 CBA"); + // Each line is reordered on its own: the first line holds the first words. + assert_eq!(shown(&rtl, 0..7, 1), "123 CBA"); + assert_eq!(shown(&rtl, 8..11, 1), "FED"); + // Boxes run left to right without gaps, each as wide as its cluster. + let boxes: Vec = place(&mixed, 0..9, 0).into_iter().map(|p| p.1).collect(); + assert!(boxes.windows(2).all(|w| w[0].x1 == w[1].x0) && boxes[0].x0 == 0.0 && boxes[8].x1 == 90.0); + assert_eq!(boxes.iter().map(|b| b.rtl).collect::>(), [false, false, false, true, true, true, false, false, false]); + assert_eq!(boxes[3].start, 5, "the word's last letter is its leftmost"); + assert_eq!(place(<r, 3..3, 0), Vec::new()); + assert_eq!(place(<r, 5..99, 0), Vec::new(), "a range outside the paragraph places nothing"); + } + + #[test] + fn the_caret_stands_where_each_cluster_is_read_from() { + // "ab" then "CDE" right to left: a b E D C. Before C (boundary 2) is the line's right + // end; after E (boundary 5, the line's end) is E's left edge, where "ab" ends. + let cl = clusters("abCDE", &[0, 0, 1, 1, 1]); + let boxes: Vec = place(&cl, 0..5, 0).into_iter().map(|p| p.1).collect(); + assert_eq!(stops(&boxes, (0, 0.0)), vec![(0, 0.0), (1, 10.0), (2, 50.0), (3, 40.0), (4, 30.0), (5, 20.0)]); + // Left to right, the stops are the clusters' left edges and the line's end. + let ltr: Vec = place(&clusters("abc", &[]), 0..3, 0).into_iter().map(|p| p.1).collect(); + assert_eq!(stops(<r, (0, 0.0)), vec![(0, 0.0), (1, 10.0), (2, 20.0), (3, 30.0)]); + assert_eq!(stops(&[], (7, 4.0)), vec![(7, 4.0)]); + // A cluster of several characters has one stop, and the line's end is after all of it. + let lig = [CaretBox { start: 0, end: 3, x0: 0.0, x1: 12.0, rtl: false }]; + assert_eq!(stops(&lig, (0, 0.0)), vec![(0, 0.0), (3, 12.0)]); + } + + #[test] + fn shared_characters_take_the_script_beside_them() { + let mut s = Scripts::new(); + let of = |s: &mut Scripts, t: &str| s.of(&t.chars().collect::>()); + assert!(of(&mut s, "12 - 3").iter().all(Option::is_none)); + let latin = Some(harfrust::script::LATIN); + assert_eq!(of(&mut s, "(a 1)"), vec![latin; 5], "before the first letter: the script after"); + let mixed = of(&mut s, "ab \u{05D0}\u{05D1} 12"); + assert_eq!(&mixed[..3], &[latin; 3]); + assert!(mixed[3].is_some() && mixed[3] != latin, "Hebrew letters have their own script"); + assert_eq!(&mixed[4..], &[mixed[3]; 4], "the space and digits after them are shaped with them"); + assert_eq!(of(&mut s, ""), Vec::new()); + } +} diff --git a/crates/text/src/rich.rs b/crates/text/src/rich.rs index 50f5aaa1..a01b3868 100644 --- a/crates/text/src/rich.rs +++ b/crates/text/src/rich.rs @@ -4,14 +4,23 @@ //! glyphs come out grouped by the run's `paint` (the caller's colour and link), so a block with //! several colours draws as one filled path per colour. //! +//! Text that mixes directions (ADR 0130): a run is shaped in stretches of one direction and one +//! script, lines are found in reading order and each is then put in the order it is displayed +//! ([`crate::lines`]); a cluster its run's face has no glyph for is shaped again in a fallback +//! face ([`crate::fallback`]). +//! //! One run in one paragraph lays out exactly as [`crate::Fonts::layout`] always has: the same //! outline, box, lines and carets. -use crate::{Align, CaretLine, Fonts, Layout, MAX_CHARS, Pen, PlacedGlyph, TextError}; +use crate::fallback::{Coverage, MAX_FALLBACK_FACES, MAX_WIDE_SEARCHES, needs_glyph, pick_face}; +use crate::lines::{Cluster, Scripts, break_lines, place, stops}; +use crate::{Align, CaretBox, CaretLine, Fonts, Layout, MAX_CHARS, Pen, PlacedGlyph, TextError}; use anicraft_geom::{Path, PathCmd, Vec2}; +use craft_text::bidi; use skrifa::MetadataProvider as _; use skrifa::raw::TableProvider as _; use std::collections::HashMap; +use std::ops::Range; use std::sync::Arc; /// Most runs laid out in one block; more are joined into the last. @@ -123,43 +132,188 @@ struct RunMetrics { } /// One shaped glyph, ready to place. +#[derive(Clone)] struct Shaped { outline: Option>, - /// Character it starts at (of the whole text). + /// The character its cluster starts at (of the whole text). index: u32, run: u32, x_offset: f32, y_offset: f32, advance: f32, - space: bool, + /// Its face has no glyph for it: this is the face's "notdef" box. + notdef: bool, } -/// A stretch of one paragraph in one run: what is shaped on its own. +/// A stretch of one paragraph in one run, one direction and one script: what is shaped on its +/// own. struct Segment { + para: usize, run: usize, - /// Byte range in the text, and the character its start is. + /// Its bytes and its characters in the text (from the first, up to the second). bytes: (usize, usize), - first_char: u32, + chars: (u32, u32), + /// Its embedding level: odd reads right to left. + level: u8, + script: Option, } /// A laid-out line: its paragraph, whether it is the paragraph's first, its width, its glyphs -/// with their pen x (from the line's start). +/// in the order they are displayed with their pen x (from the line's left end), and where its +/// clusters stand. struct Line { para: usize, first: bool, width: f32, glyphs: Vec<(Shaped, f32)>, + rtl: bool, + boxes: Vec, } -/// One paragraph: its first character, its length in characters, and its byte range (without -/// a trailing `\r`). +/// One paragraph: its first character, its length in characters, its byte range (without a +/// trailing `\r`) and its embedding level (odd: it reads right to left). struct Para { start: u32, len: u32, bytes: (usize, usize), + level: u8, +} + +/// A face ready to shape with. +struct Face<'a> { + font: skrifa::FontRef<'a>, + shaper: harfrust::Shaper<'a>, + outlines: skrifa::outline::OutlineGlyphCollection<'a>, + /// Outlines drawn so far, by glyph and size. + cache: HashMap<(u32, u32), Option>>, +} + +/// A stretch of text to shape in one face. +struct Job<'t> { + text: &'t str, + /// Its paragraph's bytes (the letters around the stretch are its context) and its own. + para: (usize, usize), + bytes: (usize, usize), + first_char: u32, + run: u32, + rtl: bool, + script: Option, + /// The size its glyphs are drawn at, and the extra space after each cluster (pixels). + size: f32, + letter_spacing: f32, +} + +/// A cluster (or several in a row) its run's face has no glyph for, to shape in a fallback +/// face: its segment, the glyphs it replaces there, its characters and the fallback face. +struct Hole { + seg: usize, + glyphs: Range, + chars: (u32, u32), + face: usize, +} + +/// Shapes a stretch of text. Glyphs come back in the order they are displayed (left to right), +/// as the shaper gives them, each with the character its cluster starts at. +fn shape(face: &mut Face<'_>, job: &Job<'_>) -> Vec { + let Some(piece) = job.text.get(job.bytes.0..job.bytes.1) else { return Vec::new() }; + let mut to_char = vec![0u32; piece.len() + 1]; + let mut n = 0u32; + for (b, _) in piece.char_indices() { + if let Some(slot) = to_char.get_mut(b) { + *slot = n; + } + n += 1; + } + if let Some(last) = to_char.last_mut() { + *last = n; + } + let size = skrifa::instance::Size::new(job.size); + let upem = f32::from(skrifa::MetadataProvider::metrics(&face.font, size, skrifa::instance::LocationRef::default()).units_per_em.max(1)); + let scale = job.size / upem; + let mut buffer = harfrust::UnicodeBuffer::new(); + buffer.push_str(piece); + // The letters around it in its paragraph: Arabic letters join across a change of style or + // face as they do inside one. + if let Some(before) = job.text.get(job.para.0..job.bytes.0) { + buffer.set_pre_context(before); + } + if let Some(after) = job.text.get(job.bytes.1..job.para.1) { + buffer.set_post_context(after); + } + buffer.set_direction(if job.rtl { harfrust::Direction::RightToLeft } else { harfrust::Direction::LeftToRight }); + if let Some(script) = job.script { + buffer.set_script(script); + } + buffer.guess_segment_properties(); + let out = face.shaper.shape(buffer, harfrust::ShapeOptions::new()); + let mut list: Vec = Vec::with_capacity(out.glyph_infos().len()); + for (info, pos) in out.glyph_infos().iter().zip(out.glyph_positions()) { + let local = to_char.get(info.cluster as usize).copied().unwrap_or(n).min(n); + let outlines = &face.outlines; + let outline = face + .cache + .entry((info.glyph_id, job.size.to_bits())) + .or_insert_with(|| { + let g = outlines.get(skrifa::GlyphId::new(info.glyph_id))?; + let mut p = Path::new(); + let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); + let mut pen = Pen { cmds: &mut p.cmds, x: 0.0, y: 0.0 }; + let _ = g.draw(settings, &mut pen); + Some(Arc::new(p)) + }) + .clone(); + list.push(Shaped { outline, index: job.first_char + local, run: job.run, x_offset: pos.x_offset as f32 * scale, y_offset: pos.y_offset as f32 * scale, advance: pos.x_advance as f32 * scale, notdef: info.glyph_id == 0 }); + } + // Letter spacing follows each cluster, not each glyph: a letter's marks stay on it. + let mut i = 0; + while let Some(index) = list.get(i).map(|g| g.index) { + if list.get(i + 1).is_none_or(|next| next.index != index) + && let Some(g) = list.get_mut(i) + { + g.advance += job.letter_spacing; + } + i += 1; + } + list +} + +/// The clusters of one segment's glyphs, in reading order: each one's glyphs (a range of +/// `glyphs`) and its characters, from its first up to the next cluster's (`end` for the last). +fn clusters_of(glyphs: &[Shaped], end: u32) -> Vec<(Range, u32, u32)> { + let mut out: Vec<(Range, u32, u32)> = Vec::new(); + let mut i = 0; + while let Some(g) = glyphs.get(i) { + let mut j = i + 1; + while glyphs.get(j).is_some_and(|next| next.index == g.index) { + j += 1; + } + out.push((i..j, g.index, end)); + i = j; + } + // Right-to-left glyphs come last character first. + out.sort_by_key(|c| c.1); + for k in 1..out.len() { + let next = out.get(k).map(|c| c.1); + if let (Some(c), Some(next)) = (out.get_mut(k - 1), next) { + c.2 = next; + } + } + out } impl Fonts { + /// Opens face `id` to shape with it. + fn with_face(&self, id: fontdb::ID, f: impl FnOnce(&mut Face<'_>) -> R) -> Option { + self.db + .with_face_data(id, |data, index| { + let font = skrifa::FontRef::from_index(data, index).ok()?; + let shaper_data = harfrust::ShaperData::new(&font); + let mut face = Face { shaper: shaper_data.shaper(&font).build(), outlines: font.outline_glyphs(), font, cache: HashMap::new() }; + Some(f(&mut face)) + }) + .flatten() + } + /// Lays styled text out ([`RichText`]). `glyphs` also hands back each glyph on its own. pub fn layout_rich(&self, rich: &RichText, glyphs: bool) -> Result { let text = rich.text; @@ -212,6 +366,8 @@ impl Fonts { families.push(faces.get(face).map_or(family, |f| f.1.clone())); } let chars: Vec = text.chars().collect(); + // Embedding levels (UAX #9), when anything in the text reads right to left. + let levels = Some(text).filter(|t| !t.is_ascii()).map(|t| bidi::Paragraph::new(t, bidi::Direction::Auto)).filter(bidi::Paragraph::needs_reordering); // Paragraphs at line breaks. let mut paras: Vec = Vec::new(); @@ -219,18 +375,25 @@ impl Fonts { for raw in text.split('\n') { let body = raw.strip_suffix('\r').unwrap_or(raw); let len = body.chars().count() as u32; - paras.push(Para { start: ch, len, bytes: (byte, byte + body.len()) }); + let level = levels.as_ref().map_or(0, |l| l.paragraph_level_at(byte)); + paras.push(Para { start: ch, len, bytes: (byte, byte + body.len()), level }); byte += raw.len() + 1; ch += raw.chars().count() as u32 + 1; } // Byte offset of every character (and of the end). let mut byte_of: Vec = text.char_indices().map(|(b, _)| b).collect(); byte_of.push(text.len()); - // Segments: each paragraph cut at run boundaries (both in order: one pass over each). - let mut segs: Vec<(usize, Segment)> = Vec::new(); + let byte_at = |c: u32| byte_of.get(c as usize).copied().unwrap_or(text.len()); + // Segments: each paragraph cut at run boundaries (both in order: one pass over each), + // and each of those where the direction or the script changes. + let mut scripts = Scripts::new(); + let mut segs: Vec = Vec::new(); let mut ri = 0usize; for (pi, p) in paras.iter().enumerate() { let (s, e) = (p.start, p.start + p.len); + let plain = text.get(p.bytes.0..p.bytes.1).is_none_or(str::is_ascii); + let script_of = if plain { Vec::new() } else { scripts.of(chars.get(s as usize..e as usize).unwrap_or(&[])) }; + let kind = |c: u32| (levels.as_ref().map_or(0, |l| l.level_at(byte_at(c))), script_of.get((c - s) as usize).copied().flatten()); while runs.get(ri).is_some_and(|r| r.1 <= s) && ri + 1 < runs.len() { ri += 1; } @@ -240,16 +403,22 @@ impl Fonts { break; } let (a, b) = (s.max(*rs), e.min(*re)); - if a < b { - let bytes = (byte_of.get(a as usize).copied().unwrap_or(p.bytes.1), byte_of.get(b as usize).copied().unwrap_or(p.bytes.1)); - segs.push((pi, Segment { run: k, bytes, first_char: a })); + let mut from = a; + while from < b { + let (level, script) = kind(from); + let mut to = from + 1; + while to < b && kind(to) == (level, script) { + to += 1; + } + segs.push(Segment { para: pi, run: k, bytes: (byte_at(from), byte_at(to)), chars: (from, to), level, script }); + from = to; } k += 1; } } // The segments of each run. let mut segs_of_run: Vec> = vec![Vec::new(); runs.len()]; - for (si, (_, seg)) in segs.iter().enumerate() { + for (si, seg) in segs.iter().enumerate() { if let Some(list) = segs_of_run.get_mut(seg.run) { list.push(si); } @@ -261,145 +430,161 @@ impl Fonts { list.push(ri); } } + let job_for = |seg: &Segment, bytes: (usize, usize), first_char: u32, m: &RunMetrics| -> Job<'_> { + let para = paras.get(seg.para).map_or(bytes, |p| p.bytes); + let letter_spacing = runs.get(seg.run).map_or(0.0, |r| r.2.letter_spacing); + Job { text, para, bytes, first_char, run: seg.run as u32, rtl: seg.level % 2 == 1, script: seg.script, size: m.glyph_size, letter_spacing } + }; let mut shaped: Vec> = (0..segs.len()).map(|_| Vec::new()).collect(); let mut metrics: Vec = vec![RunMetrics::default(); runs.len()]; - let mut missing = 0usize; for (fi, (id, _)) in faces.iter().enumerate() { - let ok = self.db.with_face_data(*id, |data, index| { - let font = skrifa::FontRef::from_index(data, index).ok()?; - let shaper_data = harfrust::ShaperData::new(&font); - let shaper = shaper_data.shaper(&font).build(); - let outlines = font.outline_glyphs(); - let charmap = font.charmap(); - let os2 = font.os2().ok(); - let mut cache: HashMap<(u32, u32), Option>> = HashMap::new(); + let ok = self.with_face(*id, |face| { + let os2 = face.font.os2().ok(); for &ri in runs_of_face.get(fi).map_or(&[][..], Vec::as_slice) { - let Some((rs, re, st)) = runs.get(ri) else { continue }; - let m = run_metrics(&font, os2.as_ref(), st); + let Some((_, _, st)) = runs.get(ri) else { continue }; + let m = run_metrics(&face.font, os2.as_ref(), st); if let Some(slot) = metrics.get_mut(ri) { *slot = m; } - missing += chars.get(*rs as usize..*re as usize).unwrap_or(&[]).iter().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(**c).is_none()).count(); - let size = skrifa::instance::Size::new(m.glyph_size); - let upem = f32::from(skrifa::MetadataProvider::metrics(&font, size, skrifa::instance::LocationRef::default()).units_per_em.max(1)); - let scale = m.glyph_size / upem; for &si in segs_of_run.get(ri).map_or(&[][..], Vec::as_slice) { - let Some((_, seg)) = segs.get(si) else { continue }; - let Some(piece) = text.get(seg.bytes.0..seg.bytes.1) else { continue }; - let mut to_char = vec![0u32; piece.len() + 1]; - let mut n = 0u32; - for (b, _) in piece.char_indices() { - if let Some(slot) = to_char.get_mut(b) { - *slot = n; - } - n += 1; - } - if let Some(last) = to_char.last_mut() { - *last = n; - } - let mut buffer = harfrust::UnicodeBuffer::new(); - buffer.push_str(piece); - buffer.guess_segment_properties(); - let out = shaper.shape(buffer, harfrust::ShapeOptions::new()); - let mut list: Vec = Vec::with_capacity(out.glyph_infos().len()); - for (info, pos) in out.glyph_infos().iter().zip(out.glyph_positions()) { - let local = to_char.get(info.cluster as usize).copied().unwrap_or(n).min(n); - let index = seg.first_char + local; - let outline = cache - .entry((info.glyph_id, m.glyph_size.to_bits())) - .or_insert_with(|| { - let g = outlines.get(skrifa::GlyphId::new(info.glyph_id))?; - let mut p = Path::new(); - let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); - let mut pen = Pen { cmds: &mut p.cmds, x: 0.0, y: 0.0 }; - let _ = g.draw(settings, &mut pen); - Some(Arc::new(p)) - }) - .clone(); - list.push(Shaped { - outline, - index, - run: ri as u32, - x_offset: pos.x_offset as f32 * scale, - y_offset: pos.y_offset as f32 * scale, - advance: pos.x_advance as f32 * scale + st.letter_spacing, - space: chars.get(index as usize).is_some_and(|c| c.is_whitespace()), - }); - } + let Some(seg) = segs.get(si) else { continue }; + let list = shape(face, &job_for(seg, seg.bytes, seg.chars.0, &m)); if let Some(slot) = shaped.get_mut(si) { *slot = list; } } } - Some(()) }); - if ok.flatten().is_none() { + if ok.is_none() { return Err(TextError::NoFonts); } } + // Fallback faces (ADR 0130): a cluster its run's face has no glyph for goes, whole, to + // the first fallback face that has all of it, and is shaped again there. + let mut missing = 0usize; + let mut fallback_ids: Vec = Vec::new(); + let mut holes: Vec = Vec::new(); + if shaped.iter().flatten().any(|g| g.notdef) { + let mut cover = Coverage::new(self); + let mut lists: HashMap<(bool, bool), Vec> = HashMap::new(); + let mut searches = 0usize; + for (si, seg) in segs.iter().enumerate() { + let Some(list) = shaped.get(si).filter(|l| l.iter().any(|g| g.notdef)) else { continue }; + let Some((_, _, st)) = runs.get(seg.run) else { continue }; + let Some(own) = face_of_run.get(seg.run).and_then(|f| faces.get(*f)).map(|f| f.0) else { continue }; + let mut open: Option = None; + for (g, c0, c1) in clusters_of(list, seg.chars.1) { + let lacking = list.get(g.clone()).is_some_and(|gs| gs.iter().any(|x| x.notdef)); + let drawn: Vec = if lacking { chars.get(c0 as usize..c1 as usize).unwrap_or(&[]).iter().copied().filter(|c| needs_glyph(*c)).collect() } else { Vec::new() }; + let had = drawn.iter().filter(|c| cover.has(own, **c)).count(); + let mut chosen: Option = None; + if had < drawn.len() { + let candidates = lists.entry((st.bold, st.italic)).or_insert_with(|| self.fallback_list(st.bold, st.italic).into_iter().filter(|id| *id != own).collect()); + let mut pick = pick_face(&drawn, had, candidates.len(), &mut |f, c| candidates.get(f).is_some_and(|id| cover.has(*id, c))); + let lacks = |id: Option, cover: &mut Coverage| drawn.iter().copied().find(|c| !cover.has(id.unwrap_or(own), *c)); + // No listed face has all of it: any installed face with the letter. + if let Some(c) = lacks(pick.and_then(|f| candidates.get(f).copied()), &mut cover) + && searches < MAX_WIDE_SEARCHES + { + searches += 1; + if let Some(id) = self.any_face_with(c).filter(|id| *id != own && !candidates.contains(id)) { + candidates.push(id); + pick = pick_face(&drawn, had, candidates.len(), &mut |f, c| candidates.get(f).is_some_and(|id| cover.has(*id, c))); + } + } + chosen = pick.and_then(|f| candidates.get(f).copied()).and_then(|id| match fallback_ids.iter().position(|known| *known == id) { + Some(k) => Some(k), + None if fallback_ids.len() < MAX_FALLBACK_FACES => { + fallback_ids.push(id); + Some(fallback_ids.len() - 1) + } + None => None, + }); + let face = chosen.and_then(|k| fallback_ids.get(k).copied()).unwrap_or(own); + missing += drawn.iter().filter(|c| !cover.has(face, **c)).count(); + } + match (&mut open, chosen) { + (Some(h), Some(f)) if h.face == f && h.chars.1 == c0 => { + h.chars.1 = c1; + h.glyphs = h.glyphs.start.min(g.start)..h.glyphs.end.max(g.end); + } + _ => { + holes.extend(open.take()); + open = chosen.map(|face| Hole { seg: si, glyphs: g, chars: (c0, c1), face }); + } + } + } + holes.extend(open); + } + } + let mut patches: Vec<(usize, Range, Vec)> = Vec::new(); + for (k, id) in fallback_ids.iter().enumerate() { + let done = self.with_face(*id, |face| { + let mut out = Vec::new(); + for h in holes.iter().filter(|h| h.face == k) { + let (Some(seg), Some(m)) = (segs.get(h.seg), segs.get(h.seg).and_then(|s| metrics.get(s.run))) else { continue }; + out.push((h.seg, h.glyphs.clone(), shape(face, &job_for(seg, (byte_at(h.chars.0), byte_at(h.chars.1)), h.chars.0, m)))); + } + out + }); + // A face that can't be read after all leaves its clusters as boxes. + patches.extend(done.unwrap_or_default()); + } + // Last glyphs first, so the ranges before them stay where they are. + patches.sort_by_key(|p| std::cmp::Reverse((p.0, p.1.start))); + for (si, range, list) in patches { + if let Some(slot) = shaped.get_mut(si) + && range.start <= range.end + && range.end <= slot.len() + { + slot.splice(range, list); + } + } + let fallbacks: Vec = fallback_ids.iter().map(|id| self.family_of(*id)).collect(); + // Paragraph styles, sanitized; missing ones take the last one's. let para_style = |pi: usize| -> ParaStyle { rich.paragraphs.get(pi).or(rich.paragraphs.last()).map(sanitize_para).unwrap_or_default() }; let width = rich.width.filter(|w| w.is_finite() && *w > 0.0).map(|w| w.min(100_000.0)); - // Lines: each paragraph's glyphs, wrapped at spaces to its room if there is a width. + // Lines: each paragraph's clusters in reading order, wrapped at spaces to its room if + // there is a width; then each line in the order it is displayed. let mut lines: Vec = Vec::new(); - let mut seg_iter = segs.into_iter().zip(shaped).peekable(); - for (pi, _) in paras.iter().enumerate() { + let mut seg_iter = segs.iter().zip(shaped).peekable(); + for (pi, p) in paras.iter().enumerate() { let ps = para_style(pi); - let mut run_glyphs: Vec = Vec::new(); - while let Some(((p, _), _)) = seg_iter.peek() { - if *p != pi { - break; - } - if let Some((_, g)) = seg_iter.next() { - run_glyphs.extend(g); + let mut para_glyphs: Vec = Vec::new(); + let mut clusters: Vec = Vec::new(); + while seg_iter.peek().is_some_and(|(seg, _)| seg.para == pi) { + let Some((seg, list)) = seg_iter.next() else { break }; + let base = para_glyphs.len(); + for (g, start, end) in clusters_of(&list, seg.chars.1) { + let advance = list.get(g.clone()).map_or(0.0, |gs| gs.iter().map(|x| x.advance).sum()); + let first = chars.get(start as usize).copied().unwrap_or(' '); + clusters.push(Cluster { glyphs: base + g.start..base + g.end, start, end, first, space: first.is_whitespace(), advance, level: seg.level }); } + para_glyphs.extend(list); } let room = |first: bool| width.map(|w| w - ps.left_margin - ps.right_margin - if first { ps.indent } else { 0.0 }); - let mut first = true; - let mut line: Vec<(Shaped, f32)> = Vec::new(); - let mut x = 0.0f32; - // Where the current line could break: after its last space. - let mut break_at: Option = None; - for g in run_glyphs { - if let Some(w) = room(first) - && !g.space - && x + g.advance > w - && !line.is_empty() - { - // Wrap: at the last space if there is one (dropping trailing spaces), else here. - let rest = match break_at { - Some(b) => line.split_off(b), - None => Vec::new(), - }; - while line.last().is_some_and(|(g, _)| g.space) { - line.pop(); + for (n, range) in break_lines(&clusters, &room).into_iter().enumerate() { + let mut line = Line { para: pi, first: n == 0, width: 0.0, glyphs: Vec::new(), rtl: p.level % 2 == 1, boxes: Vec::new() }; + for (k, at) in place(&clusters, range, p.level) { + let mut x = at.x0; + for g in clusters.get(k).and_then(|c| para_glyphs.get(c.glyphs.clone())).unwrap_or(&[]) { + line.glyphs.push((g.clone(), x)); + x += g.advance; } - let lw = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push(Line { para: pi, first, width: lw, glyphs: std::mem::take(&mut line) }); - first = false; - let shift = rest.first().map_or(0.0, |(_, gx)| *gx); - line = rest.into_iter().map(|(g, gx)| (g, gx - shift)).collect(); - x = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - break_at = None; - } - line.push((g, x)); - x += line.last().map_or(0.0, |(g, _)| g.advance); - if line.last().is_some_and(|(g, _)| g.space) { - break_at = Some(line.len()); + line.width = at.x1; + line.boxes.push(at); } + lines.push(line); } - while line.last().is_some_and(|(g, _)| g.space) { - line.pop(); - } - let lw = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push(Line { para: pi, first, width: lw, glyphs: line }); } // Each line's room above and below its baseline: the most any run on it needs (an // empty line: the run its paragraph starts in). `(ascent, descent, line height)`, the - // height with the paragraph's line spacing. + // height with the paragraph's line spacing. A fallback face's letters sit on the line + // their run's face makes. let run_at = |c: u32| runs.partition_point(|r| r.0 <= c).saturating_sub(1); let line_metrics = |l: &Line| -> (f32, f32, f32) { let mut list: Vec = l.glyphs.iter().map(|(g, _)| g.run as usize).collect(); @@ -536,6 +721,7 @@ impl Fonts { glyphs: placed, pieces, families, + fallbacks, }) } } @@ -592,21 +778,18 @@ fn caret_lines(lines: &[Line], paras: &[Para], tops: &[f32], lm: &[(f32, f32, f3 let shift = shift_of(l); let (pstart, plen) = paras.get(l.para).map_or((0, 0), |p| (p.start, p.len)); let ch = |i: u32| i.clamp(pstart, pstart + plen); - let start = if l.first { pstart } else { l.glyphs.first().map_or(pstart, |(g, _)| ch(g.index)) }; - let mut stops: Vec<(u32, f32)> = l.glyphs.iter().map(|(g, gx)| (ch(g.index), shift + gx)).collect(); - stops.sort_by_key(|s| s.0); - stops.dedup_by_key(|s| s.0); + let boxes: Vec = l.boxes.iter().map(|b| CaretBox { start: ch(b.start), end: ch(b.end), x0: shift + b.x0, x1: shift + b.x1, rtl: b.rtl }).collect(); + let start = if l.first { pstart } else { boxes.iter().map(|b| b.start).min().unwrap_or(pstart) }; + // Where the line starts: its left end, or its right end in a right-to-left paragraph. + let edge = shift + if l.rtl { l.width } else { 0.0 }; + let mut stops = stops(&boxes, (start, edge)); if l.first && stops.first().is_none_or(|s| s.0 > start) { - stops.insert(0, (start, shift)); - } - // The boundary after the last glyph (its trailing spaces, if any, follow it). - if let Some(&(c, _)) = stops.last() { - stops.push((c + 1, shift + l.width)); + stops.insert(0, (start, edge)); } let m = lm.get(row).copied().unwrap_or_default(); let top = tops.get(row).copied().unwrap_or(0.0); let baseline = if uniform { first_ascent + top } else { top + m.0 }; - out.push(CaretLine { start, end: start, stops, top, height: m.2, baseline }); + out.push(CaretLine { start, end: start, stops, top, height: m.2, baseline, rtl: l.rtl, boxes }); // The previous line of the same paragraph ends where this one starts. if !l.first && let Some(prev) = out.len().checked_sub(2).and_then(|i| out.get_mut(i)) { prev.end = start; diff --git a/crates/text/src/rich_tests.rs b/crates/text/src/rich_tests.rs index f9bc8940..2c6b3a00 100644 --- a/crates/text/src/rich_tests.rs +++ b/crates/text/src/rich_tests.rs @@ -179,3 +179,185 @@ fn hostile_runs_are_capped_and_sanitized() { } assert_eq!(f.layout_rich(&RichText { text: &"x".repeat(MAX_CHARS + 1), runs: &[], paragraphs: &[], width: None }, false), Err(TextError::TooLong)); } + +// Mixed directions and fallback faces (ADR 0130), on fonts made in memory (`testfont`): every +// letter is a box half an em wide, so at size 20 a letter is 10 pixels. + +use crate::testfont::{self, LETTER_HEIGHT, NOTDEF_HEIGHT}; + +const LATIN: &str = "abcdefghijklmnopqrstuvwxyz0123456789 .-"; +/// Alef, bet, gimel, dalet, he. +const HEBREW: &str = "\u{05D0}\u{05D1}\u{05D2}\u{05D3}\u{05D4} "; + +fn both() -> Fonts { + Fonts::from_faces([testfont::font("Test Both", &format!("{LATIN}{HEBREW}"), 500)]) +} + +fn set(f: &Fonts, family: &str, text: &str, width: Option) -> Layout { + let runs = [Run { chars: usize::MAX, style: RunStyle { family: family.into(), size: 20.0, ..RunStyle::default() } }]; + f.layout_rich(&RichText { text, runs: &runs, paragraphs: &[], width }, true).unwrap() +} + +/// The characters of the glyphs on line `row`, left to right. +fn shown(l: &Layout, row: usize) -> Vec { + let baseline = l.carets[row].baseline; + let mut on: Vec<&PlacedGlyph> = l.glyphs.iter().filter(|g| g.baseline == baseline).collect(); + on.sort_by(|a, b| a.x.total_cmp(&b.x)); + on.iter().map(|g| g.index).collect() +} + +/// How many of a layout's glyphs are "notdef" boxes. +fn boxes(l: &Layout) -> usize { + let notdef = 20.0 * f32::from(NOTDEF_HEIGHT) / f32::from(testfont::EM); + let letter = 20.0 * f32::from(LETTER_HEIGHT) / f32::from(testfont::EM); + let tall = |g: &&PlacedGlyph| g.outline.bounds().height(); + assert!(l.glyphs.iter().filter(|g| !g.outline.cmds.is_empty()).all(|g| (tall(&g) - notdef).abs() < 0.01 || (tall(&g) - letter).abs() < 0.01)); + l.glyphs.iter().filter(|g| !g.outline.cmds.is_empty() && (tall(g) - notdef).abs() < 0.01).count() +} + +#[test] +fn a_right_to_left_word_in_left_to_right_text_reads_from_its_right() { + let f = both(); + // a b _ alef bet gimel _ c d: the Hebrew word is displayed gimel, bet, alef. + let l = set(&f, "Test Both", "ab \u{05D0}\u{05D1}\u{05D2} cd", None); + assert_eq!(shown(&l, 0), vec![0, 1, 2, 5, 4, 3, 6, 7, 8]); + assert_eq!((l.width, l.missing, boxes(&l)), (90.0, 0, 0)); + let c = &l.carets[0]; + assert!(!c.rtl); + // The caret before alef is at the word's right end, after gimel at its left end. + assert_eq!((c.x_at(3), c.x_at(4), c.x_at(5), c.x_at(6)), (60.0, 50.0, 40.0, 60.0)); + assert_eq!(c.boxes.len(), 9); + assert!(c.boxes.windows(2).all(|w| w[0].x1 == w[1].x0), "boxes run left to right without gaps"); + // Text that reads one way is laid out as it always was. + let plain = set(&f, "Test Both", "ab cd", None); + assert_eq!(shown(&plain, 0), vec![0, 1, 2, 3, 4]); + assert_eq!(plain.carets[0].stops, vec![(0, 0.0), (1, 10.0), (2, 20.0), (3, 30.0), (4, 40.0), (5, 50.0)]); +} + +/// From outside PR #39: a number inside right-to-left text keeps its digits in order, and a +/// wrapped right-to-left paragraph starts with its first words. +#[test] +fn a_right_to_left_paragraph_runs_from_the_right_and_wraps_in_reading_order() { + let f = both(); + // alef bet _ 1 2 _ gimel dalet, displayed: dalet gimel _ 1 2 _ bet alef. + let l = set(&f, "Test Both", "\u{05D0}\u{05D1} 12 \u{05D2}\u{05D3}", None); + assert_eq!(shown(&l, 0), vec![7, 6, 5, 3, 4, 2, 1, 0]); + let c = &l.carets[0]; + assert!(c.rtl); + assert_eq!((c.x_at(0), c.x_at(8)), (l.width, 0.0), "the paragraph starts at its right end and ends at its left"); + // Wrapped: the first line holds the first word, each line displayed right to left. + let w = set(&f, "Test Both", "\u{05D0}\u{05D1} \u{05D2}\u{05D3}", Some(25.0)); + assert_eq!(w.lines, 2); + assert_eq!((shown(&w, 0), shown(&w, 1)), (vec![1, 0], vec![4, 3])); + assert_eq!((w.carets[0].start, w.carets[0].end, w.carets[1].start, w.carets[1].end), (0, 3, 3, 5)); + // Each paragraph has its own direction. + let two = set(&f, "Test Both", "ab\n\u{05D0}\u{05D1}", None); + assert_eq!((two.carets[0].rtl, two.carets[1].rtl), (false, true)); + assert_eq!(shown(&two, 1), vec![4, 3]); +} + +#[test] +fn styled_runs_keep_their_style_through_reordering() { + let f = both(); + // The first run ends inside the Hebrew word: alef is its last letter. + let style = |paint| RunStyle { family: "Test Both".into(), size: 20.0, underline: paint == 2, paint, ..RunStyle::default() }; + let runs = [Run { chars: 3, style: style(1) }, Run { chars: 2, style: style(2) }]; + let l = f.layout_rich(&RichText { text: "ab\u{05D0}\u{05D1}\u{05D2}", runs: &runs, paragraphs: &[], width: None }, true).unwrap(); + assert_eq!(shown(&l, 0), vec![0, 1, 4, 3, 2]); + let paint_at = |i: u32| l.glyphs.iter().find(|g| g.index == i).unwrap().paint; + assert_eq!([0, 1, 2, 3, 4].map(paint_at), [1, 1, 1, 2, 2]); + // The underline is under the second run's two letters, which are displayed first. + let piece = &l.pieces.iter().find(|p| p.0 == 2).unwrap().1; + let b = piece.bounds(); + assert!(b.min.x >= 20.0 && b.max.x <= 40.0, "{b:?}"); +} + +/// From outside PR #40: letters the chosen face lacks come from a fallback face, the block +/// keeps its family, and a character no face has is counted. +#[test] +fn letters_the_face_lacks_come_from_a_fallback_face() { + // A listed fallback family wins over another face that has the letters. + let f = Fonts::from_faces([testfont::font("Test Latin", LATIN, 500), testfont::font("Noto Sans Hebrew", HEBREW, 800), testfont::font("Aaa Hebrew", HEBREW, 600)]); + let l = set(&f, "Test Latin", "ab \u{05D0}\u{05D1}", None); + assert_eq!((l.missing, boxes(&l)), (0, 0)); + assert_eq!((l.family.as_str(), l.families.clone(), l.fallbacks.clone()), ("Test Latin", vec!["Test Latin".to_string()], vec!["Noto Sans Hebrew".to_string()])); + assert_eq!(l.width, 30.0 + 32.0, "the Hebrew letters are as wide as the fallback face makes them"); + assert_eq!(shown(&l, 0), vec![0, 1, 2, 4, 3]); + // The line is the chosen face's line, whatever the fallback's metrics are. + assert_eq!(l.line_height, set(&f, "Test Latin", "ab", None).line_height); + // No listed family: any installed face with the letter. + let wide = Fonts::from_faces([testfont::font("Test Latin", LATIN, 500), testfont::font("Zzz Hebrew", HEBREW, 600)]); + let l = set(&wide, "Test Latin", "ab \u{05D0}\u{05D1}", None); + assert_eq!((l.missing, l.fallbacks.clone(), l.width), (0, vec!["Zzz Hebrew".to_string()], 30.0 + 24.0)); + // A character no face has is counted and drawn as the chosen face's box; invisible format + // characters are neither. + let none = set(&f, "Test Latin", "a\u{05E9}", None); + assert_eq!((none.missing, boxes(&none), none.fallbacks.len()), (1, 1, 0)); + let hidden = set(&f, "Test Latin", "a\u{200D}b\u{200F}", None); + assert_eq!((hidden.missing, boxes(&hidden)), (0, 0)); + // Text the face has all of asks no other face. + assert_eq!(set(&f, "Test Latin", "abc 123", None).fallbacks, Vec::::new()); +} + +/// From outside PR #40: a mark its letter's face lacks takes the letter along to a face with +/// both, so the two are shaped together. +#[test] +fn a_letter_goes_with_its_mark_to_the_fallback_face() { + let f = Fonts::from_faces([testfont::font("Test Latin", LATIN, 500), testfont::font("Noto Sans", "e\u{0301}", 800)]); + let l = set(&f, "Test Latin", "e\u{0301}x", None); + assert_eq!((l.missing, boxes(&l), l.fallbacks.clone()), (0, 0, vec!["Noto Sans".to_string()])); + let cluster: Vec<&PlacedGlyph> = l.glyphs.iter().filter(|g| g.index == 0).collect(); + assert_eq!(cluster.len(), 2, "the letter and its mark are one cluster"); + assert!(cluster.iter().any(|g| g.advance == 16.0), "the letter is the fallback face's"); + assert_eq!(l.glyphs.iter().find(|g| g.index == 2).unwrap().advance, 10.0, "the next letter stays in its face"); + // The caret doesn't stop between a letter and its mark. + assert_eq!(l.carets[0].stops.iter().map(|s| s.0).collect::>(), vec![0, 2, 3]); +} + +#[test] +fn hostile_directions_lay_out_without_panicking() { + let f = both(); + let nested = format!("{}ab\u{05D0}{}", "\u{2067}".repeat(300), "\u{2069}".repeat(300)); + let texts = ["\u{202E}abc\u{202C}", "\u{05D0}\n\n\u{05D1}\r\n", "a\u{2029}\u{05D0}", "\u{0301}\u{0301}", "\u{200F}", "\u{05D0} \u{05D1} ", " \u{05D0}", "1\u{05D0}2\u{05D1}3", nested.as_str(), "\u{202B}ab\u{05D0}\n\u{202C}\u{05D1}cd"]; + for text in texts { + for width in [None, Some(1.0), Some(35.0)] { + let l = set(&f, "Test Both", text, width); + assert!(l.width.is_finite() && l.height.is_finite()); + assert!(l.glyphs.iter().all(|g| g.x.is_finite() && g.advance.is_finite()), "{text:?}"); + assert_eq!(l.carets.len(), l.lines); + for c in &l.carets { + assert!(c.start <= c.end && !c.stops.is_empty() && c.stops.iter().all(|s| s.1.is_finite() && (c.start..=c.end).contains(&s.0)), "{text:?} {c:?}"); + assert!(c.boxes.iter().all(|b| b.start < b.end && b.x0 <= b.x1), "{text:?} {c:?}"); + } + // Every drawn character is on exactly one line. + let mut seen: Vec = l.carets.iter().flat_map(|c| c.boxes.iter().map(|b| b.start)).collect(); + let n = seen.len(); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), n, "{text:?}"); + } + } +} + +/// With this computer's fonts: Arabic letters join, a number inside them keeps its digits in +/// order at the line's left, and a face without Arabic letters borrows them (outside PRs #39 +/// and #40). Skipped where no installed face has Arabic letters. +#[test] +fn arabic_with_a_number_reads_the_right_way_round_in_any_face() { + let Some(f) = fonts() else { return }; + let l = f.layout_glyphs("\u{0645}\u{0631}\u{062D}\u{0628}\u{0627} 2026", &Style { size: 40.0, ..Style::default() }).unwrap(); + if l.missing > 0 { + eprintln!("no face here has Arabic letters: skipped"); + return; + } + let x_of = |i: u32| l.glyphs.iter().filter(|g| g.index == i).map(|g| g.x).fold(f32::INFINITY, f32::min); + assert!(x_of(6) < x_of(7) && x_of(7) < x_of(8) && x_of(8) < x_of(9), "the digits read left to right"); + assert!(x_of(9) < x_of(4) && x_of(4) < x_of(0), "the number is left of the word, whose first letter is rightmost"); + assert!(l.carets[0].rtl); + // Every family draws it: one without Arabic letters says which family lent them. + for family in f.families().iter().take(40) { + let Ok(in_family) = f.layout("\u{0628}\u{064A}\u{062A} ab", &Style { family: family.clone(), size: 40.0, ..Style::default() }) else { continue }; + assert_eq!(in_family.family, *family); + assert_eq!(in_family.missing, 0, "{family}: the letters it lacks come from a fallback face"); + } +} diff --git a/crates/text/src/testfont.rs b/crates/text/src/testfont.rs new file mode 100644 index 00000000..4fccc970 --- /dev/null +++ b/crates/text/src/testfont.rs @@ -0,0 +1,152 @@ +//! Fonts made in memory for tests, so layout that depends on which letters a face has (mixed +//! directions, fallback faces: ADR 0130) is tested the same on every computer. Our own work: +//! the tables are written here from the OpenType specification ("Font file", `head`, `hhea`, +//! `maxp`, `hmtx`, `cmap` format 12, `loca`, `glyf`, `name`, `post`), and every letter is a box. + +fn be16(out: &mut Vec, v: u16) { + out.extend(v.to_be_bytes()); +} + +fn be32(out: &mut Vec, v: u32) { + out.extend(v.to_be_bytes()); +} + +/// The em square, and how tall a letter's box and the "notdef" box are (font units). +pub(crate) const EM: u16 = 1000; +pub(crate) const LETTER_HEIGHT: i16 = 700; +pub(crate) const NOTDEF_HEIGHT: i16 = 300; + +/// A TrueType font named `family` with a glyph for each character of `chars`, every one +/// `advance` font units wide: a box [`LETTER_HEIGHT`] tall standing on the baseline (white +/// space: nothing). Its "notdef" glyph is a box [`NOTDEF_HEIGHT`] tall. No kerning, ligatures +/// or mark positioning. +pub(crate) fn font(family: &str, chars: &str, advance: u16) -> Vec { + let mut cps: Vec = chars.chars().collect(); + cps.sort_unstable(); + cps.dedup(); + let n = cps.len() as u16 + 1; + let right = advance.saturating_sub(50).max(60) as i16; + + let (mut glyf, mut loca) = (Vec::new(), vec![0u32]); + for g in 0..n { + let c = g.checked_sub(1).and_then(|i| cps.get(i as usize)).copied(); + if !c.is_some_and(char::is_whitespace) { + let top = if c.is_some() { LETTER_HEIGHT } else { NOTDEF_HEIGHT }; + for v in [1, 50, 0, right, top] { + glyf.extend(i16::to_be_bytes(v)); + } + be16(&mut glyf, 3); // the contour's last point + be16(&mut glyf, 0); // no instructions + glyf.extend([1u8; 4]); // four on-curve points, coordinates as words + for v in [50, 0, right - 50, 0, 0, top, 0, -top] { + glyf.extend(i16::to_be_bytes(v)); + } + while glyf.len() % 4 != 0 { + glyf.push(0); + } + } + loca.push(glyf.len() as u32); + } + let loca: Vec = loca.iter().flat_map(|o| o.to_be_bytes()).collect(); + + let mut head = Vec::new(); + be32(&mut head, 0x0001_0000); + be32(&mut head, 0x0001_0000); + be32(&mut head, 0); + be32(&mut head, 0x5F0F_3CF5); + be16(&mut head, 3); + be16(&mut head, EM); + head.extend([0u8; 16]); // created, modified + for v in [0, 0, right, LETTER_HEIGHT] { + head.extend(i16::to_be_bytes(v)); + } + be16(&mut head, 0); + be16(&mut head, 8); + for v in [2i16, 1, 0] { + head.extend(v.to_be_bytes()); // direction hint, long `loca` offsets, glyph format + } + + let mut hhea = Vec::new(); + be32(&mut hhea, 0x0001_0000); + for v in [800i16, -200, 0] { + hhea.extend(v.to_be_bytes()); + } + be16(&mut hhea, advance); + for v in [0i16, 0, right, 1, 0, 0, 0, 0, 0, 0, 0] { + hhea.extend(v.to_be_bytes()); + } + be16(&mut hhea, n); + + let mut maxp = Vec::new(); + be32(&mut maxp, 0x0001_0000); + for v in [n, 4, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0] { + be16(&mut maxp, v); + } + + let mut hmtx = Vec::new(); + for _ in 0..n { + be16(&mut hmtx, advance); + be16(&mut hmtx, 50); + } + + let mut cmap = Vec::new(); + for v in [0u16, 1, 3, 10] { + be16(&mut cmap, v); + } + be32(&mut cmap, 12); + be16(&mut cmap, 12); + be16(&mut cmap, 0); + be32(&mut cmap, 16 + 12 * cps.len() as u32); + be32(&mut cmap, 0); + be32(&mut cmap, cps.len() as u32); + for (i, c) in cps.iter().enumerate() { + for v in [*c as u32, *c as u32, i as u32 + 1] { + be32(&mut cmap, v); + } + } + + let names = [(1u16, family.to_string()), (2, "Regular".to_string()), (4, family.to_string()), (6, family.replace(' ', ""))]; + let (mut name, mut strings) = (Vec::new(), Vec::new()); + be16(&mut name, 0); + be16(&mut name, names.len() as u16); + be16(&mut name, 6 + 12 * names.len() as u16); + for (id, s) in &names { + let utf16: Vec = s.encode_utf16().flat_map(u16::to_be_bytes).collect(); + for v in [3, 1, 0x0409, *id, utf16.len() as u16, strings.len() as u16] { + be16(&mut name, v); + } + strings.extend(utf16); + } + name.extend(strings); + + let mut post = Vec::new(); + be32(&mut post, 0x0003_0000); + be32(&mut post, 0); + post.extend(i16::to_be_bytes(-100)); + post.extend(i16::to_be_bytes(50)); + post.extend([0u8; 20]); + + let tables: [(&[u8; 4], Vec); 9] = [(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp), (b"name", name), (b"post", post)]; + let mut out = Vec::new(); + be32(&mut out, 0x0001_0000); + for v in [9u16, 128, 3, 16] { + be16(&mut out, v); + } + let mut offset = 12 + 16 * tables.len() as u32; + let mut body = Vec::new(); + for (tag, data) in &tables { + let mut padded = data.clone(); + while padded.len() % 4 != 0 { + padded.push(0); + } + let sum = padded.as_chunks::<4>().0.iter().fold(0u32, |a, w| a.wrapping_add(u32::from_be_bytes(*w))); + out.extend(*tag); + be32(&mut out, sum); + be32(&mut out, offset); + be32(&mut out, data.len() as u32); + offset += padded.len() as u32; + body.extend(padded); + } + out.extend(body); + out +} From 912d524c6e92e8e8ae57969250f045e640ce031e Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 23 Nov 2026 12:55:02 -0700 Subject: [PATCH 42/44] feat(text): carets move the way the arrows point through mixed directions, and the commands say which font lent letters (M5) In a field while a movie plays, Left and Right move the caret by where text is displayed, crossing lines by the paragraph's direction, and a selection across a change of direction is highlighted in its separate stretches. text.create and text.edit return a note naming the families letters were borrowed from and how many characters no installed font has; the stage shows it in the status bar. craft-text is pinned to the craft-libs commit the app already uses. ADR 0130, the guide, the roadmap and the parity matrix say what is done and what is left; outside PRs #39 and #40 are credited. --- ATTRIBUTION.md | 3 + AUTHORS.md | 1 + CHANGELOG.md | 22 ++++ Cargo.lock | 2 +- Cargo.toml | 2 +- crates/doc/src/eval.rs | 18 ++- crates/doc/src/field.rs | 97 +++++++++++++- crates/doc/src/field_tests.rs | 89 +++++++++++++ crates/engine/src/cmds_text.rs | 54 ++++++-- crates/engine/src/player.rs | 7 +- crates/engine/src/rich_text_tests.rs | 57 +++++++++ docs/adr/0012-text.md | 11 +- ...130-mixed-directions-and-fallback-faces.md | 121 ++++++++++++++++++ docs/guide/text.md | 24 +++- docs/legal/compliance.md | 4 + docs/parity.md | 4 +- docs/roadmap.md | 11 +- src/app.rs | 11 ++ src/stage.rs | 8 +- 19 files changed, 502 insertions(+), 44 deletions(-) create mode 100644 docs/adr/0130-mixed-directions-and-fallback-faces.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 6388fc40..9538d645 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -134,6 +134,9 @@ OR Apache-2.0) is noted in the table. | Stroke caps, joins, miter limit and dash patterns (`butt`/`square` caps, miter length and limit, dash arrays restarting per subpath, zero-length round-capped dashes as dots) | `crates/doc/src/stroke_style.rs`, `crates/render/src/stroke.rs`, SVG/HTML/Lottie export, `crates/svg` | W3C SVG 1.1 §11.4 and SVG 2 / CSS Fill and Stroke Module Level 3 (stroke properties); WHATWG HTML canvas line styles; the public Lottie JSON schema (`lc`, `lj`, `ml`, `d`); public descriptions of XFL `SolidStroke`/`DashedStroke`/`DottedStroke` attributes | W3C Royalty-Free Patent Policy; open specifications. | | Soft masks (alpha and luminance masks, `luminanceToAlpha` coefficients, `mask-type`) and text on a path (`textPath`, `startOffset`, `side`, glyph midpoints on the path, per-character `x`/`y`/`dx`/`dy`/`rotate`) | `crates/render`, `crates/gpu`, `crates/text`, `crates/svg` | W3C CSS Masking Module Level 1 (§7 mask types); W3C SVG 1.1 §10.13 and §14.4, SVG 2 §11.8 (text on a path); W3C Filter Effects (`luminanceToAlpha`); the public Lottie JSON schema (track mattes `td`/`tt`); WHATWG HTML canvas compositing | W3C Royalty-Free Patent Policy; open specifications. Own implementation (ADR 0070). | | Text-field members in the ActionScript subset: `htmlText` (the tags and attributes Flash text fields accept, relative font sizes, entities), `restrict` notation (ranges, `^`, escapes), `maxChars`, `Event.CHANGE` on user edits only | `crates/doc/src/html_text.rs`, `crates/doc/src/field.rs`, `crates/doc/src/player.rs`, `crates/render/src/html/player.js` | Adobe, *ActionScript 3.0 Reference for the Adobe Flash Platform* (`flash.text.TextField`: `htmlText`, `restrict`, `maxChars`; `flash.events.Event.CHANGE`), public documentation; WHATWG HTML (named and numeric character references) | Behaviour learned from public documentation only; own implementation (ADR 0107). | +| Text that mixes directions: embedding levels, line breaking before reordering, reordering each line (rules L1 and L2), where a caret stands at a change of direction | `crates/text/src/lines.rs`, `crates/text/src/rich.rs`, `crates/doc/src/field.rs` | The Unicode Consortium, *Unicode Standard Annex #9: Unicode Bidirectional Algorithm*, ; levels and reordering by storytold/craft-libs `craft-text` (MIT OR Apache-2.0) on `unicode-bidi` (MIT OR Apache-2.0) | Open standard. Layout on shaped clusters is our own (ADR 0130); the first version was outside PR #39 by SoldierPePe. | +| Fallback faces for letters a font lacks (cluster by cluster after shaping) | `crates/text/src/fallback.rs` | Common practice in text layout engines, described in the HarfBuzz manual ("Shaping and shape plans", clusters) and the OpenType specification (`cmap`, glyph 0 as "notdef") | Own implementation (ADR 0130); the family list and the rules for marks and invisible characters are from outside PR #40 by SoldierPePe. The family names are names only: no font is bundled. | +| Fonts made in memory for tests (boxes for letters) | `crates/text/src/testfont.rs` | Microsoft and Adobe, *OpenType specification*: "Font file", `head`, `hhea`, `maxp`, `hmtx`, `cmap` (format 12), `loca`, `glyf`, `name`, `post` | Open specification. Written from the table descriptions; test code only, no font file is committed. | | Font embedding permissions (`fsType`: restricted licence, preview and print, editable, no subsetting, bitmap embedding only) | `crates/text/src/embed.rs` | Microsoft and Adobe, *OpenType specification*, `OS/2` table (`fsType`); the three-case rule proposed in storytold/craft-libs issue #82 | Open specification. Own implementation (ADR 0107). | | Lines of text on curves parallel to a path (offset curves measured by arc length) | `crates/text/src/lib.rs` | Standard differential geometry of parallel (offset) curves; public domain mathematics | Own implementation (ADR 0107). | | Lottie keyframes and eases (hold keys, cubic Bézier eases with `o`/`i` handles, split position, shape keyframes, group transform order T · R · Skew · S · T(−anchor)); subdividing a cubic at its midpoint (de Casteljau) | `crates/render/src/lottie.rs`, `crates/render/src/lottie_keys.rs`, `crates/engine/tests/lottie_player` | The public Lottie JSON format description (Lottie Animation Community); W3C CSS Easing Functions Level 1 (`cubic-bezier`); de Casteljau's algorithm (public domain mathematics) | Open specifications. Own implementation (ADR 0089). | diff --git a/AUTHORS.md b/AUTHORS.md index c14cf24f..fe63e3bc 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -27,3 +27,4 @@ People who have contributed to AniCraft. The repository starts from one initial * Agapenor (Agapenordev): XFL folder paths with backslashes, the frame limit on loaded documents, the report behind the evaluation allowance. * 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). +* SoldierPePe: text that mixes directions and letters from a fallback face (#39, #40). diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c81a50a..140109e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ ## Unreleased +* **Text reads right: mixed directions, and letters from a fallback face** (M5, backlog P-008, + ADR 0130). With outside pull requests #39 and #40 by SoldierPePe, whose commits are merged + here and rebuilt on styled text. + * **Hebrew and Arabic with Latin words and numbers read the right way round.** Text follows + the Unicode bidi algorithm: a number or a Latin word inside right-to-left text keeps its + order ("2026" was drawn as "6202"), a right-to-left paragraph runs from the right, and a + wrapped one starts with its first words. Styled runs keep their style, colour and underline + through the reordering. It is the same in static text, text on a path and text fields, and + so in every export. + * **Letters your font doesn't have come from another font** instead of showing as boxes: + Arabic in Consolas, Japanese in Arial. The rest of the block keeps your font, a letter + takes its marks along, and the line keeps its height. `text.create` and `text.edit` say + which font lent the letters, and how many characters no installed font has. + * **In a text field in Test Movie, Left and Right move the caret the way they point** through + text that mixes directions, and a selection across a change of direction is highlighted in + its separate stretches. + * Arabic letters join across a change of style inside a word. Letter spacing follows a + letter with its marks instead of each glyph. A stretch of text in another script is shaped + with that script's rules. + * Not yet: a direction setting for a paragraph (it is the first letter's) and alignment to + its start; the typing field beside the stage still shows right-to-left text unordered + while the block on the stage is right; right-to-left text a script sets in the HTML page. * **Reliability pass on the tests** (M8). Twelve runs of the whole suite after the review's fixes (the picture cache race and the split command fuzz) found no further flaky test. Tests that wait for another thread (a save, a freed port, a GPU start) now give it a minute instead diff --git a/Cargo.lock b/Cargo.lock index 1ffc9ba1..23db2434 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1408,7 +1408,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=249a41bd9306a1b34330ac94e596a1a8b881378a#249a41bd9306a1b34330ac94e596a1a8b881378a" +source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" dependencies = [ "unicode-bidi", "unicode-bidi-mirroring", diff --git a/Cargo.toml b/Cargo.toml index c4fa71b9..e66c205b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,7 @@ craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01 craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b67b9f90c50091a3090f93fa054c34e409edba11" } # The Unicode bidi algorithm (UAX #9) for text that mixes directions (ADR 0130): only the `bidi` # module, which brings unicode-bidi and unicode-bidi-mirroring (both MIT OR Apache-2.0). -craft-text = { git = "https://github.com/storytold/craft-libs", rev = "249a41bd9306a1b34330ac94e596a1a8b881378a", default-features = false, features = ["bidi"] } +craft-text = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false, features = ["bidi"] } # The GPU stage (ADR 0019) uses the wgpu that eframe's egui-wgpu brings, with the same # (default) features, so the tree keeps one wgpu build. wgpu = "30" diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 53e3e748..2cd41bdc 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1079,10 +1079,22 @@ fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option< if from > to || (from == to && !(a <= l.end && b > l.end)) { continue; } - let (x0, x1) = (l.x_at(from), if b > l.end { l.x_at(l.end) + t.size * 0.25 } else { l.x_at(to) }); + // One stretch per direction the selection runs through (ADR 0130). + let mut spans = l.spans(from, to); + if b > l.end { + // The line break is selected too: a little past where the line ends. + let (x, tail) = (l.x_at(l.end), t.size * 0.25); + match spans.last_mut() { + Some(last) if !l.rtl && (last.1 - x).abs() < 1e-3 => last.1 = x + tail, + _ if l.rtl => spans.push((x - tail, x)), + _ => spans.push((x, x + tail)), + } + } let y = row as f32 * look.line_height; - let r = Path::rect(crate::FIELD_GUTTER + x0, crate::FIELD_GUTTER + y, (x1 - x0).max(0.0), look.line_height); - out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(SELECTION)), None, Some(inner), None)); + for (x0, x1) in spans { + let r = Path::rect(crate::FIELD_GUTTER + x0, crate::FIELD_GUTTER + y, (x1 - x0).max(0.0), look.line_height); + out.items.push(item(Arc::new(r), text_xf, Some(Paint::Solid(SELECTION)), None, Some(inner), None)); + } } } } diff --git a/crates/doc/src/field.rs b/crates/doc/src/field.rs index 7c60fbe5..193a8e6f 100644 --- a/crates/doc/src/field.rs +++ b/crates/doc/src/field.rs @@ -12,18 +12,80 @@ use crate::{FIELD_GUTTER, LineType, MAX_FIELD_CHARS, Rgba, TextBlock, TextField, use anicraft_geom::{Path, Vec2}; use std::sync::Arc; +/// Where one cluster (a letter with its marks, or a ligature) stands on its line (ADR 0130). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CaretBox { + /// The characters it covers: from `start` up to `end`. + pub start: u32, + pub end: u32, + /// Its left and right edges, from the text's left edge. + pub x0: f32, + pub x1: f32, + /// It reads right to left. + pub rtl: bool, +} + /// One laid-out line's characters and caret places (indices count `char`s of the shown text). #[derive(Clone, Debug, Default, PartialEq)] pub struct CaretLine { /// The first character on the line and the boundary after its last. pub start: u32, pub end: u32, - /// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending; `x` from - /// the text's left edge (the box's, less the gutter). + /// `(index, x)` of the boundaries clusters start at and of the line's end, ascending by + /// index; `x` from the text's left edge (the box's, less the gutter). A boundary is at the + /// edge its cluster is read from, so in text that mixes directions `x` does not rise with + /// the index. pub stops: Vec<(u32, f32)>, + /// The paragraph reads right to left: the line starts at its right end (ADR 0130). + pub rtl: bool, + /// The line's clusters as they are displayed, left to right. Empty: every character reads + /// left to right, one after another, as `stops` has them. + pub boxes: Vec, } impl CaretLine { + /// Whether anything on the line reads right to left. + pub fn mixed(&self) -> bool { + self.rtl || self.boxes.iter().any(|b| b.rtl) + } + + /// The stretches of the line a selection from boundary `a` to `b` highlights, as left and + /// right x, left to right. Text in one direction is one stretch; a selection across a change + /// of direction is several (ADR 0130). A cluster is highlighted whole. + pub fn spans(&self, a: u32, b: u32) -> Vec<(f32, f32)> { + let (a, b) = (a.max(self.start), b.min(self.end)); + if a >= b { + return Vec::new(); + } + if self.boxes.is_empty() { + let x0 = self.x_at(a); + return vec![(x0, self.x_at(b).max(x0))]; + } + let mut out: Vec<(f32, f32)> = Vec::new(); + for c in self.boxes.iter().filter(|c| c.start < b && c.end > a) { + match out.last_mut() { + Some(last) if (last.1 - c.x0).abs() < 1e-3 => last.1 = c.x1, + _ => out.push((c.x0, c.x1)), + } + } + out + } + + /// The boundary the Left or Right key takes a caret at `i` to: the next place a caret can + /// stand in that direction on this line, by where it is displayed. `None` at the line's + /// edge. `open`: the line's end is shown on the next line (a wrapped line), so the caret + /// doesn't stand there. + pub fn step(&self, i: u32, right: bool, open: bool) -> Option { + let mut places: Vec<(u32, f32)> = self.stops.iter().copied().filter(|s| (self.start..=self.end).contains(&s.0) && !(open && s.0 == self.end && s.0 > self.start)).collect(); + // Left to right; places at one x in the order the paragraph reads. + places.sort_by(|p, q| p.1.total_cmp(&q.1).then(if self.rtl { q.0.cmp(&p.0) } else { p.0.cmp(&q.0) })); + // Inside a cluster, the caret is at the cluster's start. + let here = places.iter().map(|p| p.0).filter(|c| *c <= i).max()?; + let at = places.iter().position(|p| p.0 == here)?; + let next = if right { at.checked_add(1)? } else { at.checked_sub(1)? }; + places.get(next).map(|p| p.0) + } + /// The caret's x at boundary `i`. pub fn x_at(&self, i: u32) -> f32 { let mut x = self.stops.first().map_or(0.0, |s| s.1); @@ -87,6 +149,25 @@ impl FieldLook { Vec2::new(x, n as f32 * self.line_height) } + /// Where the Left or Right key takes a caret at boundary `i` in text that mixes directions + /// (ADR 0130): the next place to that side as displayed, and at a line's edge the line + /// before or after it, whichever lies that way in its paragraph's direction. `None` on a + /// line that reads left to right throughout: the key moves one character. + pub fn step(&self, i: u32, right: bool) -> Option { + let n = self.line_of(i); + let line = self.lines.get(n).filter(|l| l.mixed())?; + let next = self.lines.get(n + 1); + if let Some(to) = line.step(i, right, next.is_some_and(|m| m.start == line.end)) { + return Some(to); + } + // The line's edge: back to the line before, or on to the line after. + Some(if right == line.rtl { + if n == 0 { i } else { line.start.saturating_sub(1) } + } else { + next.map_or(i, |m| m.start) + }) + } + /// The boundary nearest a point in the text's space. pub fn index_at(&self, p: Vec2) -> u32 { let h = self.line_height.max(1e-3); @@ -316,12 +397,14 @@ impl Editor<'_> { } Edit::Left if !shift && a != b => moved(self.st, a, false), Edit::Right if !shift && a != b => moved(self.st, b, false), + // In text that mixes directions the caret moves the way the key points, as the + // text is displayed (ADR 0130); elsewhere one character back or on. Edit::Left => { - let to = self.st.caret.saturating_sub(1); + let to = look.and_then(|l| l.step(self.st.caret, false)).unwrap_or_else(|| self.st.caret.saturating_sub(1)); moved(self.st, to, shift) } Edit::Right => { - let to = self.st.caret.saturating_add(1); + let to = look.and_then(|l| l.step(self.st.caret, true)).unwrap_or_else(|| self.st.caret.saturating_add(1)); moved(self.st, to, shift) } Edit::Home | Edit::End | Edit::Up | Edit::Down => { @@ -422,14 +505,14 @@ pub(crate) fn mono_look(text: &str, cw: f32, lh: f32, wrap: Option) -> Fiel let mut i = 0u32; for c in text.chars() { if c == '\n' { - lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) }); + lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops), ..CaretLine::default() }); i += 1; (start, col) = (i, 0); stops.push((i, 0.0)); continue; } if per.is_some_and(|p| col == p) { - lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops) }); + lines.push(CaretLine { start, end: i, stops: std::mem::take(&mut stops), ..CaretLine::default() }); (start, col) = (i, 0); stops.push((i, 0.0)); } @@ -442,7 +525,7 @@ pub(crate) fn mono_look(text: &str, cw: f32, lh: f32, wrap: Option) -> Fiel stops.push((i, col as f32 * cw)); width = width.max(col as f32 * cw); } - lines.push(CaretLine { start, end: i, stops }); + lines.push(CaretLine { start, end: i, stops, ..CaretLine::default() }); let n = lines.len(); FieldLook { outline: Arc::new(outline), pieces: Arc::from(Vec::new()), lines: lines.into(), line_height: lh, width, height: n as f32 * lh } } diff --git a/crates/doc/src/field_tests.rs b/crates/doc/src/field_tests.rs index dd73adf9..edea5ba8 100644 --- a/crates/doc/src/field_tests.rs +++ b/crates/doc/src/field_tests.rs @@ -199,3 +199,92 @@ fn restrict_reads_as_actionscript_writes_it() { assert!(allowed(&"\\".repeat(1023), '\\')); } + +// Text that mixes directions (ADR 0130). Looks are written by hand, as the layout hands them +// over: every character 10 wide, capitals reading right to left. + +fn cell(start: u32, x0: f32, rtl: bool) -> CaretBox { + CaretBox { start, end: start + 1, x0, x1: x0 + 10.0, rtl } +} + +fn look_of(lines: Vec) -> FieldLook { + let n = lines.len() as f32; + FieldLook { outline: Arc::new(Path::new()), pieces: Arc::from(Vec::new()), lines: lines.into(), line_height: 10.0, width: 50.0, height: n * 10.0 } +} + +/// "abCDE" in a left-to-right paragraph, displayed a b E D C. +fn word_in_latin() -> FieldLook { + let boxes = vec![cell(0, 0.0, false), cell(1, 10.0, false), cell(4, 20.0, true), cell(3, 30.0, true), cell(2, 40.0, true)]; + look_of(vec![CaretLine { start: 0, end: 5, stops: vec![(0, 0.0), (1, 10.0), (2, 50.0), (3, 40.0), (4, 30.0), (5, 20.0)], rtl: false, boxes }]) +} + +/// "AB CD" in a right-to-left paragraph wrapped after the space: B A on the first line, D C on +/// the second, each starting at its right end. +fn wrapped_rtl() -> FieldLook { + let first = CaretLine { start: 0, end: 3, stops: vec![(0, 20.0), (1, 10.0), (2, 0.0), (3, 0.0)], rtl: true, boxes: vec![cell(1, 0.0, true), cell(0, 10.0, true)] }; + let second = CaretLine { start: 3, end: 5, stops: vec![(3, 20.0), (4, 10.0), (5, 0.0)], rtl: true, boxes: vec![cell(4, 0.0, true), cell(3, 10.0, true)] }; + look_of(vec![first, second]) +} + +/// The carets a key visits from `from`, pressed `n` times. +fn walk(text: &str, look: &FieldLook, from: u32, key: Edit, n: usize) -> Vec { + let field = TextField { lines: LineType::Multiline, ..TextField::new(TextKind::Input) }; + let b = block(text, field.clone()); + let mut st = FieldState { caret: from, anchor: from, ..FieldState::default() }; + (0..n) + .map(|_| { + Editor { block: &b, field: &field, st: &mut st }.key(key, false, Some(look)); + st.caret + }) + .collect() +} + +#[test] +fn arrows_move_the_caret_the_way_they_point_through_a_right_to_left_word() { + let look = word_in_latin(); + // Right from the start: past a and b, then through the word from its left (its end) to + // its right (its start), where the line ends. + assert_eq!(walk("abCDE", &look, 0, Edit::Right, 6), vec![1, 5, 4, 3, 2, 2]); + assert_eq!(walk("abCDE", &look, 2, Edit::Left, 6), vec![3, 4, 5, 1, 0, 0]); + // Each press moves the caret further the way the key points. + let xs: Vec = [0, 1, 5, 4, 3, 2].iter().map(|i| look.caret_at(*i).x).collect(); + assert!(xs.windows(2).all(|w| w[0] < w[1]), "{xs:?}"); + // Shift keeps the anchor: the selection is still a range of characters. + let field = TextField::new(TextKind::Input); + let b = block("abCDE", field.clone()); + let mut st = FieldState { caret: 1, anchor: 1, ..FieldState::default() }; + Editor { block: &b, field: &field, st: &mut st }.key(Edit::Right, true, Some(&look)); + assert_eq!(st.selection(), (1, 5)); + // A line that reads left to right throughout moves by characters, as it always has. + assert_eq!(mono_look("abc", 10.0, 10.0, None).step(1, true), None); +} + +#[test] +fn arrows_cross_lines_in_the_paragraphs_direction() { + let look = wrapped_rtl(); + // Left reads on in a right-to-left paragraph: to the line's left end, then the next line's + // right end. The wrapped line's end is the next line's start, shown there. + assert_eq!(walk("AB CD", &look, 0, Edit::Left, 6), vec![1, 2, 3, 4, 5, 5]); + assert_eq!(walk("AB CD", &look, 5, Edit::Right, 6), vec![4, 3, 2, 1, 0, 0]); + assert_eq!((look.caret_at(3), look.caret_at(2)), (Vec2::new(20.0, 10.0), Vec2::new(0.0, 0.0))); + // Home is where the line starts and End where it ends, whichever side that is. + assert_eq!(walk("AB CD", &look, 4, Edit::Home, 1), vec![3]); + assert_eq!(look.lines[1].x_at(3), 20.0); +} + +#[test] +fn a_selection_across_directions_is_highlighted_in_stretches() { + let look = word_in_latin(); + let line = &look.lines[0]; + assert_eq!(line.spans(0, 2), vec![(0.0, 20.0)]); + assert_eq!(line.spans(2, 5), vec![(20.0, 50.0)], "the whole word"); + // b and the word's first two letters (C and D, its rightmost): two stretches. + assert_eq!(line.spans(1, 4), vec![(10.0, 20.0), (30.0, 50.0)]); + assert_eq!(line.spans(0, 9), vec![(0.0, 50.0)]); + assert_eq!(line.spans(3, 3), Vec::new()); + assert_eq!(line.spans(7, 9), Vec::new()); + // Without boxes (text in one direction): from one caret place to the other. + let plain = mono_look("abcd", 10.0, 10.0, None); + assert_eq!(plain.lines[0].spans(1, 3), vec![(10.0, 30.0)]); + assert!(!plain.lines[0].mixed() && line.mixed() && wrapped_rtl().lines[0].mixed()); +} diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 0ee4e815..3b3663b3 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -302,16 +302,18 @@ fn rich_parts(d: &TextBlock) -> (Vec, Vec, families: &[String], paints: &[(Rgba, String)]) -> (TextBlock, Option) { - let mut note = None; +fn finish(mut d: TextBlock, pieces: Vec<(u32, Path)>, used: Used, paints: &[(Rgba, String)]) -> (TextBlock, Option) { + let mut notes: Vec = Vec::new(); let mut runs = d.styled_runs(); - for (r, used) in runs.iter_mut().zip(families) { + for (r, used) in runs.iter_mut().zip(used.families) { let asked = r.style.font.trim(); - if note.is_none() && !asked.is_empty() && !used.eq_ignore_ascii_case(asked) { - note = Some(format!("“{asked}” isn't installed on this computer; used {used}")); + if notes.is_empty() && !asked.is_empty() && !used.eq_ignore_ascii_case(asked) { + notes.push(format!("“{asked}” isn't installed on this computer; used {used}")); } r.style.font.clone_from(used); } + notes.extend(borrowed_note(used.fallbacks, used.missing)); + let note = (!notes.is_empty()).then(|| notes.join("; ")); let paras = d.paragraph_styles(); d.set_styles(runs, paras); let pieces = pieces.into_iter().map(|(k, p)| paints.get(k as usize).map_or((d.color, String::new(), p.clone()), |(c, u)| (*c, u.clone(), p))).collect(); @@ -319,6 +321,36 @@ fn finish(mut d: TextBlock, pieces: Vec<(u32, Path)>, families: &[String], paint (d, note) } +/// What a layout drew a block with: each run's family, the families that lent letters the +/// runs' own faces lack, and how many characters no face has (ADR 0130). +struct Used<'a> { + families: &'a [String], + fallbacks: &'a [String], + missing: usize, +} + +/// What to tell the user when a block's fonts don't have all of its letters: which families +/// the others were drawn from, and how many show as boxes because no installed font has them. +/// The block keeps the font that was chosen, so nothing else says so. +pub(crate) fn borrowed_note(fallbacks: &[String], missing: usize) -> Option { + let mut notes = Vec::new(); + match fallbacks { + [] => {} + [one] => notes.push(format!("letters the font doesn't have are drawn in {one}")), + [first, rest @ ..] => { + let shown: Vec<&str> = rest.iter().take(3).map(String::as_str).collect(); + let more = if rest.len() > shown.len() { " and other fonts" } else { "" }; + notes.push(format!("letters the font doesn't have are drawn in {first}, {}{more}", shown.join(", "))); + } + } + match missing { + 0 => {} + 1 => notes.push("1 character isn't in any installed font and shows as a box".to_string()), + n => notes.push(format!("{n} characters aren't in any installed font and show as boxes")), + } + (!notes.is_empty()).then(|| notes.join("; ")) +} + fn layout_err(e: anicraft_text::TextError) -> EngineError { EngineError::State(format!("can't lay out text: {e}")) } @@ -346,7 +378,7 @@ pub(crate) fn lay_out_block(d: &TextBlock) -> Result<(TextBlock, Option, d.box_height = set.height; d.on_path = Some(TextPath { path: set.path, offset, flip: on.flip }); let shift = set.shift; - let (b, n) = finish(d, set.pieces, &l.families, &paints); + let (b, n) = finish(d, set.pieces, Used { families: &l.families, fallbacks: &l.fallbacks, missing: l.missing }, &paints); Ok((b, n, shift)) } (Some(f), None) => { @@ -355,14 +387,16 @@ pub(crate) fn lay_out_block(d: &TextBlock) -> Result<(TextBlock, Option, let shown = f.shown(&d.text); let l = field_lay(fonts, &anicraft_text::RichText { text: &shown, runs: &runs, paragraphs: ¶s, width: f.wrap_width(d.box_width) }, d.align, &f, d.box_width).map_err(layout_err)?; d.width = f.wrap_width(d.box_width); - let (b, n) = finish(d, l.pieces, &l.families, &paints); + let used = Used { families: &l.families, fallbacks: &l.fallbacks, missing: l.missing }; + let (b, n) = finish(d, l.pieces, used, &paints); Ok((b, n, Vec2::ZERO)) } (None, None) => { let l = fonts.layout_rich(&anicraft_text::RichText { text: &d.text, runs: &runs, paragraphs: ¶s, width: d.width }, false).map_err(layout_err)?; d.box_width = l.width; d.box_height = l.height; - let (b, n) = finish(d, l.pieces, &l.families, &paints); + let used = Used { families: &l.families, fallbacks: &l.fallbacks, missing: l.missing }; + let (b, n) = finish(d, l.pieces, used, &paints); Ok((b, n, Vec2::ZERO)) } } @@ -389,6 +423,10 @@ fn field_lay(fonts: &Fonts, rich: &anicraft_text::RichText, align: TextAlign, fi for s in &mut line.stops { s.1 += shift; } + for b in &mut line.boxes { + b.x0 += shift; + b.x1 += shift; + } } l.width += shift; } diff --git a/crates/engine/src/player.rs b/crates/engine/src/player.rs index 128d6dd9..030fdf1c 100644 --- a/crates/engine/src/player.rs +++ b/crates/engine/src/player.rs @@ -12,7 +12,7 @@ use anicraft_doc::actions::as3::Problem; use anicraft_doc::actions::{Action, CompileResult, FrameScript, MAX_ACTIONS, PluginScript, check_actions}; use anicraft_doc::player::{Event, Node, NodeKind, PlayerState, ScriptContext, ScriptHost, ScriptRun, Step, TimelineRef}; -use anicraft_doc::field::{CaretLine, FieldLook}; +use anicraft_doc::field::{CaretBox, CaretLine, FieldLook}; use anicraft_doc::{Document, LayerKind, SymbolKind, TextBlock, Timeline, player}; use anicraft_geom::Vec2; use anicraft_plugins::{Host, Kind, Limits, Registry}; @@ -110,9 +110,10 @@ pub fn field_look(block: &TextBlock, shown: &str, rich: Option<&anicraft_doc::ht None => (crate::cmds_text::field_layout(fonts, &crate::cmds_text::style_of(block), f, block.box_width, shown).ok()?, Vec::new()), }; let pieces: Vec<(anicraft_doc::Rgba, std::sync::Arc)> = if colors.len() > 1 || colors.first().is_some_and(|c| *c != block.color) { l.pieces.iter().filter_map(|(k, p)| Some((*colors.get(*k as usize)?, std::sync::Arc::new(p.clone())))).collect() } else { Vec::new() }; - let mut lines: Vec = l.carets.into_iter().map(|c| CaretLine { start: c.start, end: c.end, stops: c.stops }).collect(); + let boxes = |c: &anicraft_text::CaretLine| c.boxes.iter().map(|b| CaretBox { start: b.start, end: b.end, x0: b.x0, x1: b.x1, rtl: b.rtl }).collect(); + let mut lines: Vec = l.carets.into_iter().map(|c| CaretLine { start: c.start, end: c.end, rtl: c.rtl, boxes: boxes(&c), stops: c.stops }).collect(); if lines.is_empty() { - lines.push(CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] }); + lines.push(CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)], ..CaretLine::default() }); } Some(FieldLook { outline: std::sync::Arc::new(l.outline), pieces: pieces.into(), lines: lines.into(), line_height: l.line_height, width: l.width, height: l.height }) } diff --git a/crates/engine/src/rich_text_tests.rs b/crates/engine/src/rich_text_tests.rs index a7b8f03c..69d8b474 100644 --- a/crates/engine/src/rich_text_tests.rs +++ b/crates/engine/src/rich_text_tests.rs @@ -227,3 +227,60 @@ 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"); } + +/// ADR 0130: text that mixes directions through the commands, as static text, as a field and +/// on a path, with this computer's fonts. The command says so when letters were borrowed from +/// another font or show as boxes, and in a field the arrow keys walk the caret the way they +/// point. +#[test] +fn mixed_directions_and_borrowed_letters_through_the_commands() { + use crate::cmds_text::borrowed_note; + assert_eq!(borrowed_note(&[], 0), None, "nothing to say about a font that has every letter"); + let both = borrowed_note(&["One".to_string(), "Two".to_string()], 3).unwrap(); + assert!(both.contains("One") && both.contains("Two") && both.contains('3'), "{both}"); + if !fonts() { + return; + } + let fonts = anicraft_text::Fonts::get(); + // a b _ alef bet gimel _ 1 2 _ and a private-use character few fonts have. + let text = "ab \u{05D0}\u{05D1}\u{05D2} 12 \u{10FFFD}"; + let mut s = Session::default(); + let out = run(&mut s, "text.create", json!({"text": text, "x": 20, "y": 20, "size": 40, "color": "#000000"})); + let id = ElementId(out["element"].as_u64().unwrap()); + let block = text_of(&s, id); + let style = anicraft_text::Style { family: block.font.clone(), size: 40.0, ..anicraft_text::Style::default() }; + let probe = fonts.layout_glyphs(text, &style).unwrap(); + assert_eq!(out["note"].is_string(), probe.missing > 0 || !probe.fallbacks.is_empty(), "{out}"); + assert_eq!(block.text, text, "the text is kept as it was typed"); + assert_eq!(block.outline.cmds, probe.outline.cmds, "the block's outline is the layout's"); + // A field of it: the player's caret places come with the layout's boxes. + run(&mut s, "text.field", json!({"type": "input", "width": 600, "height": 80})); + let field = text_of(&s, id); + let look = crate::player::field_look(&field, &field.text, None).unwrap(); + let hebrew = fonts.layout("\u{05D0}\u{05D1}\u{05D2}", &style).unwrap().missing == 0; + if hebrew { + let line = &look.lines[0]; + assert!(line.mixed() && !line.rtl, "a Hebrew word in a paragraph that starts with Latin letters"); + // Right, pressed from the line's left end, visits every caret place once, each + // further right than the last. + let mut at = line.stops.iter().min_by(|a, b| a.1.total_cmp(&b.1)).unwrap().0; + let mut xs = vec![look.caret_at(at).x]; + for _ in 0..line.stops.len() { + let next = look.step(at, true).unwrap(); + if next == at { + break; + } + at = next; + xs.push(look.caret_at(at).x); + } + assert_eq!(xs.len(), line.stops.len(), "{xs:?}"); + assert!(xs.windows(2).all(|w| w[0] <= w[1]), "{xs:?}"); + // The Hebrew word's first letter is right of its last. + assert!(line.x_at(3) > line.x_at(5), "{:?}", line.stops); + } + // On a path it lays out too, and undo brings the lines back. + run(&mut s, "text.field", json!({"type": "static"})); + run(&mut s, "text.edit", json!({"text": "\u{05D0}\u{05D1} ab\n12 \u{05D2}", "width": 30})); + let wrapped = text_of(&s, id); + assert!(wrapped.box_height > block.box_height * 1.5 && wrapped.outline.cmds.iter().all(|c| !matches!(c, anicraft_geom::PathCmd::MoveTo(p) if !p.is_finite()))); +} diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index d3460173..b27c92d9 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -35,11 +35,8 @@ so neither may depend on which fonts happen to be installed. `skrifa`, and breaks lines (paragraphs at line breaks; with a width, greedily at spaces). These crates are already in the dependency tree through egui, so no new licences. Text that mixes directions (Arabic or Hebrew with numbers or Latin words) follows the - Unicode bidi algorithm through `unicode-bidi` (MIT OR Apache-2.0): lines are found in - reading order, then each line's runs are shaped in their own direction and placed in - visual order. Characters the chosen face doesn't have (Arabic in Inter, say) come from the - first of `FALLBACK_FAMILIES` that has them, character by character, so the rest of the block - keeps its face; any that no face has are counted, and the command says they show as boxes. + Unicode bidi algorithm, and letters the chosen face doesn't have (Arabic in Inter, say) + come from a fallback face: [ADR 0130](0130-mixed-directions-and-fallback-faces.md). Bold and italic pick the matching face of the family; there is no synthetic styling. 5. **Break Apart** turns a text element into a shape with the same outlines, as Animate's second Break Apart does. @@ -52,8 +49,8 @@ so neither may depend on which fonts happen to be installed. edited, and the user is told. * Text in Animate documents imports onto this model (ADR 0014). * Not yet: per-character styles in one block, vertical text, text along a path, font - embedding for export, fallback to installed fonts outside the fallback list (a character - none of the loaded faces has draws as the font's "notdef" box, and the command says so). + embedding for export (a character no installed face has draws as the font's "notdef" box, + and the command says so: ADR 0130). ## Note (2026-11-11): text fields diff --git a/docs/adr/0130-mixed-directions-and-fallback-faces.md b/docs/adr/0130-mixed-directions-and-fallback-faces.md new file mode 100644 index 00000000..2b32a1e3 --- /dev/null +++ b/docs/adr/0130-mixed-directions-and-fallback-faces.md @@ -0,0 +1,121 @@ +# ADR 0130: Text that mixes directions, and letters from a fallback face + +* Status: accepted (2026-11-23), built +* Relates to: ADR 0012 (text as stored outlines), ADR 0085 (styled runs and paragraphs), + ADR 0066 (text fields), ADR 0070 and ADR 0107 (text on a path), ADR 0125 (backlog item P-008), + outside PRs #39 and #40 (SoldierPePe) + +## Context + +Two things made text read wrong. + +**Mixed directions.** Layout shaped each run of a paragraph as one stretch, in the direction of +its first letter. A number or a Latin word inside Arabic or Hebrew came out reversed ("2026" as +"6202"), and a wrapped right-to-left paragraph was broken from its visual left, so its last +words came first. + +**Missing letters.** A block was drawn with the faces its runs chose and nothing else. Arabic +in a face without Arabic letters (Inter, the default where the app embeds it; Consolas) showed +as boxes, and nothing said so. + +Outside PRs #39 and #40 fixed both on the single-style layout that existed before ADR 0085. +That layout is gone: text is now runs with their own faces, sizes and paints, in paragraphs +with their own alignment and margins, and it is also set along paths and typed into fields +while a movie plays. This ADR rebuilds both fixes on that layout and keeps the PRs' ideas and +tests. + +The constraints are the old ones: text is stored as outlines, so nothing downstream of layout +(the renderers, every exporter, the file) knows about directions or fonts; layout must not +panic on any text; and a document must not change because of which fonts a computer has until +its text is edited there. + +## Decision + +1. **The order of work is the bidi algorithm's** (Unicode Standard Annex #9). Embedding levels + are resolved once for the text; text is shaped and broken into lines in reading order; each + line is then put in the order it is displayed. Levels and reordering come from the shared + `craft-text` crate's `bidi` module (storytold/craft-libs, on `unicode-bidi`), not from an + app copy. A paragraph's direction is its first strong character's (rules P2 and P3). +2. **A run is shaped in stretches of one direction and one script.** Each stretch gets its + direction from its level and its script from its letters; characters every script shares + (spaces, digits, punctuation, marks) take the script before them. Each stretch is shaped + with the letters around it as context, so Arabic letters join across a change of style or + face as they do inside one. Script itemisation uses the shaper's own script table: no new + dependency. +3. **Lines are made of shaped clusters.** A cluster is what the shaper says belongs together: + a letter with its marks, or a ligature. Lines break after the last space that fits, or + between the clusters of a word wider than the line, never inside a cluster; reordering moves + clusters whole. Text is shaped once: a line takes its clusters as they were shaped, so a + word broken across lines in the middle (only when it is wider than the line) keeps the + joining forms it had. +4. **Letters a run's face lacks come from a fallback face, cluster by cluster.** After + shaping, a cluster with a glyph its face has no letter for is shaped again in another face: + the first of `FALLBACK_FAMILIES` (faces with wide coverage that come with Windows, macOS and + common Linux desktops, then the system faces for Chinese, Japanese, Korean, Indic and Thai + text, then symbols) that has every drawn character of the cluster, in the run's weight and + slant; when no listed face has all of it, any installed face that has the letter. A letter + and its marks always go together. The rest of the block keeps its face, and so do the line's + height and baseline: a fallback face's letters sit on the line the run's face makes. + Invisible format characters (joiners, direction marks, variation selectors) are never + missing. Limits: 16 fallback faces per block, and 16 searches of every installed face per + layout (each remembered). +5. **The user is told.** `text.create`, `text.edit` and the other text commands return a note + when letters were drawn from another family (naming it) and when characters are in no + installed font and show as boxes (how many). The block's font stays the one chosen. +6. **Carets know where clusters stand.** A laid-out line carries its paragraph's direction and + each cluster's box in display order. A caret's place is the edge its cluster is read from + (the right edge of a right-to-left letter). In a field while a movie plays, Left and Right + move the caret the way the key points through text that mixes directions, crossing to the + line before or after at a line's edge by the paragraph's direction; a selection is still a + range of characters and is highlighted as one stretch per direction it runs through. Lines + that read left to right throughout behave exactly as before. +7. **Nothing downstream changes.** Static text, text on a path and fields store the outlines + layout made, in display order, so the CPU and GPU renderers and every exporter draw them as + they draw any text. Text on a path takes each glyph's place on its line as it is displayed. + No new field in the document: files are unchanged. +8. **Tests use fonts made in memory.** `crates/text/src/testfont.rs` writes small TrueType + fonts (boxes for letters) from the OpenType specification, so mixed directions and fallback + are tested the same on every computer instead of being skipped where a font is missing. + +## Consequences + +* Text in one direction lays out as it did, except where it mixes scripts: a stretch in + another script is now shaped with that script's rules. +* Letter spacing follows each cluster, not each glyph, so a letter's marks stay on it. +* `Layout::missing` counts characters no face has; before, it counted characters the run's own + face lacked. +* Which fallback face is used depends on the computer. That is the same rule as for fonts + (ADR 0012): the outline is stored, so a document only changes where it is edited. +* One caret per boundary: at a change of direction a boundary has two places it could be + shown, and we show it at the edge of the letter after it (the line's end at the edge of the + letter before it). Typing a letter of the other direction there can make it appear away from + the caret. Editors with two carets or a caret affinity avoid that; we don't have either yet. + +## Not in this slice + +* A direction setting for a paragraph (it is always the first strong character's), and + alignment to the paragraph's start: a right-to-left paragraph is aligned as its paragraph + style says, left by default, as left-to-right text is. +* The stage editor (the field beside the block) is egui's text editor, which does not reorder; + the block updates live and reads correctly. Typing in the block itself is P-019, which will + use the caret boxes from point 6. +* Script-set text in the HTML export's own player (ADR 0107) is laid out by the page's script + from embedded glyph tables, one glyph per character and left to right; authored text there is + outlines and reads correctly. +* The direction SVG text asks for (`direction`, `unicode-bidi`) on import. +* Reshaping a word broken in its middle, hyphenation and kashida justification. +* The interface's own right-to-left layout (P-034). + +## Alternatives considered + +* **Depending on `unicode-bidi` directly**, as PR #39 did. The shared crate already wraps it + with the line rules (L1 and L2) on slices of levels, which is what a layout made of clusters + needs, and rule 9 of the Craft standards asks apps to use shared code. +* **Choosing a face per character before shaping**, as PR #40 did, with the Unicode class of + each character deciding what a mark attaches to. Shaping first lets the shaper say what a + cluster is, needs no extra character tables, costs nothing when the face has every letter, + and treats a letter the shaper can compose from parts as present. +* **Reshaping every line** after breaking, as PR #39 did. It shapes all text twice; shaping + once and breaking between clusters gives the same result at every break that is at a space. +* **A bundled font for tests.** A font file is an asset with a licence and a provenance row; + the fonts written in `testfont.rs` are code. diff --git a/docs/guide/text.md b/docs/guide/text.md index c4939bb3..965f96e8 100644 --- a/docs/guide/text.md +++ b/docs/guide/text.md @@ -82,9 +82,27 @@ font and tells you, so nothing changes behind your back. ### Missing characters -If a font doesn't have a character you type (an emoji, or a letter from another script), the -character shows as an empty box. AniCraft doesn't borrow it from another font yet, so pick a font -that covers your language. +If your font doesn't have a character you type (a letter from another script, or a symbol), +AniCraft draws that character with another font on your computer that has it, and tells you +which one. The rest of the block stays in your font, and the lines keep their height. For the +best look, pick a font that covers your language. + +A character that no font on your computer has shows as an empty box, and AniCraft tells you how +many there are. + +### Hebrew, Arabic and other right-to-left text + +Right-to-left text reads the right way round, also when it is mixed with Latin words and +numbers: a paragraph that starts with a right-to-left letter runs from the right, a number +inside it keeps its digits in order, and a wrapped paragraph starts with its first words. Arabic +letters join as they should. This is the same for static text, text on a path and text fields, +and in every export. + +* A paragraph is still aligned as its alignment says. For a right-to-left paragraph, choose + **Align Right**. +* The box you type in over the stage shows the letters in the order you typed them; the text on + the stage shows them as they read. +* In a text field in Test Movie, **Left** and **Right** move the caret the way they point. ## Static, dynamic and input text diff --git a/docs/legal/compliance.md b/docs/legal/compliance.md index f574f45d..2b151ae7 100644 --- a/docs/legal/compliance.md +++ b/docs/legal/compliance.md @@ -33,6 +33,10 @@ Data tables (ADR 0118) read CSV and TSV through `craft-csv` (MIT OR Apache-2.0; dependency is `thiserror`), pinned to the same reviewed commit of `storytold/craft-libs` as `craft-mime` and `craft-gif`. No new licence. +Text that mixes directions (ADR 0130) resolves embedding levels through `craft-text` (MIT OR +Apache-2.0, `storytold/craft-libs`, pinned by `rev`) with only its `bidi` feature, which brings +`unicode-bidi` and `unicode-bidi-mirroring` (both MIT OR Apache-2.0). No new licence. + **Shared-library exceptions (approved by the project lead, 2026-11-17).** The move to the shared Craft crates brought two licences the allowlist doesn't name. Both are accepted as crate-scoped exceptions in `deny.toml`, and the allowlist itself is unchanged: diff --git a/docs/parity.md b/docs/parity.md index 3c898ae4..49017c79 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -192,8 +192,8 @@ not this table, says what matters most. | Justified text | **missing** | Drawn left-aligned (P-033). | | Superscript, subscript, first-line indent, margins | **missing** | P-033. | | Vertical text | **missing** | P-033. | -| Mixed directions (Hebrew or Arabic with Latin and numbers) | **partial** | Shaped per paragraph in one direction; outside PR [#39](https://github.com/storytold/anicraft/issues/39) fixes it (P-008). | -| Letters the font lacks drawn from a fallback face | **partial** | Outside PR [#40](https://github.com/storytold/anicraft/issues/40) (P-008). | +| Mixed directions (Hebrew or Arabic with Latin and numbers) | **partial** | Static text, text on a path and fields follow the Unicode bidi algorithm, in every export; in a field the arrow keys move the caret the way they point ([ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md); [text](guide/text.md)). Missing: a direction setting for a paragraph with alignment to its start, and right-to-left text a script sets in the HTML page (P-033). | +| Letters the font lacks drawn from a fallback face | **done** | From a list of system faces, then any installed face; the command says which family lent them ([ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md)). | | Anti-alias modes and device fonts | **partial** | Text is stored as outlines, so it draws the same everywhere; there is no choice of anti-aliasing or of device fonts. | | Break Apart text into letters, then shapes | **done** | One step to shapes. | | Filters on text | **done** | [ADR 0099](adr/0099-filter-colour-and-stepped-tracks-built-in-presets-and-filters-on-text.md). | diff --git a/docs/roadmap.md b/docs/roadmap.md index 76deeb6e..45acaa59 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -50,7 +50,6 @@ the changelog. | 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 | | P-006 | Animate files open right: lines missing or filled in ([#498](https://github.com/storytold/anicraft/issues/498)), a `.fla` refused on macOS ([#347](https://github.com/storytold/anicraft/issues/347)); each fixed file joins the corpus | Import | M | the reporters' files | xfl | | P-007 | The web build is usable: import, export and save ([#55](https://github.com/storytold/anicraft/issues/55)), preferences kept ([#56](https://github.com/storytold/anicraft/issues/56)), a web asset on each release ([#316](https://github.com/storytold/anicraft/issues/316), [#210](https://github.com/storytold/anicraft/issues/210)), a run in a real browser in CI | Preferences, platforms | M | | platform | -| 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 | @@ -66,7 +65,7 @@ the changelog. |---|---|---|---|---|---| | P-017 | Selecting as in the reference app: a marquee takes instances, groups and objects it touches ([#522](https://github.com/storytold/anicraft/issues/522)); Hide Edges ([#298](https://github.com/storytold/anicraft/issues/298)); a first-use hint that a fill and its outline are separate, with double-click selecting both ([#484](https://github.com/storytold/anicraft/issues/484), [#485](https://github.com/storytold/anicraft/issues/485), [#343](https://github.com/storytold/anicraft/issues/343)); Match Size and Space in Align | Tools, drawing model | S each | | stage | | P-018 | Lasso, Polygon and Magic Wand tools ([#515](https://github.com/storytold/anicraft/issues/515)) | Tools | M | | stage | -| P-019 | Text is typed in its block on the stage, in its real font and alignment ([#303](https://github.com/storytold/anicraft/issues/303)) | Text | L | P-008 | text | +| P-019 | Text is typed in its block on the stage, in its real font and alignment ([#303](https://github.com/storytold/anicraft/issues/303)) | Text | L | | text | | P-020 | Modify › Shape: Smooth, Straighten, Advanced Smooth and Optimize ([#510](https://github.com/storytold/anicraft/issues/510)); Distort; oval angles and primitive shapes | Drawing model | M | | geom | | P-021 | Timeline and symbol commands that are missing: Reverse Frames, Distribute to Layers and to Keyframes, convert a tween to frame-by-frame, a symbol to layers and back ([#517](https://github.com/storytold/anicraft/issues/517)), New Symbol (Ctrl+F8), copy and paste layers, comment and anchor labels, a loop range | Timeline, symbols | M (splits into S) | | timeline | | P-022 | A sound's in and out points: trim handles in Edit Envelope, Split Audio ([#502](https://github.com/storytold/anicraft/issues/502)), read from Animate files | Sound | M | | audio | @@ -85,8 +84,8 @@ the changelog. |---|---|---|---|---|---| | P-031 | Scripts: arrays, objects, `switch`, string methods, event bubbling and fields, sound from scripts ([#3](https://github.com/storytold/anicraft/issues/3)); a debugger later; ActionScript 1.0 and 2.0 last ([#293](https://github.com/storytold/anicraft/issues/293)) | Interactivity | L | | player | | P-032 | Strokes: gradient and bitmap strokes, ragged, stipple and hatched styles, scale modes, a hairline style | Drawing model, colour | M | | render | -| P-033 | Typography: justified text, superscript and subscript, indents and margins, vertical text, spell checking | Text | M (splits) | P-008 | text | -| P-034 | A right-to-left interface, and Hebrew ([#45](https://github.com/storytold/anicraft/issues/45)) | Preferences | M | P-008 | shell | +| P-033 | Typography: justified text, superscript and subscript, indents and margins, vertical text, spell checking; a direction setting for a paragraph with alignment to its start, and right-to-left text a script sets in the HTML page (left from P-008, [ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md)) | Text | M (splits) | | text | +| P-034 | A right-to-left interface, and Hebrew ([#45](https://github.com/storytold/anicraft/issues/45)) | Preferences | M | | shell | | P-035 | The HTML page and Test Movie, complete: 9-slice, bent bitmaps, stream sounds after a go-to, links that click, masks in hit tests, scaling choices, a preloader; Test Movie full screen and zoom | Publishing, interactivity | M (splits) | | player | | P-036 | Publish formats: an animated SVG in one file (outside PR [#9](https://github.com/storytold/anicraft/issues/9)), SVG sequence and file name patterns in Publish Settings, JPEG, a texture atlas, publish settings read from Animate files, per-sound settings | Publishing | M (splits) | | engine | | P-037 | More formats in: AIFF, FLAC and ADPCM WAV sounds; GIF, BMP, WebP bitmaps; numbered images as frames | Import | S each | craft-libs readers | audio, doc | @@ -142,8 +141,8 @@ 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. | -| [#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. | +| [#39](https://github.com/storytold/anicraft/issues/39) | Text that mixes directions | (P-008, done) | **superseded by** | Its commits are merged in the P-008 pull request, which rebuilds it on the styled-text layout ([ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md)): lines found in reading order and never inside a cluster, and its tests, are kept; levels and reordering come from `craft-text`. Nothing in it is left out. | +| [#40](https://github.com/storytold/anicraft/issues/40) | Letters from a fallback face | (P-008, done) | **superseded by** | Merged and rebuilt with [#39](https://github.com/storytold/anicraft/issues/39) ([ADR 0130](adr/0130-mixed-directions-and-fallback-faces.md)): its family list, the cluster that moves whole with its marks, invisible characters that are never missing and the note about boxes are kept; installed faces outside the list, which it left for later, are searched too. | | [#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`. | diff --git a/src/app.rs b/src/app.rs index 687524a8..107fdfea 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1011,6 +1011,16 @@ impl App { self.status = Some(Status { text: text.into(), error: true, at: 0.0 }); } + /// What a text command had to say about the fonts it used, in the status bar: a font that + /// isn't installed, letters drawn from another font, characters no font has (ADR 0012, + /// ADR 0130). The block looks right either way, so this is the only place it is said. + pub fn text_note(&mut self, result: &Value) { + if let Some(note) = result["note"].as_str() { + // The engine's English, translated when a catalog has that exact message. + self.status_ok(crate::i18n::t_dyn(note).into_owned()); + } + } + /// Runs an engine command, reporting failures in the status bar. /// After a move, selected raw shapes float over what they landed on, and merge with it when /// they are deselected, as in Animate (ADR 0122, #487): until then they can be moved on. @@ -3711,6 +3721,7 @@ impl App { } "plugin.run" | "plugin.install" | "plugin.remove" | "plugin.reload" => crate::plugins_ui::status(self, id, v), id if id.starts_with("macro.") => crate::macros_ui::done(self, id, v), + id if id.starts_with("text.") => self.text_note(v), "timeline.remove_frame" => { let n = v["removed"].as_u64().unwrap_or(1); self.status_ok(if n == 1 { tr!("Removed frame — {undo} to undo", undo = self.undo_key()).to_string() } else { trn!("Removed {n} frame — {undo} to undo", "Removed {n} frames — {undo} to undo", n, undo = self.undo_key()) }); diff --git a/src/stage.rs b/src/stage.rs index 704c8ca8..83bdef7e 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -4622,15 +4622,17 @@ pub fn commit_text(app: &mut App) { let mut p = te.edit_params(); p["x"] = json!(te.at.x); p["y"] = json!(te.at.y); - app.run("text.create", p); + if let Some(made) = app.run("text.create", p) { + app.text_note(&made); + } } Some(_) if te.text == te.original => {} Some(id) => { app.run("element.select", json!({"ids": [id.0]})); if te.text.trim().is_empty() { app.run("edit.delete", json!({})); - } else { - app.run("text.edit", te.edit_params()); + } else if let Some(edited) = app.run("text.edit", te.edit_params()) { + app.text_note(&edited); } } } From 19efbd7e5440a318c1184fbd4fc66298362fbfaa Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 23 Nov 2026 12:56:15 -0700 Subject: [PATCH 43/44] perf(text): remember the fallback faces and which letters they have (M5) A block that keeps needing a fallback face is laid out again on every edit; asking each listed face for each letter again opened about thirty font files a time. Measured on a three-character block with two characters no face has: 1.0 ms a layout before, 0.09 ms after. --- crates/text/src/fallback.rs | 35 ++++++++++++++++++++++++++++++++--- crates/text/src/lib.rs | 11 +++++++++-- crates/text/src/rich.rs | 2 +- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/text/src/fallback.rs b/crates/text/src/fallback.rs index d9fc2283..eb84167c 100644 --- a/crates/text/src/fallback.rs +++ b/crates/text/src/fallback.rs @@ -9,6 +9,7 @@ use crate::Fonts; use skrifa::MetadataProvider as _; use std::collections::HashMap; +use std::sync::Arc; /// Families tried, in order, for characters a run's own face doesn't have: faces with wide /// coverage that come with Windows, macOS and common Linux desktops, then the system faces for @@ -100,13 +101,19 @@ impl<'f> Coverage<'f> { pub(crate) fn has(&mut self, id: fontdb::ID, c: char) -> bool { let fonts = self.fonts; - *self.memo.entry((id, c)).or_insert_with(|| fonts.db.with_face_data(id, |data, index| crate::face_has(data, index, c)).unwrap_or(false)) + *self.memo.entry((id, c)).or_insert_with(|| fonts.covers(id, c)) } } impl Fonts { - /// The faces of [`FALLBACK_FAMILIES`] on this computer in a weight and slant, in order. - pub(crate) fn fallback_list(&self, bold: bool, italic: bool) -> Vec { + /// The faces of [`FALLBACK_FAMILIES`] on this computer in a weight and slant, in order + /// (found once for each). + pub(crate) fn fallback_list(&self, bold: bool, italic: bool) -> Arc<[fontdb::ID]> { + if let Ok(known) = self.lists.lock() + && let Some(list) = known.get(&(bold, italic)) + { + return list.clone(); + } let mut out: Vec = Vec::new(); for name in FALLBACK_FAMILIES { let q = fontdb::Query { @@ -121,6 +128,10 @@ impl Fonts { out.push(id); } } + let out: Arc<[fontdb::ID]> = out.into(); + if let Ok(mut known) = self.lists.lock() { + known.insert((bold, italic), out.clone()); + } out } @@ -144,6 +155,24 @@ impl Fonts { found } + /// Whether face `id` has a glyph for `c`: read from the font once and remembered, so text + /// that keeps needing a fallback (every keystroke lays the block out again) doesn't open + /// the fallback faces each time. + pub(crate) fn covers(&self, id: fontdb::ID, c: char) -> bool { + if let Ok(known) = self.covered.lock() + && let Some(has) = known.get(&(id, c)) + { + return *has; + } + let has = self.db.with_face_data(id, |data, index| crate::face_has(data, index, c)).unwrap_or(false); + if let Ok(mut known) = self.covered.lock() + && known.len() < MAX_REMEMBERED * 16 + { + known.insert((id, c), has); + } + has + } + /// A face's family name. pub(crate) fn family_of(&self, id: fontdb::ID) -> String { self.db.face(id).and_then(|f| f.families.first().map(|(n, _)| n.clone())).unwrap_or_default() diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 4b768066..529dddbb 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -467,9 +467,16 @@ pub struct Fonts { db: fontdb::Database, families: Vec, /// Which face, if any, has each character the fallback list didn't (`Fonts::any_face_with`). - wide: std::sync::Mutex>>, + wide: Remembered>, + /// The fallback families' faces by weight and slant (`Fonts::fallback_list`), found once. + lists: Remembered<(bool, bool), Arc<[fontdb::ID]>>, + /// Whether a face has a character, for the letters fallback asked about (`Fonts::covers`). + covered: Remembered<(fontdb::ID, char), bool>, } +/// Answers about the fonts that are worked out once and kept (ADR 0130). +type Remembered = std::sync::Mutex>; + static FONTS: OnceLock = OnceLock::new(); static EXTRA: OnceLock>> = OnceLock::new(); @@ -504,7 +511,7 @@ impl Fonts { let mut families: Vec = db.faces().filter_map(|f| f.families.first().map(|(n, _)| n.clone())).filter(|n| !n.starts_with('.')).collect(); families.sort_by_key(|f| f.to_lowercase()); families.dedup(); - Fonts { db, families, wide: std::sync::Mutex::default() } + Fonts { db, families, wide: Remembered::default(), lists: Remembered::default(), covered: Remembered::default() } } /// A library of just these faces (tests, and documents carrying their own fonts). diff --git a/crates/text/src/rich.rs b/crates/text/src/rich.rs index a01b3868..f6d3adf3 100644 --- a/crates/text/src/rich.rs +++ b/crates/text/src/rich.rs @@ -480,7 +480,7 @@ impl Fonts { let had = drawn.iter().filter(|c| cover.has(own, **c)).count(); let mut chosen: Option = None; if had < drawn.len() { - let candidates = lists.entry((st.bold, st.italic)).or_insert_with(|| self.fallback_list(st.bold, st.italic).into_iter().filter(|id| *id != own).collect()); + let candidates = lists.entry((st.bold, st.italic)).or_insert_with(|| self.fallback_list(st.bold, st.italic).iter().copied().filter(|id| *id != own).collect()); let mut pick = pick_face(&drawn, had, candidates.len(), &mut |f, c| candidates.get(f).is_some_and(|id| cover.has(*id, c))); let lacks = |id: Option, cover: &mut Coverage| drawn.iter().copied().find(|c| !cover.has(id.unwrap_or(own), *c)); // No listed face has all of it: any installed face with the letter. From 2bfa513e503d10ef01c21b679df119858ac35431 Mon Sep 17 00:00:00 2001 From: FredApps Date: Tue, 24 Nov 2026 13:10:44 +0100 Subject: [PATCH 44/44] docs: keep AGENTS.md's repository section under 4 KB (RFC-0072) The section was 4,579 bytes; it is 4,018. Every convention, check and the workspace map's crate and layer columns stay; only descriptions are shorter. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 54 +++++++++++++++++++++++++++--------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index eb3f00fa..684bcfcd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,42 +63,42 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119 ## This repository -AniCraft is an open-source, native, clean-room 2D animation studio (Adobe Animate class), written in Rust only (egui/eframe UI). The product name is written **AniCraft**; machine names are lowercase (`anicraft-*`). `docs/` has the design: ADRs in `docs/adr/`, UI guidelines, the prioritised backlog and status in `docs/roadmap.md` (a guideline, not a timeline: ADR 0125), and parity with the reference app in `docs/parity.md`. +AniCraft is an open-source, native, clean-room 2D animation studio in Rust only (egui/eframe UI). The product name is written **AniCraft**; machine names are lowercase (`anicraft-*`). The design is in `docs/`: ADRs in `docs/adr/`, UI guidelines, the backlog and status in `docs/roadmap.md` (a guideline, not a timeline: ADR 0125), and parity in `docs/parity.md`. ## Workspace map ```text -crates/geom L0 Vec2, Affine (decompose/compose), Rect, Path, flattening, hit testing -crates/xml L0 Bounded XML element reader shared by the importers (XFL, SVG) -crates/plugins L0 Sandboxed WebAssembly plug-ins: wasmi host, ABI v1, limits, registry (ADR 0017) -crates/audio L0 Sound decoding (WAV, Ogg Vorbis, MP3), pure mixing and resampling, WAV, peaks (ADR 0020) -crates/actions L0 Timeline action IR: stop/play/goto, targets, button events, frame scripts (ADR 0024) -crates/guide L0 The user guide (docs/guide) as a bundled static HTML book, with its link checks (ADR 0069) -crates/doc L1 Document model, easing, timeline evaluation, the interactive player, sample scene -crates/text L1 Fonts on this computer, shaping and line layout into outlines (ADR 0012) -crates/render L2 CPU oracle renderer (coverage accumulation, paints, strokes, PNG) -crates/xfl L2 XFL/FLA import: own XML + zip readers, edges → paths (ADR 0009) -crates/svg L2 SVG import: shapes, groups, use, styles, gradients, clips/masks → mask layers, text -crates/engine L3 Session, undo (with gesture coalescing), command registry, .anicraft format -crates/gpu L3 wgpu stage renderer (the default stage): tile binning, compute coverage, bitmaps, filters (ADR 0019, 0029, 0032) -crates/cli L4 anicraft-cli: info/render/render-seq/commands/exec/run/new/guide/serve/mcp -src/ L5 egui shell (app, menus, stage, timeline, panels, theme) +crates/geom L0 Vec2, Affine, Rect, Path, flattening, hit testing +crates/xml L0 Bounded XML reader shared by the XFL and SVG importers +crates/plugins L0 Sandboxed WebAssembly plug-ins: wasmi host, ABI v1, limits (ADR 0017) +crates/audio L0 WAV, Ogg Vorbis and MP3 decoding, mixing, resampling, peaks (ADR 0020) +crates/actions L0 Timeline action IR, button events, frame scripts (ADR 0024) +crates/guide L0 docs/guide as a bundled HTML book, with link checks (ADR 0069) +crates/doc L1 Document model, easing, timeline evaluation, player, sample scene +crates/text L1 System fonts, shaping, line layout into outlines (ADR 0012) +crates/render L2 CPU oracle renderer (coverage, paints, strokes, PNG) +crates/xfl L2 XFL/FLA import with its own XML and zip readers (ADR 0009) +crates/svg L2 SVG import; clips and masks become mask layers +crates/engine L3 Session, undo, command registry, .anicraft format +crates/gpu L3 wgpu stage renderer, the default (ADR 0019, 0029, 0032) +crates/cli L4 anicraft-cli, including serve and mcp +src/ L5 egui shell: app, menus, stage, timeline, panels, theme ``` -A crate depends only on lower layers, and nothing below `src/` uses egui, eframe or winit. `src/architecture_tests.rs` checks both, and that this map lists every crate with its layer (a new crate needs a row here and in its `LAYERS` table). +A crate depends only on lower layers; nothing below `src/` uses egui, eframe or winit. `src/architecture_tests.rs` checks both, and that this map lists every crate with its layer (a new crate needs a row here and in its `LAYERS` table). ## Conventions -- New behaviour is a `CommandSpec` in `crates/engine/src/cmds_*.rs`; menus and shortcuts come from the registry. `panic_hunt_every_command` fuzzes every command. A new command namespace needs a plug-in policy (`plugin_may_call` in `crates/engine/src/cmds_plugin.rs`). -- Commands read and write files through `engine::vfs`, never `std::fs`: `vfs` is where an agent's automation roots are applied (ADR 0124, `engine::access`). A command that takes a path gets a row in `access::PATH_PARAMS` (`every_command_with_a_path_parameter_is_listed` checks it), and code that hands a path to something else (ffmpeg, another crate's reader) calls `access::check` first. -- `doc::evaluate` is pure: time is a function, and animation never mutates the document. The CPU renderer in `crates/render` is the oracle the GPU renderer is tested against. -- Text goes through `theme::Type` roles (`guidelines_tests` checks it; `docs/ui-guidelines.md`). Interface text uses `tr!`, `trn!` and `tr_noop!` (ADR 0040, `docs/localisation.md`; check with `--lang pseudo`). The app-local craft-i18n catalog parser stays until ADR 0040's cutover. -- OS-specific code lives in `src/platform.rs`; shortcut text goes through `platform::shortcut_label`. -- `unsafe_code = "forbid"`; no workspace module allows `unsafe`. The plug-in SDK in `examples/plugins/sdk` is outside the workspace and uses `unsafe` for the WebAssembly host calls. -- `deny.toml` is the dependency policy (permissive licences; craft-libs is the one allowed Git source, pinned by `rev`). Assets get a row in `ATTRIBUTION.md` with licence text under `licenses/`; fonts come from craft-fonts through `CRAFT_FONTS_DIR`. Legal notes: `docs/legal/compliance.md`. -- `scripts/git-hooks` refuses commits on `main` (`git config core.hooksPath scripts/git-hooks`). Branches are `feat/`, `fix/`, `docs/` or `m/`; commit subjects use conventional prefixes (`feat(render): ...`), and milestone work ends them with `(M5)`. Credits: `AUTHORS.md`. -- Build footprint settings (one `target/`, incremental off): `docs/development.md`. +- New behaviour is a `CommandSpec` in `crates/engine/src/cmds_*.rs`; menus and shortcuts come from the registry, and `panic_hunt_every_command` fuzzes every command. A new namespace needs a plug-in policy (`plugin_may_call` in `cmds_plugin.rs`). +- Commands use `engine::vfs`, never `std::fs`: it applies an agent's automation roots (ADR 0124, `engine::access`). A command with a path parameter gets a row in `access::PATH_PARAMS` (checked by `every_command_with_a_path_parameter_is_listed`); code handing a path to something else (ffmpeg, another crate's reader) calls `access::check` first. +- `doc::evaluate` is pure: animation never mutates the document. `crates/render` is the oracle the GPU renderer is tested against. +- Text uses `theme::Type` roles (`guidelines_tests`; `docs/ui-guidelines.md`). Interface text uses `tr!`, `trn!` and `tr_noop!` (ADR 0040, `docs/localisation.md`; check with `--lang pseudo`); the app-local craft-i18n catalog parser stays until ADR 0040's cutover. +- OS-specific code is in `src/platform.rs`; shortcut text goes through `platform::shortcut_label`. +- `unsafe_code = "forbid"`: no workspace module allows `unsafe`. The plug-in SDK in `examples/plugins/sdk` is outside the workspace and uses it for WebAssembly host calls. +- `deny.toml` is the dependency policy (permissive licences; craft-libs, pinned by `rev`, is the one Git source). Assets get an `ATTRIBUTION.md` row with licence text in `licenses/`; fonts come from craft-fonts via `CRAFT_FONTS_DIR`. Legal notes: `docs/legal/compliance.md`. +- `scripts/git-hooks` refuses commits on `main` (`git config core.hooksPath scripts/git-hooks`). Branches are `feat/`, `fix/`, `docs/` or `m/`; subjects use conventional prefixes (`feat(render): ...`), and milestone work ends with `(M5)`. Credits: `AUTHORS.md`. +- Build footprint (one `target/`, incremental off): `docs/development.md`. ## Checks -For the crates you changed: `cargo clippy -p --all-targets -- -D warnings` and `cargo test -p `. For the shell, `cargo test` and `cargo clippy --all-targets`. When dependencies change: `cargo deny check licenses bans sources`. For UI changes: `cargo run -- --screenshot shots/now.png` and look at the PNG. +For the crates you changed: `cargo clippy -p --all-targets -- -D warnings` and `cargo test -p `. For the shell: `cargo test` and `cargo clippy --all-targets`. When dependencies change: `cargo deny check licenses bans sources`. For UI changes: `cargo run -- --screenshot shots/now.png`, then look at the PNG.