1use 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#[derive(Clone, Debug)]
23pub struct LayoutPlan {
24 root: Box<LayoutNode>,
26 shapes: Vec<(Arc<ShapesPlan>, u128)>,
28 shapes_animate: bool,
30 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 #[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 #[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 #[must_use]
79 pub fn is_animated(&self) -> bool {
80 self.fixed.is_none()
81 }
82
83 #[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#[derive(Clone, Debug, PartialEq)]
107pub struct EvaluatedLayout {
108 pub root: EvaluatedNode,
110 pub time: MediaTime,
112 pub key: u128,
114}
115
116#[derive(Clone, Debug, PartialEq)]
118pub struct EvaluatedNode {
119 pub layout: NodeLayout,
121 pub paint: NodePaint,
123 pub visual: Option<NodeVisual>,
125 pub clip: bool,
127 pub content: NodeContent,
129}
130
131impl EvaluatedNode {
132 #[must_use]
134 pub const fn is_isolated(&self) -> bool {
135 self.visual.is_some() || self.clip
136 }
137}
138
139#[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#[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 pub row_gap: f32,
178 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 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 pub inset: [Option<LayoutLength>; 4],
206}
207
208#[derive(Clone, Debug, PartialEq)]
210pub struct NodePaint {
211 pub background: Option<Paint>,
213 pub border: Option<(f32, Paint)>,
215 pub border_radius: f32,
217}
218
219#[derive(Copy, Clone, Debug, PartialEq)]
221pub struct NodeVisual {
222 pub opacity: f32,
224 pub translate: Vec2,
226 pub scale: Vec2,
228 pub rotation_degrees: f32,
230}
231
232#[derive(Clone, Debug, PartialEq)]
234pub enum NodeContent {
235 Empty,
237 Children(Vec<EvaluatedNode>),
239 Text(Box<EvaluatedText>),
241 Shape(Arc<ShapesPlan>),
243}
244
245#[derive(Clone, Debug, PartialEq)]
247pub struct EvaluatedText {
248 pub content: alpha2_model::TextContent,
250 pub font_family: Option<String>,
252 pub font_size: f32,
254 pub fill: Paint,
256 pub line_height: f32,
258 pub letter_spacing: f32,
260 pub font_weight: u16,
262 pub text_align: TextAlign,
264 pub strokes: Vec<TextStroke>,
266 pub shadows: Vec<TextShadow>,
268 pub animators: Vec<crate::SampledAnimator>,
270 pub animator_grouping: alpha2_model::AnimatorGrouping,
272 pub animator_pivot: Vec2,
274 pub advance_headroom: f32,
277 pub font_size_fit: Option<alpha2_model::FontSizeFit>,
279 pub line_clamp: Option<alpha2_model::LineClamp>,
281}
282
283const MOST_FRACTION: f32 = alpha2_model::MAX_LAYOUT_PX;
286
287fn fraction(value: f32) -> f32 {
288 value.clamp(-MOST_FRACTION, MOST_FRACTION)
289}
290
291fn flex_factor(animation: Option<&Animated<f32>>, time: MediaTime, default: f32) -> f32 {
292 animation.map_or(default, |value| {
293 sample_scalar(value, time, &SampleContext::NONE).clamp(0.0, alpha2_model::MAX_FLEX_FACTOR)
294 })
295}
296
297fn size_or(
298 animation: Option<&Animated<alpha2_model::LayoutSize>>,
299 time: MediaTime,
300 default: f32,
301) -> f32 {
302 animation.map_or(default, |value| {
303 sample_size(value, time).clamp(0.0, MOST_FRACTION)
304 })
305}
306
307fn length(animation: Option<&Animated<LayoutLength>>, time: MediaTime) -> Option<LayoutLength> {
308 animation.map(|value| {
309 let length = sample_length(value, time);
310 let bound = match length {
311 LayoutLength::Percent(_) => alpha2_model::MAX_LAYOUT_PERCENT,
312 LayoutLength::Fraction(_) | LayoutLength::Px(_) => MOST_FRACTION,
313 };
314 length.with_value(length.value().clamp(-bound, bound))
315 })
316}
317
318fn size(animation: Option<&Animated<LayoutLength>>, time: MediaTime) -> Option<LayoutLength> {
319 length(animation, time).map(|length| length.with_value(length.value().max(0.0)))
320}
321
322fn node_layout(node: &LayoutNode, time: MediaTime, border_width: f32) -> NodeLayout {
323 let insets = |value: Option<&Animated<alpha2_model::Insets>>| {
324 value.map_or_else(Sides::default, |value| {
325 Sides::from_array(sample_insets(value, time).map(fraction))
326 })
327 };
328 let padding = Sides::from_array(
329 insets(node.padding.as_ref())
330 .to_array()
331 .map(|side| side.max(0.0)),
332 );
333 let inset = node.inset.as_ref().map_or([None; 4], |inset| {
334 [
335 length(inset.left.as_ref(), time),
336 length(inset.top.as_ref(), time),
337 length(inset.right.as_ref(), time),
338 length(inset.bottom.as_ref(), time),
339 ]
340 });
341 let gap = size_or(node.gap.as_ref(), time, 0.0);
342 NodeLayout {
343 display: node.display.unwrap_or_default(),
344 flex_direction: node.flex_direction.unwrap_or_default(),
345 flex_wrap: node.flex_wrap.unwrap_or_default(),
346 grid_template_columns: node.grid_template_columns.clone(),
347 grid_template_rows: node.grid_template_rows.clone(),
348 grid_auto_columns: node.grid_auto_columns.clone(),
349 grid_auto_rows: node.grid_auto_rows.clone(),
350 grid_auto_flow: node.grid_auto_flow.unwrap_or_default(),
351 row_gap: size_or(node.row_gap.as_ref(), time, gap),
352 column_gap: size_or(node.column_gap.as_ref(), time, gap),
353 justify_content: node.justify_content.unwrap_or_default(),
354 align_items: node.align_items.unwrap_or_default(),
355 align_content: node.align_content.unwrap_or_default(),
356 justify_items: node.justify_items.unwrap_or_default(),
357 padding,
358 border_width,
359 overflow: node.overflow.unwrap_or_default(),
360 width: size(node.width.as_ref(), time),
361 height: size(node.height.as_ref(), time),
362 min_width: size(node.min_width.as_ref(), time),
363 min_height: size(node.min_height.as_ref(), time),
364 max_width: size(node.max_width.as_ref(), time),
365 max_height: size(node.max_height.as_ref(), time),
366 aspect_ratio: node.aspect_ratio,
367 margin: insets(node.margin.as_ref()),
368 flex_grow: flex_factor(node.flex_grow.as_ref(), time, 0.0),
369 flex_shrink: flex_factor(node.flex_shrink.as_ref(), time, 1.0),
370 flex_basis: size(node.flex_basis.as_ref(), time),
371 align_self: node.align_self,
372 justify_self: node.justify_self,
373 grid_column: node.grid_column.unwrap_or_default(),
374 grid_row: node.grid_row.unwrap_or_default(),
375 position: node.position.unwrap_or_default(),
376 inset,
377 }
378}
379
380fn text_style(node: &LayoutNode, time: MediaTime, inherited: &LayoutTextStyle) -> LayoutTextStyle {
382 LayoutTextStyle {
383 font_family: node
384 .font_family
385 .clone()
386 .or_else(|| inherited.font_family.clone()),
387 font_size: node.font_size.as_ref().map_or(inherited.font_size, |size| {
388 sample_size(size, time).max(f32::MIN_POSITIVE)
389 }),
390 fill: node.fill.clone().unwrap_or_else(|| inherited.fill.clone()),
391 line_height: node.line_height.unwrap_or(inherited.line_height),
392 letter_spacing: node.letter_spacing.unwrap_or(inherited.letter_spacing),
393 font_weight: node.font_weight.unwrap_or(inherited.font_weight),
394 text_align: node.text_align.unwrap_or(inherited.text_align),
395 strokes: node
396 .strokes
397 .clone()
398 .unwrap_or_else(|| inherited.strokes.clone()),
399 shadows: node
400 .shadows
401 .clone()
402 .unwrap_or_else(|| inherited.shadows.clone()),
403 }
404}
405
406fn evaluate_node<'a>(
407 node: &LayoutNode,
408 time: MediaTime,
409 shapes: &mut impl Iterator<Item = &'a (Arc<ShapesPlan>, u128)>,
410 inherited: &LayoutTextStyle,
411) -> EvaluatedNode {
412 let border = node.border.as_ref().map(|border| {
413 (
414 sample_size(&border.width, time).clamp(0.0, MOST_FRACTION),
415 sample_paint(&border.paint, time),
416 )
417 });
418 let layout = node_layout(node, time, border.as_ref().map_or(0.0, |(width, _)| *width));
419 let paint = NodePaint {
420 background: node
421 .background
422 .as_ref()
423 .map(|paint| sample_paint(paint, time)),
424 border,
425 border_radius: size_or(node.border_radius.as_ref(), time, 0.0),
426 };
427 let visual = node.has_visual().then(|| NodeVisual {
428 opacity: node.opacity.as_ref().map_or(1.0, |value| {
429 sample_scalar(value, time, &SampleContext::NONE).clamp(0.0, 1.0)
430 }),
431 translate: node.translate.as_ref().map_or_else(Vec2::default, |value| {
432 let offset = sample_offset(value, time);
433 Vec2::new(fraction(offset.x), fraction(offset.y))
434 }),
435 scale: node.scale.as_ref().map_or(Vec2::new(1.0, 1.0), |value| {
436 sample_vec2(value, time, &SampleContext::NONE)
437 }),
438 rotation_degrees: node.rotation_degrees.as_ref().map_or(0.0, |value| {
439 sample_scalar(value, time, &SampleContext::NONE)
440 }),
441 });
442 let style = text_style(node, time, inherited);
443 let content = if let Some(text) = &node.text {
444 NodeContent::Text(Box::new(EvaluatedText {
445 content: sample_hold(text, time),
446 font_family: style.font_family,
447 font_size: style.font_size,
448 fill: style.fill.clone(),
449 line_height: style.line_height,
450 letter_spacing: style.letter_spacing,
451 font_weight: style.font_weight,
452 text_align: style.text_align,
453 strokes: style.strokes.clone(),
454 shadows: style.shadows.clone(),
455 animators: crate::sample_text_animators(&node.text_animators, time),
456 animator_grouping: node.text_animator_grouping.unwrap_or_default(),
457 animator_pivot: node.text_animator_pivot.unwrap_or(Vec2::new(0.5, 0.5)),
458 advance_headroom: crate::advance_headroom(&node.text_animators, &[]),
459 font_size_fit: node.font_size_fit.map(|fit| alpha2_model::FontSizeFit {
460 min: fit.min.value(),
461 max: fit.max.map(alpha2_model::LayoutSize::value),
462 }),
463 line_clamp: node.line_clamp.clone(),
464 }))
465 } else if node.shape.is_some() {
466 let (plan, _) = shapes.next().expect("one plan per shape node");
467 NodeContent::Shape(Arc::clone(plan))
468 } else if node.children.is_empty() {
469 NodeContent::Empty
470 } else {
471 NodeContent::Children(
472 node.children
473 .iter()
474 .map(|child| evaluate_node(child, time, shapes, &style))
475 .collect(),
476 )
477 };
478 EvaluatedNode {
479 layout,
480 paint,
481 visual,
482 clip: matches!(node.overflow, Some(Overflow::Hidden)),
483 content,
484 }
485}
486
487fn hash_length(hash: &mut StableHash, length: Option<LayoutLength>) {
488 match length {
489 None => hash.u32(0),
490 Some(LayoutLength::Fraction(value)) => {
491 hash.u32(1);
492 hash.f32(value);
493 }
494 Some(LayoutLength::Percent(value)) => {
495 hash.u32(2);
496 hash.f32(value);
497 }
498 Some(LayoutLength::Px(value)) => {
499 hash.u32(3);
500 hash.f32(value);
501 }
502 }
503}
504
505fn hash_sides(hash: &mut StableHash, sides: Sides) {
506 for side in sides.to_array() {
507 hash.f32(side);
508 }
509}
510
511fn hash_color(hash: &mut StableHash, color: Rgba) {
512 for component in [color.red, color.green, color.blue, color.alpha] {
513 hash.f32(component);
514 }
515}
516
517fn hash_run_styles(hash: &mut StableHash, runs: &[alpha2_model::TextRun]) {
518 if !runs.iter().any(|run| run.style.is_some()) {
519 return;
520 }
521 hash.u64(runs.len() as u64);
522 for run in runs {
523 hash.u64(run.text.len() as u64);
524 let Some(style) = &run.style else {
525 hash.u32(0);
526 continue;
527 };
528 hash.u32(1);
529 match &style.font_family {
530 None => hash.u32(0),
531 Some(None) => hash.u32(1),
532 Some(Some(family)) => {
533 hash.u32(2);
534 hash.bytes(family.as_bytes());
535 }
536 }
537 hash.u32(style.font_weight.map_or(0, |weight| u32::from(weight) + 1));
538 hash.u32(
539 style
540 .font_style
541 .map_or(0, |font_style| font_style as u32 + 1),
542 );
543 hash.f32(style.font_scale.as_ref().map_or(1.0, |scale| {
544 crate::sample_scalar(scale, MediaTime::ZERO, &SampleContext::NONE)
545 }));
546 hash.f32(style.letter_spacing.unwrap_or(f32::NAN));
547 hash_paint(hash, style.fill.as_ref());
548 match &style.strokes {
549 None => hash.u32(0),
550 Some(strokes) => {
551 hash.u64(strokes.len() as u64 + 1);
552 for stroke in strokes {
553 hash_color(hash, stroke.color);
554 hash.f32(stroke.width);
555 }
556 }
557 }
558 match style.background_color {
559 None => hash.u32(0),
560 Some(color) => {
561 hash.u32(1);
562 hash_color(hash, color);
563 }
564 }
565 for flag in [style.underline, style.line_through] {
566 hash.u32(flag.map_or(0, |flag| u32::from(flag) + 1));
567 }
568 }
569}
570
571fn hash_paint(hash: &mut StableHash, paint: Option<&Paint>) {
572 let stops = |hash: &mut StableHash, stops: &[alpha2_model::GradientStop]| {
573 hash.u64(stops.len() as u64);
574 for stop in stops {
575 hash.f32(stop.offset);
576 hash_color(hash, stop.color);
577 }
578 };
579 match paint {
580 None => hash.u32(0),
581 Some(Paint::Solid { color }) => {
582 hash.u32(1);
583 hash_color(hash, *color);
584 }
585 Some(Paint::LinearGradient {
586 start,
587 end,
588 stops: list,
589 spread,
590 }) => {
591 hash.u32(2);
592 for value in [start.x, start.y, end.x, end.y] {
593 hash.f32(value);
594 }
595 stops(hash, list);
596 hash.u32(*spread as u32);
597 }
598 Some(Paint::RadialGradient {
599 center,
600 radius,
601 stops: list,
602 spread,
603 }) => {
604 hash.u32(3);
605 for value in [center.x, center.y, *radius] {
606 hash.f32(value);
607 }
608 stops(hash, list);
609 hash.u32(*spread as u32);
610 }
611 Some(Paint::ConicGradient {
612 center,
613 angle_degrees,
614 stops: list,
615 }) => {
616 hash.u32(4);
617 for value in [center.x, center.y, *angle_degrees] {
618 hash.f32(value);
619 }
620 stops(hash, list);
621 }
622 }
623}
624
625fn hash_node(hash: &mut StableHash, node: &EvaluatedNode, shapes: &[(Arc<ShapesPlan>, u128)]) {
626 let mut shape_index = 0;
627 hash_node_in(hash, node, shapes, &mut shape_index);
628}
629
630fn hash_layout(hash: &mut StableHash, layout: &NodeLayout) {
631 for value in [
632 layout.display as u32,
633 layout.flex_direction as u32,
634 layout.flex_wrap as u32,
635 layout.grid_auto_flow as u32,
636 layout.justify_content as u32,
637 layout.align_items as u32,
638 layout.align_content as u32,
639 layout.justify_items as u32,
640 layout.overflow as u32,
641 layout.position as u32,
642 layout.align_self.map_or(u32::MAX, |align| align as u32),
643 layout.justify_self.map_or(u32::MAX, |align| align as u32),
644 ] {
645 hash.u32(value);
646 }
647 for tracks in [
649 &layout.grid_template_columns,
650 &layout.grid_template_rows,
651 &layout.grid_auto_columns,
652 &layout.grid_auto_rows,
653 ] {
654 match tracks {
655 None => hash.u32(0),
656 Some(tracks) => {
657 hash.u32(1);
658 hash.bytes(tracks.to_string().as_bytes());
659 }
660 }
661 }
662 for placement in [layout.grid_column, layout.grid_row] {
663 hash.bytes(placement.to_string().as_bytes());
664 }
665 for value in [
666 layout.row_gap,
667 layout.column_gap,
668 layout.border_width,
669 layout.flex_grow,
670 layout.flex_shrink,
671 layout.aspect_ratio.unwrap_or(-1.0),
672 ] {
673 hash.f32(value);
674 }
675 hash_sides(hash, layout.padding);
676 hash_sides(hash, layout.margin);
677 for length in [
678 layout.width,
679 layout.height,
680 layout.min_width,
681 layout.min_height,
682 layout.max_width,
683 layout.max_height,
684 layout.flex_basis,
685 ]
686 .into_iter()
687 .chain(layout.inset)
688 {
689 hash_length(hash, length);
690 }
691}
692
693fn hash_text_motion(hash: &mut StableHash, text: &EvaluatedText) {
696 if text.animator_grouping != alpha2_model::AnimatorGrouping::Character
697 || text.animator_pivot != Vec2::new(0.5, 0.5)
698 || text.advance_headroom > 1.0
699 {
700 hash.u32(0x9e0);
701 hash.u32(text.animator_grouping as u32);
702 hash.f32(text.animator_pivot.x);
703 hash.f32(text.animator_pivot.y);
704 hash.f32(text.advance_headroom);
705 }
706}
707
708fn hash_node_in(
709 hash: &mut StableHash,
710 node: &EvaluatedNode,
711 shapes: &[(Arc<ShapesPlan>, u128)],
712 shape_index: &mut usize,
713) {
714 hash_layout(hash, &node.layout);
715 hash_paint(hash, node.paint.background.as_ref());
716 match &node.paint.border {
717 None => hash.u32(0),
718 Some((width, paint)) => {
719 hash.u32(1);
720 hash.f32(*width);
721 hash_paint(hash, Some(paint));
722 }
723 }
724 hash.f32(node.paint.border_radius);
725 match node.visual {
726 None => hash.u32(0),
727 Some(visual) => {
728 hash.u32(1);
729 for value in [
730 visual.opacity,
731 visual.translate.x,
732 visual.translate.y,
733 visual.scale.x,
734 visual.scale.y,
735 visual.rotation_degrees,
736 ] {
737 hash.f32(value);
738 }
739 }
740 }
741 hash.u32(u32::from(node.clip));
742 match &node.content {
743 NodeContent::Empty => hash.u32(0),
744 NodeContent::Children(children) => {
745 hash.u32(1);
746 hash.u64(children.len() as u64);
747 for child in children {
748 hash_node_in(hash, child, shapes, shape_index);
749 }
750 }
751 NodeContent::Text(text) => {
752 hash.u32(2);
753 hash.bytes(text.content.text().as_bytes());
754 hash_run_styles(hash, text.content.runs());
755 match &text.font_family {
756 None => hash.u32(0),
757 Some(family) => {
758 hash.u32(1);
759 hash.bytes(family.as_bytes());
760 }
761 }
762 hash.f32(text.font_size);
763 hash_paint(hash, Some(&text.fill));
764 hash.f32(text.line_height);
765 hash.f32(text.letter_spacing);
766 hash.u32(u32::from(text.font_weight));
767 hash.u32(text.text_align as u32);
768 hash.u64(text.strokes.len() as u64);
769 for stroke in &text.strokes {
770 hash_color(hash, stroke.color);
771 hash.f32(stroke.width);
772 }
773 hash.u64(text.shadows.len() as u64);
774 for shadow in &text.shadows {
775 hash_color(hash, shadow.color);
776 hash.f32(shadow.offset.x);
777 hash.f32(shadow.offset.y);
778 hash.f32(shadow.blur);
779 }
780 if !text.animators.is_empty() {
782 crate::hash_sampled_animators(hash, &text.animators);
783 hash_text_motion(hash, text);
784 }
785 if let Some(fit) = text.font_size_fit {
786 hash.u32(0xf17);
787 hash.f32(fit.min);
788 hash.f32(fit.max.unwrap_or(-1.0));
789 }
790 if let Some(clamp) = &text.line_clamp {
791 hash.u32(0xc1a);
792 hash.u32(clamp.max_lines.unwrap_or(0));
793 match clamp.block_ellipsis.text() {
794 None => hash.u32(0),
795 Some(ellipsis) => {
796 hash.u32(1);
797 hash.bytes(ellipsis.as_bytes());
798 }
799 }
800 }
801 }
802 NodeContent::Shape(_) => {
803 hash.u32(3);
804 let digest = shapes.get(*shape_index).map_or(0, |(_, digest)| *digest);
805 *shape_index += 1;
806 hash.bytes(&digest.to_le_bytes());
807 }
808 }
809}
810
811#[must_use]
813pub(crate) fn layout_bytes(
814 node: &LayoutNode,
815 shape_items_bytes: &impl Fn(&[alpha2_model::ShapeItem]) -> usize,
816) -> usize {
817 fn keys<T>(animation: Option<&Animated<T>>) -> usize {
818 match animation {
819 Some(Animated::Keyframes { keyframes, .. }) => {
820 keyframes.len() * size_of::<alpha2_model::Keyframe<T>>()
821 }
822 _ => 0,
823 }
824 }
825 let text = node.text.as_ref().map_or(0, |text| match text {
826 Animated::Constant { value } => value.len(),
827 Animated::Keyframes { keyframes, .. } => keyframes
828 .iter()
829 .map(|keyframe| {
830 size_of::<alpha2_model::Keyframe<alpha2_model::TextContent>>()
831 + keyframe.value.len()
832 })
833 .sum(),
834 Animated::Data(_) | Animated::Split { .. } => 0,
835 });
836 let style = node.font_family.as_ref().map_or(0, String::len) + keys(node.font_size.as_ref());
837 let tracks = [
838 &node.grid_template_columns,
839 &node.grid_template_rows,
840 &node.grid_auto_columns,
841 &node.grid_auto_rows,
842 ]
843 .into_iter()
844 .flatten()
845 .map(|tracks| tracks.track_count() * size_of::<alpha2_model::TrackSize>())
846 .sum::<usize>();
847 let paints = |paint: Option<&Animated<Paint>>| match paint {
848 Some(Animated::Keyframes { keyframes, .. }) => {
849 keyframes.len() * size_of::<alpha2_model::Keyframe<Paint>>()
850 }
851 Some(Animated::Constant { .. } | Animated::Data(_) | Animated::Split { .. }) | None => 0,
852 };
853 let inset = node.inset.as_ref().map_or(0, |inset| {
854 [&inset.left, &inset.top, &inset.right, &inset.bottom]
855 .into_iter()
856 .map(|side| keys(side.as_ref()))
857 .sum()
858 });
859 size_of::<LayoutNode>()
860 + text
861 + style
862 + tracks
863 + node
864 .shape
865 .as_ref()
866 .map_or(0, |shape| shape_items_bytes(&shape.items))
867 + [
868 &node.gap,
869 &node.row_gap,
870 &node.column_gap,
871 &node.border_radius,
872 ]
873 .into_iter()
874 .map(|value| keys(value.as_ref()))
875 .sum::<usize>()
876 + keys(node.padding.as_ref())
877 + paints(node.background.as_ref())
878 + node.border.as_ref().map_or(0, |border| {
879 keys(Some(&border.width)) + paints(Some(&border.paint))
880 })
881 + [
882 &node.width,
883 &node.height,
884 &node.min_width,
885 &node.min_height,
886 &node.max_width,
887 &node.max_height,
888 &node.flex_basis,
889 ]
890 .into_iter()
891 .map(|length| keys(length.as_ref()))
892 .sum::<usize>()
893 + keys(node.margin.as_ref())
894 + keys(node.flex_grow.as_ref())
895 + keys(node.flex_shrink.as_ref())
896 + inset
897 + keys(node.opacity.as_ref())
898 + keys(node.translate.as_ref())
899 + keys(node.scale.as_ref())
900 + keys(node.rotation_degrees.as_ref())
901 + node
902 .children
903 .iter()
904 .map(|child| layout_bytes(child, shape_items_bytes))
905 .sum::<usize>()
906}
907
908#[derive(Clone, Debug, PartialEq)]
910pub enum GeneratorPlan {
911 Shapes(ShapesPlan),
913 Layout(LayoutPlan),
915}
916
917impl GeneratorPlan {
918 #[must_use]
920 pub fn new(generator: &alpha2_model::Generator, canvas: (u32, u32)) -> Option<Self> {
921 match generator {
922 alpha2_model::Generator::Shapes { items } => Some(Self::Shapes(ShapesPlan::new(items))),
923 alpha2_model::Generator::Layout { root } => {
924 Some(Self::Layout(LayoutPlan::new(root, canvas)))
925 }
926 alpha2_model::Generator::Fill { .. }
927 | alpha2_model::Generator::Text { .. }
928 | alpha2_model::Generator::Effect { .. } => None,
929 }
930 }
931
932 #[must_use]
934 pub const fn shapes(&self) -> Option<&ShapesPlan> {
935 match self {
936 Self::Shapes(plan) => Some(plan),
937 Self::Layout(_) => None,
938 }
939 }
940
941 #[must_use]
943 pub const fn layout(&self) -> Option<&LayoutPlan> {
944 match self {
945 Self::Layout(plan) => Some(plan),
946 Self::Shapes(_) => None,
947 }
948 }
949}
950
951#[cfg(test)]
952#[path = "layout_tests.rs"]
953mod tests;