Skip to main content

ultrafast_geom/
geom.rs

1//! Vector geometry for the GPU rasterizer: paths (SVG data, presets,
2//! strokes, dashes, trims) and text (font lookup, shaping, layout).
3//!
4//! Everything expensive is cached: shaped lines by (font, size, text),
5//! glyph outlines by (font, glyph), and final flattened segments by a hash
6//! of every input (params, transform, time when animated). A static path or
7//! label costs nothing per frame; an animated one re-flattens only.
8
9use crate::{Affine, GeomError, text};
10use kurbo::{BezPath, ParamCurve, ParamCurveArclen, PathEl, Point, Shape};
11use std::collections::HashMap;
12use std::hash::{Hash, Hasher};
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use ultrafast_graph::{Format, Node, Param};
16use unicode_script::{Script, UnicodeScript};
17
18/// Flattened geometry ready for upload: per segment two float4s,
19/// (x0, y0, x1, y1) and (weight, color group, 0, 0), in output pixels.
20#[derive(Debug, Clone, Default)]
21pub struct Geometry {
22    pub segments: Vec<f32>,
23    /// Bounds in output pixels (min x, min y, max x, max y).
24    pub bounds: [f32; 4],
25    /// Colors of the segment groups, composited in order (each over the
26    /// ones before): linear straight-alpha, or None for the node's own
27    /// color. Empty means one group in the node's color.
28    pub groups: Vec<Option<[f32; 4]>>,
29    /// Color glyphs (emoji) drawn from their bitmaps over the groups.
30    pub images: Vec<GlyphImage>,
31    /// A text's glyph units laid out: what its `reveal` counts (0 for
32    /// paths).
33    pub units: usize,
34}
35
36/// A color glyph's bitmap (an sbix or CBDT strike): linear premultiplied
37/// RGBA as half floats, row-major from the top.
38pub struct GlyphBitmap {
39    /// Identifies the bitmap (face, glyph, strike) for GPU caches.
40    pub key: u64,
41    pub width: u32,
42    pub height: u32,
43    pub rgba: Vec<u16>,
44    /// Where it sits in font units: left, bottom, width, height (y up).
45    pub place: [f64; 4],
46}
47
48impl std::fmt::Debug for GlyphBitmap {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(f, "GlyphBitmap({:x}, {}x{})", self.key, self.width, self.height)
51    }
52}
53
54/// A color glyph placed in the output.
55#[derive(Clone, Debug)]
56pub struct GlyphImage {
57    pub bitmap: Arc<GlyphBitmap>,
58    /// Maps the bitmap's unit square (u right, v down) to output pixels.
59    pub xf: [f64; 6],
60    /// Coverage weight (reveal, per-glyph opacity).
61    pub weight: f32,
62}
63
64impl Geometry {
65    pub fn count(&self) -> usize {
66        self.segments.len() / 8
67    }
68
69    fn push(&mut self, a: Point, b: Point, w: f32, group: u32) {
70        if a == b {
71            return;
72        }
73        self.segments.extend([
74            a.x as f32,
75            a.y as f32,
76            b.x as f32,
77            b.y as f32,
78            w,
79            group as f32,
80            0.0,
81            0.0,
82        ]);
83        for p in [a, b] {
84            self.bounds[0] = self.bounds[0].min(p.x as f32);
85            self.bounds[1] = self.bounds[1].min(p.y as f32);
86            self.bounds[2] = self.bounds[2].max(p.x as f32);
87            self.bounds[3] = self.bounds[3].max(p.y as f32);
88        }
89    }
90
91    fn empty() -> Self {
92        Geometry {
93            segments: Vec::new(),
94            bounds: [f32::MAX, f32::MAX, f32::MIN, f32::MIN],
95            groups: Vec::new(),
96            images: Vec::new(),
97            units: 0,
98        }
99    }
100
101    /// Adds a color glyph, growing the bounds by its corners.
102    fn push_image(&mut self, im: GlyphImage) {
103        let m = im.xf;
104        for (u, v) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] {
105            let x = (m[0] * u + m[2] * v + m[4]) as f32;
106            let y = (m[1] * u + m[3] * v + m[5]) as f32;
107            self.bounds[0] = self.bounds[0].min(x);
108            self.bounds[1] = self.bounds[1].min(y);
109            self.bounds[2] = self.bounds[2].max(x);
110            self.bounds[3] = self.bounds[3].max(y);
111        }
112        self.images.push(im);
113    }
114
115    /// Whether there is nothing to draw.
116    pub fn is_empty(&self) -> bool {
117        self.segments.is_empty() && self.images.is_empty()
118    }
119}
120
121/// Flattening tolerance in output pixels.
122const TOLERANCE: f64 = 0.1;
123
124/// Appends `path` (already in output space) as closed contours: fills need
125/// every subpath closed, whether or not the data closes it.
126fn flatten_closed(path: &BezPath, weight: f32, group: u32, out: &mut Geometry) {
127    let mut start = Point::ZERO;
128    let mut last = Point::ZERO;
129    let mut open = false;
130    kurbo::flatten(path.iter(), TOLERANCE, |el| match el {
131        PathEl::MoveTo(p) => {
132            if open {
133                out.push(last, start, weight, group);
134            }
135            start = p;
136            last = p;
137            open = true;
138        }
139        PathEl::LineTo(p) => {
140            out.push(last, p, weight, group);
141            last = p;
142        }
143        PathEl::ClosePath => {
144            out.push(last, start, weight, group);
145            last = start;
146            open = false;
147        }
148        _ => {}
149    });
150    if open {
151        out.push(last, start, weight, group);
152    }
153}
154
155pub struct Fonts {
156    db: Option<fontdb::Database>,
157    data: HashMap<fontdb::ID, (Arc<Vec<u8>>, u32)>,
158    files: HashMap<PathBuf, fontdb::ID>,
159    shaped: crate::lru::Lru<u64, Arc<ShapedLine>>,
160    /// Outlines by face, glyph and variation-instance hash.
161    glyphs: crate::lru::Lru<(fontdb::ID, u16, u64), Arc<BezPath>>,
162    /// Whether a face has a glyph for a character, and which face stands in
163    /// for characters the requested one lacks.
164    covers: HashMap<(fontdb::ID, char), bool>,
165    fallback: HashMap<char, Option<fontdb::ID>>,
166    /// Families looked up by name: whether the database has them (after
167    /// fetching from the font cache or Google Fonts when it did not).
168    families: HashMap<String, bool>,
169    /// Decoded color glyph bitmaps by face, glyph and strike.
170    bitmaps: crate::lru::Lru<(fontdb::ID, u16, u16), Option<Arc<GlyphBitmap>>>,
171    /// Color emoji faces installed, in preference order.
172    emoji: Option<Vec<fontdb::ID>>,
173    /// Whether a face has color bitmaps (sbix, CBDT).
174    color: HashMap<fontdb::ID, bool>,
175    /// Faces resolved by (font, weight, italic, base dir) hash: matching a
176    /// family by weight scans every face, so it happens once (and again
177    /// when faces are added).
178    resolved: HashMap<u64, fontdb::ID>,
179    /// Pinned faces by (lowercase family, weight, italic): ahead of every
180    /// other source until [`Fonts::unpin`].
181    pins: HashMap<(String, u16, bool), fontdb::ID>,
182    /// How this document sets writing systems its fonts do not cover. Empty
183    /// for almost every document, which then lays out exactly as it always
184    /// has.
185    script_fonts: Vec<ScriptFont>,
186}
187
188/// How a document sets one writing system: the face that stands in for each
189/// requested font, and what that system's text may do. `meta.script_fonts`
190/// in a document, for this render only.
191#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
192#[serde(deny_unknown_fields)]
193pub struct ScriptFont {
194    /// ISO 15924 codes this row sets ("Deva", or "Hani", "Hira", "Kana" for
195    /// Japanese).
196    pub scripts: Vec<String>,
197    /// Requested family (lowercase) to the family that sets this script,
198    /// "Family@800" to set it at that weight whatever the text asks for.
199    #[serde(default)]
200    pub faces: HashMap<String, String>,
201    /// The family for any other requested font.
202    pub default: String,
203    /// Size relative to the requested one, so a line reads at one size.
204    #[serde(default = "one")]
205    pub scale: f64,
206    /// Line height relative to the requested one, for tall marks.
207    #[serde(default = "one")]
208    pub leading: f64,
209    /// Whether letter spacing applies. Connected scripts and scripts whose
210    /// letters hang from one line break apart with it.
211    #[serde(default = "yes")]
212    pub tracking: bool,
213    /// Whether per-letter animation moves whole words instead of clusters
214    /// (the same scripts).
215    #[serde(default)]
216    pub whole_words: bool,
217    /// Language for the font's localized forms ("mr", "ur").
218    #[serde(default)]
219    pub language: Option<String>,
220}
221
222fn one() -> f64 {
223    1.0
224}
225
226fn yes() -> bool {
227    true
228}
229
230/// A font file that answers for a family, weight and style (see
231/// [`Fonts::pin`]).
232#[derive(Debug, Clone, PartialEq)]
233pub struct FontPin {
234    pub family: String,
235    pub weight: u16,
236    pub italic: bool,
237    pub path: PathBuf,
238}
239
240/// A glyph of a laid-out line: its face (the requested one, or a fallback
241/// for characters it lacks), position and advance in pixels.
242#[derive(Debug, Clone)]
243pub struct LineGlyph {
244    pub font: fontdb::ID,
245    pub id: u16,
246    pub x: f64,
247    pub y: f64,
248    pub advance: f64,
249    /// Byte offset of the text it sets.
250    pub cluster: usize,
251    /// Pixels per font unit of its face.
252    pub scale: f64,
253    /// Letter spacing units before it. Each glyph's own in Latin text;
254    /// a vowel sign shares its letter's, and a connected script has none.
255    pub track: u32,
256    /// Which animation unit it moves with, in reading order: each glyph in
257    /// Latin text, a letter with its marks, or a whole word.
258    pub unit: u32,
259    /// Set in a stand-in face for its script: never slanted to fake italics.
260    pub upright: bool,
261}
262
263/// Faces tried first for characters the requested font lacks.
264const FALLBACK_FAMILIES: &[&str] = &[
265    "Helvetica Neue",
266    "Apple Symbols",
267    "Arial Unicode MS",
268    "PingFang SC",
269    "Hiragino Sans",
270    "Apple SD Gothic Neo",
271    "Noto Sans",
272    "Noto Sans Symbols 2",
273    "DejaVu Sans",
274    "Segoe UI Symbol",
275];
276
277/// Color emoji faces, in preference order.
278const EMOJI_FAMILIES: &[&str] = &[
279    "Apple Color Emoji",
280    "Noto Color Emoji",
281    "Segoe UI Emoji",
282    "Twemoji Mozilla",
283];
284
285/// Whether `c` (followed by `next`) is shown as an emoji: characters whose
286/// default presentation is emoji (Unicode's Emoji_Presentation), and any
287/// character asking for it with VARIATION SELECTOR-16.
288fn emoji_presentation(c: char, next: Option<char>) -> bool {
289    match next {
290        Some('\u{fe0f}') => return true,
291        Some('\u{fe0e}') => return false,
292        _ => {}
293    }
294    matches!(c as u32,
295        0x231A..=0x231B | 0x23E9..=0x23EC | 0x23F0 | 0x23F3 | 0x25FD..=0x25FE | 0x2614..=0x2615
296        | 0x2648..=0x2653 | 0x267F | 0x2693 | 0x26A1 | 0x26AA..=0x26AB | 0x26BD..=0x26BE
297        | 0x26C4..=0x26C5 | 0x26CE | 0x26D4 | 0x26EA | 0x26F2..=0x26F3 | 0x26F5 | 0x26FA | 0x26FD
298        | 0x2705 | 0x270A..=0x270B | 0x2728 | 0x274C | 0x274E | 0x2753..=0x2755 | 0x2757
299        | 0x2795..=0x2797 | 0x27B0 | 0x27BF | 0x2B1B..=0x2B1C | 0x2B50 | 0x2B55
300        | 0x1F004 | 0x1F0CF | 0x1F18E | 0x1F191..=0x1F19A | 0x1F1E6..=0x1F1FF | 0x1F201 | 0x1F21A
301        | 0x1F22F | 0x1F232..=0x1F236 | 0x1F238..=0x1F23A | 0x1F250..=0x1F251 | 0x1F300..=0x1F320
302        | 0x1F32D..=0x1F335 | 0x1F337..=0x1F37C | 0x1F37E..=0x1F393 | 0x1F3A0..=0x1F3CA
303        | 0x1F3CF..=0x1F3D3 | 0x1F3E0..=0x1F3F0 | 0x1F3F4 | 0x1F3F8..=0x1F43E | 0x1F440
304        | 0x1F442..=0x1F4FC | 0x1F4FF..=0x1F53D | 0x1F54B..=0x1F54E | 0x1F550..=0x1F567 | 0x1F57A
305        | 0x1F595..=0x1F596 | 0x1F5A4 | 0x1F5FB..=0x1F64F | 0x1F680..=0x1F6C5 | 0x1F6CC
306        | 0x1F6D0..=0x1F6D2 | 0x1F6D5..=0x1F6D7 | 0x1F6DC..=0x1F6DF | 0x1F6EB..=0x1F6EC
307        | 0x1F6F4..=0x1F6FC | 0x1F7E0..=0x1F7EB | 0x1F7F0 | 0x1F90C..=0x1F93A | 0x1F93C..=0x1F945
308        | 0x1F947..=0x1F9FF | 0x1FA70..=0x1FAFF)
309}
310
311/// Characters that belong to the one before them in an emoji sequence.
312fn attaches(c: char) -> bool {
313    matches!(c as u32, 0x200D | 0xFE0E | 0xFE0F | 0x20E3 | 0x1F3FB..=0x1F3FF | 0xE0020..=0xE007F)
314}
315
316/// Decodes a glyph's raster image to linear premultiplied RGBA (half
317/// floats) and its placement in font units (left, bottom, width, height).
318fn decode_glyph_image(
319    img: &rustybuzz::ttf_parser::RasterGlyphImage,
320    units_per_em: f64,
321) -> Option<(u32, u32, Vec<u16>, [f64; 4])> {
322    use rustybuzz::ttf_parser::RasterImageFormat;
323    // Straight-alpha sRGB8 or premultiplied sRGB8 pixels.
324    let (w, h, px, premultiplied): (u32, u32, Vec<u8>, bool) = match img.format {
325        RasterImageFormat::PNG => {
326            let im = image::load_from_memory_with_format(img.data, image::ImageFormat::Png).ok()?;
327            let im = im.to_rgba8();
328            (im.width(), im.height(), im.into_raw(), false)
329        }
330        RasterImageFormat::BitmapPremulBgra32 => {
331            let (w, h) = (img.width as u32, img.height as u32);
332            let mut px = img.data.get(..(w * h * 4) as usize)?.to_vec();
333            for p in px.chunks_exact_mut(4) {
334                p.swap(0, 2);
335            }
336            (w, h, px, true)
337        }
338        _ => return None,
339    };
340    if w == 0 || h == 0 {
341        return None;
342    }
343    let lut: Vec<f32> = (0..256)
344        .map(|v| {
345            let c = v as f32 / 255.0;
346            if c <= 0.04045 {
347                c / 12.92
348            } else {
349                ((c + 0.055) / 1.055).powf(2.4)
350            }
351        })
352        .collect();
353    let mut rgba = Vec::with_capacity(px.len());
354    for p in px.chunks_exact(4) {
355        let a = p[3] as f32 / 255.0;
356        let un = |v: u8| {
357            if premultiplied && a > 0.0 {
358                lut[((v as f32 / a).round().min(255.0)) as usize]
359            } else {
360                lut[v as usize]
361            }
362        };
363        for c in [un(p[0]) * a, un(p[1]) * a, un(p[2]) * a, a] {
364            rgba.push(crate::f32_to_f16(c));
365        }
366    }
367    let s = units_per_em / img.pixels_per_em.max(1) as f64;
368    // The image may be larger than its metrics say: scale to what it is.
369    let (mw, mh) = (img.width.max(1) as f64, img.height.max(1) as f64);
370    let place = [img.x as f64 * s, img.y as f64 * s, mw * s, mh * s];
371    let _ = (w, h);
372    Some((w, h, rgba, place))
373}
374
375/// A variable font instance: axis tag and value pairs.
376pub type Variations = Vec<rustybuzz::Variation>;
377
378fn variations_key(vars: &[rustybuzz::Variation]) -> u64 {
379    let mut h = std::collections::hash_map::DefaultHasher::new();
380    for v in vars {
381        v.tag.to_bytes().hash(&mut h);
382        v.value.to_bits().hash(&mut h);
383    }
384    h.finish()
385}
386
387#[derive(Debug, Clone)]
388pub struct ShapedGlyph {
389    pub id: u16,
390    /// Pen position and offset in font units.
391    pub x: f32,
392    pub y: f32,
393    /// Advance in font units, and the byte offset of the text it came from.
394    pub advance: f32,
395    pub cluster: u32,
396}
397
398#[derive(Debug)]
399pub struct ShapedLine {
400    pub glyphs: Vec<ShapedGlyph>,
401    /// Total advance in font units.
402    pub advance: f32,
403}
404
405/// Applies a face's pair-kerning `kerx` subtables (formats 0, 2 and 6),
406/// which rustybuzz 0.20 reads but never applies (its skipping iterator
407/// ignores base glyphs), as HarfBuzz does: half of each pair's value on
408/// each glyph. Faces such as macOS's Helvetica Neue kern only through
409/// `kerx`. Shaping that applied a state-machine `kerx` (formats 1, 4) or
410/// GPOS is left alone.
411fn kerx_pairs(face: &rustybuzz::Face, infos: &[rustybuzz::GlyphInfo], pos: &mut [(i32, i32, i32)]) {
412    use rustybuzz::ttf_parser::{GlyphId, kerx::Format};
413    let t = face.tables();
414    let Some(kerx) = t.kerx else { return };
415    if t.gpos.is_some() && t.gsub.is_some() {
416        return;
417    }
418    for sub in kerx.subtables {
419        if sub.variable || !sub.horizontal || sub.has_cross_stream {
420            continue;
421        }
422        if !matches!(sub.format, Format::Format0(_) | Format::Format2(_) | Format::Format6(_)) {
423            continue;
424        }
425        for i in 0..infos.len().saturating_sub(1) {
426            let k = sub
427                .glyphs_kerning(GlyphId(infos[i].glyph_id as u16), GlyphId(infos[i + 1].glyph_id as u16))
428                .unwrap_or(0) as i32;
429            if k != 0 {
430                let k1 = k >> 1;
431                let k2 = k - k1;
432                pos[i].0 += k1;
433                pos[i + 1].0 += k2;
434                pos[i + 1].1 += k2;
435            }
436        }
437    }
438}
439
440struct FontMetrics {
441    units_per_em: f32,
442    ascender: f32,
443    descender: f32,
444}
445
446/// Faces bundled into ultrafast (SIL Open Font License; see
447/// examples/assets/fonts/licenses, linked from this crate's fonts/), loadable by family name or as
448/// `ultrafast:sans`, `ultrafast:mono`, `ultrafast:serif`, `ultrafast:display`, `ultrafast:wide`.
449const BUNDLED: &[&[u8]] = &[
450    include_bytes!("../fonts/Geist-VF.ttf"),
451    include_bytes!("../fonts/GeistMono-VF.ttf"),
452    include_bytes!("../fonts/InstrumentSerif-Regular.ttf"),
453    include_bytes!("../fonts/InstrumentSerif-Italic.ttf"),
454    include_bytes!("../fonts/Fraunces-VF.ttf"),
455    include_bytes!("../fonts/Fraunces-Italic-VF.ttf"),
456    include_bytes!("../fonts/Unbounded-VF.ttf"),
457];
458
459/// The font files bundled into ultrafast (for tools that search faces).
460pub fn bundled_fonts() -> &'static [&'static [u8]] {
461    BUNDLED
462}
463
464impl Fonts {
465    pub fn new() -> Self {
466        Self {
467            db: None,
468            data: HashMap::new(),
469            files: HashMap::new(),
470            // Bounded: text edited live would otherwise grow these forever.
471            shaped: crate::lru::Lru::new(4096),
472            glyphs: crate::lru::Lru::new(32768),
473            covers: HashMap::new(),
474            fallback: HashMap::new(),
475            families: HashMap::new(),
476            bitmaps: crate::lru::Lru::new(512),
477            emoji: None,
478            color: HashMap::new(),
479            resolved: HashMap::new(),
480            pins: HashMap::new(),
481            script_fonts: Vec::new(),
482        }
483    }
484
485    /// How this document sets the writing systems its fonts do not cover,
486    /// until [`Fonts::unpin`] or the next call.
487    pub fn set_script_fonts(&mut self, rows: Vec<ScriptFont>) {
488        self.script_fonts = rows;
489    }
490
491    /// The row that sets `c`, when a document has one for its script.
492    fn script_row(&self, c: char) -> Option<usize> {
493        if self.script_fonts.is_empty() {
494            return None;
495        }
496        let script = c.script();
497        if matches!(script, Script::Common | Script::Inherited | Script::Unknown) {
498            return None;
499        }
500        let name = script.short_name();
501        self.script_fonts
502            .iter()
503            .position(|row| row.scripts.iter().any(|s| s == name))
504    }
505
506    /// Line height multiplier of `text`: the tallest of its scripts.
507    pub fn script_leading(&self, text: &str) -> f64 {
508        if self.script_fonts.is_empty() {
509            return 1.0;
510        }
511        text.chars()
512            .filter_map(|c| self.script_row(c))
513            .map(|row| self.script_fonts[row].leading)
514            .fold(1.0, f64::max)
515    }
516
517    /// Whether `text` reads right to left (for a document that sets a
518    /// script: every other document lays out as it always has).
519    pub fn reads_rtl(&self, text: &str) -> bool {
520        !self.script_fonts.is_empty() && unicode_bidi::get_base_direction(text) == unicode_bidi::Direction::Rtl
521    }
522
523    /// The family, weight and italic a face answers for.
524    fn face_key(&mut self, id: fontdb::ID) -> (String, u16, bool) {
525        if let Some(((family, weight, italic), _)) = self.pins.iter().find(|(_, v)| **v == id) {
526            return (family.clone(), *weight, *italic);
527        }
528        self.db()
529            .face(id)
530            .map(|f| {
531                (
532                    f.families.first().map(|(n, _)| n.to_lowercase()).unwrap_or_default(),
533                    f.weight.0,
534                    f.style != fontdb::Style::Normal,
535                )
536            })
537            .unwrap_or_default()
538    }
539
540    /// The face a row sets `primary`'s text in, closest to its weight.
541    fn script_face(&mut self, primary: fontdb::ID, row: usize) -> Result<fontdb::ID, String> {
542        let (family, weight, _) = self.face_key(primary);
543        let spec = &self.script_fonts[row];
544        let target = spec.faces.get(&family).unwrap_or(&spec.default).clone();
545        // "Family@800": a one-weight display font asks for 400 but reads heavy.
546        let (target, weight) = match target
547            .rsplit_once('@')
548            .and_then(|(f, w)| Some((f, w.parse::<u16>().ok()?)))
549        {
550            Some((f, w)) => (f.to_string(), w),
551            None => (target, weight),
552        };
553        if let Some(id) = self.pinned(&target, weight, false) {
554            return Ok(id);
555        }
556        let q = fontdb::Query {
557            families: &[fontdb::Family::Name(&target)],
558            weight: fontdb::Weight(weight),
559            ..Default::default()
560        };
561        self.db()
562            .query(&q)
563            .ok_or_else(|| format!("no face for script font `{target}` (it must be pinned in meta.fonts)"))
564    }
565
566    /// The face a family and weight resolve to (for [`Fonts::missing_glyphs`]).
567    pub fn lookup(&mut self, family: &str, weight: u16) -> Result<fontdb::ID, String> {
568        self.resolve(family, weight, false, Path::new("."))
569    }
570
571    /// Characters of `text` no face in this document can draw, as a render
572    /// would find them (a look's check, before anything renders).
573    pub fn missing_glyphs(&mut self, primary: fontdb::ID, text: &str) -> Vec<char> {
574        let mut out = Vec::new();
575        let chars: Vec<char> = text.chars().collect();
576        for (i, &c) in chars.iter().enumerate() {
577            // Spaces and the marks that draw nothing (joiners, direction marks).
578            if c.is_whitespace()
579                || c.is_control()
580                || attaches(c)
581                || matches!(c as u32, 0xAD | 0x200B..=0x200F | 0x202A..=0x202E | 0x2060..=0x2064 | 0xFEFF)
582            {
583                continue;
584            }
585            if emoji_presentation(c, chars.get(i + 1).copied()) {
586                continue;
587            }
588            let found = match self.script_row(c) {
589                Some(row) => {
590                    self.has_glyph(primary, c)
591                        || self.script_face(primary, row).is_ok_and(|face| self.has_glyph(face, c))
592                }
593                None => self.has_glyph(primary, c) || self.fallback_for(c).is_some(),
594            };
595            if !found && !out.contains(&c) {
596                out.push(c);
597            }
598        }
599        out
600    }
601
602    /// Pins font files to their family, weight and style: until
603    /// [`Fonts::unpin`], those files answer for them ahead of every other
604    /// font (installed, bundled or fetched), so text is set with exactly the
605    /// files it was measured with elsewhere. Replaces earlier pins.
606    pub fn pin(&mut self, pins: &[FontPin]) -> Result<(), String> {
607        self.unpin();
608        for p in pins {
609            let ids = self.db().load_font_source(fontdb::Source::File(p.path.clone()));
610            let id = *ids
611                .first()
612                .ok_or_else(|| format!("no font in {} (pinned for {})", p.path.display(), p.family))?;
613            self.pins
614                .insert((p.family.trim().to_lowercase(), p.weight, p.italic), id);
615        }
616        self.forget_resolved();
617        Ok(())
618    }
619
620    /// Drops the pins (their faces leave the database).
621    pub fn unpin(&mut self) {
622        self.script_fonts.clear();
623        if self.pins.is_empty() {
624            return;
625        }
626        let pinned: Vec<(String, fontdb::ID)> = self.pins.drain().map(|((f, _, _), id)| (f, id)).collect();
627        for (family, id) in pinned {
628            self.db().remove_face(id);
629            self.data.remove(&id);
630            self.color.remove(&id);
631            self.families.remove(&family);
632        }
633        self.forget_resolved();
634    }
635
636    /// After faces come or go: lookups that may name them start over.
637    fn forget_resolved(&mut self) {
638        self.resolved.clear();
639        self.fallback.clear();
640        self.covers.clear();
641        self.emoji = None;
642    }
643
644    /// The pinned face for a family closest to `weight` (same style first).
645    fn pinned(&self, family: &str, weight: u16, italic: bool) -> Option<fontdb::ID> {
646        if self.pins.is_empty() {
647            return None;
648        }
649        let key = family.trim().to_lowercase();
650        self.pins
651            .iter()
652            .filter(|((f, _, _), _)| *f == key)
653            .min_by_key(|((_, w, i), _)| ((*i != italic) as u32, (*w as i32 - weight as i32).unsigned_abs()))
654            .map(|(_, id)| *id)
655    }
656
657    /// Whether `family` is available, loading it from the font cache or
658    /// downloading it from Google Fonts the first time it is missing.
659    fn ensure_family(&mut self, family: &str) -> bool {
660        let key = family.to_lowercase();
661        if let Some(&ok) = self.families.get(&key) {
662            return ok;
663        }
664        let has = |db: &fontdb::Database| {
665            db.faces()
666                .any(|f| f.families.iter().any(|(n, _)| n.to_lowercase() == key))
667        };
668        let mut ok = has(self.db());
669        if !ok {
670            for p in crate::fontfetch::fetch(family) {
671                let _ = self.db().load_font_file(&p);
672            }
673            self.resolved.clear();
674            ok = has(self.db());
675        }
676        self.families.insert(key, ok);
677        ok
678    }
679
680    /// Whether `family` is a named family this machine does not have yet
681    /// (generic families, ultrafast's aliases and font files never are).
682    pub fn lacks(&mut self, family: &str) -> bool {
683        let key = family.trim().to_lowercase();
684        let generic = matches!(
685            key.as_str(),
686            "" | "sans-serif"
687                | "serif"
688                | "monospace"
689                | "cursive"
690                | "fantasy"
691                | "system-ui"
692                | "ui-sans-serif"
693                | "ui-serif"
694                | "ui-monospace"
695                | "-apple-system"
696                | "blinkmacsystemfont"
697        );
698        if generic || key.starts_with("ultrafast:") || [".ttf", ".otf", ".ttc"].iter().any(|e| key.ends_with(e)) {
699            return false;
700        }
701        if self.pins.keys().any(|(f, _, _)| *f == key) {
702            return false;
703        }
704        if let Some(&ok) = self.families.get(&key) {
705            return !ok;
706        }
707        !self
708            .db()
709            .faces()
710            .any(|f| f.families.iter().any(|(n, _)| n.to_lowercase() == key))
711    }
712
713    fn db(&mut self) -> &mut fontdb::Database {
714        self.db.get_or_insert_with(|| {
715            let mut db = fontdb::Database::new();
716            db.load_system_fonts();
717            // Bundled faces (SIL Open Font License): the same type on every
718            // machine, servers included, by family name.
719            for data in BUNDLED {
720                db.load_font_data(data.to_vec());
721            }
722            // CSS generic families resolve to faces this machine has
723            // (fontdb's defaults, Arial and friends, are missing on servers):
724            // on Linux what Chrome's fontconfig picks (Liberation, metric
725            // twins of Arial, Times New Roman and Courier New), on a Mac what
726            // Safari and Chrome show.
727            let pick = |db: &fontdb::Database, names: &[&str]| {
728                names
729                    .iter()
730                    .find(|n| db.faces().any(|f| f.families.iter().any(|(fam, _)| fam == *n)))
731                    .map(|n| n.to_string())
732            };
733            let mac = cfg!(target_os = "macos");
734            let sans: &[&str] = if mac {
735                &["Helvetica", "Arial", "Geist"]
736            } else {
737                &["Liberation Sans", "Arial", "DejaVu Sans", "Noto Sans", "Geist"]
738            };
739            let serif: &[&str] = if mac {
740                &["Times", "Times New Roman", "Instrument Serif"]
741            } else {
742                &[
743                    "Liberation Serif",
744                    "Times New Roman",
745                    "DejaVu Serif",
746                    "Noto Serif",
747                    "Instrument Serif",
748                ]
749            };
750            let mono: &[&str] = if mac {
751                &["Courier", "Courier New", "Menlo", "Geist Mono"]
752            } else {
753                &[
754                    "Liberation Mono",
755                    "Courier New",
756                    "DejaVu Sans Mono",
757                    "Noto Sans Mono",
758                    "Geist Mono",
759                ]
760            };
761            if let Some(f) = pick(&db, sans) {
762                db.set_sans_serif_family(f.clone());
763                db.set_cursive_family(f.clone());
764                db.set_fantasy_family(f);
765            }
766            if let Some(f) = pick(&db, serif) {
767                db.set_serif_family(f);
768            }
769            if let Some(f) = pick(&db, mono) {
770                db.set_monospace_family(f);
771            }
772            db
773        })
774    }
775
776    /// Resolves a font from a family name, a CSS family list (`"Poppins",
777    /// sans-serif`: the first one this machine has or can fetch), a CSS
778    /// generic family, or a font file path.
779    fn resolve(&mut self, font: &str, weight: u16, italic: bool, base: &Path) -> Result<fontdb::ID, String> {
780        let key = {
781            use std::hash::{Hash, Hasher};
782            let mut h = std::collections::hash_map::DefaultHasher::new();
783            (font, weight, italic, base).hash(&mut h);
784            h.finish()
785        };
786        if let Some(&id) = self.resolved.get(&key) {
787            return Ok(id);
788        }
789        let id = self.resolve_uncached(font, weight, italic, base)?;
790        self.resolved.insert(key, id);
791        Ok(id)
792    }
793
794    fn resolve_uncached(&mut self, font: &str, weight: u16, italic: bool, base: &Path) -> Result<fontdb::ID, String> {
795        let names: Vec<&str> = font
796            .split(',')
797            .map(|f| f.trim().trim_matches(|c| c == '"' || c == '\''))
798            .filter(|f| !f.is_empty())
799            .collect();
800        if names.len() > 1 {
801            for (i, name) in names.iter().enumerate() {
802                if let Some(id) = self.resolve_one(name, weight, italic, base, i + 1 == names.len())? {
803                    return Ok(id);
804                }
805            }
806        }
807        self.resolve_one(names.first().copied().unwrap_or(""), weight, italic, base, true)?
808            .ok_or_else(|| format!("no font matches `{font}`"))
809    }
810
811    /// One family (or a file); with `fallback`, a missing family resolves
812    /// to the sans-serif family instead of None.
813    fn resolve_one(
814        &mut self,
815        font: &str,
816        weight: u16,
817        italic: bool,
818        base: &Path,
819        fallback: bool,
820    ) -> Result<Option<fontdb::ID>, String> {
821        let looks_like_file = font.ends_with(".ttf") || font.ends_with(".otf") || font.ends_with(".ttc");
822        if looks_like_file {
823            let path = if Path::new(font).is_absolute() {
824                PathBuf::from(font)
825            } else {
826                base.join(font)
827            };
828            // A service rendering many callers' documents reads font files
829            // only from the document's own inputs (its base directory), so
830            // markup cannot name another path on the machine.
831            if std::env::var("ULTRAFAST_NO_EXTERNAL_FILES").as_deref() == Ok("1")
832                && (!path.starts_with(base) || path.components().any(|c| c == std::path::Component::ParentDir))
833            {
834                return Err(format!("font file {} is outside the document's inputs", path.display()));
835            }
836            if let Some(id) = self.files.get(&path) {
837                return Ok(Some(*id));
838            }
839            let ids = self.db().load_font_source(fontdb::Source::File(path.clone()));
840            self.resolved.clear();
841            let id = *ids.first().ok_or_else(|| format!("no font in {}", path.display()))?;
842            self.files.insert(path, id);
843            return Ok(Some(id));
844        }
845        if let Some(id) = self.pinned(font, weight, italic) {
846            return Ok(Some(id));
847        }
848        let font = match font {
849            "ultrafast:sans" => "Geist",
850            "ultrafast:mono" => "Geist Mono",
851            "ultrafast:serif" => "Instrument Serif",
852            "ultrafast:display" => "Fraunces",
853            "ultrafast:wide" => "Unbounded",
854            f => f,
855        };
856        let generic = match font.to_ascii_lowercase().as_str() {
857            "sans-serif" | "system-ui" | "ui-sans-serif" | "-apple-system" | "blinkmacsystemfont" => {
858                Some(fontdb::Family::SansSerif)
859            }
860            "serif" | "ui-serif" => Some(fontdb::Family::Serif),
861            "monospace" | "ui-monospace" => Some(fontdb::Family::Monospace),
862            "cursive" => Some(fontdb::Family::Cursive),
863            "fantasy" => Some(fontdb::Family::Fantasy),
864            _ => None,
865        };
866        if !font.is_empty() && generic.is_none() {
867            self.ensure_family(font);
868        }
869        let families: Vec<fontdb::Family> = if let Some(g) = generic {
870            vec![g, fontdb::Family::SansSerif]
871        } else if font.is_empty() {
872            vec![
873                fontdb::Family::Name("Helvetica Neue"),
874                fontdb::Family::Name("Geist"),
875                fontdb::Family::SansSerif,
876            ]
877        } else if fallback {
878            vec![fontdb::Family::Name(font), fontdb::Family::SansSerif]
879        } else {
880            vec![fontdb::Family::Name(font)]
881        };
882        let q = fontdb::Query {
883            families: &families,
884            weight: fontdb::Weight(weight),
885            stretch: fontdb::Stretch::Normal,
886            style: if italic {
887                fontdb::Style::Italic
888            } else {
889                fontdb::Style::Normal
890            },
891        };
892        let Some(found) = self.db().query(&q) else {
893            return Ok(None);
894        };
895        if font.is_empty() || generic.is_some() {
896            return Ok(Some(found));
897        }
898        // Google's static families name each extra weight as its own family
899        // ("Poppins Medium", weight class 500), which a query for "Poppins"
900        // never sees, so 500 fell back to 400. Match those faces by weight.
901        let key = font.to_lowercase();
902        let prefix = format!("{key} ");
903        let want_italic = italic;
904        // A face of another width is not a weight of this family, even when
905        // its file calls it a member with normal width ("Helvetica Neue
906        // Condensed Black" in macOS's HelveticaNeue.ttc).
907        let other_width = |f: &fontdb::FaceInfo| {
908            let names = format!(
909                "{} {}",
910                f.post_script_name,
911                f.families.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>().join(" ")
912            )
913            .to_lowercase();
914            f.stretch != fontdb::Stretch::Normal
915                || ["condensed", "compressed", "narrow", "extended", "expanded"]
916                    .iter()
917                    .any(|w| names.contains(w) && !key.contains(w))
918        };
919        let mut best: Option<(fontdb::ID, i32, bool)> = None;
920        for f in self.db().faces() {
921            let named = f.families.iter().any(|(n, _)| {
922                let n = n.to_lowercase();
923                n == key || n.starts_with(&prefix)
924            });
925            if !named || other_width(f) {
926                continue;
927            }
928            let style_ok = (f.style != fontdb::Style::Normal) == want_italic;
929            let d = (f.weight.0 as i32 - weight as i32).abs();
930            let better = match best {
931                None => true,
932                Some((_, bd, bs)) => (style_ok && !bs) || (style_ok == bs && d < bd),
933            };
934            if better {
935                best = Some((f.id, d, style_ok));
936            }
937        }
938        let found_d = self
939            .db()
940            .face(found)
941            .map(|f| (f.weight.0 as i32 - weight as i32).abs())
942            .unwrap_or(i32::MAX);
943        let found_style = self
944            .db()
945            .face(found)
946            .is_some_and(|f| (f.style != fontdb::Style::Normal) == want_italic);
947        let found_width = self.db().face(found).is_some_and(other_width);
948        match best {
949            Some((id, d, style_ok)) if found_width || (style_ok && (d < found_d || !found_style)) => Ok(Some(id)),
950            _ => Ok(Some(found)),
951        }
952    }
953
954    /// Whether a face is an italic or oblique design.
955    fn is_italic(&mut self, id: fontdb::ID) -> bool {
956        self.db().face(id).is_some_and(|f| f.style != fontdb::Style::Normal)
957    }
958
959    fn face_data(&mut self, id: fontdb::ID) -> Result<(Arc<Vec<u8>>, u32), String> {
960        if let Some(d) = self.data.get(&id) {
961            return Ok(d.clone());
962        }
963        let d = self
964            .db()
965            .with_face_data(id, |data, index| (Arc::new(data.to_vec()), index))
966            .ok_or("font data unavailable")?;
967        self.data.insert(id, d.clone());
968        Ok(d)
969    }
970
971    fn metrics(&mut self, id: fontdb::ID) -> Result<FontMetrics, String> {
972        let (data, index) = self.face_data(id)?;
973        let face = rustybuzz::Face::from_slice(&data, index).ok_or("unparseable font")?;
974        Ok(FontMetrics {
975            units_per_em: face.units_per_em() as f32,
976            ascender: face.ascender() as f32,
977            descender: face.descender() as f32,
978        })
979    }
980
981    /// Variation axes of a face: (tag, min, default, max).
982    fn axes(&mut self, id: fontdb::ID) -> Result<Vec<([u8; 4], f32, f32, f32)>, String> {
983        let (data, index) = self.face_data(id)?;
984        let face = rustybuzz::Face::from_slice(&data, index).ok_or("unparseable font")?;
985        Ok(face
986            .variation_axes()
987            .into_iter()
988            .map(|a| (a.tag.to_bytes(), a.min_value, a.def_value, a.max_value))
989            .collect())
990    }
991
992    fn has_glyph(&mut self, id: fontdb::ID, c: char) -> bool {
993        if let Some(&v) = self.covers.get(&(id, c)) {
994            return v;
995        }
996        let v = self
997            .db()
998            .with_face_data(id, |data, index| {
999                rustybuzz::Face::from_slice(data, index).is_some_and(|f| f.glyph_index(c).is_some())
1000            })
1001            .unwrap_or(false);
1002        self.covers.insert((id, c), v);
1003        v
1004    }
1005
1006    /// A face that has `c`: preferred fallback families first, then any.
1007    fn fallback_for(&mut self, c: char) -> Option<fontdb::ID> {
1008        if let Some(v) = self.fallback.get(&c) {
1009            return *v;
1010        }
1011        let mut found = None;
1012        for fam in FALLBACK_FAMILIES {
1013            let q = fontdb::Query {
1014                families: &[fontdb::Family::Name(fam)],
1015                ..Default::default()
1016            };
1017            if let Some(id) = self.db().query(&q)
1018                && self.has_glyph(id, c)
1019            {
1020                found = Some(id);
1021                break;
1022            }
1023        }
1024        if found.is_none() {
1025            let ids: Vec<fontdb::ID> = self.db().faces().map(|f| f.id).collect();
1026            found = ids.into_iter().find(|&id| self.has_glyph(id, c));
1027        }
1028        self.fallback.insert(c, found);
1029        found
1030    }
1031
1032    /// The preferred color emoji face that has `c`.
1033    fn emoji_face(&mut self, c: char) -> Option<fontdb::ID> {
1034        if self.emoji.is_none() {
1035            let mut ids = self.emoji_faces();
1036            // Color emoji are drawn from bitmap strikes. Windows has only
1037            // Segoe UI Emoji (COLR layers) and a server may have none: then
1038            // Noto Color Emoji, what the render service draws with, is
1039            // fetched once.
1040            if !ids.iter().any(|&id| self.has_color_bitmaps(id)) {
1041                for p in crate::fontfetch::fetch_emoji() {
1042                    let _ = self.db().load_font_file(&p);
1043                }
1044                ids = self.emoji_faces();
1045            }
1046            self.emoji = Some(ids);
1047        }
1048        let ids = self.emoji.clone().unwrap_or_default();
1049        ids.into_iter().find(|&id| self.has_glyph(id, c))
1050    }
1051
1052    /// Installed emoji faces, in order of preference.
1053    fn emoji_faces(&mut self) -> Vec<fontdb::ID> {
1054        let mut ids = Vec::new();
1055        for fam in EMOJI_FAMILIES {
1056            let q = fontdb::Query {
1057                families: &[fontdb::Family::Name(fam)],
1058                ..Default::default()
1059            };
1060            if let Some(id) = self.db().query(&q) {
1061                ids.push(id);
1062            }
1063        }
1064        ids
1065    }
1066
1067    /// Whether a face draws (some) glyphs from color bitmaps.
1068    pub fn has_color_bitmaps(&mut self, id: fontdb::ID) -> bool {
1069        if let Some(&c) = self.color.get(&id) {
1070            return c;
1071        }
1072        let c = self.face_data(id).ok().is_some_and(|(data, index)| {
1073            rustybuzz::ttf_parser::Face::parse(&data, index)
1074                .is_ok_and(|f| f.tables().sbix.is_some() || f.tables().cbdt.is_some())
1075        });
1076        self.color.insert(id, c);
1077        c
1078    }
1079
1080    /// The bitmap of a color glyph at the strike nearest `ppem` (pixels per
1081    /// em on screen), or None for glyphs without one.
1082    pub fn glyph_bitmap(&mut self, id: fontdb::ID, glyph: u16, ppem: f64) -> Option<Arc<GlyphBitmap>> {
1083        let (data, index) = self.face_data(id).ok()?;
1084        let face = rustybuzz::ttf_parser::Face::parse(&data, index).ok()?;
1085        let want = ppem.ceil().clamp(1.0, u16::MAX as f64) as u16;
1086        let img = face.glyph_raster_image(rustybuzz::ttf_parser::GlyphId(glyph), want)?;
1087        let key = (id, glyph, img.pixels_per_em);
1088        if let Some(b) = self.bitmaps.get(&key) {
1089            return b;
1090        }
1091        let decoded = decode_glyph_image(&img, face.units_per_em() as f64).map(|(width, height, rgba, place)| {
1092            let mut h = std::collections::hash_map::DefaultHasher::new();
1093            key.hash(&mut h);
1094            Arc::new(GlyphBitmap {
1095                key: h.finish(),
1096                width,
1097                height,
1098                rgba,
1099                place,
1100            })
1101        });
1102        self.bitmaps.insert(key, decoded.clone());
1103        decoded
1104    }
1105
1106    /// Shapes a line in `primary`, setting characters it has no glyph for
1107    /// in a fallback face (split into runs; variations apply to `primary`).
1108    pub fn layout(
1109        &mut self,
1110        primary: fontdb::ID,
1111        text: &str,
1112        size: f64,
1113        features: &[rustybuzz::Feature],
1114        vars: &[rustybuzz::Variation],
1115    ) -> Result<(Vec<LineGlyph>, f64), String> {
1116        if !self.script_fonts.is_empty() {
1117            return self.layout_scripts(primary, text, size, features, vars);
1118        }
1119        // Runs of characters by the face that sets them. Characters shown
1120        // as emoji by default (or asking for it with VS16) are set in a
1121        // color emoji face, as browsers do, even when the font has a plain
1122        // glyph for them.
1123        let mut runs: Vec<(fontdb::ID, usize, usize)> = Vec::new();
1124        let mut chars = text.char_indices().peekable();
1125        while let Some((i, c)) = chars.next() {
1126            let next = chars.peek().map(|&(_, n)| n);
1127            let face = if c.is_whitespace() || c.is_control() {
1128                primary
1129            } else if let Some(e) = emoji_presentation(c, next).then(|| self.emoji_face(c)).flatten() {
1130                e
1131            } else if self.has_glyph(primary, c) {
1132                primary
1133            } else {
1134                self.fallback_for(c).unwrap_or(primary)
1135            };
1136            match runs.last_mut() {
1137                // Joiners, variation selectors, keycaps, skin tones and tag
1138                // characters stay with what they attach to, so the face
1139                // shapes the whole sequence (one glyph for a family or flag).
1140                Some(r) if r.0 == face || attaches(c) => r.2 = i + c.len_utf8(),
1141                _ => runs.push((face, i, i + c.len_utf8())),
1142            }
1143        }
1144        let mut out = Vec::new();
1145        let mut pen = 0.0f64;
1146        for (face, start, end) in runs {
1147            let fv: &[rustybuzz::Variation] = if face == primary { vars } else { &[] };
1148            let shaped = self.shape(face, &text[start..end], features, fv, None, None)?;
1149            let scale = size / self.metrics(face)?.units_per_em as f64;
1150            for g in &shaped.glyphs {
1151                let k = out.len() as u32;
1152                out.push(LineGlyph {
1153                    font: face,
1154                    id: g.id,
1155                    x: pen + g.x as f64 * scale,
1156                    y: g.y as f64 * scale,
1157                    advance: g.advance as f64 * scale,
1158                    cluster: start + g.cluster as usize,
1159                    scale,
1160                    track: k,
1161                    unit: k,
1162                    upright: false,
1163                });
1164            }
1165            pen += shaped.advance as f64 * scale;
1166        }
1167        Ok((out, pen))
1168    }
1169
1170    /// [`Fonts::layout`] for a document that sets scripts: each character in
1171    /// the face its script's row gives (unless the requested font has all of
1172    /// that stretch itself), right-to-left text in visual order, spacing and
1173    /// animation by whole clusters or words.
1174    fn layout_scripts(
1175        &mut self,
1176        primary: fontdb::ID,
1177        text: &str,
1178        size: f64,
1179        features: &[rustybuzz::Feature],
1180        vars: &[rustybuzz::Variation],
1181    ) -> Result<(Vec<LineGlyph>, f64), String> {
1182        let mut out: Vec<LineGlyph> = Vec::new();
1183        let mut pen = 0.0f64;
1184        let (mut track, mut unit) = (0u32, 0u32);
1185        let info = unicode_bidi::BidiInfo::new(text, None);
1186        for para in &info.paragraphs {
1187            let (levels, level_runs) = info.visual_runs(para, para.range.clone());
1188            for level_run in level_runs {
1189                let rtl = levels[level_run.start].is_rtl();
1190                let mut pieces = self.script_pieces(primary, text, level_run.clone())?;
1191                if rtl {
1192                    pieces.reverse();
1193                }
1194                let dir = if rtl {
1195                    rustybuzz::Direction::RightToLeft
1196                } else {
1197                    rustybuzz::Direction::LeftToRight
1198                };
1199                for (face, row, start, end) in pieces {
1200                    let spec = row.map(|r| self.script_fonts[r].clone());
1201                    let fv: &[rustybuzz::Variation] = if face == primary { vars } else { &[] };
1202                    let language = spec.as_ref().and_then(|s| s.language.clone());
1203                    let shaped = self.shape(face, &text[start..end], features, fv, Some(dir), language.as_deref())?;
1204                    let scale = size * spec.as_ref().map_or(1.0, |s| s.scale) / self.metrics(face)?.units_per_em as f64;
1205                    let (spaced, whole) = spec.as_ref().map_or((true, false), |s| (s.tracking, s.whole_words));
1206                    if !out.is_empty() {
1207                        track += 1;
1208                        unit += 1;
1209                    }
1210                    let mut previous: Option<u32> = None;
1211                    for g in &shaped.glyphs {
1212                        // Latin glyphs each move alone; in a stand-in face a
1213                        // cluster (a letter and its marks) moves as one.
1214                        let cluster = start + g.cluster as usize;
1215                        let new_cluster = previous.is_some_and(|p| row.is_none() || p != g.cluster);
1216                        if new_cluster && (spaced || row.is_none()) {
1217                            track += 1;
1218                        }
1219                        if new_cluster {
1220                            let at_space = text[cluster..].chars().next().is_some_and(char::is_whitespace);
1221                            let after_space = out.last().is_some_and(|l: &LineGlyph| {
1222                                text[l.cluster..].chars().next().is_some_and(char::is_whitespace)
1223                            });
1224                            if !whole || at_space || after_space {
1225                                unit += 1;
1226                            }
1227                        }
1228                        previous = Some(g.cluster);
1229                        out.push(LineGlyph {
1230                            font: face,
1231                            id: g.id,
1232                            x: pen + g.x as f64 * scale,
1233                            y: g.y as f64 * scale,
1234                            advance: g.advance as f64 * scale,
1235                            cluster,
1236                            scale,
1237                            track,
1238                            unit,
1239                            upright: row.is_some(),
1240                        });
1241                    }
1242                    pen += shaped.advance as f64 * scale;
1243                }
1244            }
1245        }
1246        // Reading order: a right-to-left line reveals from its right.
1247        if unicode_bidi::get_base_direction(text) == unicode_bidi::Direction::Rtl {
1248            let last = out.iter().map(|g| g.unit).max().unwrap_or(0);
1249            for g in &mut out {
1250                g.unit = last - g.unit;
1251            }
1252        }
1253        Ok((out, pen))
1254    }
1255
1256    /// Stretches of `text[range]` (in logical order) by the face that sets
1257    /// them: (face, script row, start, end).
1258    fn script_pieces(
1259        &mut self,
1260        primary: fontdb::ID,
1261        text: &str,
1262        range: std::ops::Range<usize>,
1263    ) -> Result<Vec<(fontdb::ID, Option<usize>, usize, usize)>, String> {
1264        let chars: Vec<(usize, char)> = text[range.clone()]
1265            .char_indices()
1266            .map(|(i, c)| (i + range.start, c))
1267            .collect();
1268        let mut pieces: Vec<(fontdb::ID, Option<usize>, usize, usize)> = Vec::new();
1269        // The face for the stretch of one script being read, and where it ends.
1270        let mut stretch: Option<(usize, fontdb::ID)> = None;
1271        for (index, &(at, c)) in chars.iter().enumerate() {
1272            let end = at + c.len_utf8();
1273            let next = chars.get(index + 1).map(|&(_, n)| n);
1274            let row = self.script_row(c);
1275            let neutral = matches!(c.script(), Script::Common | Script::Inherited | Script::Unknown);
1276            let (face, face_row) = if let Some(e) = emoji_presentation(c, next).then(|| self.emoji_face(c)).flatten() {
1277                (e, None)
1278            } else if let Some(r) = row {
1279                let face = match stretch {
1280                    Some((until, face)) if index < until => face,
1281                    _ => {
1282                        // The stretch runs to the next letter of another script.
1283                        let until = chars[index..]
1284                            .iter()
1285                            .position(|&(_, n)| {
1286                                self.script_row(n) != Some(r)
1287                                    && !matches!(n.script(), Script::Common | Script::Inherited | Script::Unknown)
1288                            })
1289                            .map_or(chars.len(), |p| index + p);
1290                        // A font that has every letter of it sets it itself.
1291                        let mut own = true;
1292                        for &(_, n) in &chars[index..until] {
1293                            if self.script_row(n) == Some(r) && !self.has_glyph(primary, n) {
1294                                own = false;
1295                                break;
1296                            }
1297                        }
1298                        let face = if own { primary } else { self.script_face(primary, r)? };
1299                        stretch = Some((until, face));
1300                        face
1301                    }
1302                };
1303                // A letter even the stand-in lacks still gets a glyph.
1304                if self.has_glyph(face, c) {
1305                    (face, (face != primary).then_some(r))
1306                } else {
1307                    (self.fallback_for(c).unwrap_or(face), Some(r))
1308                }
1309            } else if neutral {
1310                // Spaces, digits, punctuation and marks stay with what they
1311                // are next to when its face can draw them.
1312                match pieces.last() {
1313                    Some(&(face, r, _, _))
1314                        if c.is_whitespace()
1315                            || c.is_control()
1316                            || attaches(c)
1317                            || c == '\u{200C}'
1318                            || self.has_glyph(face, c) =>
1319                    {
1320                        (face, r)
1321                    }
1322                    _ => {
1323                        let ahead = chars[index + 1..]
1324                            .iter()
1325                            .find(|&&(_, n)| {
1326                                !matches!(n.script(), Script::Common | Script::Inherited | Script::Unknown)
1327                            })
1328                            .and_then(|&(_, n)| self.script_row(n));
1329                        let candidate = match ahead {
1330                            Some(r) => Some((self.script_face(primary, r)?, r)),
1331                            None => None,
1332                        };
1333                        match candidate {
1334                            Some((face, r)) if self.has_glyph(face, c) && !self.has_glyph(primary, c) => {
1335                                (face, Some(r))
1336                            }
1337                            _ if c.is_whitespace() || c.is_control() || self.has_glyph(primary, c) => (primary, None),
1338                            _ => (self.fallback_for(c).unwrap_or(primary), None),
1339                        }
1340                    }
1341                }
1342            } else if self.has_glyph(primary, c) {
1343                (primary, None)
1344            } else {
1345                (self.fallback_for(c).unwrap_or(primary), None)
1346            };
1347            match pieces.last_mut() {
1348                Some(last) if last.0 == face && last.1 == face_row => last.3 = end,
1349                _ => pieces.push((face, face_row, at, end)),
1350            }
1351        }
1352        Ok(pieces)
1353    }
1354
1355    fn shape(
1356        &mut self,
1357        id: fontdb::ID,
1358        text: &str,
1359        features: &[rustybuzz::Feature],
1360        vars: &[rustybuzz::Variation],
1361        direction: Option<rustybuzz::Direction>,
1362        language: Option<&str>,
1363    ) -> Result<Arc<ShapedLine>, String> {
1364        let mut h = std::collections::hash_map::DefaultHasher::new();
1365        id.hash(&mut h);
1366        text.hash(&mut h);
1367        if direction.is_some() || language.is_some() {
1368            format!("{direction:?}{language:?}").hash(&mut h);
1369        }
1370        for f in features {
1371            format!("{f:?}").hash(&mut h);
1372        }
1373        variations_key(vars).hash(&mut h);
1374        let key = h.finish();
1375        if let Some(s) = self.shaped.get(&key) {
1376            return Ok(s);
1377        }
1378        let (data, index) = self.face_data(id)?;
1379        let mut face = rustybuzz::Face::from_slice(&data, index).ok_or("unparseable font")?;
1380        if !vars.is_empty() {
1381            face.set_variations(vars);
1382        }
1383        let mut buf = rustybuzz::UnicodeBuffer::new();
1384        buf.push_str(text);
1385        buf.guess_segment_properties();
1386        if let Some(direction) = direction {
1387            buf.set_direction(direction);
1388        }
1389        if let Some(language) = language.and_then(|l| l.parse().ok()) {
1390            buf.set_language(language);
1391        }
1392        let out = rustybuzz::shape(&face, features, buf);
1393        let mut pos: Vec<(i32, i32, i32)> = out
1394            .glyph_positions()
1395            .iter()
1396            .map(|p| (p.x_advance, p.x_offset, p.y_offset))
1397            .collect();
1398        let kerning = !features
1399            .iter()
1400            .any(|f| f.tag == rustybuzz::ttf_parser::Tag::from_bytes(b"kern") && f.value == 0);
1401        if kerning {
1402            kerx_pairs(&face, out.glyph_infos(), &mut pos);
1403        }
1404        let mut pen = 0.0f32;
1405        let mut glyphs = Vec::with_capacity(out.len());
1406        for (info, &(adv, xo, yo)) in out.glyph_infos().iter().zip(&pos) {
1407            glyphs.push(ShapedGlyph {
1408                id: info.glyph_id as u16,
1409                x: pen + xo as f32,
1410                y: yo as f32,
1411                advance: adv as f32,
1412                cluster: info.cluster,
1413            });
1414            pen += adv as f32;
1415        }
1416        let line = Arc::new(ShapedLine { glyphs, advance: pen });
1417        self.shaped.insert(key, line.clone());
1418        Ok(line)
1419    }
1420
1421    /// Glyph outline in font units, y up.
1422    fn glyph(&mut self, id: fontdb::ID, glyph: u16, vars: &[rustybuzz::Variation]) -> Result<Arc<BezPath>, String> {
1423        let vkey = variations_key(vars);
1424        if let Some(p) = self.glyphs.get(&(id, glyph, vkey)) {
1425            return Ok(p);
1426        }
1427        let (data, index) = self.face_data(id)?;
1428        let mut face = rustybuzz::Face::from_slice(&data, index).ok_or("unparseable font")?;
1429        if !vars.is_empty() {
1430            face.set_variations(vars);
1431        }
1432        struct B(BezPath);
1433        impl rustybuzz::ttf_parser::OutlineBuilder for B {
1434            fn move_to(&mut self, x: f32, y: f32) {
1435                self.0.move_to((x as f64, y as f64));
1436            }
1437            fn line_to(&mut self, x: f32, y: f32) {
1438                self.0.line_to((x as f64, y as f64));
1439            }
1440            fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
1441                self.0.quad_to((x1 as f64, y1 as f64), (x as f64, y as f64));
1442            }
1443            fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
1444                self.0
1445                    .curve_to((x1 as f64, y1 as f64), (x2 as f64, y2 as f64), (x as f64, y as f64));
1446            }
1447            fn close(&mut self) {
1448                self.0.close_path();
1449            }
1450        }
1451        let mut b = B(BezPath::new());
1452        face.outline_glyph(rustybuzz::ttf_parser::GlyphId(glyph), &mut b);
1453        let p = Arc::new(b.0);
1454        self.glyphs.insert((id, glyph, vkey), p.clone());
1455        Ok(p)
1456    }
1457}
1458
1459impl Default for Fonts {
1460    fn default() -> Self {
1461        Self::new()
1462    }
1463}
1464
1465struct Reader<'a> {
1466    id: &'a str,
1467    node: &'a Node,
1468    t: f64,
1469}
1470
1471impl Reader<'_> {
1472    fn vecn(&self, name: &str, default: &[f64]) -> ultrafast_graph::Vals {
1473        let mut v = self
1474            .node
1475            .params
1476            .get(name)
1477            .and_then(|p| p.eval_vals(self.t))
1478            .unwrap_or_else(|| ultrafast_graph::Vals::from_slice(default));
1479        // Broadcast a scalar to the expected width; pad or truncate otherwise.
1480        if v.len() == 1 && default.len() > 1 {
1481            v = ultrafast_graph::Vals::filled(v[0], default.len());
1482        }
1483        v.resize(default.len(), 0.0);
1484        v
1485    }
1486    fn num(&self, name: &str, default: f64) -> f64 {
1487        self.vecn(name, &[default])[0]
1488    }
1489    fn text(&self, name: &str) -> Option<&str> {
1490        text(self.node, name)
1491    }
1492    fn bad(&self, param: &str, reason: impl Into<String>) -> GeomError {
1493        GeomError::BadParam {
1494            node: self.id.to_string(),
1495            param: param.to_string(),
1496            reason: reason.into(),
1497        }
1498    }
1499}
1500
1501/// The node's own placement: position, anchor, scale, rotation (degrees).
1502/// Unlike the `transform` op, geometry stays vector until rasterization.
1503fn placement(r: &Reader, default_anchor: [f64; 2]) -> Affine {
1504    let pos = r.vecn("position", &default_anchor);
1505    let anchor = r.vecn("anchor", &default_anchor);
1506    let scale = r.vecn("scale", &[1.0, 1.0]);
1507    let rot = r.num("rotation", 0.0).to_radians();
1508    Affine::translate(pos[0], pos[1])
1509        .mul(Affine::rotate(rot))
1510        .mul(Affine::scale(scale[0], scale[1]))
1511        .mul(Affine::translate(-anchor[0], -anchor[1]))
1512}
1513
1514fn to_kurbo(a: Affine) -> kurbo::Affine {
1515    kurbo::Affine::new(a.0)
1516}
1517
1518fn stroke_style(r: &Reader) -> Result<Option<kurbo::Stroke>, GeomError> {
1519    let width = r.num("stroke", 0.0);
1520    if width <= 0.0 {
1521        return Ok(None);
1522    }
1523    let join = match r.text("join").unwrap_or("miter") {
1524        "miter" => kurbo::Join::Miter,
1525        "round" => kurbo::Join::Round,
1526        "bevel" => kurbo::Join::Bevel,
1527        o => return Err(r.bad("join", format!("unknown join `{o}`"))),
1528    };
1529    let cap = match r.text("cap").unwrap_or("butt") {
1530        "butt" => kurbo::Cap::Butt,
1531        "round" => kurbo::Cap::Round,
1532        "square" => kurbo::Cap::Square,
1533        o => return Err(r.bad("cap", format!("unknown cap `{o}`"))),
1534    };
1535    let mut s = kurbo::Stroke::new(width).with_join(join).with_caps(cap);
1536    if let Some(dash) = r.node.params.get("dash").and_then(|p| p.eval(r.t))
1537        && !dash.is_empty()
1538        && dash.iter().any(|d| *d > 0.0)
1539    {
1540        s = s.with_dashes(r.num("dash_offset", 0.0), dash);
1541    }
1542    Ok(Some(s))
1543}
1544
1545/// Keeps the part of `path` between fractions `a` and `b` of its length.
1546fn trim(path: &BezPath, a: f64, b: f64) -> BezPath {
1547    let (a, b) = (a.clamp(0.0, 1.0), b.clamp(0.0, 1.0));
1548    if a <= 0.0 && b >= 1.0 {
1549        return path.clone();
1550    }
1551    let segs: Vec<kurbo::PathSeg> = path.segments().collect();
1552    let lens: Vec<f64> = segs.iter().map(|s| s.arclen(1e-3)).collect();
1553    let total: f64 = lens.iter().sum();
1554    let (from, to) = (a * total, b * total);
1555    let mut out = BezPath::new();
1556    let mut acc = 0.0;
1557    let mut last_end: Option<Point> = None;
1558    for (seg, len) in segs.iter().zip(&lens) {
1559        let (s0, s1) = (acc, acc + len);
1560        acc = s1;
1561        if s1 <= from || s0 >= to || *len <= 0.0 {
1562            continue;
1563        }
1564        let t0 = if from > s0 {
1565            seg.inv_arclen(from - s0, 1e-4)
1566        } else {
1567            0.0
1568        };
1569        let t1 = if to < s1 { seg.inv_arclen(to - s0, 1e-4) } else { 1.0 };
1570        let sub = seg.subsegment(t0..t1);
1571        if last_end.is_none_or(|p| p.distance(sub.start()) > 1e-6) {
1572            out.move_to(sub.start());
1573        }
1574        match sub {
1575            kurbo::PathSeg::Line(l) => out.line_to(l.p1),
1576            kurbo::PathSeg::Quad(q) => out.quad_to(q.p1, q.p2),
1577            kurbo::PathSeg::Cubic(c) => out.curve_to(c.p1, c.p2, c.p3),
1578        }
1579        last_end = Some(sub.end());
1580    }
1581    out
1582}
1583
1584fn preset_path(r: &Reader, kind: &str, fmt: &Format) -> Result<BezPath, GeomError> {
1585    let c = r.vecn("center", &[fmt.width as f64 / 2.0, fmt.height as f64 / 2.0]);
1586    let radius = r.num("radius", fmt.height as f64 / 4.0);
1587    let mut p = BezPath::new();
1588    match kind {
1589        "polygon" | "star" => {
1590            let sides = r.num("sides", if kind == "star" { 5.0 } else { 6.0 }).round().max(3.0) as usize;
1591            let inner = r.num("inner_radius", radius * 0.45);
1592            let n = if kind == "star" { sides * 2 } else { sides };
1593            for i in 0..n {
1594                let a = -std::f64::consts::FRAC_PI_2 + i as f64 * std::f64::consts::TAU / n as f64;
1595                let rr = if kind == "star" && i % 2 == 1 { inner } else { radius };
1596                let pt = (c[0] + rr * a.cos(), c[1] + rr * a.sin());
1597                if i == 0 {
1598                    p.move_to(pt);
1599                } else {
1600                    p.line_to(pt);
1601                }
1602            }
1603            p.close_path();
1604        }
1605        "circle" => p = kurbo::Circle::new((c[0], c[1]), radius).to_path(0.01),
1606        "line" => {
1607            let pts = r.vecn("points", &[0.0, 0.0, 100.0, 100.0]);
1608            p.move_to((pts[0], pts[1]));
1609            p.line_to((pts[2], pts[3]));
1610        }
1611        "polyline" | "polygon_points" => {
1612            let pts = r
1613                .node
1614                .params
1615                .get("points")
1616                .and_then(|p| p.eval(r.t))
1617                .unwrap_or_default();
1618            for (i, xy) in pts.chunks_exact(2).enumerate() {
1619                if i == 0 {
1620                    p.move_to((xy[0], xy[1]));
1621                } else {
1622                    p.line_to((xy[0], xy[1]));
1623                }
1624            }
1625            if kind == "polygon_points" {
1626                p.close_path();
1627            }
1628        }
1629        o => return Err(r.bad("kind", format!("unknown path kind `{o}`"))),
1630    }
1631    Ok(p)
1632}
1633
1634/// Builds the geometry of a `path` node under `outer` (absorbed transforms).
1635pub fn path(id: &str, node: &Node, fmt: &Format, t: f64, outer: Affine) -> Result<Geometry, GeomError> {
1636    let r = Reader { id, node, t };
1637    let local = match (r.text("d"), r.text("kind")) {
1638        (Some(d), _) => BezPath::from_svg(d).map_err(|e| r.bad("d", format!("invalid SVG path data: {e}")))?,
1639        (None, Some(kind)) => preset_path(&r, kind, fmt)?,
1640        (None, None) => return Err(r.bad("d", "path needs `d` (SVG path data) or `kind`")),
1641    };
1642    // Shape morphing toward `to` (another path's data).
1643    let local = match r.text("to") {
1644        // Several targets (`|`-separated): `morph` runs 0..n through them.
1645        Some(to) => {
1646            // Only the two shapes `morph` is between are parsed.
1647            let n = to.matches('|').count() + 2;
1648            let m = r.num("morph", 0.0).clamp(0.0, (n - 1) as f64);
1649            let k = (m.floor() as usize).min(n - 2);
1650            let f = m - k as f64;
1651            let shape = |i: usize| -> Result<BezPath, GeomError> {
1652                if i == 0 {
1653                    return Ok(local.clone());
1654                }
1655                let part = to.split('|').nth(i - 1).unwrap_or("");
1656                BezPath::from_svg(part.trim()).map_err(|e| r.bad("to", format!("invalid SVG path data: {e}")))
1657            };
1658            if f <= 0.0 {
1659                shape(k)?
1660            } else {
1661                morph(&shape(k)?, &shape(k + 1)?, f)
1662            }
1663        }
1664        None => local,
1665    };
1666    let local = trim(&local, r.num("trim_start", 0.0), r.num("trim_end", 1.0));
1667    let xf = outer.mul(placement(&r, [0.0, 0.0]));
1668    let mut g = Geometry::empty();
1669    match stroke_style(&r)? {
1670        Some(style) => {
1671            // Stroke in local space so width scales with the transform.
1672            let outline = kurbo::stroke(local.iter(), &style, &kurbo::StrokeOpts::default(), TOLERANCE * 0.25);
1673            flatten_closed(&(to_kurbo(xf) * outline), 1.0, 0, &mut g);
1674        }
1675        None => flatten_closed(&(to_kurbo(xf) * local), 1.0, 0, &mut g),
1676    }
1677    Ok(g)
1678}
1679
1680/// The variable-font instance for a `text` node: `weight` drives the
1681/// `wght` axis (so weight animates smoothly), the optical size axis follows
1682/// the type's size in px (as browsers do: display cuts for big type, sturdy
1683/// ones for small), `variations` sets axes by tag (`"wdth=80, opsz=144"`),
1684/// and `axis_<tag>` params set one axis each, animatable (`axis_wdth`,
1685/// `axis_SOFT`). Values are clamped to the font's ranges; static fonts get
1686/// none.
1687fn font_variations(
1688    r: &Reader,
1689    fonts: &mut Fonts,
1690    font: fontdb::ID,
1691    weight: f64,
1692    size: f64,
1693) -> Result<Variations, GeomError> {
1694    let axes = fonts.axes(font).map_err(|e| r.bad("font", e))?;
1695    if axes.is_empty() {
1696        return Ok(Vec::new());
1697    }
1698    let mut set: Vec<([u8; 4], f64)> = Vec::new();
1699    if axes.iter().any(|a| &a.0 == b"wght") {
1700        set.push((*b"wght", weight));
1701    }
1702    if axes.iter().any(|a| &a.0 == b"opsz") {
1703        set.push((*b"opsz", size));
1704    }
1705    let tag_of = |s: &str| -> Option<[u8; 4]> {
1706        let b = s.trim().as_bytes();
1707        (!b.is_empty() && b.len() <= 4).then(|| std::array::from_fn(|i| *b.get(i).unwrap_or(&b' ')))
1708    };
1709    if let Some(spec) = r.text("variations") {
1710        for part in spec.split(',').filter(|p| !p.trim().is_empty()) {
1711            let (tag, value) = part
1712                .split_once('=')
1713                .and_then(|(t, v)| Some((tag_of(t)?, v.trim().parse::<f64>().ok()?)))
1714                .ok_or_else(|| r.bad("variations", format!("`{part}` is not tag=value")))?;
1715            set.push((tag, value));
1716        }
1717    }
1718    for (name, _) in r.node.params.iter().filter(|(k, _)| k.starts_with("axis_")) {
1719        let tag = tag_of(&name[5..]).ok_or_else(|| r.bad(name, "axis tags are 1-4 characters"))?;
1720        let def = axes.iter().find(|a| a.0 == tag).map(|a| a.2 as f64).unwrap_or(0.0);
1721        set.push((tag, r.num(name, def)));
1722    }
1723    let mut out: Variations = Vec::new();
1724    for (tag, value) in set {
1725        let Some(axis) = axes.iter().find(|a| a.0 == tag) else {
1726            continue;
1727        };
1728        let v = (value as f32).clamp(axis.1, axis.3);
1729        out.retain(|x| x.tag.to_bytes() != tag);
1730        out.push(rustybuzz::Variation {
1731            tag: rustybuzz::ttf_parser::Tag::from_bytes(&tag),
1732            value: v,
1733        });
1734    }
1735    Ok(out)
1736}
1737
1738/// Text params evaluated per glyph at its staggered time.
1739const GLYPH_ANIMATORS: [&str; 4] = ["glyph_offset", "glyph_scale", "glyph_rotation", "glyph_opacity"];
1740
1741/// Closed polylines of a path's subpaths.
1742fn polylines(p: &BezPath) -> Vec<Vec<Point>> {
1743    let mut out: Vec<Vec<Point>> = Vec::new();
1744    let mut cur: Vec<Point> = Vec::new();
1745    kurbo::flatten(p.iter(), 0.2, |el| match el {
1746        PathEl::MoveTo(q) => {
1747            if cur.len() > 1 {
1748                out.push(std::mem::take(&mut cur));
1749            }
1750            cur.clear();
1751            cur.push(q);
1752        }
1753        PathEl::LineTo(q) => cur.push(q),
1754        PathEl::ClosePath => {
1755            if cur.len() > 1 {
1756                out.push(std::mem::take(&mut cur));
1757            }
1758        }
1759        _ => {}
1760    });
1761    if cur.len() > 1 {
1762        out.push(cur);
1763    }
1764    out
1765}
1766
1767fn signed_area(c: &[Point]) -> f64 {
1768    (0..c.len())
1769        .map(|i| {
1770            let (a, b) = (c[i], c[(i + 1) % c.len()]);
1771            a.x * b.y - b.x * a.y
1772        })
1773        .sum::<f64>()
1774        / 2.0
1775}
1776
1777/// `n` points evenly spaced along the closed polyline.
1778fn resample(c: &[Point], n: usize) -> Vec<Point> {
1779    let len: Vec<f64> = (0..c.len()).map(|i| c[i].distance(c[(i + 1) % c.len()])).collect();
1780    let total: f64 = len.iter().sum::<f64>().max(1e-9);
1781    let mut out = Vec::with_capacity(n);
1782    let (mut seg, mut acc) = (0usize, 0.0f64);
1783    for k in 0..n {
1784        let target = total * k as f64 / n as f64;
1785        while seg < c.len() - 1 && acc + len[seg] < target {
1786            acc += len[seg];
1787            seg += 1;
1788        }
1789        let u = if len[seg] > 0.0 {
1790            ((target - acc) / len[seg]).clamp(0.0, 1.0)
1791        } else {
1792            0.0
1793        };
1794        out.push(c[seg].lerp(c[(seg + 1) % c.len()], u));
1795    }
1796    out
1797}
1798
1799/// Morphs `a` into `b` at `m` (0..1): contours are paired largest to
1800/// largest (missing partners grow from a point), resampled to matching
1801/// point counts, wound the same way and rotated to line up, then blended.
1802pub fn morph(a: &BezPath, b: &BezPath, m: f64) -> BezPath {
1803    if m <= 0.0 {
1804        return a.clone();
1805    }
1806    if m >= 1.0 {
1807        return b.clone();
1808    }
1809    // Paths built alike (same commands in the same order) interpolate point
1810    // for point: exact, and how Lottie and most editors morph.
1811    let (ea, eb) = (a.elements(), b.elements());
1812    if ea.len() == eb.len()
1813        && ea
1814            .iter()
1815            .zip(eb)
1816            .all(|(x, y)| std::mem::discriminant(x) == std::mem::discriminant(y))
1817    {
1818        let l = |p: Point, q: Point| p.lerp(q, m);
1819        let mut out = BezPath::new();
1820        for (x, y) in ea.iter().zip(eb) {
1821            match (x, y) {
1822                (PathEl::MoveTo(p), PathEl::MoveTo(q)) => out.move_to(l(*p, *q)),
1823                (PathEl::LineTo(p), PathEl::LineTo(q)) => out.line_to(l(*p, *q)),
1824                (PathEl::QuadTo(p1, p2), PathEl::QuadTo(q1, q2)) => out.quad_to(l(*p1, *q1), l(*p2, *q2)),
1825                (PathEl::CurveTo(p1, p2, p3), PathEl::CurveTo(q1, q2, q3)) => {
1826                    out.curve_to(l(*p1, *q1), l(*p2, *q2), l(*p3, *q3))
1827                }
1828                _ => out.close_path(),
1829            }
1830        }
1831        return out;
1832    }
1833    let by_size = |p: &BezPath| {
1834        let mut v = polylines(p);
1835        v.sort_by(|x, y| signed_area(y).abs().partial_cmp(&signed_area(x).abs()).unwrap());
1836        v
1837    };
1838    let (ca, cb) = (by_size(a), by_size(b));
1839    let centroid = |c: &[Point]| {
1840        let n = c.len().max(1) as f64;
1841        Point::new(
1842            c.iter().map(|p| p.x).sum::<f64>() / n,
1843            c.iter().map(|p| p.y).sum::<f64>() / n,
1844        )
1845    };
1846    let mut out = BezPath::new();
1847    for i in 0..ca.len().max(cb.len()) {
1848        let (pa, pb) = match (ca.get(i), cb.get(i)) {
1849            (Some(x), Some(y)) => (x.clone(), y.clone()),
1850            (Some(x), None) => (x.clone(), vec![centroid(x); 3]),
1851            (None, Some(y)) => (vec![centroid(y); 3], y.clone()),
1852            (None, None) => unreachable!(),
1853        };
1854        let perim = |c: &[Point]| (0..c.len()).map(|k| c[k].distance(c[(k + 1) % c.len()])).sum::<f64>();
1855        let n = ((perim(&pa).max(perim(&pb)) / 3.0) as usize).clamp(48, 600);
1856        let ra = resample(&pa, n);
1857        let mut rb = resample(&pb, n);
1858        if signed_area(&ra) * signed_area(&rb) < 0.0 {
1859            rb.reverse();
1860        }
1861        // The rotation of b that best lines up with a.
1862        let step = (n / 120).max(1);
1863        let best = (0..n)
1864            .step_by(step)
1865            .min_by(|&x, &y| {
1866                let cost = |o: usize| {
1867                    (0..n)
1868                        .step_by(step)
1869                        .map(|k| ra[k].distance_squared(rb[(k + o) % n]))
1870                        .sum::<f64>()
1871                };
1872                cost(x).partial_cmp(&cost(y)).unwrap()
1873            })
1874            .unwrap_or(0);
1875        for k in 0..n {
1876            let p = ra[k].lerp(rb[(k + best) % n], m);
1877            if k == 0 {
1878                out.move_to(p);
1879            } else {
1880                out.line_to(p);
1881            }
1882        }
1883        out.close_path();
1884    }
1885    out
1886}
1887
1888/// Glyph outlines of a `text` node, positioned in output space (laid out,
1889/// revealed, stroked), each with its reveal weight.
1890/// Paths of a text node, each with its weight (reveal and glyph opacity)
1891/// and color group, and the colors of the groups (see [`Geometry::groups`]).
1892pub type TextPaths = (Vec<(BezPath, f32, u32)>, Vec<Option<[f32; 4]>>);
1893
1894/// At most this many differently colored layers in one text node; more
1895/// colors share the last.
1896const MAX_GROUPS: usize = 16;
1897
1898/// The style of a run of rich text, resolved to a face.
1899#[derive(Clone)]
1900struct RunStyle {
1901    font: fontdb::ID,
1902    size: f64,
1903    vars: Variations,
1904    /// Synthetic oblique (tangent of the slant) for an italic the face lacks.
1905    slant: f64,
1906    /// Linear straight alpha; None is the node's own color.
1907    color: Option<[f32; 4]>,
1908    highlight: Option<[f32; 4]>,
1909    underline: f64,
1910    underline_color: Option<[f32; 4]>,
1911    rise: f64,
1912    /// How much of the highlight and underline is drawn, from the left.
1913    draw: f64,
1914}
1915
1916/// A style before resolution: what the node, the `em_*` params or a span
1917/// set (unset fields inherit).
1918#[derive(Clone, Default)]
1919struct StyleSpec {
1920    font: Option<String>,
1921    weight: Option<f64>,
1922    italic: Option<bool>,
1923    size: Option<f64>,
1924    color: Option<[f32; 4]>,
1925    highlight: Option<[f32; 4]>,
1926    underline: Option<f64>,
1927    underline_color: Option<[f32; 4]>,
1928    rise: Option<f64>,
1929    draw: Option<f64>,
1930}
1931
1932impl StyleSpec {
1933    fn over(&self, o: &StyleSpec) -> StyleSpec {
1934        StyleSpec {
1935            font: o.font.clone().or_else(|| self.font.clone()),
1936            weight: o.weight.or(self.weight),
1937            italic: o.italic.or(self.italic),
1938            size: o.size.or(self.size),
1939            color: o.color.or(self.color),
1940            highlight: o.highlight.or(self.highlight),
1941            underline: o.underline.or(self.underline),
1942            underline_color: o.underline_color.or(self.underline_color),
1943            rise: o.rise.or(self.rise),
1944            draw: o.draw.or(self.draw),
1945        }
1946    }
1947}
1948
1949/// Attributes a `[text]{...}` span takes.
1950pub const SPAN_ATTRS: &[&str] = &[
1951    "color",
1952    "font",
1953    "weight",
1954    "style",
1955    "size",
1956    "highlight",
1957    "underline",
1958    "underline_color",
1959    "rise",
1960    "draw",
1961];
1962
1963fn linear_color(c: [f64; 4]) -> [f32; 4] {
1964    let l = |x: f64| crate::srgb_to_linear(x) as f32;
1965    [l(c[0]), l(c[1]), l(c[2]), c[3].clamp(0.0, 1.0) as f32]
1966}
1967
1968impl Reader<'_> {
1969    /// A color param as linear straight alpha.
1970    fn color(&self, name: &str) -> Result<Option<[f32; 4]>, GeomError> {
1971        let c = match self.node.params.get(name) {
1972            None => return Ok(None),
1973            Some(Param::Text(s)) => crate::parse_hex(s)
1974                .ok_or_else(|| self.bad(name, format!("`{s}` is not a #rgb, #rrggbb or #rrggbbaa color")))?,
1975            Some(p) => {
1976                let v = p.eval(self.t).unwrap_or_default();
1977                match v.len() {
1978                    3 => [v[0], v[1], v[2], 1.0],
1979                    4 => [v[0], v[1], v[2], v[3]],
1980                    _ => return Err(self.bad(name, "color needs 3 or 4 components")),
1981                }
1982            }
1983        };
1984        Ok(Some(linear_color(c)))
1985    }
1986    fn opt(&self, name: &str) -> Option<f64> {
1987        self.node.params.contains_key(name).then(|| self.num(name, 0.0))
1988    }
1989}
1990
1991/// The emphasis style of `*words*`: the `em_*` params, or italic when
1992/// none is set.
1993fn em_spec(r: &Reader) -> Result<StyleSpec, GeomError> {
1994    let set = r.node.params.keys().any(|k| k.starts_with("em_"));
1995    Ok(StyleSpec {
1996        font: r.text("em_font").map(String::from),
1997        weight: r.opt("em_weight"),
1998        italic: match r.text("em_style") {
1999            Some(s) => Some(s == "italic"),
2000            None if !set => Some(true),
2001            None => None,
2002        },
2003        size: r.opt("em_size"),
2004        color: r.color("em_color")?,
2005        highlight: r.color("em_highlight")?,
2006        underline: r.opt("em_underline"),
2007        underline_color: r.color("em_underline_color")?,
2008        rise: r.opt("em_rise"),
2009        draw: r.opt("em_draw"),
2010    })
2011}
2012
2013fn attr_spec(r: &Reader, a: &std::collections::BTreeMap<String, String>) -> Result<StyleSpec, GeomError> {
2014    if let Some(k) = a.keys().find(|k| !SPAN_ATTRS.contains(&k.as_str())) {
2015        return Err(r.bad(
2016            "text",
2017            format!("unknown span attribute `{k}` ({})", SPAN_ATTRS.join(", ")),
2018        ));
2019    }
2020    let num = |k: &str| -> Result<Option<f64>, GeomError> {
2021        a.get(k)
2022            .map(|v| {
2023                v.parse::<f64>()
2024                    .map_err(|_| r.bad("text", format!("span `{k}={v}` is not a number")))
2025            })
2026            .transpose()
2027    };
2028    let col = |k: &str| -> Result<Option<[f32; 4]>, GeomError> {
2029        a.get(k)
2030            .map(|v| {
2031                crate::parse_hex(v).map(linear_color).ok_or_else(|| {
2032                    r.bad(
2033                        "text",
2034                        format!("span `{k}={v}` is not a #rgb, #rrggbb or #rrggbbaa color"),
2035                    )
2036                })
2037            })
2038            .transpose()
2039    };
2040    Ok(StyleSpec {
2041        font: a.get("font").cloned(),
2042        weight: match a.get("weight").map(String::as_str) {
2043            Some("bold") => Some(700.0),
2044            Some("regular" | "normal") => Some(400.0),
2045            _ => num("weight")?,
2046        },
2047        italic: a.get("style").map(|s| s == "italic"),
2048        size: num("size")?,
2049        color: col("color")?,
2050        highlight: col("highlight")?,
2051        // A bare `underline` is a hairline sized to the type.
2052        underline: match a.get("underline").map(String::as_str) {
2053            Some("true") => Some(-1.0),
2054            _ => num("underline")?,
2055        },
2056        underline_color: col("underline_color")?,
2057        rise: num("rise")?,
2058        draw: num("draw")?,
2059    })
2060}
2061
2062/// A text node's content as styled runs.
2063struct Rich {
2064    plain: String,
2065    /// (start, end, style) byte ranges of `plain`, in order.
2066    runs: Vec<(usize, usize, usize)>,
2067    /// Style 0 is the node's own.
2068    styles: Vec<RunStyle>,
2069    features: Vec<rustybuzz::Feature>,
2070    ascent: f64,
2071    descent: f64,
2072    size: f64,
2073}
2074
2075impl Rich {
2076    /// Glyphs of `plain[a..b]` laid out on one line, with their styles.
2077    fn shape(&self, fonts: &mut Fonts, a: usize, b: usize) -> Result<(Vec<(LineGlyph, usize)>, f64), String> {
2078        let mut out: Vec<(LineGlyph, usize)> = Vec::new();
2079        let mut pen = 0.0;
2080        // Styled spans of a right-to-left line run from its right.
2081        let rtl = fonts.reads_rtl(&self.plain[a..b]);
2082        let order: Vec<&(usize, usize, usize)> = if rtl {
2083            self.runs.iter().rev().collect()
2084        } else {
2085            self.runs.iter().collect()
2086        };
2087        for &&(rs, re, si) in &order {
2088            let (s, e) = (rs.max(a), re.min(b));
2089            if s >= e {
2090                continue;
2091            }
2092            let st = &self.styles[si];
2093            let (glyphs, adv) = fonts.layout(st.font, &self.plain[s..e], st.size, &self.features, &st.vars)?;
2094            let (track, unit) = out.last().map_or((0, 0), |(g, _)| (g.track + 1, g.unit + 1));
2095            for mut g in glyphs {
2096                g.x += pen;
2097                g.cluster += s;
2098                g.track += track;
2099                g.unit += unit;
2100                out.push((g, si));
2101            }
2102            pen += adv;
2103        }
2104        Ok((out, pen))
2105    }
2106}
2107
2108/// The text a node sets, with markup parsed into spans (`markup: false`
2109/// turns parsing off).
2110fn rich_content(r: &Reader) -> (String, Vec<crate::markup::Span>) {
2111    let raw = number_content(r).unwrap_or_else(|| r.text("text").unwrap_or("").to_string());
2112    let on = !matches!(r.node.params.get("markup"), Some(Param::Bool(false)));
2113    let (plain, mut spans) = if on && crate::markup::has_markup(&raw) {
2114        crate::markup::parse(&raw)
2115    } else {
2116        (raw, Vec::new())
2117    };
2118    let Some(p) = r
2119        .node
2120        .params
2121        .get("scramble")
2122        .and_then(|p| p.eval(r.t))
2123        .and_then(|v| v.first().copied())
2124    else {
2125        return (plain, spans);
2126    };
2127    // Scrambling swaps characters in place; spans follow them.
2128    let s = scramble(&plain, p, r);
2129    if !spans.is_empty() && s.len() != plain.len() {
2130        let bytes: Vec<usize> = s.char_indices().map(|(i, _)| i).chain([s.len()]).collect();
2131        let at = |b: usize| bytes[plain[..b].chars().count()];
2132        for sp in &mut spans {
2133            (sp.start, sp.end) = (at(sp.start), at(sp.end));
2134        }
2135    }
2136    (s, spans)
2137}
2138
2139/// What a `text` node shows at `t`, markup removed (for reading checks).
2140pub fn display_text(node: &Node, t: f64) -> String {
2141    rich_content(&Reader { id: "", node, t }).0
2142}
2143
2144/// Resolves a node's styled runs: `r` reads styles, `content` the text
2145/// (counters read it on the frame).
2146fn rich(r: &Reader, content: &Reader, fonts: &mut Fonts, base: &Path) -> Result<Rich, GeomError> {
2147    let (plain, spans) = rich_content(content);
2148    let size = r.num("size", 64.0);
2149    let base_spec = StyleSpec {
2150        font: Some(r.text("font").unwrap_or("").to_string()),
2151        weight: Some(r.num("weight", 400.0)),
2152        italic: Some(r.text("style") == Some("italic")),
2153        size: Some(size),
2154        rise: Some(0.0),
2155        draw: Some(1.0),
2156        ..Default::default()
2157    };
2158    let em = if spans.iter().any(|s| s.style == crate::markup::Style::Em) {
2159        Some(em_spec(r)?)
2160    } else {
2161        None
2162    };
2163    let resolve = |spec: &StyleSpec, fonts: &mut Fonts| -> Result<RunStyle, GeomError> {
2164        let weight = spec.weight.unwrap_or(400.0).clamp(1.0, 1000.0);
2165        let italic = spec.italic.unwrap_or(false);
2166        let name = spec.font.as_deref().unwrap_or("");
2167        let field = if spec.font == base_spec.font { "font" } else { "text" };
2168        let font = fonts
2169            .resolve(name, weight as u16, italic, base)
2170            .map_err(|e| r.bad(field, e))?;
2171        let size = spec.size.unwrap_or(size);
2172        let vars = font_variations(r, fonts, font, weight, size)?;
2173        Ok(RunStyle {
2174            font,
2175            size,
2176            vars,
2177            slant: if italic && !fonts.is_italic(font) { 0.2 } else { 0.0 },
2178            color: spec.color,
2179            highlight: spec.highlight,
2180            underline: match spec.underline {
2181                Some(v) if v < 0.0 => (size * 0.06).max(1.0),
2182                Some(v) => v,
2183                None => 0.0,
2184            },
2185            underline_color: spec.underline_color,
2186            rise: spec.rise.unwrap_or(0.0),
2187            draw: spec.draw.unwrap_or(1.0).clamp(0.0, 1.0),
2188        })
2189    };
2190    let mut styles = vec![resolve(&base_spec, fonts)?];
2191    let mut runs: Vec<(usize, usize, usize)> = Vec::new();
2192    if spans.is_empty() {
2193        runs.push((0, plain.len(), 0));
2194    } else {
2195        let mut cuts: Vec<usize> = spans.iter().flat_map(|s| [s.start, s.end]).collect();
2196        cuts.extend([0, plain.len()]);
2197        cuts.sort_unstable();
2198        cuts.dedup();
2199        let mut keys: Vec<Vec<usize>> = vec![Vec::new()];
2200        for w in cuts.windows(2) {
2201            let (a, b) = (w[0], w[1]);
2202            // Spans covering this piece, outermost first.
2203            let mut cover: Vec<usize> = (0..spans.len())
2204                .filter(|&i| spans[i].start <= a && spans[i].end >= b)
2205                .collect();
2206            cover.sort_by_key(|&i| std::cmp::Reverse(spans[i].end - spans[i].start));
2207            let si = match keys.iter().position(|k| *k == cover) {
2208                Some(si) => si,
2209                None => {
2210                    let mut spec = base_spec.clone();
2211                    for &i in &cover {
2212                        let s = match &spans[i].style {
2213                            crate::markup::Style::Em => em.clone().unwrap_or_default(),
2214                            crate::markup::Style::Attrs(a) => attr_spec(r, a)?,
2215                        };
2216                        spec = spec.over(&s);
2217                    }
2218                    styles.push(resolve(&spec, fonts)?);
2219                    keys.push(cover);
2220                    keys.len() - 1
2221                }
2222            };
2223            match runs.last_mut() {
2224                Some(last) if last.2 == si && last.1 == a => last.1 = b,
2225                _ => runs.push((a, b, si)),
2226            }
2227        }
2228    }
2229    let m = fonts.metrics(styles[0].font).map_err(|e| r.bad("font", e))?;
2230    let scale = size / m.units_per_em as f64;
2231    Ok(Rich {
2232        plain,
2233        runs,
2234        styles,
2235        features: text_features(r),
2236        ascent: m.ascender as f64 * scale,
2237        descent: -m.descender as f64 * scale,
2238        size,
2239    })
2240}
2241
2242pub fn text_paths(
2243    id: &str,
2244    node: &Node,
2245    fmt: &Format,
2246    t: f64,
2247    outer: Affine,
2248    fonts: &mut Fonts,
2249    base: &Path,
2250) -> Result<TextPaths, GeomError> {
2251    layout_text(id, node, fmt, t, outer, fonts, base).map(|(paths, _, _)| paths)
2252}
2253
2254/// A text node's glyph outlines and colors ([`text_paths`]) and its color
2255/// glyphs (emoji bitmaps), under `outer`.
2256pub fn text_layout(
2257    id: &str,
2258    node: &Node,
2259    fmt: &Format,
2260    t: f64,
2261    outer: Affine,
2262    fonts: &mut Fonts,
2263    base: &Path,
2264) -> Result<(TextPaths, Vec<GlyphImage>), GeomError> {
2265    layout_text(id, node, fmt, t, outer, fonts, base).map(|(paths, images, _)| (paths, images))
2266}
2267
2268/// [`text_layout`], and the glyph units laid out (what `reveal` counts).
2269fn layout_text(
2270    id: &str,
2271    node: &Node,
2272    fmt: &Format,
2273    t: f64,
2274    outer: Affine,
2275    fonts: &mut Fonts,
2276    base: &Path,
2277) -> Result<(TextPaths, Vec<GlyphImage>, usize), GeomError> {
2278    let r = Reader { id, node, t };
2279    // Counters change digits, they do not move: read the number on the
2280    // frame (motion-blur samples share it), so digits never smear.
2281    let on_frame = Reader {
2282        id,
2283        node,
2284        t: (t * fmt.fps).round() / fmt.fps,
2285    };
2286    let rich = rich(&r, &on_frame, fonts, base)?;
2287    let plain = rich.plain.as_str();
2288    let size = rich.size;
2289    let line_height = r.num("line_height", 1.2) * size * fonts.script_leading(plain);
2290    let tracking = r.num("tracking", 0.0);
2291    let wrap = r
2292        .node
2293        .params
2294        .get("width")
2295        .and_then(|p| p.eval(t))
2296        .and_then(|v| v.first().copied());
2297
2298    // Break into lines (byte ranges of the plain text): explicit newlines,
2299    // then greedy wrapping at Unicode line-break opportunities when a width
2300    // is set.
2301    let mut lines: Vec<(usize, usize)> = Vec::new();
2302    let mut para_start = 0;
2303    for para in plain.split('\n') {
2304        let p0 = para_start;
2305        para_start += para.len() + 1;
2306        let Some(width) = wrap else {
2307            lines.push((p0, p0 + para.len()));
2308            continue;
2309        };
2310        let mut start = 0;
2311        let mut last_ok: Option<usize> = None;
2312        for (pos, _) in unicode_linebreak::linebreaks(para) {
2313            let end = start + para[start..pos].trim_end().len();
2314            let (glyphs, adv) = rich.shape(fonts, p0 + start, p0 + end).map_err(|e| r.bad("text", e))?;
2315            let w = adv + tracking * glyphs.last().map_or(0, |g| g.0.track + 1) as f64;
2316            if w > width
2317                && let Some(ok) = last_ok
2318            {
2319                lines.push((p0 + start, p0 + start + para[start..ok].trim_end().len()));
2320                start = ok;
2321                last_ok = Some(pos);
2322                continue;
2323            }
2324            last_ok = Some(pos);
2325        }
2326        lines.push((p0 + start, p0 + start + para[start..].trim_end().len()));
2327    }
2328
2329    let align = r.text("align").unwrap_or("left");
2330    let valign = r.text("valign").unwrap_or("top");
2331    let (ascent, descent) = (rich.ascent, rich.descent);
2332    let block_h = ascent + descent + line_height * (lines.len().max(1) - 1) as f64;
2333    let first_baseline = match valign {
2334        "top" => ascent,
2335        "baseline" => 0.0,
2336        "middle" => ascent - block_h / 2.0,
2337        "bottom" => ascent - block_h,
2338        o => return Err(r.bad("valign", format!("unknown valign `{o}`"))),
2339    };
2340
2341    // Per-glyph reveal: glyph i has weight clamp((reveal - i) / softness).
2342    let total_glyphs: f64 = 1e9;
2343    let reveal = r.num("reveal", total_glyphs);
2344    let softness = r.num("reveal_softness", 1.0).max(1e-3);
2345    let reveal_offset = r.vecn("reveal_offset", &[0.0, 0.0]);
2346
2347    let xf = outer.mul(placement(&r, [0.0, 0.0]));
2348    let style = stroke_style(&r)?;
2349    // Output pixels per layout pixel: color glyphs pick their bitmap strike
2350    // by the size they appear at.
2351    let screen_scale = (xf.0[0] * xf.0[3] - xf.0[1] * xf.0[2]).abs().sqrt().max(1e-6);
2352    let mut images: Vec<GlyphImage> = Vec::new();
2353
2354    // Per-glyph animators: each glyph evaluates the glyph_* params at its
2355    // own time, t - stagger * (its place in stagger_order).
2356    let animated = GLYPH_ANIMATORS.iter().any(|p| r.node.params.contains_key(*p));
2357    let stagger = r.num("stagger", 0.0);
2358    let order_mode = r.text("stagger_order").unwrap_or("forward");
2359    let total = if animated {
2360        let mut n = 0;
2361        for &(a, b) in &lines {
2362            let shaped = rich.shape(fonts, a, b).map_err(|e| r.bad("text", e))?.0;
2363            n += shaped.iter().map(|g| g.0.unit as usize + 1).max().unwrap_or(0);
2364        }
2365        n
2366    } else {
2367        0
2368    };
2369    let order = |g: usize| -> f64 {
2370        match order_mode {
2371            "reverse" => (total.saturating_sub(1) - g.min(total.saturating_sub(1))) as f64,
2372            "center" => (g as f64 - (total as f64 - 1.0) / 2.0).abs(),
2373            "random" => {
2374                let mut x = (g as u32 ^ 0x9E37_79B9).wrapping_mul(0x85EB_CA6B);
2375                x ^= x >> 13;
2376                x = x.wrapping_mul(0xC2B2_AE35);
2377                x ^= x >> 16;
2378                (x as f64 / u32::MAX as f64 * total as f64).floor()
2379            }
2380            _ => g as f64,
2381        }
2382    };
2383    let at = |name: &str, tk: f64, default: &[f64]| -> Vec<f64> {
2384        let mut v = r
2385            .node
2386            .params
2387            .get(name)
2388            .and_then(|p| p.eval(tk))
2389            .unwrap_or_else(|| default.to_vec());
2390        if v.len() == 1 && default.len() > 1 {
2391            v = vec![v[0]; default.len()];
2392        }
2393        v.resize(default.len(), 0.0);
2394        v
2395    };
2396
2397    // Text on a path: each glyph's center rides the path (its baseline on
2398    // the path for valign baseline), turned to the path's direction.
2399    let on_path = match r.text("on_path") {
2400        Some(d) => Some(ArcPath::new(
2401            &BezPath::from_svg(d).map_err(|e| r.bad("on_path", format!("invalid SVG path data: {e}")))?,
2402        )),
2403        None => None,
2404    };
2405    let path_offset = r.num("path_offset", 0.0);
2406
2407    // Lay out every line first: marks (highlights, underlines) sweep
2408    // across lines in reading order.
2409    let mut laid: Vec<(Vec<(LineGlyph, usize)>, f64, f64)> = Vec::with_capacity(lines.len());
2410    for (li, &(la, lb)) in lines.iter().enumerate() {
2411        let (glyphs, adv) = rich.shape(fonts, la, lb).map_err(|e| r.bad("text", e))?;
2412        let width = adv + tracking * glyphs.last().map_or(0, |g| g.0.track) as f64;
2413        let x0 = match (align, &on_path) {
2414            ("left", None) => 0.0,
2415            ("center", None) => -width / 2.0,
2416            ("right", None) => -width,
2417            // Along a path, alignment is to the path's start, middle or end.
2418            ("left", Some(_)) => 0.0,
2419            ("center", Some(p)) => (p.length - width) / 2.0,
2420            ("right", Some(p)) => p.length - width,
2421            (o, _) => return Err(r.bad("align", format!("unknown align `{o}`"))),
2422        } + if on_path.is_some() { path_offset } else { 0.0 };
2423        laid.push((glyphs, x0, first_baseline + li as f64 * line_height));
2424    }
2425
2426    // Marks: runs of consecutive glyphs whose style highlights or
2427    // underlines, as (style, x from, x to, baseline).
2428    let mut marks: Vec<(usize, f64, f64, f64)> = Vec::new();
2429    if on_path.is_none() {
2430        for (glyphs, x0, baseline) in &laid {
2431            let mut prev: Option<usize> = None;
2432            for (gl, si) in glyphs {
2433                let st = &rich.styles[*si];
2434                if st.highlight.is_none() && st.underline <= 0.0 {
2435                    prev = None;
2436                    continue;
2437                }
2438                let gx = x0 + gl.x + tracking * gl.track as f64;
2439                match marks.last_mut() {
2440                    Some(m) if prev == Some(*si) => m.2 = gx + gl.advance,
2441                    _ => marks.push((*si, gx, gx + gl.advance, *baseline)),
2442                }
2443                prev = Some(*si);
2444            }
2445        }
2446    }
2447    // `draw` is the share of a style's marks drawn, as one stroke.
2448    let mut length: HashMap<usize, (f64, f64)> = HashMap::new();
2449    for &(si, xa, xb, _) in &marks {
2450        length.entry(si).or_default().0 += xb - xa;
2451    }
2452
2453    // Highlights go behind the type; glyphs and underlines in front.
2454    let mut back: Vec<(BezPath, [f32; 4])> = Vec::new();
2455    let mut front: Vec<(BezPath, f32, Option<[f32; 4]>)> = Vec::new();
2456    for &(si, xa, xb, baseline) in &marks {
2457        let st = &rich.styles[si];
2458        let (total, done) = length[&si];
2459        let d = ((st.draw * total - done) / (xb - xa).max(1e-9)).clamp(0.0, 1.0);
2460        length.get_mut(&si).unwrap().1 += xb - xa;
2461        if d <= 0.0 {
2462            continue;
2463        }
2464        let y = baseline - st.rise;
2465        if let Some(c) = st.highlight {
2466            let pad = st.size * 0.12;
2467            let (a, b) = (xa - pad, xb + pad);
2468            let rect =
2469                kurbo::RoundedRect::new(a, y - st.size * 0.8, a + (b - a) * d, y + st.size * 0.22, st.size * 0.1);
2470            back.push((to_kurbo(xf) * kurbo::Shape::to_path(&rect, 0.05), c));
2471        }
2472        if st.underline > 0.0 {
2473            let (th, uy) = (st.underline, y + st.size * 0.13);
2474            let rect = kurbo::RoundedRect::new(xa, uy - th / 2.0, xa + (xb - xa) * d, uy + th / 2.0, th / 2.0);
2475            front.push((
2476                to_kurbo(xf) * kurbo::Shape::to_path(&rect, 0.05),
2477                1.0,
2478                st.underline_color.or(st.color),
2479            ));
2480        }
2481    }
2482
2483    // Glyphs reveal and animate by their unit: the glyph itself in Latin text.
2484    let mut unit_base = 0usize;
2485    for (glyphs, x0, baseline) in &laid {
2486        let (x0, baseline) = (*x0, *baseline);
2487        let units = glyphs.iter().map(|g| g.0.unit as usize + 1).max().unwrap_or(0);
2488        // The span of a unit of several glyphs: it turns about its middle.
2489        let mut spans: HashMap<u32, (f64, f64, u32)> = HashMap::new();
2490        if animated {
2491            for (gl, _) in glyphs {
2492                let x = x0 + gl.x + tracking * gl.track as f64;
2493                let e = spans.entry(gl.unit).or_insert((x, x, 0));
2494                (e.0, e.1, e.2) = (e.0.min(x), e.1.max(x + gl.advance), e.2 + 1);
2495            }
2496        }
2497        for (gl, si) in glyphs {
2498            let st = &rich.styles[*si];
2499            let gi = unit_base + gl.unit as usize;
2500            let w = ((reveal - gi as f64) / softness).clamp(0.0, 1.0);
2501            if w <= 0.0 {
2502                continue;
2503            }
2504            let gv: &[rustybuzz::Variation] = if gl.font == st.font { &st.vars } else { &[] };
2505            let outline = fonts.glyph(gl.font, gl.id, gv).map_err(|e| r.bad("font", e))?;
2506            // Color glyphs (emoji) are drawn from their bitmaps (their
2507            // outlines, if any, are placeholders).
2508            let bitmap = if fonts.has_color_bitmaps(gl.font) {
2509                fonts.glyph_bitmap(gl.font, gl.id, st.size * screen_scale)
2510            } else {
2511                None
2512            };
2513            if bitmap.is_none() && outline.elements().is_empty() {
2514                continue;
2515            }
2516            let scale = gl.scale;
2517            let ox = x0 + gl.x + tracking * gl.track as f64 + reveal_offset[0] * (1.0 - w);
2518            let oy = baseline - gl.y - st.rise + reveal_offset[1] * (1.0 - w);
2519            let (anim, w) = if animated {
2520                let tk = r.t - stagger * order(gi);
2521                let off = at("glyph_offset", tk, &[0.0, 0.0]);
2522                let sc = at("glyph_scale", tk, &[1.0, 1.0]);
2523                let rot = at("glyph_rotation", tk, &[0.0])[0].to_radians();
2524                let op = at("glyph_opacity", tk, &[1.0])[0].clamp(0.0, 1.0);
2525                // About the glyph's own ink center.
2526                let bb = match &bitmap {
2527                    Some(b) => {
2528                        kurbo::Rect::new(b.place[0], b.place[1], b.place[0] + b.place[2], b.place[1] + b.place[3])
2529                    }
2530                    None => outline.bounding_box(),
2531                };
2532                let (cx, cy) = match spans.get(&gl.unit) {
2533                    Some(&(a, b, n)) if n > 1 => ((a + b) / 2.0, baseline - st.rise - st.size * 0.35),
2534                    _ => (ox + (bb.x0 + bb.x1) / 2.0 * scale, oy - (bb.y0 + bb.y1) / 2.0 * scale),
2535                };
2536                let a = Affine::translate(cx + off[0], cy + off[1])
2537                    .mul(Affine::rotate(rot))
2538                    .mul(Affine::scale(sc[0], sc[1]))
2539                    .mul(Affine::translate(-cx, -cy));
2540                (a, w * op)
2541            } else {
2542                (Affine::IDENTITY, w)
2543            };
2544            if w <= 0.0 {
2545                continue;
2546            }
2547            let xf = match &on_path {
2548                Some(p) => {
2549                    let c = x0 + gl.x + tracking * gl.track as f64 + gl.advance / 2.0;
2550                    let ((px, py), angle) = p.at(c);
2551                    xf.mul(Affine::translate(px, py))
2552                        .mul(Affine::rotate(angle))
2553                        .mul(Affine::translate(-c, 0.0))
2554                }
2555                None => xf,
2556            };
2557            let xf = xf.mul(anim);
2558            // Font units are y-up; flip into pixel space (slanted for a
2559            // synthetic italic).
2560            let slant = if gl.upright { 0.0 } else { st.slant };
2561            let local = Affine([scale, 0.0, slant * scale, -scale, 0.0, 0.0]);
2562            if let Some(b) = bitmap {
2563                // The bitmap's unit square onto its place in font units.
2564                let p = b.place;
2565                let m = xf.mul(Affine::translate(ox, oy)).mul(local).mul(Affine([
2566                    p[2],
2567                    0.0,
2568                    0.0,
2569                    -p[3],
2570                    p[0],
2571                    p[1] + p[3],
2572                ]));
2573                images.push(GlyphImage {
2574                    bitmap: b,
2575                    xf: m.0,
2576                    weight: w as f32,
2577                });
2578                continue;
2579            }
2580            match &style {
2581                Some(s) => {
2582                    let unit = kurbo::stroke(
2583                        (to_kurbo(local) * (*outline).clone()).iter(),
2584                        s,
2585                        &kurbo::StrokeOpts::default(),
2586                        TOLERANCE * 0.25,
2587                    );
2588                    let place = xf.mul(Affine::translate(ox, oy));
2589                    front.push((to_kurbo(place) * unit, w as f32, st.color));
2590                }
2591                None => {
2592                    let glyph_xf = xf.mul(Affine::translate(ox, oy)).mul(local);
2593                    front.push((to_kurbo(glyph_xf) * (*outline).clone(), w as f32, st.color));
2594                }
2595            }
2596        }
2597        unit_base += units;
2598    }
2599
2600    // Color groups: every highlight color, then every type color, each
2601    // composited over the ones before.
2602    let mut groups: Vec<Option<[f32; 4]>> = Vec::new();
2603    let group_of = |c: Option<[f32; 4]>, from: usize, groups: &mut Vec<Option<[f32; 4]>>| -> u32 {
2604        match groups[from..].iter().position(|g| *g == c) {
2605            Some(i) => (from + i) as u32,
2606            None if groups.len() < MAX_GROUPS => {
2607                groups.push(c);
2608                (groups.len() - 1) as u32
2609            }
2610            None => (MAX_GROUPS - 1) as u32,
2611        }
2612    };
2613    let mut out = Vec::with_capacity(back.len() + front.len());
2614    for (p, c) in back {
2615        let g = group_of(Some(c), 0, &mut groups);
2616        out.push((p, 1.0, g));
2617    }
2618    let first_front = groups.len();
2619    for (p, w, c) in front {
2620        let g = group_of(c, first_front, &mut groups);
2621        out.push((p, w, g));
2622    }
2623    if groups.len() == 1 && groups[0].is_none() {
2624        groups.clear();
2625    }
2626    Ok(((out, groups), images, unit_base))
2627}
2628
2629/// Decoding text: characters settle into place in a shuffled order as
2630/// `scramble` goes 0 to 1; the rest cycle through `scramble_chars`, a new
2631/// pick every other frame. Spaces and line breaks keep their place.
2632fn scramble(content: &str, progress: f64, r: &Reader) -> String {
2633    let chars: Vec<char> = r
2634        .text("scramble_chars")
2635        .unwrap_or("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#%&*+/<>=?")
2636        .chars()
2637        .collect();
2638    if chars.is_empty() || progress >= 1.0 {
2639        return content.to_string();
2640    }
2641    let hash = |a: u64, b: u64| {
2642        let mut x = a.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ b.wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
2643        x ^= x >> 29;
2644        x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
2645        x ^ (x >> 32)
2646    };
2647    let n = content.chars().filter(|c| !c.is_whitespace()).count().max(1);
2648    let tick = (r.t * 15.0).floor() as u64;
2649    let mut k = 0;
2650    content
2651        .chars()
2652        .enumerate()
2653        .map(|(i, c)| {
2654            if c.is_whitespace() {
2655                return c;
2656            }
2657            k += 1;
2658            // Each character settles at its own point of the progress.
2659            let order = (hash(i as u64, 7) % 10_000) as f64 / 10_000.0 * 0.6 + (k as f64 / n as f64) * 0.4;
2660            if order < progress {
2661                c
2662            } else {
2663                chars[(hash(i as u64, tick) % chars.len() as u64) as usize]
2664            }
2665        })
2666        .collect()
2667}
2668
2669/// With `number` (animatable), the text is that value formatted with
2670/// `decimals`, `thousands` separator, `prefix` and `suffix`, for counters.
2671fn number_content(r: &Reader) -> Option<String> {
2672    let v = r
2673        .node
2674        .params
2675        .get("number")
2676        .and_then(|p| p.eval(r.t))
2677        .and_then(|v| v.first().copied())?;
2678    let decimals = r.num("decimals", 0.0).clamp(0.0, 8.0) as usize;
2679    let s = format!("{:.*}", decimals, v.abs());
2680    let (int, frac) = s
2681        .split_once('.')
2682        .map(|(a, b)| (a, Some(b)))
2683        .unwrap_or((s.as_str(), None));
2684    let sep = r.text("thousands").unwrap_or(",");
2685    let mut grouped = String::new();
2686    for (i, c) in int.chars().enumerate() {
2687        if i > 0 && (int.len() - i) % 3 == 0 {
2688            grouped.push_str(sep);
2689        }
2690        grouped.push(c);
2691    }
2692    let sign = if v < 0.0 && s.chars().any(|c| c.is_ascii_digit() && c != '0') {
2693        "-"
2694    } else {
2695        ""
2696    };
2697    Some(format!(
2698        "{}{sign}{grouped}{}{}",
2699        r.text("prefix").unwrap_or(""),
2700        frac.map(|f| format!(".{f}")).unwrap_or_default(),
2701        r.text("suffix").unwrap_or("")
2702    ))
2703}
2704
2705/// OpenType features: the node's own, plus tabular figures for counters so
2706/// digits do not jitter as they change.
2707fn text_features(r: &Reader) -> Vec<rustybuzz::Feature> {
2708    let mut f: Vec<rustybuzz::Feature> = match r.text("features") {
2709        Some(f) => f.split(',').filter_map(|s| s.trim().parse().ok()).collect(),
2710        None => Vec::new(),
2711    };
2712    if (r.node.params.contains_key("number") || r.node.params.contains_key("scramble"))
2713        && !r.text("features").is_some_and(|s| s.contains("tnum"))
2714        && let Ok(t) = "tnum".parse()
2715    {
2716        f.push(t);
2717    }
2718    f
2719}
2720
2721/// A path measured by arc length, for text that follows it.
2722struct ArcPath {
2723    pts: Vec<(f64, f64)>,
2724    cum: Vec<f64>,
2725    length: f64,
2726    closed: bool,
2727}
2728
2729impl ArcPath {
2730    fn new(p: &BezPath) -> Self {
2731        let mut pts: Vec<(f64, f64)> = Vec::new();
2732        let mut closed = false;
2733        // Text follows the first subpath only.
2734        let mut done = false;
2735        kurbo::flatten(p.iter(), 0.05, |el| match el {
2736            _ if done => {}
2737            kurbo::PathEl::MoveTo(q) => {
2738                if pts.is_empty() {
2739                    pts.push((q.x, q.y));
2740                } else {
2741                    done = true;
2742                }
2743            }
2744            kurbo::PathEl::LineTo(q) => pts.push((q.x, q.y)),
2745            kurbo::PathEl::ClosePath => {
2746                closed = true;
2747                done = true;
2748            }
2749            _ => {}
2750        });
2751        if closed && pts.len() > 1 && pts.first() != pts.last() {
2752            pts.push(pts[0]);
2753        }
2754        if pts.len() < 2 {
2755            pts = vec![(0.0, 0.0), (1.0, 0.0)];
2756        }
2757        let mut cum = vec![0.0];
2758        for w in pts.windows(2) {
2759            let d = ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt();
2760            cum.push(cum.last().unwrap() + d);
2761        }
2762        let length = cum.last().copied().unwrap_or(0.0).max(1e-9);
2763        ArcPath {
2764            pts,
2765            cum,
2766            length,
2767            closed,
2768        }
2769    }
2770
2771    /// Point and direction (radians) at arc length `s`. Closed paths wrap;
2772    /// open ones continue straight past their ends.
2773    fn at(&self, s: f64) -> ((f64, f64), f64) {
2774        let s = if self.closed { s.rem_euclid(self.length) } else { s };
2775        let i = match self.cum.binary_search_by(|c| c.total_cmp(&s)) {
2776            Ok(i) => i.min(self.pts.len() - 2),
2777            Err(i) => i.saturating_sub(1).min(self.pts.len() - 2),
2778        };
2779        let (a, b) = (self.pts[i], self.pts[i + 1]);
2780        let seg = (self.cum[i + 1] - self.cum[i]).max(1e-9);
2781        let u = (s - self.cum[i]) / seg;
2782        let angle = (b.1 - a.1).atan2(b.0 - a.0);
2783        ((a.0 + (b.0 - a.0) * u, a.1 + (b.1 - a.1) * u), angle)
2784    }
2785}
2786
2787/// One glyph of a measured line, in pixels from the baseline origin (before
2788/// alignment and placement).
2789#[derive(Debug, Clone, serde::Serialize)]
2790pub struct GlyphBox {
2791    /// The text this glyph sets (a ligature covers several characters).
2792    pub text: String,
2793    /// Pen position and advance, tracking included.
2794    pub x: f64,
2795    pub advance: f64,
2796    /// Ink box [x0, y0, x1, y1] (y down; None for spaces).
2797    pub ink: Option<[f64; 4]>,
2798}
2799
2800/// Line metrics of a single-line `text` node: glyph boxes, total advance,
2801/// ascent and descent (pixels). For agents laying out type by hand, such as
2802/// one 3D mesh per letter.
2803#[derive(Debug, Clone, serde::Serialize)]
2804pub struct LineMetrics {
2805    pub glyphs: Vec<GlyphBox>,
2806    pub advance: f64,
2807    pub ascent: f64,
2808    pub descent: f64,
2809}
2810
2811pub fn measure(id: &str, node: &Node, t: f64, fonts: &mut Fonts, base: &Path) -> Result<LineMetrics, GeomError> {
2812    let r = Reader { id, node, t };
2813    let rich = rich(&r, &r, fonts, base)?;
2814    let content = rich.plain.as_str();
2815    let tracking = r.num("tracking", 0.0);
2816    let (laid, adv) = rich.shape(fonts, 0, content.len()).map_err(|e| r.bad("text", e))?;
2817    let mut glyphs = Vec::new();
2818    for (gl, si) in laid.iter() {
2819        let st = &rich.styles[*si];
2820        let start = gl.cluster;
2821        let end = laid
2822            .iter()
2823            .map(|g| g.0.cluster)
2824            .filter(|&c| c > start)
2825            .min()
2826            .unwrap_or(content.len());
2827        let x = gl.x + tracking * gl.track as f64;
2828        let gv: &[rustybuzz::Variation] = if gl.font == st.font { &st.vars } else { &[] };
2829        let outline = fonts.glyph(gl.font, gl.id, gv).map_err(|e| r.bad("font", e))?;
2830        let ink = (!outline.elements().is_empty()).then(|| {
2831            let b = outline.bounding_box();
2832            let s = gl.scale;
2833            let y = gl.y + st.rise;
2834            [x + b.x0 * s, -b.y1 * s - y, x + b.x1 * s, -b.y0 * s - y]
2835        });
2836        glyphs.push(GlyphBox {
2837            text: content.get(start..end).unwrap_or("").to_string(),
2838            x,
2839            advance: gl.advance + tracking,
2840            ink,
2841        });
2842    }
2843    Ok(LineMetrics {
2844        advance: adv + tracking * laid.last().map_or(0, |g| g.0.track) as f64,
2845        ascent: rich.ascent,
2846        descent: rich.descent,
2847        glyphs,
2848    })
2849}
2850
2851/// Builds the geometry of a `text` node under `outer`.
2852pub fn text_node(
2853    id: &str,
2854    node: &Node,
2855    fmt: &Format,
2856    t: f64,
2857    outer: Affine,
2858    fonts: &mut Fonts,
2859    base: &Path,
2860) -> Result<Geometry, GeomError> {
2861    let mut g = Geometry::empty();
2862    let ((paths, groups), images, units) = layout_text(id, node, fmt, t, outer, fonts, base)?;
2863    for (path, w, group) in paths {
2864        flatten_closed(&path, w, group, &mut g);
2865    }
2866    g.groups = groups;
2867    g.units = units;
2868    for im in images {
2869        g.push_image(im);
2870    }
2871    Ok(g)
2872}
2873
2874/// The node's own placement affine at `t` (position, anchor, scale,
2875/// rotation), as text and path geometry apply it.
2876pub fn placement_affine(node: &Node, t: f64) -> Affine {
2877    placement(&Reader { id: "", node, t }, [0.0, 0.0])
2878}
2879
2880/// Hash of what a geometry's shape depends on apart from where it is
2881/// placed: everything but `position` and the outer transform. Two
2882/// geometries with equal content keys and the same linear transform differ
2883/// only by a translation.
2884pub fn content_key(node: &Node, t: f64) -> u64 {
2885    let mut n = node.clone();
2886    n.params.remove("position");
2887    geometry_key(&n, t, &Affine::IDENTITY)
2888}
2889
2890impl Geometry {
2891    /// The same geometry moved by (dx, dy).
2892    /// The geometry mapped through the affine `m` (output px to output px):
2893    /// type that turns or scales but keeps its shape.
2894    pub fn transformed(&self, m: [f64; 6]) -> Geometry {
2895        let map = |x: f32, y: f32| {
2896            let (x, y) = (x as f64, y as f64);
2897            ((m[0] * x + m[2] * y + m[4]) as f32, (m[1] * x + m[3] * y + m[5]) as f32)
2898        };
2899        let mut out = Geometry::empty();
2900        out.segments = self.segments.clone();
2901        for s in out.segments.chunks_exact_mut(8) {
2902            let (ax, ay) = map(s[0], s[1]);
2903            let (bx, by) = map(s[2], s[3]);
2904            s[..4].copy_from_slice(&[ax, ay, bx, by]);
2905            out.bounds = [
2906                out.bounds[0].min(ax.min(bx)),
2907                out.bounds[1].min(ay.min(by)),
2908                out.bounds[2].max(ax.max(bx)),
2909                out.bounds[3].max(ay.max(by)),
2910            ];
2911        }
2912        out.groups = self.groups.clone();
2913        out.units = self.units;
2914        for im in &self.images {
2915            let x = im.xf;
2916            let mut im = im.clone();
2917            im.xf = [
2918                m[0] * x[0] + m[2] * x[1],
2919                m[1] * x[0] + m[3] * x[1],
2920                m[0] * x[2] + m[2] * x[3],
2921                m[1] * x[2] + m[3] * x[3],
2922                m[0] * x[4] + m[2] * x[5] + m[4],
2923                m[1] * x[4] + m[3] * x[5] + m[5],
2924            ];
2925            out.push_image(im);
2926        }
2927        out
2928    }
2929
2930    pub fn translated(&self, dx: f64, dy: f64) -> Geometry {
2931        let (dx, dy) = (dx as f32, dy as f32);
2932        let mut segments = self.segments.clone();
2933        for s in segments.chunks_exact_mut(8) {
2934            s[0] += dx;
2935            s[1] += dy;
2936            s[2] += dx;
2937            s[3] += dy;
2938        }
2939        let b = self.bounds;
2940        let images = self
2941            .images
2942            .iter()
2943            .map(|im| {
2944                let mut im = im.clone();
2945                im.xf[4] += dx as f64;
2946                im.xf[5] += dy as f64;
2947                im
2948            })
2949            .collect();
2950        Geometry {
2951            segments,
2952            bounds: [b[0] + dx, b[1] + dy, b[2] + dx, b[3] + dy],
2953            groups: self.groups.clone(),
2954            images,
2955            units: self.units,
2956        }
2957    }
2958}
2959
2960/// Stable hash of everything a geometry depends on, for caching.
2961pub fn geometry_key(node: &Node, t: f64, outer: &Affine) -> u64 {
2962    let mut h = std::collections::hash_map::DefaultHasher::new();
2963    node.op.hash(&mut h);
2964    for (k, p) in &node.params {
2965        k.hash(&mut h);
2966        match p {
2967            Param::Text(s) => s.hash(&mut h),
2968            p => {
2969                for v in p.eval(t).unwrap_or_default() {
2970                    v.to_bits().hash(&mut h);
2971                }
2972            }
2973        }
2974    }
2975    for v in outer.0 {
2976        v.to_bits().hash(&mut h);
2977    }
2978    // Scrambling text changes characters on its own clock until it is done.
2979    if node
2980        .params
2981        .get("scramble")
2982        .and_then(|p| p.eval(t))
2983        .is_some_and(|v| v.first().is_some_and(|&p| p < 1.0))
2984    {
2985        ((t * 15.0).floor() as i64).hash(&mut h);
2986    }
2987    // Staggered glyph animators read their params at shifted times, so the
2988    // geometry can change while the values at `t` hold still.
2989    let staggered = node
2990        .params
2991        .get("stagger")
2992        .and_then(|p| p.eval(t))
2993        .is_some_and(|v| v.first() != Some(&0.0));
2994    if staggered
2995        && GLYPH_ANIMATORS
2996            .iter()
2997            .any(|p| node.params.get(*p).is_some_and(Param::is_animated))
2998    {
2999        t.to_bits().hash(&mut h);
3000    }
3001    h.finish()
3002}
3003
3004#[cfg(test)]
3005mod tests {
3006    use super::*;
3007
3008    fn node(json: &str) -> Node {
3009        serde_json::from_str(json).unwrap()
3010    }
3011
3012    #[test]
3013    fn square_flattens_to_four_segments() {
3014        let n = node(r#"{"op":"path","params":{"d":"M10 10 H 20 V 20 H 10 Z"}}"#);
3015        let fmt = Format {
3016            width: 64,
3017            height: 64,
3018            fps: 30.0,
3019            duration: 1.0,
3020            motion_blur: None,
3021        };
3022        let g = path("p", &n, &fmt, 0.0, Affine::IDENTITY).unwrap();
3023        assert_eq!(g.count(), 4);
3024        assert_eq!(g.bounds, [10.0, 10.0, 20.0, 20.0]);
3025    }
3026
3027    #[test]
3028    fn trim_halves_length() {
3029        let p = BezPath::from_svg("M0 0 L100 0").unwrap();
3030        let t = trim(&p, 0.25, 0.75);
3031        let segs: Vec<_> = t.segments().collect();
3032        assert_eq!(segs.len(), 1);
3033        assert!((segs[0].start().x - 25.0).abs() < 1e-6 && (segs[0].end().x - 75.0).abs() < 1e-6);
3034    }
3035
3036    #[test]
3037    fn text_shapes_and_lays_out() {
3038        let n = node(r#"{"op":"text","params":{"text":"Hi there","size":40,"position":[10,10]}}"#);
3039        let fmt = Format {
3040            width: 400,
3041            height: 100,
3042            fps: 30.0,
3043            duration: 1.0,
3044            motion_blur: None,
3045        };
3046        let mut fonts = Fonts::new();
3047        let g = text_node("t", &n, &fmt, 0.0, Affine::IDENTITY, &mut fonts, Path::new(".")).unwrap();
3048        assert!(g.count() > 20, "{}", g.count());
3049        // Every letter and the space: what `reveal` counts.
3050        assert_eq!(g.units, 8);
3051        assert!(
3052            g.bounds[0] >= 10.0 && g.bounds[1] >= 10.0 && g.bounds[2] < 400.0,
3053            "{:?}",
3054            g.bounds
3055        );
3056    }
3057}
3058
3059#[cfg(test)]
3060mod emoji_tests {
3061    use super::*;
3062
3063    #[test]
3064    fn color_emoji_have_bitmaps() {
3065        let mut f = Fonts::new();
3066        let Some(face) = f.emoji_face('\u{1F525}') else {
3067            eprintln!("no color emoji face installed");
3068            return;
3069        };
3070        if !f.has_color_bitmaps(face) {
3071            // Windows' Segoe UI Emoji draws color with COLR layers, not
3072            // bitmaps: its emoji come out as plain outlines for now.
3073            eprintln!("the installed emoji face has no color bitmaps");
3074            return;
3075        }
3076        let (data, index) = f.face_data(face).unwrap();
3077        let tf = rustybuzz::ttf_parser::Face::parse(&data, index).unwrap();
3078        let gid = tf.glyph_index('\u{1F525}').unwrap();
3079        eprintln!(
3080            "face {:?} glyph {:?} tables sbix {} cbdt {}",
3081            f.db().face(face).map(|x| x.families.clone()),
3082            gid,
3083            tf.tables().sbix.is_some(),
3084            tf.tables().cbdt.is_some()
3085        );
3086        let raw = tf.glyph_raster_image(gid, 80);
3087        eprintln!(
3088            "raw: {:?}",
3089            raw.map(|r| (r.x, r.y, r.width, r.height, r.pixels_per_em, r.format))
3090        );
3091        let b = f.glyph_bitmap(face, gid.0, 80.0);
3092        eprintln!("bitmap: {:?}", b.as_ref().map(|b| (b.width, b.height, b.place)));
3093        assert!(b.is_some());
3094    }
3095}