Skip to main content

alpha2_model/
shapes.rs

1//! The content tree of a shapes generator: geometry, paints and modifiers in the order an
2//! After Effects or Lottie shape layer lists them.
3//!
4//! Positions and sizes are normalized to the generator's picture, `(0, 0)` top-left to
5//! `(1, 1)` bottom-right; lengths (radii, stroke widths, dashes) are fractions of the
6//! picture's shorter side. Rotation and scale act in pixel space, so a rotated square stays
7//! square on a wide canvas.
8
9use crate::animation::{opaque, unit_scale, valid_keyframes, visit_keyed, visit_keyed_point};
10use crate::checks::{
11    ValueIssue, ValueProblem, any, non_negative, point, scalar, unit, validate_paint, vec2,
12};
13use crate::{Animated, AnimatedPoint, Paint, Vec2};
14use serde::{Deserialize, Serialize};
15use std::fmt;
16
17/// Most items one shapes generator holds, including nested groups and their items.
18pub const MAX_SHAPE_ITEMS: usize = 1_024;
19/// Deepest group nesting in one shapes generator.
20pub const MAX_SHAPE_DEPTH: usize = 32;
21/// Most vertices one path holds, over all its subpaths.
22pub const MAX_PATH_VERTICES: usize = 4_096;
23/// Most subpaths one path holds.
24pub const MAX_PATH_SUBPATHS: usize = 256;
25/// Most entries in a stroke's dash pattern.
26pub const MAX_DASH_ENTRIES: usize = 16;
27/// Most points a polystar has. A fractional count is valid; the fraction is dropped when
28/// drawn.
29pub const MAX_POLYSTAR_POINTS: f32 = 100.0;
30/// Fewest points a polystar has.
31pub const MIN_POLYSTAR_POINTS: f32 = 3.0;
32
33/// One entry of a shapes generator's content tree.
34///
35/// A group is read front to back. Geometry accumulates in its group; a fill or stroke paints
36/// the geometry listed before it in the same group (nested groups included), and a trim cuts
37/// and replaces that geometry. Earlier paints draw on top of later ones, as in After Effects
38/// and Lottie.
39#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
42pub enum ShapeItem {
43    /// Items drawn together through one transform and opacity. Their geometry also counts as the
44    /// enclosing group's for paints and trims after the group.
45    Group {
46        /// The group's items, front first.
47        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_SHAPE_ITEMS }>")]
48        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_SHAPE_ITEMS)))]
49        items: Vec<ShapeItem>,
50        /// Where the group lies, and how opaque it is.
51        #[serde(default)]
52        transform: ShapeTransform,
53    },
54    /// A rectangle, optionally with rounded corners.
55    Rectangle(RectangleGeometry),
56    /// An ellipse.
57    Ellipse(EllipseGeometry),
58    /// A regular polygon or star.
59    Polystar(PolystarGeometry),
60    /// A Bezier path.
61    Path(PathGeometry),
62    /// Paints the inside of the geometry listed before it in its group, as one compound path
63    /// under `rule`. Open paths are closed for it.
64    Fill {
65        /// What covers it.
66        paint: Animated<Paint>,
67        /// Opacity in `0..=1`.
68        #[serde(default = "opaque")]
69        opacity: Animated<f32>,
70        /// Which regions of the compound path are inside.
71        #[serde(default)]
72        rule: FillRule,
73    },
74    /// Strokes the geometry listed before it in its group.
75    Stroke(StrokeItem),
76    /// Keeps part of the geometry listed before it in its group, by length.
77    Trim(TrimItem),
78}
79
80fn zero() -> Animated<f32> {
81    Animated::Constant { value: 0.0 }
82}
83
84/// A geometry alone, as a mask's outline is.
85#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
86#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
87#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
88pub enum ShapeGeometry {
89    /// A rectangle, optionally with rounded corners.
90    Rectangle(RectangleGeometry),
91    /// An ellipse.
92    Ellipse(EllipseGeometry),
93    /// A regular polygon or star.
94    Polystar(PolystarGeometry),
95    /// A Bezier path.
96    Path(PathGeometry),
97}
98
99/// A rectangle about its centre, turned clockwise about it. Its outline starts at the
100/// top-right corner and runs clockwise.
101#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
102#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
103#[serde(deny_unknown_fields)]
104pub struct RectangleGeometry {
105    /// Centre.
106    pub center: AnimatedPoint,
107    /// Full width and height before rotation: x a fraction of the picture's width, y of its
108    /// height. Non-negative.
109    pub size: Animated<Vec2>,
110    /// Corner radius, as a fraction of the shorter side. Non-negative; capped at half the
111    /// rectangle.
112    #[serde(default = "zero")]
113    pub corner_radius: Animated<f32>,
114    /// Clockwise rotation about the centre, in degrees.
115    #[serde(default = "zero")]
116    pub rotation_degrees: Animated<f32>,
117}
118
119/// The ellipse inscribed in a size, turned clockwise about its centre. Its outline starts at
120/// the top and runs clockwise.
121#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
122#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
123#[serde(deny_unknown_fields)]
124pub struct EllipseGeometry {
125    /// Centre.
126    pub center: AnimatedPoint,
127    /// Full width and height before rotation: x a fraction of the picture's width, y of its
128    /// height. Non-negative.
129    pub size: Animated<Vec2>,
130    /// Clockwise rotation about the centre, in degrees.
131    #[serde(default = "zero")]
132    pub rotation_degrees: Animated<f32>,
133}
134
135/// A regular polygon or star, its first point straight up from the centre before rotation,
136/// the rest clockwise.
137#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
138#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
139#[serde(deny_unknown_fields)]
140pub struct PolystarGeometry {
141    /// A polygon or a star.
142    pub kind: PolystarKind,
143    /// Centre.
144    pub center: AnimatedPoint,
145    /// Number of points (polygon corners or star tips), from [`MIN_POLYSTAR_POINTS`] to
146    /// [`MAX_POLYSTAR_POINTS`]. A fraction is dropped when drawn, as Lottie does, so an animated
147    /// count changes one whole point at a time.
148    pub points: Animated<f32>,
149    /// Distance of the points from the centre, as a fraction of the shorter side. Non-negative.
150    pub outer_radius: Animated<f32>,
151    /// A star's distance of its inner corners from the centre. Non-negative.
152    #[serde(default = "zero")]
153    pub inner_radius: Animated<f32>,
154    /// How round the outer corners are, in `0..=1`: 0 sharp, 1 a smooth curve through them.
155    #[serde(default = "zero")]
156    pub outer_roundness: Animated<f32>,
157    /// How round a star's inner corners are, in `0..=1`.
158    #[serde(default = "zero")]
159    pub inner_roundness: Animated<f32>,
160    /// Clockwise rotation about the centre, in degrees.
161    #[serde(default = "zero")]
162    pub rotation_degrees: Animated<f32>,
163}
164
165/// What kind of figure a polystar is.
166#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
167#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
168#[serde(rename_all = "snake_case")]
169pub enum PolystarKind {
170    /// Points joined by inner corners.
171    #[default]
172    Star,
173    /// Points joined by straight sides.
174    Polygon,
175}
176
177/// A path, animated as one value.
178///
179/// Keyframes must agree in structure: the same subpath count, each closed or open alike with
180/// the same vertex count. Between keyframes every point and tangent moves linearly.
181#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
182#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
183#[serde(deny_unknown_fields)]
184pub struct PathGeometry {
185    /// The path.
186    pub path: Animated<Path>,
187}
188
189/// One or more subpaths.
190#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
191#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
192#[serde(deny_unknown_fields)]
193pub struct Path {
194    /// The subpaths, at most [`MAX_PATH_SUBPATHS`], with at most [`MAX_PATH_VERTICES`] vertices
195    /// in total.
196    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_PATH_SUBPATHS }>")]
197    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_PATH_SUBPATHS)))]
198    pub subpaths: Vec<Subpath>,
199}
200
201/// A run of vertices joined by cubic Bezier segments.
202#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
203#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
204#[serde(deny_unknown_fields)]
205pub struct Subpath {
206    /// Whether a segment joins the last vertex back to the first.
207    #[serde(default)]
208    pub closed: bool,
209    /// The vertices, in order.
210    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_PATH_VERTICES }>")]
211    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_PATH_VERTICES)))]
212    pub vertices: Vec<PathVertex>,
213}
214
215/// A path vertex and its tangents. The segment from `a` to `b` is the cubic Bezier through
216/// `a.point`, `a.point + a.out_tangent`, `b.point + b.in_tangent` and `b.point`; zero tangents
217/// make it straight.
218#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
219#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
220#[serde(deny_unknown_fields)]
221pub struct PathVertex {
222    /// Where the vertex lies.
223    pub point: Vec2,
224    /// The control point of the segment ending here, relative to `point`.
225    #[serde(default)]
226    pub in_tangent: Vec2,
227    /// The control point of the segment starting here, relative to `point`.
228    #[serde(default)]
229    pub out_tangent: Vec2,
230}
231
232/// A group's placement. In pixel space: translate by `position`, rotate, scale, then
233/// translate by minus `anchor`, so `anchor` lands on `position`. The default is identity.
234#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
235#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
236#[serde(deny_unknown_fields)]
237pub struct ShapeTransform {
238    /// The point of the items that is placed at `position`.
239    #[serde(default = "origin")]
240    pub anchor: Animated<Vec2>,
241    /// Where `anchor` is placed.
242    #[serde(default)]
243    pub position: AnimatedPoint,
244    /// Per-axis scale; 1 leaves the items unscaled. Stroke widths scale with it.
245    #[serde(default = "unit_scale")]
246    pub scale: Animated<Vec2>,
247    /// Clockwise rotation, in degrees.
248    #[serde(default = "zero")]
249    pub rotation_degrees: Animated<f32>,
250    /// Opacity of the group as a whole, in `0..=1`; overlapping items are composited first and
251    /// faded together.
252    #[serde(default = "opaque")]
253    pub opacity: Animated<f32>,
254}
255
256fn origin() -> Animated<Vec2> {
257    Animated::Constant {
258        value: Vec2::new(0.0, 0.0),
259    }
260}
261
262impl Default for ShapeTransform {
263    fn default() -> Self {
264        Self {
265            anchor: origin(),
266            position: AnimatedPoint::default(),
267            scale: unit_scale(),
268            rotation_degrees: zero(),
269            opacity: opaque(),
270        }
271    }
272}
273
274/// A stroke along geometry, centred on its outline.
275#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
276#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
277#[serde(deny_unknown_fields)]
278pub struct StrokeItem {
279    /// What covers the stroke.
280    pub paint: Animated<Paint>,
281    /// Full width, as a fraction of the shorter side. Non-negative; zero draws nothing.
282    pub width: Animated<f32>,
283    /// Opacity in `0..=1`.
284    #[serde(default = "opaque")]
285    pub opacity: Animated<f32>,
286    /// How segments meet.
287    #[serde(default)]
288    pub join: LineJoin,
289    /// Longest a miter join reaches, as a multiple of half the width, before it is beveled. At
290    /// least 1.
291    #[serde(default = "four")]
292    pub miter_limit: f32,
293    /// How open ends look.
294    #[serde(default)]
295    pub cap: LineCap,
296    /// Dashes, or a solid stroke when absent.
297    #[serde(default)]
298    pub dash: Option<Dash>,
299}
300
301const fn four() -> f32 {
302    4.0
303}
304
305/// How stroke segments meet at a vertex.
306#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
307#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
308#[serde(rename_all = "snake_case")]
309pub enum LineJoin {
310    /// Extended edges meeting at a point, up to the miter limit.
311    #[default]
312    Miter,
313    /// A circular arc.
314    Round,
315    /// A straight cut across the corner.
316    Bevel,
317}
318
319/// How an open stroke ends.
320#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
321#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
322#[serde(rename_all = "snake_case")]
323pub enum LineCap {
324    /// Flat at the end point.
325    #[default]
326    Butt,
327    /// A half circle past the end point.
328    Round,
329    /// A half square past the end point.
330    Square,
331}
332
333/// A dash pattern.
334#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
335#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
336#[serde(deny_unknown_fields)]
337pub struct Dash {
338    /// Alternating dash and gap lengths, as fractions of the shorter side: one to
339    /// [`MAX_DASH_ENTRIES`] non-negative entries, not all zero. An odd count repeats once more to
340    /// pair up.
341    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_DASH_ENTRIES }>")]
342    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_DASH_ENTRIES)))]
343    pub pattern: Vec<Animated<f32>>,
344    /// How far into the pattern the stroke starts.
345    #[serde(default = "zero")]
346    pub offset: Animated<f32>,
347}
348
349/// Keeps a span of geometry's length.
350#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
351#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
352#[serde(deny_unknown_fields)]
353pub struct TrimItem {
354    /// Where the kept span starts, as a fraction of the length, in `0..=1`.
355    pub start: Animated<f32>,
356    /// Where it ends, in `0..=1`. Nothing is kept unless it is after `start`.
357    pub end: Animated<f32>,
358    /// Turns the span is shifted by; it wraps around a closed path.
359    #[serde(default = "zero")]
360    pub offset: Animated<f32>,
361    /// Whether the span is of all the geometry together or of each part.
362    #[serde(default)]
363    pub mode: TrimMode,
364}
365
366/// What a trim measures.
367#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
368#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
369#[serde(rename_all = "snake_case")]
370pub enum TrimMode {
371    /// One span over the length of every subpath end to end, in order.
372    #[default]
373    Together,
374    /// A span of each subpath alone.
375    Individually,
376}
377
378/// Which regions of a path are inside it.
379#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
380#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
381#[serde(rename_all = "snake_case")]
382pub enum FillRule {
383    /// Where the outline winds around a point at all.
384    #[default]
385    Nonzero,
386    /// Where it winds around a point an odd number of times.
387    Evenodd,
388}
389
390/// Why a content tree or a mask outline is invalid.
391#[derive(Copy, Clone, Debug, Eq, PartialEq)]
392#[non_exhaustive]
393pub enum ShapeProblem {
394    /// More than [`MAX_SHAPE_ITEMS`] items.
395    TooManyItems,
396    /// Groups nested deeper than [`MAX_SHAPE_DEPTH`].
397    TooDeep,
398    /// A path with more than [`MAX_PATH_SUBPATHS`] subpaths or [`MAX_PATH_VERTICES`] vertices.
399    PathTooLarge,
400    /// A dash pattern with no entries, more than [`MAX_DASH_ENTRIES`], or only zeros.
401    InvalidDash,
402    /// Keyframes that are empty, out of order, or have an unusable curve.
403    InvalidKeyframes,
404    /// A value that is not finite or outside its range.
405    OutOfRange,
406    /// Path keyframes that differ in subpath count, closing, or vertex count.
407    PathKeyframesDiffer,
408    /// Paint keyframes that differ in kind, stop count, or spread.
409    PaintKeyframesDiffer,
410}
411
412impl fmt::Display for ShapeProblem {
413    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
414        formatter.write_str(match self {
415            Self::TooManyItems => "has more items than a shapes generator may hold",
416            Self::TooDeep => "nests groups too deeply",
417            Self::PathTooLarge => "has more subpaths or vertices than a path may hold",
418            Self::InvalidDash => "has an invalid dash pattern",
419            Self::InvalidKeyframes => "has invalid keyframes",
420            Self::OutOfRange => "has a value out of range",
421            Self::PathKeyframesDiffer => "has path keyframes that differ in structure",
422            Self::PaintKeyframesDiffer => "has paint keyframes that differ in kind or stops",
423        })
424    }
425}
426
427/// Where in a content tree a problem lies, and what it is.
428#[derive(Clone, Debug, Eq, PartialEq)]
429pub struct ShapeIssue {
430    /// The item's path from the tree's root, like `items[2].items[0].path`, or a mask's field,
431    /// like `shape.size`.
432    pub at: String,
433    /// What is wrong there.
434    pub problem: ShapeProblem,
435}
436
437impl From<ValueIssue> for ShapeIssue {
438    fn from(issue: ValueIssue) -> Self {
439        Self::new(
440            issue.at,
441            match issue.problem {
442                ValueProblem::InvalidKeyframes => ShapeProblem::InvalidKeyframes,
443                ValueProblem::OutOfRange => ShapeProblem::OutOfRange,
444                ValueProblem::PaintKeyframesDiffer => ShapeProblem::PaintKeyframesDiffer,
445            },
446        )
447    }
448}
449
450impl ShapeIssue {
451    fn new(at: impl Into<String>, problem: ShapeProblem) -> Self {
452        Self {
453            at: at.into(),
454            problem,
455        }
456    }
457}
458
459type Checked = Result<(), ShapeIssue>;
460
461/// Checks a content tree: its limits, every value's range, and that animated paths and paints
462/// agree in structure between keyframes.
463///
464/// # Errors
465/// Returns the first problem in document order.
466pub fn validate_shape_items(items: &[ShapeItem]) -> Result<(), ShapeIssue> {
467    let mut count = 0;
468    validate_items(items, "items", 1, &mut count)
469}
470
471pub(crate) fn validate_items(
472    items: &[ShapeItem],
473    at: &str,
474    depth: usize,
475    count: &mut usize,
476) -> Checked {
477    if depth > MAX_SHAPE_DEPTH {
478        return Err(ShapeIssue::new(at, ShapeProblem::TooDeep));
479    }
480    for (index, item) in items.iter().enumerate() {
481        let at = format!("{at}[{index}]");
482        *count += 1;
483        if *count > MAX_SHAPE_ITEMS {
484            return Err(ShapeIssue::new(at, ShapeProblem::TooManyItems));
485        }
486        match item {
487            ShapeItem::Group { items, transform } => {
488                validate_transform(transform, &format!("{at}.transform"))?;
489                validate_items(items, &format!("{at}.items"), depth + 1, count)?;
490            }
491            ShapeItem::Rectangle(geometry) => validate_rectangle(geometry, &at)?,
492            ShapeItem::Ellipse(geometry) => validate_ellipse(geometry, &at)?,
493            ShapeItem::Polystar(geometry) => validate_polystar(geometry, &at)?,
494            ShapeItem::Path(geometry) => validate_path(&geometry.path, &format!("{at}.path"))?,
495            ShapeItem::Fill { paint, opacity, .. } => {
496                validate_paint(paint, &format!("{at}.paint"))?;
497                scalar(opacity, &format!("{at}.opacity"), unit)?;
498            }
499            ShapeItem::Stroke(stroke) => validate_stroke(stroke, &at)?,
500            ShapeItem::Trim(trim) => {
501                scalar(&trim.start, &format!("{at}.start"), unit)?;
502                scalar(&trim.end, &format!("{at}.end"), unit)?;
503                scalar(&trim.offset, &format!("{at}.offset"), any)?;
504            }
505        }
506    }
507    Ok(())
508}
509
510impl ShapeGeometry {
511    /// Checks the outline as a content tree's geometry is checked; `at` names it in the issue.
512    ///
513    /// # Errors
514    /// Returns the first problem in document order.
515    pub fn validate(&self, at: &str) -> Result<(), ShapeIssue> {
516        match self {
517            Self::Rectangle(geometry) => validate_rectangle(geometry, at),
518            Self::Ellipse(geometry) => validate_ellipse(geometry, at),
519            Self::Polystar(geometry) => validate_polystar(geometry, at),
520            Self::Path(geometry) => validate_path(&geometry.path, &format!("{at}.path")),
521        }
522    }
523}
524
525fn sizes(value: Vec2) -> bool {
526    value.x >= 0.0 && value.y >= 0.0
527}
528
529fn validate_rectangle(geometry: &RectangleGeometry, at: &str) -> Checked {
530    point(&geometry.center, &format!("{at}.center"))?;
531    vec2(&geometry.size, &format!("{at}.size"), sizes)?;
532    scalar(
533        &geometry.corner_radius,
534        &format!("{at}.corner_radius"),
535        non_negative,
536    )?;
537    scalar(
538        &geometry.rotation_degrees,
539        &format!("{at}.rotation_degrees"),
540        any,
541    )?;
542    Ok(())
543}
544
545fn validate_ellipse(geometry: &EllipseGeometry, at: &str) -> Checked {
546    point(&geometry.center, &format!("{at}.center"))?;
547    vec2(&geometry.size, &format!("{at}.size"), sizes)?;
548    scalar(
549        &geometry.rotation_degrees,
550        &format!("{at}.rotation_degrees"),
551        any,
552    )?;
553    Ok(())
554}
555
556fn validate_polystar(geometry: &PolystarGeometry, at: &str) -> Checked {
557    point(&geometry.center, &format!("{at}.center"))?;
558    scalar(&geometry.points, &format!("{at}.points"), |points| {
559        crate::Domain::POLYSTAR_POINTS.contains(points)
560    })?;
561    scalar(
562        &geometry.outer_radius,
563        &format!("{at}.outer_radius"),
564        non_negative,
565    )?;
566    scalar(
567        &geometry.inner_radius,
568        &format!("{at}.inner_radius"),
569        non_negative,
570    )?;
571    scalar(
572        &geometry.outer_roundness,
573        &format!("{at}.outer_roundness"),
574        unit,
575    )?;
576    scalar(
577        &geometry.inner_roundness,
578        &format!("{at}.inner_roundness"),
579        unit,
580    )?;
581    scalar(
582        &geometry.rotation_degrees,
583        &format!("{at}.rotation_degrees"),
584        any,
585    )?;
586    Ok(())
587}
588
589fn validate_transform(transform: &ShapeTransform, at: &str) -> Checked {
590    vec2(&transform.anchor, &format!("{at}.anchor"), |_| true)?;
591    point(&transform.position, &format!("{at}.position"))?;
592    vec2(&transform.scale, &format!("{at}.scale"), |_| true)?;
593    scalar(
594        &transform.rotation_degrees,
595        &format!("{at}.rotation_degrees"),
596        any,
597    )?;
598    scalar(&transform.opacity, &format!("{at}.opacity"), unit)?;
599    Ok(())
600}
601
602fn validate_stroke(stroke: &StrokeItem, at: &str) -> Checked {
603    validate_paint(&stroke.paint, &format!("{at}.paint"))?;
604    scalar(&stroke.width, &format!("{at}.width"), non_negative)?;
605    scalar(&stroke.opacity, &format!("{at}.opacity"), unit)?;
606    if !stroke.miter_limit.is_finite() || stroke.miter_limit < 1.0 {
607        return Err(ShapeIssue::new(
608            format!("{at}.miter_limit"),
609            ShapeProblem::OutOfRange,
610        ));
611    }
612    if let Some(dash) = &stroke.dash {
613        let at = format!("{at}.dash");
614        if dash.pattern.is_empty() || dash.pattern.len() > MAX_DASH_ENTRIES {
615            return Err(ShapeIssue::new(
616                format!("{at}.pattern"),
617                ShapeProblem::InvalidDash,
618            ));
619        }
620        for (index, entry) in dash.pattern.iter().enumerate() {
621            scalar(entry, &format!("{at}.pattern[{index}]"), non_negative)?;
622        }
623        // A pattern of only zeros has no length to repeat over. Animated entries need some positive
624        // keyframe.
625        let positive = dash.pattern.iter().any(|entry| match entry {
626            Animated::Constant { value } => *value > 0.0,
627            Animated::Keyframes { keyframes } => keyframes.iter().any(|key| key.value > 0.0),
628            Animated::Data(_) => true,
629        });
630        if !positive {
631            return Err(ShapeIssue::new(
632                format!("{at}.pattern"),
633                ShapeProblem::InvalidDash,
634            ));
635        }
636        scalar(&dash.offset, &format!("{at}.offset"), any)?;
637    }
638    Ok(())
639}
640
641fn validate_path(path: &Animated<Path>, at: &str) -> Checked {
642    let check_one = |path: &Path| -> Checked {
643        let vertices: usize = path
644            .subpaths
645            .iter()
646            .map(|subpath| subpath.vertices.len())
647            .sum();
648        if path.subpaths.len() > MAX_PATH_SUBPATHS || vertices > MAX_PATH_VERTICES {
649            return Err(ShapeIssue::new(at, ShapeProblem::PathTooLarge));
650        }
651        let finite = |value: Vec2| value.x.is_finite() && value.y.is_finite();
652        let all_finite = path.subpaths.iter().all(|subpath| {
653            subpath.vertices.iter().all(|vertex| {
654                finite(vertex.point) && finite(vertex.in_tangent) && finite(vertex.out_tangent)
655            })
656        });
657        all_finite
658            .then_some(())
659            .ok_or_else(|| ShapeIssue::new(at, ShapeProblem::OutOfRange))
660    };
661    match path {
662        Animated::Data(_) => Err(ShapeIssue::new(at, ShapeProblem::OutOfRange)),
663        Animated::Constant { value } => check_one(value),
664        Animated::Keyframes { keyframes } => {
665            if !valid_keyframes(keyframes) {
666                return Err(ShapeIssue::new(at, ShapeProblem::InvalidKeyframes));
667            }
668            for keyframe in keyframes {
669                check_one(&keyframe.value)?;
670            }
671            let structure = |path: &Path| {
672                path.subpaths
673                    .iter()
674                    .map(|subpath| (subpath.closed, subpath.vertices.len()))
675                    .collect::<Vec<_>>()
676            };
677            let first = structure(&keyframes[0].value);
678            if keyframes[1..]
679                .iter()
680                .any(|keyframe| structure(&keyframe.value) != first)
681            {
682                return Err(ShapeIssue::new(at, ShapeProblem::PathKeyframesDiffer));
683            }
684            Ok(())
685        }
686    }
687}
688
689impl Path {
690    /// Number of vertices over all subpaths.
691    #[must_use]
692    pub fn vertex_count(&self) -> usize {
693        self.subpaths
694            .iter()
695            .map(|subpath| subpath.vertices.len())
696            .sum()
697    }
698}
699
700impl ShapeItem {
701    /// Whether the item or anything in it changes over time.
702    #[must_use]
703    pub fn is_animated(&self) -> bool {
704        match self {
705            Self::Group { items, transform } => {
706                transform.is_animated() || items.iter().any(Self::is_animated)
707            }
708            Self::Rectangle(geometry) => geometry.is_animated(),
709            Self::Ellipse(geometry) => geometry.is_animated(),
710            Self::Polystar(geometry) => geometry.is_animated(),
711            Self::Path(geometry) => keyed(&geometry.path),
712            Self::Fill { paint, opacity, .. } => keyed(paint) || keyed(opacity),
713            Self::Stroke(stroke) => {
714                keyed(&stroke.paint)
715                    || keyed(&stroke.width)
716                    || keyed(&stroke.opacity)
717                    || stroke
718                        .dash
719                        .as_ref()
720                        .is_some_and(|dash| dash.pattern.iter().any(keyed) || keyed(&dash.offset))
721            }
722            Self::Trim(trim) => keyed(&trim.start) || keyed(&trim.end) || keyed(&trim.offset),
723        }
724    }
725}
726
727/// Calls `visit` with each keyframed value of `items`, by its path below `at`
728/// (`items[0].transform.opacity` for `at` "items"), and its keyframe times, in document order.
729pub(crate) fn for_each_keyed_item(
730    items: &[ShapeItem],
731    at: &str,
732    visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
733) {
734    for (index, item) in items.iter().enumerate() {
735        item.for_each_keyed(&format!("{at}[{index}]"), visit);
736    }
737}
738
739impl ShapeItem {
740    /// Calls `visit` with each of its keyframed values, by path below `at`, and their times.
741    pub(crate) fn for_each_keyed(
742        &self,
743        at: &str,
744        visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
745    ) {
746        match self {
747            Self::Group { items, transform } => {
748                let transform_at = format!("{at}.transform");
749                visit_keyed(&format!("{transform_at}.anchor"), &transform.anchor, visit);
750                visit_keyed_point(
751                    &format!("{transform_at}.position"),
752                    &transform.position,
753                    visit,
754                );
755                visit_keyed(&format!("{transform_at}.scale"), &transform.scale, visit);
756                visit_keyed(
757                    &format!("{transform_at}.rotation_degrees"),
758                    &transform.rotation_degrees,
759                    visit,
760                );
761                visit_keyed(
762                    &format!("{transform_at}.opacity"),
763                    &transform.opacity,
764                    visit,
765                );
766                for_each_keyed_item(items, &format!("{at}.items"), visit);
767            }
768            Self::Rectangle(geometry) => geometry.for_each_keyed(at, visit),
769            Self::Ellipse(geometry) => geometry.for_each_keyed(at, visit),
770            Self::Polystar(geometry) => geometry.for_each_keyed(at, visit),
771            Self::Path(geometry) => visit_keyed(&format!("{at}.path"), &geometry.path, visit),
772            Self::Fill { paint, opacity, .. } => {
773                visit_keyed(&format!("{at}.paint"), paint, visit);
774                visit_keyed(&format!("{at}.opacity"), opacity, visit);
775            }
776            Self::Stroke(stroke) => {
777                visit_keyed(&format!("{at}.paint"), &stroke.paint, visit);
778                visit_keyed(&format!("{at}.width"), &stroke.width, visit);
779                visit_keyed(&format!("{at}.opacity"), &stroke.opacity, visit);
780                if let Some(dash) = &stroke.dash {
781                    for (index, entry) in dash.pattern.iter().enumerate() {
782                        visit_keyed(&format!("{at}.dash.pattern[{index}]"), entry, visit);
783                    }
784                    visit_keyed(&format!("{at}.dash.offset"), &dash.offset, visit);
785                }
786            }
787            Self::Trim(trim) => {
788                visit_keyed(&format!("{at}.start"), &trim.start, visit);
789                visit_keyed(&format!("{at}.end"), &trim.end, visit);
790                visit_keyed(&format!("{at}.offset"), &trim.offset, visit);
791            }
792        }
793    }
794}
795
796impl ShapeGeometry {
797    /// Calls `visit` with each of its keyframed values, by path below `at`, and their times.
798    pub(crate) fn for_each_keyed(
799        &self,
800        at: &str,
801        visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
802    ) {
803        match self {
804            Self::Rectangle(geometry) => geometry.for_each_keyed(at, visit),
805            Self::Ellipse(geometry) => geometry.for_each_keyed(at, visit),
806            Self::Polystar(geometry) => geometry.for_each_keyed(at, visit),
807            Self::Path(geometry) => visit_keyed(&format!("{at}.path"), &geometry.path, visit),
808        }
809    }
810
811    /// Whether the outline changes over time.
812    #[must_use]
813    pub fn is_animated(&self) -> bool {
814        match self {
815            Self::Rectangle(geometry) => geometry.is_animated(),
816            Self::Ellipse(geometry) => geometry.is_animated(),
817            Self::Polystar(geometry) => geometry.is_animated(),
818            Self::Path(geometry) => keyed(&geometry.path),
819        }
820    }
821}
822
823impl RectangleGeometry {
824    fn is_animated(&self) -> bool {
825        self.center.is_animated()
826            || keyed(&self.size)
827            || keyed(&self.corner_radius)
828            || keyed(&self.rotation_degrees)
829    }
830}
831
832impl EllipseGeometry {
833    fn is_animated(&self) -> bool {
834        self.center.is_animated() || keyed(&self.size) || keyed(&self.rotation_degrees)
835    }
836}
837
838impl RectangleGeometry {
839    fn for_each_keyed(&self, at: &str, visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>)) {
840        visit_keyed_point(&format!("{at}.center"), &self.center, visit);
841        visit_keyed(&format!("{at}.size"), &self.size, visit);
842        visit_keyed(&format!("{at}.corner_radius"), &self.corner_radius, visit);
843        visit_keyed(
844            &format!("{at}.rotation_degrees"),
845            &self.rotation_degrees,
846            visit,
847        );
848    }
849}
850
851impl EllipseGeometry {
852    fn for_each_keyed(&self, at: &str, visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>)) {
853        visit_keyed_point(&format!("{at}.center"), &self.center, visit);
854        visit_keyed(&format!("{at}.size"), &self.size, visit);
855        visit_keyed(
856            &format!("{at}.rotation_degrees"),
857            &self.rotation_degrees,
858            visit,
859        );
860    }
861}
862
863impl PolystarGeometry {
864    fn for_each_keyed(&self, at: &str, visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>)) {
865        visit_keyed_point(&format!("{at}.center"), &self.center, visit);
866        visit_keyed(&format!("{at}.points"), &self.points, visit);
867        visit_keyed(&format!("{at}.outer_radius"), &self.outer_radius, visit);
868        visit_keyed(&format!("{at}.inner_radius"), &self.inner_radius, visit);
869        visit_keyed(
870            &format!("{at}.outer_roundness"),
871            &self.outer_roundness,
872            visit,
873        );
874        visit_keyed(
875            &format!("{at}.inner_roundness"),
876            &self.inner_roundness,
877            visit,
878        );
879        visit_keyed(
880            &format!("{at}.rotation_degrees"),
881            &self.rotation_degrees,
882            visit,
883        );
884    }
885
886    fn is_animated(&self) -> bool {
887        self.center.is_animated()
888            || keyed(&self.points)
889            || keyed(&self.outer_radius)
890            || keyed(&self.inner_radius)
891            || keyed(&self.outer_roundness)
892            || keyed(&self.inner_roundness)
893            || keyed(&self.rotation_degrees)
894    }
895}
896
897impl ShapeTransform {
898    fn is_animated(&self) -> bool {
899        keyed(&self.anchor)
900            || self.position.is_animated()
901            || keyed(&self.scale)
902            || keyed(&self.rotation_degrees)
903            || keyed(&self.opacity)
904    }
905}
906
907const fn keyed<T>(animation: &Animated<T>) -> bool {
908    matches!(animation, Animated::Keyframes { .. })
909}