Skip to main content

alpha2_text/
animated.rs

1//! Per-cluster animation states (motion and color) for text animators.
2//!
3//! [`TextRasterizer::layout`] reports where each cluster lies so a caller can compute states;
4//! [`TextRasterizer::rasterize_animated`] draws with them. Tracking re-aligns a line but never
5//! re-wraps it.
6//!
7//! Outlines are transformed before rasterizing, so scaled or rotated glyphs stay sharp. Each
8//! cluster is drawn into its own tile and tiles combine by maximum coverage, taking color from the
9//! winning cluster; strokes work the same way. Color glyphs are drawn upright and resampled
10//! bilinearly in fixed point. Integer and `libm` arithmetic keep native and wasm output identical.
11
12use super::{
13    BoxExtent, Drawing, DrawingKey, Faces, HashMap, HostTexture, HostTexturePixels, Layout,
14    PixelBox, PixelLook, Premultiplication, RasterColorSpace, RequestLook, TextFill,
15    TextRasterError, TextRasterRequest, TextRasterResult, TextRasterizer, TextStroke, TextTexture,
16    decoration_extents, dilate, disc_extent, drawing_key, gradient, normalize_mapped, over, paint,
17    point, raster_bytes_per_pixel, raster_pixels, stroke_radius, validate_request,
18};
19use std::ops::Range;
20use std::sync::Arc;
21use unicode_segmentation::UnicodeSegmentation;
22
23/// Cluster and line positions, matching [`TextRasterizer::rasterize`].
24#[derive(Clone, Debug, PartialEq)]
25pub struct TextLayout {
26    /// Clusters (the unit of letter spacing) in logical order.
27    pub clusters: Vec<ClusterInfo>,
28    /// Lines, top to bottom.
29    pub lines: Vec<LineInfo>,
30    /// Font size in pixels.
31    pub font_size: f32,
32}
33
34/// One cluster of a [`TextLayout`].
35#[derive(Clone, Debug, PartialEq)]
36pub struct ClusterInfo {
37    /// Byte range in the request's text.
38    pub bytes: Range<usize>,
39    /// Line index.
40    pub line: u32,
41    /// Index of its UAX #29 word, counting only words with a letter or digit; `None` for spaces
42    /// and punctuation between words.
43    pub word: Option<u32>,
44    /// Whether it holds only white space.
45    pub is_space: bool,
46    /// Start of its advance in pixels from the layout box's left edge.
47    pub x: f32,
48    /// Advance in pixels; zero for a space hanging at a line end.
49    pub advance: f32,
50    /// Line baseline in pixels from the layout box's top.
51    pub baseline: f32,
52    /// Font size in pixels: its span's, else the request's.
53    pub font_size: f32,
54    /// The bounds of what it draws, strokes and a rim pixel included, when
55    /// [`TextRasterizer::layout_with_ink`] reports it; `None` for a cluster that draws nothing
56    /// and from [`TextRasterizer::layout`].
57    pub ink: Option<[f32; 4]>,
58    /// Whether it is the ellipsis a [`crate::TextClamp`] ends a cut line with. Its byte range
59    /// is empty, at the cut, and it is in no word.
60    pub ellipsis: bool,
61}
62
63/// One line of a [`TextLayout`].
64#[derive(Clone, Debug, PartialEq)]
65pub struct LineInfo {
66    /// Cluster indices, in logical order.
67    pub clusters: Range<usize>,
68    /// Start in pixels from the layout box's left edge.
69    pub left: f32,
70    /// Advance excluding trailing spaces.
71    pub width: f32,
72    /// Baseline in pixels from the layout box's top.
73    pub baseline: f32,
74    /// Its largest size in pixels, at least the request's.
75    pub size: f32,
76    /// Its line box's top in pixels from the layout box's top; the box is the request's line
77    /// height times `size` tall.
78    pub box_top: f32,
79}
80
81/// A color change `base * keep + add` in premultiplied linear light. Mixing toward a target by
82/// `w` is `keep = 1 - w`, `add = w * target`; mixes compose.
83#[derive(Copy, Clone, Debug, PartialEq)]
84pub struct ColorMix {
85    /// Factor on the base color, in `[0, 1]`.
86    pub keep: f32,
87    /// Premultiplied linear-light RGBA in `[0, 1]`.
88    pub add: [f32; 4],
89}
90
91/// Largest scale of a [`ClusterState`] on either axis.
92pub const MAX_CLUSTER_SCALE: f32 = 10.0;
93
94/// Most reveal edges a [`ClusterState`] takes.
95pub const MAX_REVEAL_EDGES: usize = 8;
96
97/// A straight edge that shows a cluster's unit (its group's box, outset by the text's strokes) up
98/// to it, as a linear wipe. In the unit's own frame, before its transform, the edge's centre lies
99/// at `a - w / 2 + progress (b - a + w)` along `direction`, `[a, b]` the box's extent along it and
100/// `w` the feather, at least a pixel; a point at `s` keeps `clamp((e - s) / w + 0.5, 0, 1)` of
101/// itself. Progress 0 hides the unit and 1 shows it whole, exactly.
102#[derive(Copy, Clone, Debug, PartialEq)]
103pub struct RevealEdge {
104    /// The unit vector the edge travels along, +y down.
105    pub direction: [f32; 2],
106    /// How much of the unit shows, in `[0, 1]`.
107    pub progress: f32,
108    /// The edge's softness in pixels, at least 0.
109    pub feather: f32,
110}
111
112impl RevealEdge {
113    fn is_valid(&self) -> bool {
114        let [x, y] = self.direction;
115        x.is_finite()
116            && y.is_finite()
117            && (x != 0.0 || y != 0.0)
118            && (0.0..=1.0).contains(&self.progress)
119            && self.feather.is_finite()
120            && self.feather >= 0.0
121    }
122
123    /// Where its centre lies along its direction across a unit whose box is `unit`; `None` at
124    /// progress 0, which hides the unit.
125    fn centre(&self, unit: [f32; 4]) -> Option<f32> {
126        if self.progress <= 0.0 {
127            return None;
128        }
129        let [u, v] = self.direction;
130        let [left, top, right, bottom] = unit;
131        let corners = [
132            left * u + top * v,
133            right * u + top * v,
134            left * u + bottom * v,
135            right * u + bottom * v,
136        ];
137        let low = corners.iter().copied().fold(f32::INFINITY, f32::min);
138        let high = corners.iter().copied().fold(f32::NEG_INFINITY, f32::max);
139        let width = self.feather.max(1.0);
140        Some(low - width * 0.5 + self.progress * (high - low + width))
141    }
142
143    /// The share of a point at `[x, y]` of a unit whose box is `[left, top, right, bottom]` that
144    /// shows, both in the unit's own frame.
145    fn keep(&self, unit: [f32; 4], [x, y]: [f32; 2]) -> f32 {
146        if self.progress >= 1.0 {
147            return 1.0;
148        }
149        let Some(edge) = self.centre(unit) else {
150            return 0.0;
151        };
152        let [u, v] = self.direction;
153        ((edge - (x * u + y * v)) / self.feather.max(1.0) + 0.5).clamp(0.0, 1.0)
154    }
155}
156
157/// The units whose clusters scale and turn about one pivot, as After Effects' Anchor Point
158/// Grouping.
159#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
160pub enum ClusterGrouping {
161    /// Each cluster about its own pivot.
162    #[default]
163    Character,
164    /// Each word of [`ClusterInfo::word`]; a cluster in no word is its own group.
165    Word,
166    /// Each line.
167    Line,
168    /// The whole text.
169    All,
170}
171
172/// Animation state of one cluster.
173#[derive(Copy, Clone, Debug, PartialEq)]
174pub struct ClusterState {
175    /// Translation in pixels, +y down.
176    pub offset: [f32; 2],
177    /// Scale about its center, in `[0, MAX_CLUSTER_SCALE]`.
178    pub scale: [f32; 2],
179    /// Clockwise rotation about its center, in radians.
180    pub rotation: f32,
181    /// Multiplies fill and stroke coverage, in `[0, 1]`.
182    pub opacity: f32,
183    /// Fill color change; `None` keeps it.
184    pub fill: Option<ColorMix>,
185    /// Stroke color change; `None` keeps them.
186    pub stroke: Option<ColorMix>,
187    /// Extra space after the cluster in pixels, like letter spacing.
188    pub tracking: f32,
189    /// How much its advance widens, in `[0, MAX_CLUSTER_SCALE]`: mapped about its group's pivot,
190    /// the advances of a group push the groups after it along their line, which is re-aligned.
191    pub advance_scale: f32,
192    /// Edges that reveal its unit; their shares multiply. An edge at progress 1 changes nothing.
193    pub reveals: [Option<RevealEdge>; MAX_REVEAL_EDGES],
194}
195
196impl ClusterState {
197    /// No change.
198    pub const IDENTITY: Self = Self {
199        offset: [0.0, 0.0],
200        scale: [1.0, 1.0],
201        rotation: 0.0,
202        opacity: 1.0,
203        fill: None,
204        stroke: None,
205        tracking: 0.0,
206        advance_scale: 1.0,
207        reveals: [None; MAX_REVEAL_EDGES],
208    };
209
210    /// Whether the state changes nothing.
211    #[must_use]
212    pub fn is_identity(&self) -> bool {
213        Self {
214            reveals: Self::IDENTITY.reveals,
215            ..*self
216        } == Self::IDENTITY
217            && !self.reveals()
218    }
219
220    /// Whether an edge cuts its unit: one at progress below 1.
221    fn reveals(&self) -> bool {
222        self.reveals
223            .iter()
224            .flatten()
225            .any(|edge| edge.progress < 1.0)
226    }
227
228    fn is_valid(&self) -> bool {
229        let mix = |mix: &Option<ColorMix>| {
230            mix.is_none_or(|mix| {
231                (0.0..=1.0).contains(&mix.keep)
232                    && mix.add.iter().all(|value| (0.0..=1.0).contains(value))
233            })
234        };
235        self.offset.iter().all(|value| value.is_finite())
236            && self
237                .scale
238                .iter()
239                .all(|value| (0.0..=MAX_CLUSTER_SCALE).contains(value))
240            && self.rotation.is_finite()
241            && (0.0..=1.0).contains(&self.opacity)
242            && self.tracking.is_finite()
243            && (0.0..=MAX_CLUSTER_SCALE).contains(&self.advance_scale)
244            && self.reveals.iter().flatten().all(RevealEdge::is_valid)
245            && mix(&self.fill)
246            && mix(&self.stroke)
247    }
248}
249
250/// An affine map of layout pixels: `[a, b, c, d, e, f]` sends `(x, y)` to
251/// `(a x + c y + e, b x + d y + f)`.
252type Affine = [f32; 6];
253
254pub(super) const IDENTITY_AFFINE: Affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
255
256fn apply(affine: Affine, [x, y]: [f32; 2]) -> [f32; 2] {
257    [
258        affine[0] * x + affine[2] * y + affine[4],
259        affine[1] * x + affine[3] * y + affine[5],
260    ]
261}
262
263/// Scales and rotates about `pivot`, then translates by `offset`.
264fn cluster_affine(state: &ClusterState, pivot: [f32; 2]) -> Affine {
265    let (sine, cosine) = (libm::sinf(state.rotation), libm::cosf(state.rotation));
266    let [sx, sy] = state.scale;
267    // Rotation clockwise on screen, y down: x' = x cos - y sin, y' = x sin + y cos.
268    let (a, b, c, d) = (cosine * sx, sine * sx, -sine * sy, cosine * sy);
269    let [px, py] = pivot;
270    [
271        a,
272        b,
273        c,
274        d,
275        px - a * px - c * py + state.offset[0],
276        py - b * px - d * py + state.offset[1],
277    ]
278}
279
280fn invert(affine: Affine) -> Option<Affine> {
281    let determinant = affine[0] * affine[3] - affine[1] * affine[2];
282    if determinant.abs() <= f32::MIN_POSITIVE {
283        return None;
284    }
285    let (a, b, c, d) = (
286        affine[3] / determinant,
287        -affine[1] / determinant,
288        -affine[2] / determinant,
289        affine[0] / determinant,
290    );
291    Some([
292        a,
293        b,
294        c,
295        d,
296        -(a * affine[4] + c * affine[5]),
297        -(b * affine[4] + d * affine[5]),
298    ])
299}
300
301/// One cluster's coverage and color glyphs over a pixel rectangle (right and bottom exclusive)
302/// that may extend past the layout box.
303struct Tile {
304    left: i64,
305    top: i64,
306    width: usize,
307    height: usize,
308    coverage: Vec<u8>,
309    /// Premultiplied RGBA8, once a color glyph is drawn into it.
310    colors: Option<Vec<u8>>,
311}
312
313impl Tile {
314    fn empty() -> Self {
315        Self {
316            left: 0,
317            top: 0,
318            width: 0,
319            height: 0,
320            coverage: Vec::new(),
321            colors: None,
322        }
323    }
324
325    fn grow(&mut self, bounds: PixelBox) {
326        if self.width == 0 || self.height == 0 {
327            *self = Self {
328                left: bounds.left,
329                top: bounds.top,
330                width: usize::try_from(bounds.right - bounds.left).unwrap_or(0),
331                height: usize::try_from(bounds.bottom - bounds.top).unwrap_or(0),
332                coverage: Vec::new(),
333                colors: None,
334            };
335            self.coverage = vec![0; self.width * self.height];
336            return;
337        }
338        let right = (self.left + i64::try_from(self.width).unwrap_or(0)).max(bounds.right);
339        let bottom = (self.top + i64::try_from(self.height).unwrap_or(0)).max(bounds.bottom);
340        let (left, top) = (self.left.min(bounds.left), self.top.min(bounds.top));
341        if left == self.left
342            && top == self.top
343            && right == self.left + i64::try_from(self.width).unwrap_or(0)
344            && bottom == self.top + i64::try_from(self.height).unwrap_or(0)
345        {
346            return;
347        }
348        let width = usize::try_from(right - left).unwrap_or(0);
349        let height = usize::try_from(bottom - top).unwrap_or(0);
350        let (dx, dy) = (
351            usize::try_from(self.left - left).unwrap_or(0),
352            usize::try_from(self.top - top).unwrap_or(0),
353        );
354        let mut coverage = vec![0; width * height];
355        let mut colors = self.colors.as_ref().map(|_| vec![0; width * height * 4]);
356        for row in 0..self.height {
357            let to = (row + dy) * width + dx;
358            coverage[to..to + self.width]
359                .copy_from_slice(&self.coverage[row * self.width..(row + 1) * self.width]);
360            if let (Some(colors), Some(held)) = (&mut colors, &self.colors) {
361                colors[to * 4..(to + self.width) * 4]
362                    .copy_from_slice(&held[row * self.width * 4..(row + 1) * self.width * 4]);
363            }
364        }
365        *self = Self {
366            left,
367            top,
368            width,
369            height,
370            coverage,
371            colors,
372        };
373    }
374
375    fn index(&self, x: i64, y: i64) -> Option<usize> {
376        let (x, y) = (
377            usize::try_from(x - self.left).ok()?,
378            usize::try_from(y - self.top).ok()?,
379        );
380        (x < self.width && y < self.height).then_some(y * self.width + x)
381    }
382
383    fn bounds(&self) -> Option<PixelBox> {
384        (self.width > 0 && self.height > 0).then(|| PixelBox {
385            left: self.left,
386            top: self.top,
387            right: self.left + i64::try_from(self.width).unwrap_or(0),
388            bottom: self.top + i64::try_from(self.height).unwrap_or(0),
389        })
390    }
391}
392
393/// Pixel box of a glyph's font-unit `bounds` after placement and `affine`.
394#[allow(clippy::cast_possible_truncation)]
395fn mapped_box(bounds: [f32; 4], origin: [f32; 2], scale: f32, affine: Affine) -> PixelBox {
396    let [x_min, y_min, x_max, y_max] = bounds;
397    let corners = [
398        [x_min, y_min],
399        [x_max, y_min],
400        [x_min, y_max],
401        [x_max, y_max],
402    ]
403    .map(|[x, y]| apply(affine, [origin[0] + x * scale, origin[1] - y * scale]));
404    let (mut left, mut top, mut right, mut bottom) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
405    for [x, y] in corners {
406        (left, top, right, bottom) = (left.min(x), top.min(y), right.max(x), bottom.max(y));
407    }
408    PixelBox {
409        left: left.floor() as i64,
410        top: top.floor() as i64,
411        right: right.ceil() as i64,
412        bottom: bottom.ceil() as i64,
413    }
414}
415
416/// Resamples an upright color glyph into `target` through `affine`, bilinear with 8-bit weights.
417#[allow(
418    clippy::cast_possible_truncation,
419    clippy::cast_possible_wrap,
420    clippy::cast_sign_loss,
421    clippy::cast_precision_loss,
422    clippy::many_single_char_names
423)]
424fn resample(rgba8: &[u8], source: PixelBox, target: PixelBox, inverse: Affine) -> Vec<u8> {
425    let source_width = usize::try_from(source.right - source.left).unwrap_or(0);
426    let source_height = usize::try_from(source.bottom - source.top).unwrap_or(0);
427    let width = usize::try_from(target.right - target.left).unwrap_or(0);
428    let height = usize::try_from(target.bottom - target.top).unwrap_or(0);
429    let mut out = vec![0_u8; width * height * 4];
430    let texel = |x: i64, y: i64| -> [u32; 4] {
431        if x < 0 || y < 0 || x >= source_width as i64 || y >= source_height as i64 {
432            return [0; 4];
433        }
434        let at = (y as usize * source_width + x as usize) * 4;
435        std::array::from_fn(|channel| u32::from(rgba8[at + channel]))
436    };
437    for row in 0..height {
438        for column in 0..width {
439            let [x, y] = apply(
440                inverse,
441                [
442                    (target.left + column as i64) as f32 + 0.5,
443                    (target.top + row as i64) as f32 + 0.5,
444                ],
445            );
446            // Texel space, with texel centres at whole numbers.
447            let (u, v) = (x - source.left as f32 - 0.5, y - source.top as f32 - 0.5);
448            let (u0, v0) = (u.floor(), v.floor());
449            let fx = ((u - u0) * 256.0) as u32;
450            let fy = ((v - v0) * 256.0) as u32;
451            let (u0, v0) = (u0 as i64, v0 as i64);
452            let [a, b, c, d] = [
453                texel(u0, v0),
454                texel(u0 + 1, v0),
455                texel(u0, v0 + 1),
456                texel(u0 + 1, v0 + 1),
457            ];
458            let at = (row * width + column) * 4;
459            for channel in 0..4 {
460                let top = a[channel] * (256 - fx) + b[channel] * fx;
461                let bottom = c[channel] * (256 - fx) + d[channel] * fx;
462                let value = (top * (256 - fy) + bottom * fy + 32_768) >> 16;
463                out[at + channel] = value.min(255) as u8;
464            }
465        }
466    }
467    out
468}
469
470fn mixed(color: [u8; 4], mix: &ColorMix) -> [u8; 4] {
471    let base = gradient::premultiplied_linear(color.map(|value| f32::from(value) / 255.0));
472    gradient::stored_rgba8(std::array::from_fn(|channel| {
473        base[channel] * mix.keep + mix.add[channel]
474    }))
475}
476
477/// Per-pixel color ownership: each pixel takes its colors from the cluster that gives it coverage.
478struct ClusterLook<'a> {
479    looks: Vec<RequestLook<'a>>,
480    cluster_looks: Vec<u16>,
481    states: &'a [ClusterState],
482    /// Owning cluster per pixel, `u32::MAX` for none.
483    fill_owner: Vec<u32>,
484    band_owner: Vec<Vec<u32>>,
485    /// The cluster whose color glyph was drawn last at each pixel.
486    color_owner: Vec<u32>,
487    solid: Vec<Option<[u8; 4]>>,
488    strokes: Vec<Vec<[u8; 4]>>,
489}
490
491impl PixelLook for ClusterLook<'_> {
492    fn fill(&self, index: usize, point: [f32; 2]) -> [u8; 4] {
493        let owner = self.fill_owner[index] as usize;
494        let Some(state) = self.states.get(owner) else {
495            return self.looks[0].fill(index, point);
496        };
497        let look = &self.looks[usize::from(self.cluster_looks[owner])];
498        match (&look.gradient, state.fill) {
499            (Some(gradient), Some(mix)) => {
500                let base = gradient.linear_at(point);
501                gradient::stored_rgba8(std::array::from_fn(|channel| {
502                    base[channel] * mix.keep + mix.add[channel]
503                }))
504            }
505            (None, Some(_)) => self.solid[owner].unwrap_or(look.foreground),
506            (_, None) => look.fill(index, point),
507        }
508    }
509
510    fn band(&self, stroke: usize, index: usize) -> [u8; 4] {
511        let owner = self.band_owner[stroke][index] as usize;
512        self.strokes[stroke]
513            .get(owner)
514            .copied()
515            .unwrap_or_else(|| self.looks[0].band(stroke, index))
516    }
517
518    /// Opacity of the owning cluster: fill, else color glyph, else innermost band.
519    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
520    fn fade(&self, index: usize) -> Option<u32> {
521        let owner = [self.fill_owner[index], self.color_owner[index]]
522            .into_iter()
523            .chain(self.band_owner.iter().map(|owners| owners[index]))
524            .find(|&owner| owner != u32::MAX)?;
525        let opacity = (self.states.get(owner as usize)?.opacity * 255.0).round() as u32;
526        (opacity < 255).then_some(opacity)
527    }
528
529    fn color_alpha(&self, index: usize) -> u32 {
530        let owner = self.color_owner[index] as usize;
531        let look = self
532            .cluster_looks
533            .get(owner)
534            .map_or(&self.looks[0], |&look| &self.looks[usize::from(look)]);
535        u32::from(look.foreground[3])
536    }
537}
538
539/// Writes `tile`'s coverage into `plane` where it is larger (ties go to the later cluster) and
540/// records `cluster` as the owner.
541fn place_max(
542    plane: (&mut [u8], &mut [u32], u32),
543    margin: [u32; 2],
544    tile: &Tile,
545    coverage: &[u8],
546    cluster: u32,
547) {
548    let (plane, owners, width) = plane;
549    let height = plane.len() / width.max(1) as usize;
550    for row in 0..tile.height {
551        let y = tile.top + i64::try_from(row).unwrap_or(0) + i64::from(margin[1]);
552        let Ok(y) = usize::try_from(y) else { continue };
553        if y >= height {
554            continue;
555        }
556        for column in 0..tile.width {
557            let value = coverage[row * tile.width + column];
558            if value == 0 {
559                continue;
560            }
561            let x = tile.left + i64::try_from(column).unwrap_or(0) + i64::from(margin[0]);
562            let Ok(x) = usize::try_from(x) else { continue };
563            if x >= width as usize {
564                continue;
565            }
566            let at = y * width as usize + x;
567            if value >= plane[at] {
568                plane[at] = value;
569                owners[at] = cluster;
570            }
571        }
572    }
573}
574
575impl TextRasterizer {
576    /// Lays out `request`'s clusters and lines as [`Self::rasterize`] would.
577    ///
578    /// # Errors
579    /// Returns the same errors as [`Self::rasterize`].
580    pub fn layout(&self, request: &TextRasterRequest) -> Result<TextLayout, TextRasterError> {
581        validate_request(request)?;
582        if self.fonts.is_empty() {
583            return Err(TextRasterError::NoFonts);
584        }
585        let (faces, shaping) = self.prepare(request)?;
586        let layout = Self::lay_out(&faces, &shaping, request)?;
587        Ok(text_layout(&layout, &shaping, request))
588    }
589
590    /// [`Self::layout`] with each cluster's [`ClusterInfo::ink`]: the bounds of its glyphs as
591    /// drawn (outlines, sheared ones included, or color glyphs' placed boxes) grown by its
592    /// strokes' reach and a rim pixel.
593    ///
594    /// # Errors
595    /// Returns the same errors as [`Self::rasterize`].
596    pub fn layout_with_ink(
597        &self,
598        request: &TextRasterRequest,
599    ) -> Result<TextLayout, TextRasterError> {
600        validate_request(request)?;
601        if self.fonts.is_empty() {
602            return Err(TextRasterError::NoFonts);
603        }
604        let (faces, shaping) = self.prepare(request)?;
605        let layout = Self::lay_out(&faces, &shaping, request)?;
606        let mut inks = vec![None; layout.clusters.len()];
607        layout.each_glyph(
608            &faces,
609            &shaping,
610            request,
611            &mut HashMap::new(),
612            |drawing, origin, scale, glyph| {
613                if let Some([x_min, y_min, x_max, y_max]) = drawing.ink_bounds() {
614                    super::include(
615                        &mut inks[glyph.cluster],
616                        [
617                            origin[0] + x_min * scale,
618                            origin[1] - y_max * scale,
619                            origin[0] + x_max * scale,
620                            origin[1] - y_min * scale,
621                        ],
622                    );
623                }
624            },
625        );
626        for (ink, span) in inks.iter_mut().zip(&layout.clusters) {
627            let look = &shaping.looks[usize::from(span.look)];
628            let band = stroke_radius(&look.strokes).map_or(0.0, |radius| radius + 1.0);
629            *ink = ink.map(|bounds| super::grown(bounds, band));
630        }
631        let mut reported = text_layout(&layout, &shaping, request);
632        for (cluster, ink) in reported.clusters.iter_mut().zip(inks) {
633            cluster.ink = ink;
634        }
635        Ok(reported)
636    }
637
638    /// [`Self::rasterize`] with one state per [`Self::layout`] cluster, in logical order. Identity
639    /// states match [`Self::rasterize`] exactly. Results are cached by content version, so give
640    /// each set of states its own version.
641    ///
642    /// # Errors
643    /// Returns [`TextRasterError::InvalidRequest`] when the state count or a value is out of
644    /// range, otherwise what [`Self::rasterize`] returns.
645    pub fn rasterize_animated(
646        &mut self,
647        request: &TextRasterRequest,
648        states: &[ClusterState],
649    ) -> Result<Arc<TextRasterResult>, TextRasterError> {
650        validate_request(request)?;
651        if self.fonts.is_empty() {
652            return Err(TextRasterError::NoFonts);
653        }
654        if !states.iter().all(ClusterState::is_valid) {
655            return Err(TextRasterError::InvalidRequest);
656        }
657        if states.iter().all(ClusterState::is_identity) {
658            let result = self.rasterize(request)?;
659            let clusters = self.layout(request)?.clusters.len();
660            return if states.len() == clusters {
661                Ok(result)
662            } else {
663                Err(TextRasterError::InvalidRequest)
664            };
665        }
666        if let Some(cached) = self.cache.get(request.content_version) {
667            return Ok(cached);
668        }
669        let mut tiles = std::mem::take(&mut self.tiles);
670        let result = self.rasterize_states(request, states, &mut tiles);
671        self.tiles = tiles;
672        let result = Arc::new(result?);
673        self.cache.insert(request.content_version, &result);
674        Ok(result)
675    }
676
677    #[allow(
678        clippy::cast_possible_truncation,
679        clippy::cast_possible_wrap,
680        clippy::cast_precision_loss,
681        clippy::cast_sign_loss,
682        clippy::too_many_lines
683    )]
684    pub(super) fn rasterize_states(
685        &self,
686        request: &TextRasterRequest,
687        states: &[ClusterState],
688        cache: &mut TileCache,
689    ) -> Result<TextRasterResult, TextRasterError> {
690        let (faces, shaping) = self.prepare(request)?;
691        let layout = Self::lay_out(&faces, &shaping, request)?;
692        if states.len() != layout.clusters.len() {
693            return Err(TextRasterError::InvalidRequest);
694        }
695        let (box_width, box_height) = (layout.box_width, layout.box_height);
696        let mut placed = vec![(Vec::<Placed>::new(), [0.0_f32; 6]); states.len()];
697        let mut affines = vec![IDENTITY_AFFINE; states.len()];
698        let mut decorations = paint::LinePaint::default();
699        let mut drawings = HashMap::<DrawingKey, Drawing>::new();
700        let (mut ink_ascent, mut ink_descent) = (layout.ascent, layout.descent);
701        let pushed = Pushed::of(&layout, &shaping, request, states);
702        let outset = shaping
703            .looks
704            .iter()
705            .filter_map(|look| stroke_radius(&look.strokes))
706            .fold(0.0_f32, f32::max);
707        let revealing = request
708            .background
709            .as_ref()
710            .is_some_and(|background| background.extent == BoxExtent::Revealed);
711        let mut drawn_extents = vec![None; states.len()];
712        let mut shown = vec![None; states.len()];
713        for (index, line) in layout.lines.iter().enumerate() {
714            let baseline = layout.baseline(index);
715            let (shifts, offset) = (&pushed.shifts[index], pushed.offsets[index]);
716            let mut extents = HashMap::<usize, (f32, f32)>::new();
717            for (glyph, shift) in line.glyphs.iter().zip(shifts) {
718                let left = glyph.x + shift + offset + pushed.moves[glyph.cluster];
719                let extent = extents.entry(glyph.cluster).or_insert((left, left));
720                *extent = (extent.0.min(left), extent.1.max(left + glyph.advance));
721            }
722            for (&cluster, &extent) in &extents {
723                drawn_extents[cluster] = Some(extent);
724                let size = shaping.looks[usize::from(layout.clusters[cluster].look)].size;
725                shown[cluster] = if revealing {
726                    revealed_span(
727                        &states[cluster],
728                        [
729                            extent.0,
730                            baseline - 0.8 * size,
731                            extent.1,
732                            baseline + 0.2 * size,
733                        ],
734                        outset_box(pushed.units[cluster], outset),
735                    )
736                } else {
737                    Some(extent)
738                };
739            }
740            for (glyph, shift) in line.glyphs.iter().zip(shifts) {
741                let affine = cluster_affine(&states[glyph.cluster], pushed.pivots[glyph.cluster]);
742                affines[glyph.cluster] = affine;
743                let key = drawing_key(&shaping, glyph);
744                let drawing = drawings
745                    .entry(key)
746                    .or_insert_with(|| Drawing::of(&faces, key, request.emoji_policy));
747                let Some(bounds) = drawing.bounds() else {
748                    continue;
749                };
750                let scale = glyph.size / faces.units_per_em(glyph.font);
751                ink_ascent = ink_ascent.max(bounds[3] * scale + glyph.y_offset);
752                ink_descent = ink_descent.max(-(bounds[1] * scale + glyph.y_offset));
753                let slot = &mut placed[glyph.cluster];
754                slot.1 = affine;
755                slot.0.push(Placed {
756                    key,
757                    origin: [
758                        glyph.x + shift + glyph.x_offset + offset + pushed.moves[glyph.cluster],
759                        baseline - glyph.y_offset,
760                    ],
761                    scale,
762                });
763            }
764            decorations.add_line(
765                &faces,
766                &shaping,
767                &layout,
768                index,
769                (|cluster| extents[&cluster], |cluster| shown[cluster]),
770                |cluster| affines[cluster],
771            );
772        }
773        let run_boxes = std::mem::take(&mut decorations.boxes);
774        let cluster_strokes = |cluster: usize| -> &[TextStroke] {
775            &shaping.looks[usize::from(layout.clusters[cluster].look)].strokes
776        };
777        let decorations = decorations
778            .decorations
779            .iter()
780            .map(|decoration| {
781                let line = layout.clusters[decoration.owner].line;
782                let baseline = layout.baseline(line);
783                ink_ascent = ink_ascent.max(baseline - decoration.rect[1]);
784                ink_descent = ink_descent.max(decoration.rect[3] - baseline);
785                let strokes = cluster_strokes(decoration.owner);
786                let drawn = draw_box(decoration.rect, decoration.affine, strokes);
787                (decoration.owner, (Arc::new(drawn), [0, 0]))
788            })
789            .collect::<Vec<_>>();
790        // Tiles depend only on the glyphs, the linear part of the map and the subpixel position,
791        // so they can be cached. Every tile is sized here, before any is drawn.
792        let look_keys = shaping
793            .looks
794            .iter()
795            .map(|look| look_key(request, &look.strokes))
796            .collect::<Vec<_>>();
797        let mut planned = Vec::with_capacity(states.len());
798        for (cluster, (glyphs, affine)) in placed.iter().enumerate() {
799            let Some(first) = glyphs.first() else {
800                planned.push(None);
801                continue;
802            };
803            let [x, y] = apply(*affine, first.origin);
804            let whole = [x.floor(), y.floor()];
805            let local = [
806                affine[0],
807                affine[1],
808                affine[2],
809                affine[3],
810                affine[4] - whole[0],
811                affine[5] - whole[1],
812            ];
813            let (bounds, color) = cluster_box(&drawings, glyphs, local);
814            planned.push(Some(PlannedCluster {
815                key: cluster_key(
816                    look_keys[usize::from(layout.clusters[cluster].look)],
817                    &faces,
818                    glyphs,
819                    local,
820                ),
821                whole: [whole[0] as i64, whole[1] as i64],
822                local,
823                bounds,
824                color,
825            }));
826        }
827        // Same symmetric margin as the static raster, with room for strokes.
828        let (_, padding) = decoration_extents(request);
829        let outline = shaping
830            .looks
831            .iter()
832            .filter_map(|look| stroke_radius(&look.strokes).map(disc_extent))
833            .max()
834            .unwrap_or(0);
835        let band_count = shaping
836            .looks
837            .iter()
838            .map(|look| look.strokes.len())
839            .max()
840            .unwrap_or(0);
841        let infos = (revealing || request.highlight.is_some())
842            .then(|| text_layout(&layout, &shaping, request).clusters);
843        let line_box = |index: usize| {
844            (
845                pushed.offsets[index],
846                pushed.widths[index],
847                layout.line_top(index),
848                layout.line_size(index),
849            )
850        };
851        let line_boxes = match request
852            .background
853            .as_ref()
854            .map(|background| background.extent)
855        {
856            Some(BoxExtent::Block) => layout.block_box().into_iter().collect(),
857            Some(BoxExtent::Revealed) => revealed_boxes(
858                &layout,
859                infos.as_deref().unwrap_or_default(),
860                &drawn_extents,
861                &shown,
862                line_box,
863            ),
864            _ => (0..layout.lines.len())
865                .filter(|&index| layout.lines[index].width > 0.0)
866                .map(line_box)
867                .collect(),
868        };
869        let highlight = request
870            .highlight
871            .as_ref()
872            .map_or_else(Vec::new, |highlight| {
873                super::highlight::boxes(
874                    &layout,
875                    infos.as_deref().unwrap_or_default(),
876                    &drawn_extents,
877                    highlight,
878                )
879            });
880        let (mut overflow_x, mut overflow_y) = (0_i64, 0_i64);
881        for bounds in planned
882            .iter()
883            .flatten()
884            .filter_map(|cluster| cluster.bounds.map(|bounds| bounds.moved(cluster.whole)))
885            .chain(
886                decorations
887                    .iter()
888                    .filter_map(|(_, (drawn, _))| drawn.tile.bounds()),
889            )
890        {
891            overflow_x = overflow_x
892                .max(bounds.left.saturating_neg())
893                .max(bounds.right.saturating_sub(i64::from(box_width)));
894            overflow_y = overflow_y
895                .max(bounds.top.saturating_neg())
896                .max(bounds.bottom.saturating_sub(i64::from(box_height)));
897        }
898        let (mut boxes_x, mut boxes_y) = (0_i64, 0_i64);
899        for [left, top, right, bottom] in line_boxes
900            .iter()
901            .map(|&(left, width, top, height)| [left, top, left + width, top + height])
902            .chain(
903                run_boxes
904                    .iter()
905                    .map(|run| [run.left, run.top, run.right, run.bottom]),
906            )
907            .chain(
908                highlight
909                    .iter()
910                    .map(|&[left, right, top, bottom]| [left, top, right, bottom]),
911            )
912        {
913            boxes_x = boxes_x
914                .max((-left).ceil() as i64)
915                .max((right - layout.width).ceil() as i64);
916            boxes_y = boxes_y
917                .max((-top).ceil() as i64)
918                .max((bottom - layout.height).ceil() as i64);
919        }
920        let margin = |overflow: i64, boxes: i64, padding: u32| -> Result<u32, TextRasterError> {
921            let boxes = u32::try_from(boxes.max(0))
922                .ok()
923                .and_then(|boxes| boxes.checked_add(padding))
924                .ok_or(TextRasterError::TooLarge)?;
925            u32::try_from(overflow)
926                .map_err(|_| TextRasterError::TooLarge)?
927                .checked_add(outline)
928                .map(|margin| margin.max(outline.max(padding)).max(boxes))
929                .ok_or(TextRasterError::TooLarge)
930        };
931        let (margin_x, margin_y) = (
932            margin(overflow_x, boxes_x, padding[0])?,
933            margin(overflow_y, boxes_y, padding[1])?,
934        );
935        let width = margin_x
936            .checked_mul(2)
937            .and_then(|margins| box_width.checked_add(margins))
938            .ok_or(TextRasterError::TooLarge)?;
939        let height = margin_y
940            .checked_mul(2)
941            .and_then(|margins| box_height.checked_add(margins))
942            .ok_or(TextRasterError::TooLarge)?;
943        // Two owner planes of `u32`, and an owner plane per stroke band.
944        let colors = planned.iter().flatten().any(|cluster| cluster.color);
945        let owners = 8 + 4 * band_count as u64;
946        let pixel_count = raster_pixels(
947            width,
948            height,
949            raster_bytes_per_pixel(request, band_count, colors) + owners,
950        )?;
951        if u64::from(width) * u64::from(height) > MAX_ANIMATED_PIXELS {
952            return Err(TextRasterError::TooLarge);
953        }
954        let mut drawing = std::collections::HashSet::new();
955        let mut tile_bytes = 0_u64;
956        for (index, cluster) in planned.iter().enumerate() {
957            let Some(cluster) = cluster else {
958                continue;
959            };
960            let strokes = cluster_strokes(index);
961            let reach = stroke_radius(strokes).map_or(0, disc_extent);
962            if !cache.contains(cluster.key) && drawing.insert(cluster.key) {
963                tile_bytes = tile_bytes.saturating_add(cluster.drawing_bytes(strokes.len(), reach));
964            }
965        }
966        if tile_bytes > MAX_REQUEST_TILE_BYTES {
967            return Err(TextRasterError::TooLarge);
968        }
969        let mut tiles = Vec::with_capacity(states.len());
970        for cluster in &planned {
971            let Some(cluster) = cluster else {
972                tiles.push(None);
973                continue;
974            };
975            let drawn = if let Some(drawn) = cache.get(cluster.key) {
976                drawn
977            } else {
978                let glyphs = &placed[tiles.len()].0;
979                let drawn = Arc::new(draw_cluster(
980                    cluster_strokes(tiles.len()),
981                    &drawings,
982                    glyphs,
983                    cluster.local,
984                ));
985                debug_assert_eq!(
986                    drawn.tile.bounds().map(|bounds| [
987                        bounds.left,
988                        bounds.top,
989                        bounds.right,
990                        bounds.bottom
991                    ]),
992                    cluster.bounds.map(|bounds| [
993                        bounds.left,
994                        bounds.top,
995                        bounds.right,
996                        bounds.bottom
997                    ]),
998                );
999                cache.insert(cluster.key, &drawn);
1000                drawn
1001            };
1002            tiles.push(Some((drawn, cluster.whole)));
1003        }
1004        let margins = [margin_x, margin_y];
1005        let mut coverage = vec![0_u8; pixel_count];
1006        let mut fill_owner = vec![u32::MAX; pixel_count];
1007        let mut color_owner = vec![u32::MAX; pixel_count];
1008        let mut colors: Option<Vec<u8>> = None;
1009        let mut bands = vec![vec![0_u8; pixel_count]; band_count];
1010        let mut band_owner = vec![vec![u32::MAX; pixel_count]; band_count];
1011        let keeps = states
1012            .iter()
1013            .enumerate()
1014            .map(|(cluster, state)| {
1015                Keep::of(
1016                    state,
1017                    affines[cluster],
1018                    outset_box(pushed.units[cluster], outset),
1019                )
1020            })
1021            .collect::<Vec<_>>();
1022        for (index, (drawn, at)) in tiles
1023            .iter()
1024            .enumerate()
1025            .filter_map(|(cluster, tile)| tile.as_ref().map(|tile| (cluster, tile)))
1026            .chain(decorations.iter().map(|(owner, tile)| (*owner, tile)))
1027        {
1028            let keep = &keeps[index];
1029            if matches!(keep, Keep::Nothing) {
1030                continue;
1031            }
1032            let cluster = u32::try_from(index).map_err(|_| TextRasterError::TooLarge)?;
1033            let tile = drawn.tile.moved(*at);
1034            place_max(
1035                (&mut coverage, &mut fill_owner, width),
1036                margins,
1037                &tile,
1038                &keep.applied(&tile, &drawn.tile.coverage, 1),
1039                cluster,
1040            );
1041            if let Some(held) = &drawn.tile.colors {
1042                let held = keep.applied(&tile, held, 4);
1043                let plane = colors.get_or_insert_with(|| vec![0; pixel_count * 4]);
1044                for row in 0..tile.height {
1045                    for column in 0..tile.width {
1046                        let source = &held[(row * tile.width + column) * 4..][..4];
1047                        if source[3] == 0 {
1048                            continue;
1049                        }
1050                        let x = tile.left + column as i64 + i64::from(margin_x);
1051                        let y = tile.top + row as i64 + i64::from(margin_y);
1052                        if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) {
1053                            continue;
1054                        }
1055                        let pixel = y as usize * width as usize + x as usize;
1056                        color_owner[pixel] = cluster;
1057                        let at = pixel * 4;
1058                        let slot = &mut plane[at..at + 4];
1059                        let blended = over(
1060                            std::array::from_fn(|channel| u32::from(source[channel])),
1061                            std::array::from_fn(|channel| u32::from(slot[channel])),
1062                        );
1063                        for (byte, value) in slot.iter_mut().zip(blended) {
1064                            *byte = u8::try_from(value.min(255)).unwrap_or(u8::MAX);
1065                        }
1066                    }
1067                }
1068            }
1069            let padded = drawn.padded.moved(*at);
1070            for ((band, owners), dilated) in bands
1071                .iter_mut()
1072                .zip(band_owner.iter_mut())
1073                .zip(&drawn.bands)
1074            {
1075                place_max(
1076                    (band, owners, width),
1077                    margins,
1078                    &padded,
1079                    &keep.applied(&padded, dilated, 1),
1080                    cluster,
1081                );
1082            }
1083        }
1084        let size = [layout.width, layout.height];
1085        let looks = shaping
1086            .looks
1087            .iter()
1088            .map(|look| RequestLook::painting(&look.fill, &look.strokes, size))
1089            .collect::<Vec<_>>();
1090        let cluster_looks = layout
1091            .clusters
1092            .iter()
1093            .map(|cluster| cluster.look)
1094            .collect::<Vec<_>>();
1095        let solid = states
1096            .iter()
1097            .zip(&cluster_looks)
1098            .map(
1099                |(state, &look)| match &shaping.looks[usize::from(look)].fill {
1100                    TextFill::Solid(color) => state.fill.map(|mix| mixed(*color, &mix)),
1101                    TextFill::Gradient(_) => None,
1102                },
1103            )
1104            .collect();
1105        let strokes = (0..band_count)
1106            .map(|band| {
1107                states
1108                    .iter()
1109                    .zip(&cluster_looks)
1110                    .map(|(state, &look)| {
1111                        shaping.looks[usize::from(look)].strokes.get(band).map_or(
1112                            [0; 4],
1113                            |stroke| {
1114                                state
1115                                    .stroke
1116                                    .map_or(stroke.color, |mix| mixed(stroke.color, &mix))
1117                            },
1118                        )
1119                    })
1120                    .collect()
1121            })
1122            .collect();
1123        let look = ClusterLook {
1124            looks,
1125            cluster_looks,
1126            states,
1127            fill_owner,
1128            band_owner,
1129            color_owner,
1130            solid,
1131            strokes,
1132        };
1133        let (rgba8, background) = super::compose(
1134            request,
1135            &coverage,
1136            colors.as_deref(),
1137            width,
1138            margins,
1139            &line_boxes,
1140            &run_boxes,
1141            &highlight,
1142            &bands,
1143            &look,
1144        );
1145        let texture = HostTexture {
1146            content_version: request.content_version,
1147            width,
1148            height,
1149            premultiplication: Premultiplication::Premultiplied,
1150            color_space: RasterColorSpace::Srgb,
1151        };
1152        Ok(TextRasterResult {
1153            descriptor: TextTexture {
1154                texture: texture.clone(),
1155                layout_x: margin_x as f32,
1156                layout_y: margin_y as f32,
1157                layout_width: layout.width,
1158                layout_height: layout.height,
1159                first_baseline: layout.baseline(0),
1160                ascent: ink_ascent,
1161                descent: ink_descent,
1162                line_count: layout.line_count,
1163            },
1164            pixels: HostTexturePixels { texture, rgba8 },
1165            background,
1166        })
1167    }
1168}
1169
1170/// `unit` grown by `outset` on every side.
1171fn outset_box([left, top, right, bottom]: [f32; 4], outset: f32) -> [f32; 4] {
1172    [left - outset, top - outset, right + outset, bottom + outset]
1173}
1174
1175/// The horizontal span of the part of `rect` (`[left, top, right, bottom]`, a cluster's advance
1176/// by its em box) on the kept side of every reveal edge's centre across `unit`; `None` when the
1177/// cluster is hidden, faded out or scaled to nothing.
1178fn revealed_span(state: &ClusterState, rect: [f32; 4], unit: [f32; 4]) -> Option<(f32, f32)> {
1179    if state.opacity <= 0.0 || state.scale.iter().any(|axis| *axis <= 0.0) {
1180        return None;
1181    }
1182    let [left, top, right, bottom] = rect;
1183    let mut polygon = vec![[left, top], [right, top], [right, bottom], [left, bottom]];
1184    for edge in state.reveals.iter().flatten() {
1185        if edge.progress >= 1.0 {
1186            continue;
1187        }
1188        let centre = edge.centre(unit)?;
1189        let [u, v] = edge.direction;
1190        let side = |[x, y]: [f32; 2]| centre - (x * u + y * v);
1191        let mut clipped = Vec::with_capacity(polygon.len() + 1);
1192        for (index, &point) in polygon.iter().enumerate() {
1193            let next = polygon[(index + 1) % polygon.len()];
1194            let (here, there) = (side(point), side(next));
1195            if here >= 0.0 {
1196                clipped.push(point);
1197            }
1198            if (here >= 0.0) != (there >= 0.0) {
1199                let share = here / (here - there);
1200                clipped.push([
1201                    point[0] + (next[0] - point[0]) * share,
1202                    point[1] + (next[1] - point[1]) * share,
1203                ]);
1204            }
1205        }
1206        polygon = clipped;
1207        if polygon.is_empty() {
1208            return None;
1209        }
1210    }
1211    let low = polygon
1212        .iter()
1213        .map(|point| point[0])
1214        .fold(f32::INFINITY, f32::min);
1215    let high = polygon
1216        .iter()
1217        .map(|point| point[0])
1218        .fold(f32::NEG_INFINITY, f32::max);
1219    (high > low).then_some((low, high))
1220}
1221
1222/// Per line, the box from its first to its last revealed cluster that is not white space: its
1223/// `line_box` when every cluster shows whole, none when nothing shows. `extents` are each
1224/// cluster's drawn advance and its revealed span.
1225fn revealed_boxes(
1226    layout: &Layout,
1227    clusters: &[ClusterInfo],
1228    drawn: &[Option<(f32, f32)>],
1229    shown: &[Option<(f32, f32)>],
1230    line_box: impl Fn(usize) -> (f32, f32, f32, f32),
1231) -> Vec<(f32, f32, f32, f32)> {
1232    let mut boxes = Vec::new();
1233    for (index, line) in layout.lines.iter().enumerate() {
1234        if line.width <= 0.0 {
1235            continue;
1236        }
1237        let mut whole = true;
1238        let (mut first, mut last) = (f32::INFINITY, f32::NEG_INFINITY);
1239        for (cluster, info) in clusters.iter().enumerate() {
1240            if info.line as usize != index {
1241                continue;
1242            }
1243            whole &= drawn[cluster].map(|extent| extent.0.to_bits())
1244                == shown[cluster].map(|extent| extent.0.to_bits())
1245                && drawn[cluster].map(|extent| extent.1.to_bits())
1246                    == shown[cluster].map(|extent| extent.1.to_bits());
1247            if let (Some((left, right)), false) = (shown[cluster], info.is_space) {
1248                first = first.min(left);
1249                last = last.max(right);
1250            }
1251        }
1252        if whole {
1253            boxes.push(line_box(index));
1254        } else if first <= last {
1255            let (_, _, top, height) = line_box(index);
1256            boxes.push((first, last - first, top, height));
1257        }
1258    }
1259    boxes
1260}
1261
1262/// How much of a cluster's tiles its reveal edges keep.
1263enum Keep {
1264    /// All of them: no edge cuts its unit.
1265    Whole,
1266    /// None: an edge at progress 0 hides its unit, or its transform is degenerate.
1267    Nothing,
1268    /// The share each tile pixel's centre keeps, mapped back by `inverse` into the unit's frame,
1269    /// where its box is `unit`.
1270    Part {
1271        inverse: Affine,
1272        unit: [f32; 4],
1273        edges: [Option<RevealEdge>; MAX_REVEAL_EDGES],
1274    },
1275}
1276
1277impl Keep {
1278    fn of(state: &ClusterState, affine: Affine, unit: [f32; 4]) -> Self {
1279        if !state.reveals() {
1280            return Self::Whole;
1281        }
1282        if state
1283            .reveals
1284            .iter()
1285            .flatten()
1286            .any(|edge| edge.progress <= 0.0)
1287        {
1288            return Self::Nothing;
1289        }
1290        let Some(inverse) = invert(affine) else {
1291            return Self::Nothing;
1292        };
1293        Self::Part {
1294            inverse,
1295            unit,
1296            edges: state.reveals,
1297        }
1298    }
1299
1300    /// `values` (`channels` bytes per pixel of `tile`) scaled by the share each pixel keeps.
1301    #[expect(
1302        clippy::cast_possible_truncation,
1303        clippy::cast_sign_loss,
1304        clippy::cast_precision_loss,
1305        reason = "tile coordinates and bytes scaled by a share in [0, 1]"
1306    )]
1307    fn applied<'a>(
1308        &self,
1309        tile: &Tile,
1310        values: &'a [u8],
1311        channels: usize,
1312    ) -> std::borrow::Cow<'a, [u8]> {
1313        let Self::Part {
1314            inverse,
1315            unit,
1316            edges,
1317        } = self
1318        else {
1319            return std::borrow::Cow::Borrowed(values);
1320        };
1321        let mut kept = values.to_vec();
1322        for row in 0..tile.height {
1323            for column in 0..tile.width {
1324                let at = (row * tile.width + column) * channels;
1325                let pixel = &mut kept[at..at + channels];
1326                if pixel.iter().all(|value| *value == 0) {
1327                    continue;
1328                }
1329                let point = apply(
1330                    *inverse,
1331                    [
1332                        (tile.left + i64::try_from(column).unwrap_or(0)) as f32 + 0.5,
1333                        (tile.top + i64::try_from(row).unwrap_or(0)) as f32 + 0.5,
1334                    ],
1335                );
1336                let share = edges
1337                    .iter()
1338                    .flatten()
1339                    .fold(1.0_f32, |share, edge| share * edge.keep(*unit, point));
1340                for value in pixel {
1341                    *value = (f32::from(*value) * share).round() as u8;
1342                }
1343            }
1344        }
1345        std::borrow::Cow::Owned(kept)
1346    }
1347}
1348
1349/// Where an animated text's clusters go along their lines: tracked, then pushed apart by their
1350/// advance scales, group by group in visual order, and the line re-aligned.
1351struct Pushed {
1352    /// Per line, each glyph's tracking shift, in visual order.
1353    shifts: Vec<Vec<f32>>,
1354    /// Per line, where it starts once tracked and pushed.
1355    offsets: Vec<f32>,
1356    /// Per line, its advance once tracked and pushed.
1357    widths: Vec<f32>,
1358    /// Per cluster, how far its group moved along its line, from its tracked place at the
1359    /// line's final start.
1360    moves: Vec<f32>,
1361    /// Per cluster, the point it scales and turns about.
1362    pivots: Vec<[f32; 2]>,
1363    /// Per cluster, its group's box once pushed, `[left, top, right, bottom]`: its clusters'
1364    /// advances by their em boxes.
1365    units: Vec<[f32; 4]>,
1366}
1367
1368impl Pushed {
1369    fn of(
1370        layout: &Layout,
1371        shaping: &super::runs::Shaping,
1372        request: &TextRasterRequest,
1373        states: &[ClusterState],
1374    ) -> Self {
1375        let tracked = Tracked::of(layout, request, states);
1376        let groups = group_ids(layout, shaping, request);
1377        let mut boxes = vec![GroupBox::default(); groups.iter().max().map_or(0, |last| last + 1)];
1378        for (cluster, extent) in tracked.extents.iter().enumerate() {
1379            if let Some(extent) = extent {
1380                let line = layout.clusters[cluster].line;
1381                let size = tracked.sizes[cluster];
1382                boxes[groups[cluster]].add(*extent, line, layout.baseline(line), size);
1383            }
1384        }
1385        let group_pivots = boxes
1386            .iter()
1387            .map(|group| group.pivot(request.animator_pivot))
1388            .collect::<Vec<_>>();
1389        let mut moves = vec![0.0_f32; states.len()];
1390        let mut pivots = groups
1391            .iter()
1392            .map(|&group| group_pivots[group])
1393            .collect::<Vec<_>>();
1394        let mut offsets = Vec::with_capacity(layout.lines.len());
1395        let mut widths = Vec::with_capacity(layout.lines.len());
1396        let mut placed = vec![GroupBox::default(); boxes.len()];
1397        for (line, &(tracked_offset, shift)) in layout.lines.iter().zip(&tracked.lines) {
1398            let (group_moves, pushed) =
1399                push_line(line, &tracked.extents, &groups, &group_pivots, states);
1400            let offset = if pushed == 0.0 {
1401                tracked_offset
1402            } else {
1403                line_start(layout, line.rtl, line.width + shift + pushed, request)
1404            };
1405            for glyph in &line.glyphs {
1406                let (cluster, group) = (glyph.cluster, groups[glyph.cluster]);
1407                let group_move = group_moves.get(&group).copied().unwrap_or(0.0);
1408                moves[cluster] = group_move;
1409                pivots[cluster][0] =
1410                    group_pivots[group][0] + group_move + (offset - tracked_offset);
1411            }
1412            for cluster in line.glyphs.iter().map(|glyph| glyph.cluster) {
1413                if let Some((left, right)) = tracked.extents[cluster] {
1414                    let delta = moves[cluster] + (offset - tracked_offset);
1415                    let at = layout.clusters[cluster].line;
1416                    placed[groups[cluster]].add(
1417                        (left + delta, right + delta),
1418                        at,
1419                        layout.baseline(at),
1420                        tracked.sizes[cluster],
1421                    );
1422                }
1423            }
1424            offsets.push(offset);
1425            widths.push(line.width + shift + pushed);
1426        }
1427        let units = groups
1428            .iter()
1429            .map(|&group| {
1430                let [left, right, top, bottom] = placed[group].bounds.unwrap_or_default();
1431                [left, top, right, bottom]
1432            })
1433            .collect();
1434        Self {
1435            shifts: tracked.shifts,
1436            offsets,
1437            widths,
1438            moves,
1439            pivots,
1440            units,
1441        }
1442    }
1443}
1444
1445/// An animated text's clusters placed with their tracking, before any push.
1446struct Tracked {
1447    /// Per line, each glyph's tracking shift, in visual order.
1448    shifts: Vec<Vec<f32>>,
1449    /// Per line, where it starts once tracked, and its tracking in all.
1450    lines: Vec<(f32, f32)>,
1451    /// Per cluster, its advance's extent from the layout box's left edge; `None` without glyphs.
1452    extents: Vec<Option<(f32, f32)>>,
1453    /// Per cluster, its glyphs' size.
1454    sizes: Vec<f32>,
1455}
1456
1457impl Tracked {
1458    fn of(layout: &Layout, request: &TextRasterRequest, states: &[ClusterState]) -> Self {
1459        let mut tracked = Self {
1460            shifts: Vec::with_capacity(layout.lines.len()),
1461            lines: Vec::with_capacity(layout.lines.len()),
1462            extents: vec![None; states.len()],
1463            sizes: vec![0.0; states.len()],
1464        };
1465        for line in &layout.lines {
1466            // Tracking goes after each cluster except the line's last, in visual order.
1467            let mut shifts = Vec::with_capacity(line.glyphs.len());
1468            let mut shift = 0.0_f32;
1469            let mut previous: Option<usize> = None;
1470            for glyph in &line.glyphs {
1471                if let Some(before) = previous.filter(|&before| before != glyph.cluster) {
1472                    shift += states[before].tracking;
1473                }
1474                previous = Some(glyph.cluster);
1475                shifts.push(shift);
1476            }
1477            let offset = line_start(layout, line.rtl, line.width + shift, request);
1478            for (glyph, shift) in line.glyphs.iter().zip(&shifts) {
1479                let left = glyph.x + shift + offset;
1480                let extent = tracked.extents[glyph.cluster].get_or_insert((left, left));
1481                *extent = (extent.0.min(left), extent.1.max(left + glyph.advance));
1482                tracked.sizes[glyph.cluster] = glyph.size;
1483            }
1484            tracked.shifts.push(shifts);
1485            tracked.lines.push((offset, shift));
1486        }
1487        tracked
1488    }
1489}
1490
1491/// How far each group on `line` moves, in visual order, as the groups before it grow by their
1492/// clusters' advance scales about their pivots; and how much the line grew in all.
1493fn push_line(
1494    line: &super::LaidLine,
1495    extents: &[Option<(f32, f32)>],
1496    groups: &[usize],
1497    pivots: &[[f32; 2]],
1498    states: &[ClusterState],
1499) -> (HashMap<usize, f32>, f32) {
1500    let mut order = Vec::<usize>::new();
1501    let mut spans = HashMap::<usize, [f32; 4]>::new();
1502    let mut seen = std::collections::HashSet::new();
1503    for glyph in &line.glyphs {
1504        let cluster = glyph.cluster;
1505        let Some((left, right)) = extents[cluster].filter(|_| seen.insert(cluster)) else {
1506            continue;
1507        };
1508        let group = groups[cluster];
1509        let scale = states[cluster].advance_scale;
1510        let mapped = if scale - 1.0 == 0.0 {
1511            (left, right)
1512        } else {
1513            let pivot = pivots[group][0];
1514            (
1515                pivot + (left - pivot) * scale,
1516                pivot + (right - pivot) * scale,
1517            )
1518        };
1519        let span = spans.entry(group).or_insert_with(|| {
1520            order.push(group);
1521            [left, right, mapped.0, mapped.1]
1522        });
1523        *span = [
1524            span[0].min(left),
1525            span[1].max(right),
1526            span[2].min(mapped.0),
1527            span[3].max(mapped.1),
1528        ];
1529    }
1530    let mut pushed = 0.0_f32;
1531    let mut moves = HashMap::<usize, f32>::new();
1532    for group in order {
1533        let [left, right, mapped_left, mapped_right] = spans[&group];
1534        moves.insert(group, pushed + (left - mapped_left));
1535        pushed += (left - mapped_left) + (mapped_right - right);
1536    }
1537    (moves, pushed)
1538}
1539
1540/// Each cluster's group under the request's grouping, numbered from 0.
1541fn group_ids(
1542    layout: &Layout,
1543    shaping: &super::runs::Shaping,
1544    request: &TextRasterRequest,
1545) -> Vec<usize> {
1546    let count = layout.clusters.len();
1547    match request.animator_grouping {
1548        ClusterGrouping::Character => (0..count).collect(),
1549        ClusterGrouping::Line => layout.clusters.iter().map(|cluster| cluster.line).collect(),
1550        ClusterGrouping::All => vec![0; count],
1551        ClusterGrouping::Word => {
1552            let clusters = text_layout(layout, shaping, request).clusters;
1553            let words = clusters
1554                .iter()
1555                .filter_map(|cluster| cluster.word)
1556                .max()
1557                .map_or(0, |last| last as usize + 1);
1558            clusters
1559                .iter()
1560                .enumerate()
1561                .map(|(index, cluster)| cluster.word.map_or(words + index, |word| word as usize))
1562                .collect()
1563        }
1564    }
1565}
1566
1567/// A group's box: the union of its clusters' advances by their em boxes.
1568#[derive(Copy, Clone, Debug, Default)]
1569struct GroupBox {
1570    /// `[left, right, top, bottom]`, once a cluster is added.
1571    bounds: Option<[f32; 4]>,
1572    /// Its one line's baseline and largest size, while it lies on one line.
1573    line: Option<(usize, f32, f32)>,
1574    clusters: usize,
1575}
1576
1577impl GroupBox {
1578    fn add(&mut self, (left, right): (f32, f32), line: usize, baseline: f32, size: f32) {
1579        let (top, bottom) = (baseline - 0.8 * size, baseline + 0.2 * size);
1580        self.bounds = Some(self.bounds.map_or([left, right, top, bottom], |held| {
1581            [
1582                held[0].min(left),
1583                held[1].max(right),
1584                held[2].min(top),
1585                held[3].max(bottom),
1586            ]
1587        }));
1588        self.line = match self.line {
1589            None if self.clusters == 0 => Some((line, baseline, size)),
1590            Some((held, baseline, largest)) if held == line => {
1591                Some((line, baseline, largest.max(size)))
1592            }
1593            _ => None,
1594        };
1595        self.clusters += 1;
1596    }
1597
1598    /// The point at fractions `[x, y]` of the box. On one line every em box shares the baseline,
1599    /// so the box is the largest one's.
1600    #[expect(
1601        clippy::cast_possible_truncation,
1602        reason = "a point between two f32 values"
1603    )]
1604    fn pivot(&self, [x, y]: [f32; 2]) -> [f32; 2] {
1605        let Some([left, right, top, bottom]) = self.bounds else {
1606            return [0.0; 2];
1607        };
1608        let across =
1609            (f64::from(left) * f64::from(1.0 - x) + f64::from(right) * f64::from(x)) as f32;
1610        let down = match self.line {
1611            Some((_, baseline, size)) => baseline - size * (0.8 - y),
1612            None => top + (bottom - top) * y,
1613        };
1614        [across, down]
1615    }
1616}
1617
1618/// Most pixels an animated raster may have. Its planes and the owner planes take 17 to 37 bytes
1619/// per pixel, about twice a static raster.
1620const MAX_ANIMATED_PIXELS: u64 = 1 << 25;
1621
1622/// Most bytes the tiles one request draws (those not cached) may take while drawn.
1623const MAX_REQUEST_TILE_BYTES: u64 = 256 << 20;
1624
1625/// Most bytes the tile cache holds.
1626const MAX_TILE_CACHE_BYTES: usize = 64 << 20;
1627
1628/// A cluster's tile key, placement and box, known before the tile is drawn.
1629struct PlannedCluster {
1630    key: u64,
1631    whole: [i64; 2],
1632    local: Affine,
1633    /// The box [`draw_cluster`] gives the tile, in the frame offset by `whole`.
1634    bounds: Option<PixelBox>,
1635    /// Whether a glyph is a color glyph.
1636    color: bool,
1637}
1638
1639impl PlannedCluster {
1640    /// Bytes drawing the tile takes: coverage and the outline accumulator (4 bytes) per pixel,
1641    /// color glyphs and their resampled copy (8 more), and over the box padded by `reach` the
1642    /// ink plane and one band per stroke.
1643    fn drawing_bytes(&self, strokes: usize, reach: u32) -> u64 {
1644        let Some(bounds) = self.bounds else {
1645            return 0;
1646        };
1647        let side = |from: i64, to: i64| u64::try_from(to.saturating_sub(from)).unwrap_or(0);
1648        let (width, height) = (
1649            side(bounds.left, bounds.right),
1650            side(bounds.top, bounds.bottom),
1651        );
1652        let pixels = width.saturating_mul(height);
1653        let padded = width
1654            .saturating_add(2 * u64::from(reach))
1655            .saturating_mul(height.saturating_add(2 * u64::from(reach)));
1656        let per_pixel = 5 + if self.color { 8 } else { 0 };
1657        let planes = if strokes == 0 { 0 } else { strokes as u64 + 1 };
1658        pixels
1659            .saturating_mul(per_pixel)
1660            .saturating_add(padded.saturating_mul(planes))
1661    }
1662}
1663
1664/// The tile box [`draw_cluster`] draws `glyphs` into through `affine`, and whether any has color.
1665fn cluster_box(
1666    drawings: &HashMap<DrawingKey, Drawing>,
1667    glyphs: &[Placed],
1668    affine: Affine,
1669) -> (Option<PixelBox>, bool) {
1670    let mut union: Option<PixelBox> = None;
1671    let mut color = false;
1672    for glyph in glyphs {
1673        let drawing = &drawings[&glyph.key];
1674        let Some(bounds) = drawing.bounds() else {
1675            continue;
1676        };
1677        let target = mapped_box(bounds, glyph.origin, glyph.scale, affine);
1678        if target.right <= target.left || target.bottom <= target.top {
1679            continue;
1680        }
1681        color |= !matches!(drawing, Drawing::Outline(_));
1682        union = Some(union.map_or(target, |held| PixelBox {
1683            left: held.left.min(target.left),
1684            top: held.top.min(target.top),
1685            right: held.right.max(target.right),
1686            bottom: held.bottom.max(target.bottom),
1687        }));
1688    }
1689    (union, color)
1690}
1691
1692/// A glyph with its origin before the cluster's map and its pixels per font unit.
1693#[derive(Clone, Debug)]
1694struct Placed {
1695    key: DrawingKey,
1696    origin: [f32; 2],
1697    scale: f32,
1698}
1699
1700/// A cluster's tile and stroke bands, in a frame offset by whole pixels when placed.
1701struct DrawnCluster {
1702    tile: Tile,
1703    padded: Tile,
1704    bands: Vec<Vec<u8>>,
1705}
1706
1707impl Tile {
1708    fn moved(&self, [x, y]: [i64; 2]) -> Self {
1709        Self {
1710            left: self.left + x,
1711            top: self.top + y,
1712            width: self.width,
1713            height: self.height,
1714            coverage: Vec::new(),
1715            colors: None,
1716        }
1717    }
1718}
1719
1720impl PixelBox {
1721    fn moved(self, [x, y]: [i64; 2]) -> Self {
1722        Self {
1723            left: self.left.saturating_add(x),
1724            top: self.top.saturating_add(y),
1725            right: self.right.saturating_add(x),
1726            bottom: self.bottom.saturating_add(y),
1727        }
1728    }
1729}
1730
1731/// LRU cache of drawn clusters, so held or settled characters are drawn once. Bounded by
1732/// [`MAX_TILE_CACHE_BYTES`] and [`MAX_CACHED_CLUSTERS`].
1733#[derive(Debug, Default)]
1734pub(crate) struct TileCache {
1735    entries: HashMap<u64, (Arc<DrawnCluster>, u64)>,
1736    bytes: usize,
1737    next_use: u64,
1738}
1739
1740impl std::fmt::Debug for DrawnCluster {
1741    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1742        formatter
1743            .debug_struct("DrawnCluster")
1744            .field("width", &self.tile.width)
1745            .field("height", &self.tile.height)
1746            .finish_non_exhaustive()
1747    }
1748}
1749
1750impl DrawnCluster {
1751    fn bytes(&self) -> usize {
1752        self.tile.coverage.len()
1753            + self.tile.colors.as_ref().map_or(0, Vec::len)
1754            + self.bands.iter().map(Vec::len).sum::<usize>()
1755    }
1756}
1757
1758const MAX_CACHED_CLUSTERS: usize = 4_096;
1759
1760impl TileCache {
1761    fn contains(&self, key: u64) -> bool {
1762        self.entries.contains_key(&key)
1763    }
1764
1765    fn get(&mut self, key: u64) -> Option<Arc<DrawnCluster>> {
1766        self.next_use += 1;
1767        let use_now = self.next_use;
1768        self.entries.get_mut(&key).map(|(drawn, used)| {
1769            *used = use_now;
1770            Arc::clone(drawn)
1771        })
1772    }
1773
1774    /// Keeps `drawn` unless it is larger than a quarter of the byte budget, evicting the least
1775    /// recently used entries to make room.
1776    fn insert(&mut self, key: u64, drawn: &Arc<DrawnCluster>) {
1777        let bytes = drawn.bytes();
1778        if bytes > MAX_TILE_CACHE_BYTES / 4 {
1779            return;
1780        }
1781        if self.entries.len() >= MAX_CACHED_CLUSTERS {
1782            // Drop the older half so eviction stays rare.
1783            let mut uses = self
1784                .entries
1785                .values()
1786                .map(|(_, used)| *used)
1787                .collect::<Vec<_>>();
1788            uses.sort_unstable();
1789            let cut = uses[uses.len() / 2];
1790            self.entries.retain(|_, (_, used)| *used > cut);
1791            self.bytes = self.entries.values().map(|(drawn, _)| drawn.bytes()).sum();
1792        }
1793        if self.bytes + bytes > MAX_TILE_CACHE_BYTES {
1794            let mut by_use = self
1795                .entries
1796                .iter()
1797                .map(|(key, (drawn, used))| (*used, *key, drawn.bytes()))
1798                .collect::<Vec<_>>();
1799            by_use.sort_unstable();
1800            for (_, old, old_bytes) in by_use {
1801                if self.bytes + bytes <= MAX_TILE_CACHE_BYTES {
1802                    break;
1803                }
1804                self.entries.remove(&old);
1805                self.bytes -= old_bytes;
1806            }
1807        }
1808        if let Some((replaced, _)) = self.entries.insert(key, (Arc::clone(drawn), self.next_use)) {
1809            self.bytes -= replaced.bytes();
1810        }
1811        self.bytes += bytes;
1812    }
1813
1814    /// Bytes the cached tiles hold.
1815    #[cfg(test)]
1816    pub(crate) const fn bytes(&self) -> usize {
1817        self.bytes
1818    }
1819
1820    pub(crate) fn clear(&mut self) {
1821        self.entries.clear();
1822        self.bytes = 0;
1823    }
1824}
1825
1826/// FNV-1a over the request fields that affect cluster drawing besides glyphs and maps.
1827fn look_key(request: &TextRasterRequest, strokes: &[TextStroke]) -> u64 {
1828    let mut hash = Fnv::default();
1829    hash.feed(&request.font_weight.to_le_bytes());
1830    hash.feed(&[request.emoji_policy as u8]);
1831    hash.feed(&request.fill.foreground());
1832    for stroke in strokes {
1833        hash.feed(&stroke.width.to_bits().to_le_bytes());
1834    }
1835    hash.0
1836}
1837
1838fn cluster_key(look: u64, faces: &Faces<'_>, glyphs: &[Placed], affine: Affine) -> u64 {
1839    let mut hash = Fnv(look);
1840    let first = glyphs.first().map_or([0.0; 2], |glyph| glyph.origin);
1841    for glyph in glyphs {
1842        let (font, weight, italic) = faces.of[glyph.key.face];
1843        hash.feed(&font.to_le_bytes());
1844        hash.feed(&weight.to_le_bytes());
1845        hash.feed(&[u8::from(italic), u8::from(glyph.key.shear)]);
1846        hash.feed(&glyph.key.size.to_le_bytes());
1847        hash.feed(&glyph.key.foreground);
1848        hash.feed(&glyph.key.glyph.to_le_bytes());
1849        hash.feed(&glyph.scale.to_bits().to_le_bytes());
1850        for value in [glyph.origin[0] - first[0], glyph.origin[1] - first[1]] {
1851            hash.feed(&value.to_bits().to_le_bytes());
1852        }
1853    }
1854    // Key the map relative to the first glyph, so a moved cluster hits the cache.
1855    let [x, y] = apply(affine, first);
1856    for value in [affine[0], affine[1], affine[2], affine[3], x, y] {
1857        hash.feed(&value.to_bits().to_le_bytes());
1858    }
1859    hash.0
1860}
1861
1862struct Fnv(u64);
1863
1864impl Default for Fnv {
1865    fn default() -> Self {
1866        Self(0xcbf2_9ce4_8422_2325)
1867    }
1868}
1869
1870impl Fnv {
1871    fn feed(&mut self, bytes: &[u8]) {
1872        for byte in bytes {
1873            self.0 = (self.0 ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
1874        }
1875    }
1876}
1877
1878#[allow(
1879    clippy::cast_possible_truncation,
1880    clippy::cast_possible_wrap,
1881    clippy::cast_precision_loss,
1882    clippy::cast_sign_loss,
1883    clippy::too_many_lines
1884)]
1885fn draw_cluster(
1886    strokes: &[TextStroke],
1887    drawings: &HashMap<DrawingKey, Drawing>,
1888    glyphs: &[Placed],
1889    affine: Affine,
1890) -> DrawnCluster {
1891    let mut tile = Tile::empty();
1892    for glyph in glyphs {
1893        let drawing = &drawings[&glyph.key];
1894        let Some(bounds) = drawing.bounds() else {
1895            continue;
1896        };
1897        let (origin, scale) = (glyph.origin, glyph.scale);
1898        let target = mapped_box(bounds, origin, scale, affine);
1899        if target.right <= target.left || target.bottom <= target.top {
1900            continue;
1901        }
1902        tile.grow(target);
1903        let width = usize::try_from(target.right - target.left).unwrap_or(0);
1904        match drawing {
1905            Drawing::Outline(outline) => {
1906                let height = usize::try_from(target.bottom - target.top).unwrap_or(0);
1907                let (left, top) = (target.left as f32, target.top as f32);
1908                let raster = outline.raster(width, height, |[x, y]| {
1909                    let [x, y] = apply(affine, [origin[0] + x * scale, origin[1] - y * scale]);
1910                    point(x - left, y - top)
1911                });
1912                raster.for_each_pixel(|at, coverage| {
1913                    let value = (coverage.min(1.0) * 255.0).round() as u8;
1914                    let x = target.left + (at % width) as i64;
1915                    let y = target.top + (at / width) as i64;
1916                    if let Some(slot) = tile.index(x, y) {
1917                        tile.coverage[slot] = tile.coverage[slot].max(value);
1918                    }
1919                });
1920            }
1921            drawing => {
1922                let Some(inverse) = invert(affine) else {
1923                    continue;
1924                };
1925                let upright = PixelBox::of(bounds, origin, scale);
1926                let rgba8 = resample(
1927                    &drawing.draw_color(origin, scale, upright),
1928                    upright,
1929                    target,
1930                    inverse,
1931                );
1932                let size = tile.width * tile.height * 4;
1933                let slots = (0..rgba8.len() / 4)
1934                    .map(|at| {
1935                        tile.index(
1936                            target.left + (at % width) as i64,
1937                            target.top + (at / width) as i64,
1938                        )
1939                    })
1940                    .collect::<Vec<_>>();
1941                let colors = tile.colors.get_or_insert_with(|| vec![0; size]);
1942                for (source, slot) in rgba8.as_chunks::<4>().0.iter().zip(slots) {
1943                    let Some(slot) = slot.filter(|_| source[3] > 0) else {
1944                        continue;
1945                    };
1946                    let held = &mut colors[slot * 4..slot * 4 + 4];
1947                    let blended = over(
1948                        source.map(u32::from),
1949                        std::array::from_fn(|channel| u32::from(held[channel])),
1950                    );
1951                    for (byte, value) in held.iter_mut().zip(blended) {
1952                        *byte = u8::try_from(value.min(255)).unwrap_or(u8::MAX);
1953                    }
1954                }
1955            }
1956        }
1957    }
1958    with_bands(tile, strokes)
1959}
1960
1961#[expect(clippy::cast_possible_wrap, reason = "tile reach is a few pixels")]
1962fn with_bands(tile: Tile, strokes: &[TextStroke]) -> DrawnCluster {
1963    let reach = stroke_radius(strokes).map_or(0, disc_extent) as usize;
1964    let padded = Tile {
1965        left: tile.left - reach as i64,
1966        top: tile.top - reach as i64,
1967        width: tile.width + 2 * reach,
1968        height: tile.height + 2 * reach,
1969        coverage: Vec::new(),
1970        colors: None,
1971    };
1972    let mut bands = Vec::with_capacity(strokes.len());
1973    if !strokes.is_empty() && tile.width > 0 && tile.height > 0 {
1974        let mut ink = vec![0_u8; padded.width * padded.height];
1975        for row in 0..tile.height {
1976            for column in 0..tile.width {
1977                let at = row * tile.width + column;
1978                let alpha = tile.colors.as_ref().map_or(0, |held| held[at * 4 + 3]);
1979                ink[(row + reach) * padded.width + column + reach] = tile.coverage[at].max(alpha);
1980            }
1981        }
1982        let mut radius = 0.0;
1983        for stroke in strokes {
1984            radius += stroke.width;
1985            bands.push(dilate(
1986                &ink,
1987                u32::try_from(padded.width).unwrap_or(u32::MAX),
1988                u32::try_from(padded.height).unwrap_or(u32::MAX),
1989                radius,
1990            ));
1991        }
1992    }
1993    DrawnCluster {
1994        tile,
1995        padded,
1996        bands,
1997    }
1998}
1999
2000#[expect(
2001    clippy::cast_possible_truncation,
2002    clippy::cast_precision_loss,
2003    clippy::cast_sign_loss,
2004    reason = "pixel boxes of layout positions"
2005)]
2006fn draw_box(rect: [f32; 4], affine: Affine, strokes: &[TextStroke]) -> DrawnCluster {
2007    let [left, top, right, bottom] = rect;
2008    let corners = [[left, top], [right, top], [right, bottom], [left, bottom]]
2009        .map(|corner| apply(affine, corner));
2010    let (mut x_min, mut y_min, mut x_max, mut y_max) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
2011    for [x, y] in corners {
2012        (x_min, y_min, x_max, y_max) = (x_min.min(x), y_min.min(y), x_max.max(x), y_max.max(y));
2013    }
2014    let bounds = PixelBox {
2015        left: x_min.floor() as i64,
2016        top: y_min.floor() as i64,
2017        right: x_max.ceil() as i64,
2018        bottom: y_max.ceil() as i64,
2019    };
2020    let mut tile = Tile::empty();
2021    if bounds.right > bounds.left && bounds.bottom > bounds.top {
2022        tile.grow(bounds);
2023        let (origin_x, origin_y) = (bounds.left as f32, bounds.top as f32);
2024        let mut raster = ab_glyph_rasterizer::Rasterizer::new(tile.width, tile.height);
2025        for (at, corner) in corners.iter().enumerate() {
2026            let next = corners[(at + 1) % corners.len()];
2027            raster.draw_line(
2028                point(corner[0] - origin_x, corner[1] - origin_y),
2029                point(next[0] - origin_x, next[1] - origin_y),
2030            );
2031        }
2032        raster.for_each_pixel(|at, coverage| {
2033            tile.coverage[at] = (coverage.min(1.0) * 255.0).round() as u8;
2034        });
2035    }
2036    with_bands(tile, strokes)
2037}
2038
2039/// Line start in the box, as [`Layout::line_offset`] computes it.
2040fn line_start(layout: &Layout, rtl: bool, width: f32, request: &TextRasterRequest) -> f32 {
2041    use alpha2_media::TextAlign;
2042    match (request.align, rtl) {
2043        (TextAlign::Center, _) => (layout.width - width) * 0.5,
2044        (TextAlign::Start, false) | (TextAlign::End, true) => 0.0,
2045        (TextAlign::End, false) | (TextAlign::Start, true) => layout.width - width,
2046    }
2047}
2048
2049pub(crate) fn text_layout(
2050    layout: &Layout,
2051    shaping: &super::runs::Shaping,
2052    request: &TextRasterRequest,
2053) -> TextLayout {
2054    let mut map = Vec::new();
2055    normalize_mapped(&request.text, request.emoji_policy, Some(&mut map));
2056    let original = |at: usize| map.get(at).copied().unwrap_or(request.text.len());
2057    let words = request
2058        .text
2059        .split_word_bound_indices()
2060        .filter(|(_, word)| word.chars().any(char::is_alphanumeric))
2061        .map(|(start, word)| start..start + word.len())
2062        .collect::<Vec<_>>();
2063    let mut clusters = layout
2064        .clusters
2065        .iter()
2066        .map(|span| {
2067            let bytes = original(span.bytes.start)..original(span.bytes.end);
2068            let text = &request.text[bytes.clone()];
2069            let word = words
2070                .partition_point(|word| word.end <= bytes.start)
2071                .try_into()
2072                .ok()
2073                .filter(|&index: &u32| {
2074                    !span.ellipsis
2075                        && words
2076                            .get(index as usize)
2077                            .is_some_and(|word| word.contains(&bytes.start))
2078                });
2079            ClusterInfo {
2080                is_space: !text.is_empty() && text.chars().all(char::is_whitespace),
2081                bytes,
2082                line: u32::try_from(span.line).unwrap_or(u32::MAX),
2083                word,
2084                x: 0.0,
2085                advance: 0.0,
2086                baseline: 0.0,
2087                font_size: shaping.looks[usize::from(span.look)].size,
2088                ink: None,
2089                ellipsis: span.ellipsis,
2090            }
2091        })
2092        .collect::<Vec<_>>();
2093    let mut lines = Vec::with_capacity(layout.lines.len());
2094    let mut first_cluster = 0;
2095    for (index, line) in layout.lines.iter().enumerate() {
2096        let left = layout.line_offset(line, request.align);
2097        let baseline = layout.baseline(index);
2098        let line_number = u32::try_from(index).unwrap_or(u32::MAX);
2099        let last_cluster = clusters[first_cluster..]
2100            .iter()
2101            .position(|cluster| cluster.line != line_number)
2102            .map_or(clusters.len(), |count| first_cluster + count);
2103        let mut extents = HashMap::<usize, (f32, f32)>::new();
2104        for glyph in &line.glyphs {
2105            let start = glyph.x + left;
2106            let extent = extents.entry(glyph.cluster).or_insert((start, start));
2107            *extent = (extent.0.min(start), extent.1.max(start + glyph.advance));
2108        }
2109        for (cluster, info) in clusters[first_cluster..last_cluster].iter_mut().enumerate() {
2110            let (start, end) = extents
2111                .get(&(first_cluster + cluster))
2112                .copied()
2113                .unwrap_or((left + line.width, left + line.width));
2114            info.x = start;
2115            info.advance = end - start;
2116            info.baseline = baseline;
2117        }
2118        let size = layout.line_size(index);
2119        lines.push(LineInfo {
2120            clusters: first_cluster..last_cluster,
2121            left,
2122            width: line.width,
2123            baseline,
2124            size,
2125            box_top: layout.line_top(index) - super::half_leading(size, request.line_height),
2126        });
2127        first_cluster = last_cluster;
2128    }
2129    TextLayout {
2130        clusters,
2131        lines,
2132        font_size: request.font_size,
2133    }
2134}
2135
2136#[cfg(test)]
2137mod tests {
2138    use super::*;
2139
2140    fn drawn(bytes: usize) -> Arc<DrawnCluster> {
2141        Arc::new(DrawnCluster {
2142            tile: Tile {
2143                left: 0,
2144                top: 0,
2145                width: bytes,
2146                height: 1,
2147                coverage: vec![0; bytes],
2148                colors: None,
2149            },
2150            padded: Tile::empty(),
2151            bands: Vec::new(),
2152        })
2153    }
2154
2155    #[test]
2156    fn the_tile_cache_evicts_the_least_recently_used_by_bytes() {
2157        let mut cache = TileCache::default();
2158        let tile = 10 << 20;
2159        for key in 0..6 {
2160            cache.insert(key, &drawn(tile));
2161        }
2162        assert_eq!(cache.bytes(), 6 * tile);
2163        assert!(cache.get(0).is_some());
2164        cache.insert(6, &drawn(tile));
2165        assert!(cache.bytes() <= MAX_TILE_CACHE_BYTES);
2166        assert!(cache.contains(0) && cache.contains(6) && !cache.contains(1));
2167        cache.insert(7, &drawn(MAX_TILE_CACHE_BYTES / 4 + 1));
2168        assert!(!cache.contains(7));
2169        cache.insert(6, &drawn(tile));
2170        assert!(cache.bytes() <= MAX_TILE_CACHE_BYTES);
2171        cache.clear();
2172        assert_eq!(cache.bytes(), 0);
2173    }
2174}