Skip to main content

alpha2_eval/
layout.rs

1//! A layout generator's box tree evaluated at a time.
2//!
3//! A [`LayoutPlan`] is built with the index for the project canvas. It converts pixel lengths
4//! to fractions of the canvas's shorter side and pre-evaluates a tree without keyframes, so every
5//! frame shares one value and key. Text style is inherited during evaluation.
6
7use crate::animation::{
8    sample_hold, sample_insets, sample_length, sample_offset, sample_paint, sample_scalar,
9    sample_size, sample_vec2,
10};
11use crate::{SampleContext, ShapesPlan};
12use alpha2_geometry::StableHash;
13use alpha2_model::{
14    AlignContent, AlignItems, Animated, Display, FlexDirection, FlexWrap, GridAutoFlow,
15    GridPlacement, JustifyContent, LAYOUT_TEXT_DEFAULTS, LayoutLength, LayoutNode, LayoutTextStyle,
16    Overflow, Paint, Position, Rgba, TextAlign, TextShadow, TextStroke, TrackList, Vec2,
17};
18use alpha2_time::MediaTime;
19use std::sync::Arc;
20
21/// A layout tree, evaluated once when it does not animate.
22#[derive(Clone, Debug)]
23pub struct LayoutPlan {
24    /// The tree with its pixels turned into fractions.
25    root: Box<LayoutNode>,
26    /// Each shape node's plan, in preorder, with a digest of its items.
27    shapes: Vec<(Arc<ShapesPlan>, u128)>,
28    /// Whether a shape node animates, making the time part of the key.
29    shapes_animate: bool,
30    /// The whole tree, when nothing in it animates.
31    fixed: Option<Arc<EvaluatedLayout>>,
32}
33
34impl PartialEq for LayoutPlan {
35    fn eq(&self, other: &Self) -> bool {
36        self.root == other.root
37    }
38}
39
40impl LayoutPlan {
41    /// Plans `root` for a canvas of `(width, height)` pixels.
42    #[must_use]
43    pub fn new(root: &LayoutNode, canvas: (u32, u32)) -> Self {
44        #[allow(clippy::cast_precision_loss)]
45        let shorter_side = canvas.0.min(canvas.1).max(1) as f32;
46        let root = root.without_px(shorter_side);
47        let mut shapes = Vec::new();
48        root.walk(|_, node| {
49            if let Some(shape) = &node.shape {
50                let mut hash = StableHash::new();
51                hash.bytes(format!("{:?}", shape.items).as_bytes());
52                shapes.push((Arc::new(ShapesPlan::new(&shape.items)), hash.finish()));
53            }
54        });
55        let shapes_animate = shapes.iter().any(|(plan, _)| plan.is_animated());
56        let animated = root.is_animated();
57        let mut plan = Self {
58            root: Box::new(root),
59            shapes,
60            shapes_animate,
61            fixed: None,
62        };
63        if !animated {
64            plan.fixed = Some(Arc::new(plan.evaluate_now(MediaTime::ZERO)));
65        }
66        plan
67    }
68
69    /// The tree at picture time `time`.
70    #[must_use]
71    pub fn evaluate(&self, time: MediaTime) -> Arc<EvaluatedLayout> {
72        self.fixed
73            .clone()
74            .unwrap_or_else(|| Arc::new(self.evaluate_now(time)))
75    }
76
77    /// Whether anything in the tree animates.
78    #[must_use]
79    pub fn is_animated(&self) -> bool {
80        self.fixed.is_none()
81    }
82
83    /// The model tree with pixels converted to fractions of the canvas's shorter side.
84    #[must_use]
85    pub const fn root(&self) -> &LayoutNode {
86        &self.root
87    }
88
89    fn evaluate_now(&self, time: MediaTime) -> EvaluatedLayout {
90        let mut shapes = self.shapes.iter();
91        let root = evaluate_node(&self.root, time, &mut shapes, &LAYOUT_TEXT_DEFAULTS);
92        let mut hash = StableHash::new();
93        hash_node(&mut hash, &root, &self.shapes);
94        if self.shapes_animate {
95            hash.u64(time.ticks().cast_unsigned());
96        }
97        EvaluatedLayout {
98            root,
99            time,
100            key: hash.finish(),
101        }
102    }
103}
104
105/// A layout tree with every value sampled.
106#[derive(Clone, Debug, PartialEq)]
107pub struct EvaluatedLayout {
108    /// The root box: the whole picture.
109    pub root: EvaluatedNode,
110    /// The picture time shape nodes are drawn at.
111    pub time: MediaTime,
112    /// Equal for trees that lay out and draw alike (covers `time` only when a shape animates).
113    pub key: u128,
114}
115
116/// One box with its values sampled. Lengths are fractions of the picture's shorter side.
117#[derive(Clone, Debug, PartialEq)]
118pub struct EvaluatedNode {
119    /// What flexbox or grid reads.
120    pub layout: NodeLayout,
121    /// What is drawn under the content.
122    pub paint: NodePaint,
123    /// Present when the node has any visual field, with defaults filled.
124    pub visual: Option<NodeVisual>,
125    /// Whether content past the padding box is clipped.
126    pub clip: bool,
127    /// Children, text, a shape, or nothing.
128    pub content: NodeContent,
129}
130
131impl EvaluatedNode {
132    /// Whether the node is drawn into its own composite.
133    #[must_use]
134    pub const fn is_isolated(&self) -> bool {
135        self.visual.is_some() || self.clip
136    }
137}
138
139/// A length on each side of a box, as a fraction of the picture's shorter side.
140#[derive(Copy, Clone, Debug, Default, PartialEq)]
141#[allow(missing_docs)]
142pub struct Sides {
143    pub top: f32,
144    pub right: f32,
145    pub bottom: f32,
146    pub left: f32,
147}
148
149impl Sides {
150    const fn from_array([top, right, bottom, left]: [f32; 4]) -> Self {
151        Self {
152            top,
153            right,
154            bottom,
155            left,
156        }
157    }
158
159    const fn to_array(self) -> [f32; 4] {
160        [self.top, self.right, self.bottom, self.left]
161    }
162}
163
164/// A box's sampled box-model, flex and grid values. Lengths are fractions or percents.
165#[derive(Clone, Debug, PartialEq)]
166#[allow(missing_docs)]
167pub struct NodeLayout {
168    pub display: Display,
169    pub flex_direction: FlexDirection,
170    pub flex_wrap: FlexWrap,
171    pub grid_template_columns: Option<TrackList>,
172    pub grid_template_rows: Option<TrackList>,
173    pub grid_auto_columns: Option<TrackList>,
174    pub grid_auto_rows: Option<TrackList>,
175    pub grid_auto_flow: GridAutoFlow,
176    /// The gap between rows: `row_gap`, else `gap`.
177    pub row_gap: f32,
178    /// The gap between columns: `column_gap`, else `gap`.
179    pub column_gap: f32,
180    pub justify_content: JustifyContent,
181    pub align_items: AlignItems,
182    pub align_content: AlignContent,
183    pub justify_items: AlignItems,
184    pub padding: Sides,
185    /// The border's width; zero without one.
186    pub border_width: f32,
187    pub overflow: Overflow,
188    pub width: Option<LayoutLength>,
189    pub height: Option<LayoutLength>,
190    pub min_width: Option<LayoutLength>,
191    pub min_height: Option<LayoutLength>,
192    pub max_width: Option<LayoutLength>,
193    pub max_height: Option<LayoutLength>,
194    pub aspect_ratio: Option<f32>,
195    pub margin: Sides,
196    pub flex_grow: f32,
197    pub flex_shrink: f32,
198    pub flex_basis: Option<LayoutLength>,
199    pub align_self: Option<AlignItems>,
200    pub justify_self: Option<AlignItems>,
201    pub grid_column: GridPlacement,
202    pub grid_row: GridPlacement,
203    pub position: Position,
204    /// Left, top, right, bottom; `None` is auto.
205    pub inset: [Option<LayoutLength>; 4],
206}
207
208/// What a box draws under its content.
209#[derive(Clone, Debug, PartialEq)]
210pub struct NodePaint {
211    /// What covers the border box.
212    pub background: Option<Paint>,
213    /// The border's width and paint.
214    pub border: Option<(f32, Paint)>,
215    /// The border box's corner radius.
216    pub border_radius: f32,
217}
218
219/// How a box and its subtree are drawn after layout.
220#[derive(Copy, Clone, Debug, PartialEq)]
221pub struct NodeVisual {
222    /// Group opacity, in `0..=1`.
223    pub opacity: f32,
224    /// Offset, a fraction of the picture's shorter side.
225    pub translate: Vec2,
226    /// Per-axis scale about the border-box centre.
227    pub scale: Vec2,
228    /// Clockwise rotation about the border-box centre, in degrees.
229    pub rotation_degrees: f32,
230}
231
232/// A box's content.
233#[derive(Clone, Debug, PartialEq)]
234pub enum NodeContent {
235    /// Nothing: a spacer or a decoration.
236    Empty,
237    /// Boxes laid out in this one, in document order.
238    Children(Vec<EvaluatedNode>),
239    /// One paragraph of text.
240    Text(Box<EvaluatedText>),
241    /// Shapes, evaluated at draw time because spatial curves need the post-layout aspect.
242    Shape(Arc<ShapesPlan>),
243}
244
245/// A text node's sampled text and the style it inherits.
246#[derive(Clone, Debug, PartialEq)]
247pub struct EvaluatedText {
248    /// The text; may be empty.
249    pub content: String,
250    /// The family it draws in.
251    pub font_family: Option<String>,
252    /// Font size, a fraction of the picture's shorter side; positive.
253    pub font_size: f32,
254    /// What paints the glyphs, a gradient over the text's layout box.
255    pub fill: Paint,
256    /// Baseline-to-baseline distance in font sizes.
257    pub line_height: f32,
258    /// Space after each character, a fraction of the font size.
259    pub letter_spacing: f32,
260    /// The weight its faces are matched by.
261    pub font_weight: u16,
262    /// How lines align in the content width.
263    pub text_align: TextAlign,
264    /// Bands around the glyphs, innermost first.
265    pub strokes: Vec<TextStroke>,
266    /// Shadows of the glyphs and strokes, the first on top.
267    pub shadows: Vec<TextShadow>,
268    /// The node's text animators at the layout's picture time.
269    pub animators: Vec<crate::SampledAnimator>,
270    /// The font sizes it is fitted between, fractions of the picture's shorter side.
271    pub font_size_fit: Option<alpha2_model::FontSizeFit>,
272    /// Where its lines are cut.
273    pub line_clamp: Option<alpha2_model::LineClamp>,
274}
275
276/// Largest magnitude of a sampled fraction, which a valid pixel length reaches on a one-pixel
277/// picture. Eased keyframes can overshoot their values; sampling clamps them here.
278const MOST_FRACTION: f32 = alpha2_model::MAX_LAYOUT_PX;
279
280fn fraction(value: f32) -> f32 {
281    value.clamp(-MOST_FRACTION, MOST_FRACTION)
282}
283
284fn flex_factor(animation: Option<&Animated<f32>>, time: MediaTime, default: f32) -> f32 {
285    animation.map_or(default, |value| {
286        sample_scalar(value, time, &SampleContext::NONE).clamp(0.0, alpha2_model::MAX_FLEX_FACTOR)
287    })
288}
289
290fn size_or(
291    animation: Option<&Animated<alpha2_model::LayoutSize>>,
292    time: MediaTime,
293    default: f32,
294) -> f32 {
295    animation.map_or(default, |value| {
296        sample_size(value, time).clamp(0.0, MOST_FRACTION)
297    })
298}
299
300fn length(animation: Option<&Animated<LayoutLength>>, time: MediaTime) -> Option<LayoutLength> {
301    animation.map(|value| {
302        let length = sample_length(value, time);
303        let bound = match length {
304            LayoutLength::Percent(_) => alpha2_model::MAX_LAYOUT_PERCENT,
305            LayoutLength::Fraction(_) | LayoutLength::Px(_) => MOST_FRACTION,
306        };
307        length.with_value(length.value().clamp(-bound, bound))
308    })
309}
310
311fn size(animation: Option<&Animated<LayoutLength>>, time: MediaTime) -> Option<LayoutLength> {
312    length(animation, time).map(|length| length.with_value(length.value().max(0.0)))
313}
314
315fn node_layout(node: &LayoutNode, time: MediaTime, border_width: f32) -> NodeLayout {
316    let insets = |value: Option<&Animated<alpha2_model::Insets>>| {
317        value.map_or_else(Sides::default, |value| {
318            Sides::from_array(sample_insets(value, time).map(fraction))
319        })
320    };
321    let padding = Sides::from_array(
322        insets(node.padding.as_ref())
323            .to_array()
324            .map(|side| side.max(0.0)),
325    );
326    let inset = node.inset.as_ref().map_or([None; 4], |inset| {
327        [
328            length(inset.left.as_ref(), time),
329            length(inset.top.as_ref(), time),
330            length(inset.right.as_ref(), time),
331            length(inset.bottom.as_ref(), time),
332        ]
333    });
334    let gap = size_or(node.gap.as_ref(), time, 0.0);
335    NodeLayout {
336        display: node.display.unwrap_or_default(),
337        flex_direction: node.flex_direction.unwrap_or_default(),
338        flex_wrap: node.flex_wrap.unwrap_or_default(),
339        grid_template_columns: node.grid_template_columns.clone(),
340        grid_template_rows: node.grid_template_rows.clone(),
341        grid_auto_columns: node.grid_auto_columns.clone(),
342        grid_auto_rows: node.grid_auto_rows.clone(),
343        grid_auto_flow: node.grid_auto_flow.unwrap_or_default(),
344        row_gap: size_or(node.row_gap.as_ref(), time, gap),
345        column_gap: size_or(node.column_gap.as_ref(), time, gap),
346        justify_content: node.justify_content.unwrap_or_default(),
347        align_items: node.align_items.unwrap_or_default(),
348        align_content: node.align_content.unwrap_or_default(),
349        justify_items: node.justify_items.unwrap_or_default(),
350        padding,
351        border_width,
352        overflow: node.overflow.unwrap_or_default(),
353        width: size(node.width.as_ref(), time),
354        height: size(node.height.as_ref(), time),
355        min_width: size(node.min_width.as_ref(), time),
356        min_height: size(node.min_height.as_ref(), time),
357        max_width: size(node.max_width.as_ref(), time),
358        max_height: size(node.max_height.as_ref(), time),
359        aspect_ratio: node.aspect_ratio,
360        margin: insets(node.margin.as_ref()),
361        flex_grow: flex_factor(node.flex_grow.as_ref(), time, 0.0),
362        flex_shrink: flex_factor(node.flex_shrink.as_ref(), time, 1.0),
363        flex_basis: size(node.flex_basis.as_ref(), time),
364        align_self: node.align_self,
365        justify_self: node.justify_self,
366        grid_column: node.grid_column.unwrap_or_default(),
367        grid_row: node.grid_row.unwrap_or_default(),
368        position: node.position.unwrap_or_default(),
369        inset,
370    }
371}
372
373/// The text style `node` passes to its text and children, sampled at `time`.
374fn text_style(node: &LayoutNode, time: MediaTime, inherited: &LayoutTextStyle) -> LayoutTextStyle {
375    LayoutTextStyle {
376        font_family: node
377            .font_family
378            .clone()
379            .or_else(|| inherited.font_family.clone()),
380        font_size: node.font_size.as_ref().map_or(inherited.font_size, |size| {
381            sample_size(size, time).max(f32::MIN_POSITIVE)
382        }),
383        fill: node.fill.clone().unwrap_or_else(|| inherited.fill.clone()),
384        line_height: node.line_height.unwrap_or(inherited.line_height),
385        letter_spacing: node.letter_spacing.unwrap_or(inherited.letter_spacing),
386        font_weight: node.font_weight.unwrap_or(inherited.font_weight),
387        text_align: node.text_align.unwrap_or(inherited.text_align),
388        strokes: node
389            .strokes
390            .clone()
391            .unwrap_or_else(|| inherited.strokes.clone()),
392        shadows: node
393            .shadows
394            .clone()
395            .unwrap_or_else(|| inherited.shadows.clone()),
396    }
397}
398
399fn evaluate_node<'a>(
400    node: &LayoutNode,
401    time: MediaTime,
402    shapes: &mut impl Iterator<Item = &'a (Arc<ShapesPlan>, u128)>,
403    inherited: &LayoutTextStyle,
404) -> EvaluatedNode {
405    let border = node.border.as_ref().map(|border| {
406        (
407            sample_size(&border.width, time).clamp(0.0, MOST_FRACTION),
408            sample_paint(&border.paint, time),
409        )
410    });
411    let layout = node_layout(node, time, border.as_ref().map_or(0.0, |(width, _)| *width));
412    let paint = NodePaint {
413        background: node
414            .background
415            .as_ref()
416            .map(|paint| sample_paint(paint, time)),
417        border,
418        border_radius: size_or(node.border_radius.as_ref(), time, 0.0),
419    };
420    let visual = node.has_visual().then(|| NodeVisual {
421        opacity: node.opacity.as_ref().map_or(1.0, |value| {
422            sample_scalar(value, time, &SampleContext::NONE).clamp(0.0, 1.0)
423        }),
424        translate: node.translate.as_ref().map_or_else(Vec2::default, |value| {
425            let offset = sample_offset(value, time);
426            Vec2::new(fraction(offset.x), fraction(offset.y))
427        }),
428        scale: node.scale.as_ref().map_or(Vec2::new(1.0, 1.0), |value| {
429            sample_vec2(value, time, &SampleContext::NONE)
430        }),
431        rotation_degrees: node.rotation_degrees.as_ref().map_or(0.0, |value| {
432            sample_scalar(value, time, &SampleContext::NONE)
433        }),
434    });
435    let style = text_style(node, time, inherited);
436    let content = if let Some(text) = &node.text {
437        NodeContent::Text(Box::new(EvaluatedText {
438            content: sample_hold(text, time),
439            font_family: style.font_family,
440            font_size: style.font_size,
441            fill: style.fill.clone(),
442            line_height: style.line_height,
443            letter_spacing: style.letter_spacing,
444            font_weight: style.font_weight,
445            text_align: style.text_align,
446            strokes: style.strokes.clone(),
447            shadows: style.shadows.clone(),
448            animators: crate::sample_text_animators(&node.text_animators, time),
449            font_size_fit: node.font_size_fit.map(|fit| alpha2_model::FontSizeFit {
450                min: fit.min.value(),
451                max: fit.max.map(alpha2_model::LayoutSize::value),
452            }),
453            line_clamp: node.line_clamp.clone(),
454        }))
455    } else if node.shape.is_some() {
456        let (plan, _) = shapes.next().expect("one plan per shape node");
457        NodeContent::Shape(Arc::clone(plan))
458    } else if node.children.is_empty() {
459        NodeContent::Empty
460    } else {
461        NodeContent::Children(
462            node.children
463                .iter()
464                .map(|child| evaluate_node(child, time, shapes, &style))
465                .collect(),
466        )
467    };
468    EvaluatedNode {
469        layout,
470        paint,
471        visual,
472        clip: matches!(node.overflow, Some(Overflow::Hidden)),
473        content,
474    }
475}
476
477fn hash_length(hash: &mut StableHash, length: Option<LayoutLength>) {
478    match length {
479        None => hash.u32(0),
480        Some(LayoutLength::Fraction(value)) => {
481            hash.u32(1);
482            hash.f32(value);
483        }
484        Some(LayoutLength::Percent(value)) => {
485            hash.u32(2);
486            hash.f32(value);
487        }
488        Some(LayoutLength::Px(value)) => {
489            hash.u32(3);
490            hash.f32(value);
491        }
492    }
493}
494
495fn hash_sides(hash: &mut StableHash, sides: Sides) {
496    for side in sides.to_array() {
497        hash.f32(side);
498    }
499}
500
501fn hash_color(hash: &mut StableHash, color: Rgba) {
502    for component in [color.red, color.green, color.blue, color.alpha] {
503        hash.f32(component);
504    }
505}
506
507fn hash_paint(hash: &mut StableHash, paint: Option<&Paint>) {
508    let stops = |hash: &mut StableHash, stops: &[alpha2_model::GradientStop]| {
509        hash.u64(stops.len() as u64);
510        for stop in stops {
511            hash.f32(stop.offset);
512            hash_color(hash, stop.color);
513        }
514    };
515    match paint {
516        None => hash.u32(0),
517        Some(Paint::Solid { color }) => {
518            hash.u32(1);
519            hash_color(hash, *color);
520        }
521        Some(Paint::LinearGradient {
522            start,
523            end,
524            stops: list,
525            spread,
526        }) => {
527            hash.u32(2);
528            for value in [start.x, start.y, end.x, end.y] {
529                hash.f32(value);
530            }
531            stops(hash, list);
532            hash.u32(*spread as u32);
533        }
534        Some(Paint::RadialGradient {
535            center,
536            radius,
537            stops: list,
538            spread,
539        }) => {
540            hash.u32(3);
541            for value in [center.x, center.y, *radius] {
542                hash.f32(value);
543            }
544            stops(hash, list);
545            hash.u32(*spread as u32);
546        }
547        Some(Paint::ConicGradient {
548            center,
549            angle_degrees,
550            stops: list,
551        }) => {
552            hash.u32(4);
553            for value in [center.x, center.y, *angle_degrees] {
554                hash.f32(value);
555            }
556            stops(hash, list);
557        }
558    }
559}
560
561fn hash_node(hash: &mut StableHash, node: &EvaluatedNode, shapes: &[(Arc<ShapesPlan>, u128)]) {
562    let mut shape_index = 0;
563    hash_node_in(hash, node, shapes, &mut shape_index);
564}
565
566fn hash_layout(hash: &mut StableHash, layout: &NodeLayout) {
567    for value in [
568        layout.display as u32,
569        layout.flex_direction as u32,
570        layout.flex_wrap as u32,
571        layout.grid_auto_flow as u32,
572        layout.justify_content as u32,
573        layout.align_items as u32,
574        layout.align_content as u32,
575        layout.justify_items as u32,
576        layout.overflow as u32,
577        layout.position as u32,
578        layout.align_self.map_or(u32::MAX, |align| align as u32),
579        layout.justify_self.map_or(u32::MAX, |align| align as u32),
580    ] {
581        hash.u32(value);
582    }
583    // A track list's text is its canonical form.
584    for tracks in [
585        &layout.grid_template_columns,
586        &layout.grid_template_rows,
587        &layout.grid_auto_columns,
588        &layout.grid_auto_rows,
589    ] {
590        match tracks {
591            None => hash.u32(0),
592            Some(tracks) => {
593                hash.u32(1);
594                hash.bytes(tracks.to_string().as_bytes());
595            }
596        }
597    }
598    for placement in [layout.grid_column, layout.grid_row] {
599        hash.bytes(placement.to_string().as_bytes());
600    }
601    for value in [
602        layout.row_gap,
603        layout.column_gap,
604        layout.border_width,
605        layout.flex_grow,
606        layout.flex_shrink,
607        layout.aspect_ratio.unwrap_or(-1.0),
608    ] {
609        hash.f32(value);
610    }
611    hash_sides(hash, layout.padding);
612    hash_sides(hash, layout.margin);
613    for length in [
614        layout.width,
615        layout.height,
616        layout.min_width,
617        layout.min_height,
618        layout.max_width,
619        layout.max_height,
620        layout.flex_basis,
621    ]
622    .into_iter()
623    .chain(layout.inset)
624    {
625        hash_length(hash, length);
626    }
627}
628
629fn hash_node_in(
630    hash: &mut StableHash,
631    node: &EvaluatedNode,
632    shapes: &[(Arc<ShapesPlan>, u128)],
633    shape_index: &mut usize,
634) {
635    hash_layout(hash, &node.layout);
636    hash_paint(hash, node.paint.background.as_ref());
637    match &node.paint.border {
638        None => hash.u32(0),
639        Some((width, paint)) => {
640            hash.u32(1);
641            hash.f32(*width);
642            hash_paint(hash, Some(paint));
643        }
644    }
645    hash.f32(node.paint.border_radius);
646    match node.visual {
647        None => hash.u32(0),
648        Some(visual) => {
649            hash.u32(1);
650            for value in [
651                visual.opacity,
652                visual.translate.x,
653                visual.translate.y,
654                visual.scale.x,
655                visual.scale.y,
656                visual.rotation_degrees,
657            ] {
658                hash.f32(value);
659            }
660        }
661    }
662    hash.u32(u32::from(node.clip));
663    match &node.content {
664        NodeContent::Empty => hash.u32(0),
665        NodeContent::Children(children) => {
666            hash.u32(1);
667            hash.u64(children.len() as u64);
668            for child in children {
669                hash_node_in(hash, child, shapes, shape_index);
670            }
671        }
672        NodeContent::Text(text) => {
673            hash.u32(2);
674            hash.bytes(text.content.as_bytes());
675            match &text.font_family {
676                None => hash.u32(0),
677                Some(family) => {
678                    hash.u32(1);
679                    hash.bytes(family.as_bytes());
680                }
681            }
682            hash.f32(text.font_size);
683            hash_paint(hash, Some(&text.fill));
684            hash.f32(text.line_height);
685            hash.f32(text.letter_spacing);
686            hash.u32(u32::from(text.font_weight));
687            hash.u32(text.text_align as u32);
688            hash.u64(text.strokes.len() as u64);
689            for stroke in &text.strokes {
690                hash_color(hash, stroke.color);
691                hash.f32(stroke.width);
692            }
693            hash.u64(text.shadows.len() as u64);
694            for shadow in &text.shadows {
695                hash_color(hash, shadow.color);
696                hash.f32(shadow.offset.x);
697                hash.f32(shadow.offset.y);
698                hash.f32(shadow.blur);
699            }
700            // Nothing for a text without animators, so a static layout keeps its key.
701            if !text.animators.is_empty() {
702                crate::hash_sampled_animators(hash, &text.animators);
703            }
704            if let Some(fit) = text.font_size_fit {
705                hash.u32(0xf17);
706                hash.f32(fit.min);
707                hash.f32(fit.max.unwrap_or(-1.0));
708            }
709            if let Some(clamp) = &text.line_clamp {
710                hash.u32(0xc1a);
711                hash.u32(clamp.max_lines.unwrap_or(0));
712                match clamp.block_ellipsis.text() {
713                    None => hash.u32(0),
714                    Some(ellipsis) => {
715                        hash.u32(1);
716                        hash.bytes(ellipsis.as_bytes());
717                    }
718                }
719            }
720        }
721        NodeContent::Shape(_) => {
722            hash.u32(3);
723            let digest = shapes.get(*shape_index).map_or(0, |(_, digest)| *digest);
724            *shape_index += 1;
725            hash.bytes(&digest.to_le_bytes());
726        }
727    }
728}
729
730/// Approximate bytes a layout tree holds, for the plan budget. Its plan holds about as much again.
731#[must_use]
732pub(crate) fn layout_bytes(
733    node: &LayoutNode,
734    shape_items_bytes: &impl Fn(&[alpha2_model::ShapeItem]) -> usize,
735) -> usize {
736    fn keys<T>(animation: Option<&Animated<T>>) -> usize {
737        match animation {
738            Some(Animated::Keyframes { keyframes }) => {
739                keyframes.len() * size_of::<alpha2_model::Keyframe<T>>()
740            }
741            _ => 0,
742        }
743    }
744    let text = node.text.as_ref().map_or(0, |text| match text {
745        Animated::Constant { value } => value.len(),
746        Animated::Keyframes { keyframes } => keyframes
747            .iter()
748            .map(|keyframe| size_of::<alpha2_model::Keyframe<String>>() + keyframe.value.len())
749            .sum(),
750        Animated::Data(_) => 0,
751    });
752    let style = node.font_family.as_ref().map_or(0, String::len) + keys(node.font_size.as_ref());
753    let tracks = [
754        &node.grid_template_columns,
755        &node.grid_template_rows,
756        &node.grid_auto_columns,
757        &node.grid_auto_rows,
758    ]
759    .into_iter()
760    .flatten()
761    .map(|tracks| tracks.track_count() * size_of::<alpha2_model::TrackSize>())
762    .sum::<usize>();
763    let paints = |paint: Option<&Animated<Paint>>| match paint {
764        Some(Animated::Keyframes { keyframes }) => {
765            keyframes.len() * size_of::<alpha2_model::Keyframe<Paint>>()
766        }
767        Some(Animated::Constant { .. } | Animated::Data(_)) | None => 0,
768    };
769    let inset = node.inset.as_ref().map_or(0, |inset| {
770        [&inset.left, &inset.top, &inset.right, &inset.bottom]
771            .into_iter()
772            .map(|side| keys(side.as_ref()))
773            .sum()
774    });
775    size_of::<LayoutNode>()
776        + text
777        + style
778        + tracks
779        + node
780            .shape
781            .as_ref()
782            .map_or(0, |shape| shape_items_bytes(&shape.items))
783        + [
784            &node.gap,
785            &node.row_gap,
786            &node.column_gap,
787            &node.border_radius,
788        ]
789        .into_iter()
790        .map(|value| keys(value.as_ref()))
791        .sum::<usize>()
792        + keys(node.padding.as_ref())
793        + paints(node.background.as_ref())
794        + node.border.as_ref().map_or(0, |border| {
795            keys(Some(&border.width)) + paints(Some(&border.paint))
796        })
797        + [
798            &node.width,
799            &node.height,
800            &node.min_width,
801            &node.min_height,
802            &node.max_width,
803            &node.max_height,
804            &node.flex_basis,
805        ]
806        .into_iter()
807        .map(|length| keys(length.as_ref()))
808        .sum::<usize>()
809        + keys(node.margin.as_ref())
810        + keys(node.flex_grow.as_ref())
811        + keys(node.flex_shrink.as_ref())
812        + inset
813        + keys(node.opacity.as_ref())
814        + keys(node.translate.as_ref())
815        + keys(node.scale.as_ref())
816        + keys(node.rotation_degrees.as_ref())
817        + node
818            .children
819            .iter()
820            .map(|child| layout_bytes(child, shape_items_bytes))
821            .sum::<usize>()
822}
823
824/// A shapes or layout generator's tree, planned once. Other generators need none.
825#[derive(Clone, Debug, PartialEq)]
826pub enum GeneratorPlan {
827    /// A shapes generator's content tree.
828    Shapes(ShapesPlan),
829    /// A layout generator's box tree.
830    Layout(LayoutPlan),
831}
832
833impl GeneratorPlan {
834    /// The plan for `generator` on a canvas of `canvas` pixels, if it needs one.
835    #[must_use]
836    pub fn new(generator: &alpha2_model::Generator, canvas: (u32, u32)) -> Option<Self> {
837        match generator {
838            alpha2_model::Generator::Shapes { items } => Some(Self::Shapes(ShapesPlan::new(items))),
839            alpha2_model::Generator::Layout { root } => {
840                Some(Self::Layout(LayoutPlan::new(root, canvas)))
841            }
842            alpha2_model::Generator::Fill { .. } | alpha2_model::Generator::Text { .. } => None,
843        }
844    }
845
846    /// The shapes plan, for a shapes generator.
847    #[must_use]
848    pub const fn shapes(&self) -> Option<&ShapesPlan> {
849        match self {
850            Self::Shapes(plan) => Some(plan),
851            Self::Layout(_) => None,
852        }
853    }
854
855    /// The layout plan, for a layout generator.
856    #[must_use]
857    pub const fn layout(&self) -> Option<&LayoutPlan> {
858        match self {
859            Self::Layout(plan) => Some(plan),
860            Self::Shapes(_) => None,
861        }
862    }
863}
864
865#[cfg(test)]
866#[path = "layout_tests.rs"]
867mod tests;