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