Skip to main content

alpha2_model/
animation.rs

1use crate::{CubicBezier, DataBinding, Easing, EasingPoint, Steps, ValueBezier};
2use serde::{Deserialize, Serialize};
3
4/// A two-dimensional value in normalized output coordinates.
5#[derive(Copy, Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
6#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
7#[serde(deny_unknown_fields)]
8pub struct Vec2 {
9    /// Horizontal component.
10    pub x: f32,
11    /// Vertical component.
12    pub y: f32,
13}
14
15impl Vec2 {
16    /// Creates a two-dimensional value.
17    #[must_use]
18    pub const fn new(x: f32, y: f32) -> Self {
19        Self { x, y }
20    }
21
22    fn is_finite(self) -> bool {
23        self.x.is_finite() && self.y.is_finite()
24    }
25
26    /// Whether both components are zero (either sign).
27    #[must_use]
28    pub fn is_zero(&self) -> bool {
29        self.x == 0.0 && self.y == 0.0
30    }
31}
32
33/// Most keyframes of one animated value.
34pub const MAX_KEYFRAMES: usize = 100_000;
35
36/// What a keyframed value does before its first keyframe or after its last.
37///
38/// With one keyframe every choice holds its value.
39#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41#[serde(rename_all = "snake_case")]
42pub enum Extrapolation {
43    /// Keeps the nearest keyframe's value.
44    #[default]
45    Hold,
46    /// Continues at the slope the curve has at that end. Not for values that only hold.
47    Linear,
48    /// Repeats the keyed range. After the last keyframe the range is an exact period: the last
49    /// keyframe's own time already shows the first keyframe's value.
50    Repeat,
51    /// Repeats the keyed range, each pass starting where the last ended. Numbers and vectors
52    /// only.
53    RepeatOffset,
54    /// Repeats the keyed range forward and backward in turn.
55    PingPong,
56}
57
58impl Extrapolation {
59    /// Whether this is `hold`, the default.
60    #[must_use]
61    pub const fn is_hold(&self) -> bool {
62        matches!(self, Self::Hold)
63    }
64
65    const fn word(self) -> &'static str {
66        match self {
67            Self::Hold => "hold",
68            Self::Linear => "linear",
69            Self::Repeat => "repeat",
70            Self::RepeatOffset => "repeat_offset",
71            Self::PingPong => "ping_pong",
72        }
73    }
74}
75
76/// A value that is constant, controlled by sorted keyframes, split into one animated number
77/// per component, or following a data set.
78///
79/// Only value types whose [`AnimatedValue::ACCEPTS_DATA`] is true (`f32`, [`Vec2`] and
80/// [`crate::EffectValue`]) read or offer the `data` mode, and only those with an
81/// [`AnimatedValue::SPLIT`] ([`Vec2`] and [`crate::EffectValue`]) the `split` mode; for the
82/// others the mode fails to deserialize and the schema leaves it out.
83#[derive(Clone, Debug, PartialEq, Serialize)]
84#[serde(tag = "mode", rename_all = "snake_case")]
85pub enum Animated<T> {
86    /// A value without animation.
87    Constant {
88        /// Value used at every timestamp.
89        value: T,
90    },
91    /// Values evaluated from their keyframe sequence.
92    Keyframes {
93        /// Strictly ascending keyframes.
94        keyframes: Vec<Keyframe<T>>,
95        /// What the value does before the first keyframe.
96        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
97        before: Extrapolation,
98        /// What the value does after the last keyframe.
99        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
100        after: Extrapolation,
101    },
102    /// One animated number per component, each with its own keyframes, curves and
103    /// extrapolation, or its own data binding.
104    Split {
105        /// The components in order: `x` then `y`, or an effect vector's components.
106        channels: Vec<Animated<f32>>,
107    },
108    /// A channel of a data set, followed at render time.
109    Data(Box<DataBinding>),
110}
111
112const MAX_SPLIT_CHANNELS: usize = 4;
113
114mod sealed {
115    pub trait Sealed {}
116}
117
118/// A type an [`Animated`] value can hold. Sealed: implemented for the model's animatable types.
119pub trait AnimatedValue: sealed::Sealed {
120    /// Whether the type takes the `data` value mode.
121    const ACCEPTS_DATA: bool;
122    /// Whether a keyframe of the type can start a value curve ([`ValueBezier`]).
123    const VALUE_CURVES: bool = false;
124    /// Whether keyframes of the type can interpolate; those of the others only hold.
125    const INTERPOLATES: bool;
126    /// Whether two values of the type have a difference to add: what `repeat_offset` needs.
127    const OFFSETS: bool;
128    /// The fewest and the most channels the type's `split` mode takes, or `None` for a type
129    /// without the mode.
130    const SPLIT: Option<(usize, usize)> = None;
131
132    /// Whether a keyframe holding this value may start or end a value curve.
133    fn takes_value_curve(&self) -> bool {
134        Self::VALUE_CURVES
135    }
136
137    /// Whether keyframes holding this value may extrapolate by `extrapolation`.
138    fn extrapolates(&self, extrapolation: Extrapolation) -> bool {
139        match extrapolation {
140            Extrapolation::Hold | Extrapolation::Repeat | Extrapolation::PingPong => true,
141            Extrapolation::Linear => Self::INTERPOLATES,
142            Extrapolation::RepeatOffset => Self::OFFSETS,
143        }
144    }
145}
146
147macro_rules! animated_value {
148    (data: $data:literal, interpolates: $interpolates:literal, offsets: $offsets:literal;
149     $($type:ty),+) => {
150        $(
151            impl sealed::Sealed for $type {}
152            impl AnimatedValue for $type {
153                const ACCEPTS_DATA: bool = $data;
154                const INTERPOLATES: bool = $interpolates;
155                const OFFSETS: bool = $offsets;
156            }
157        )+
158    };
159}
160
161impl sealed::Sealed for f32 {}
162impl AnimatedValue for f32 {
163    const ACCEPTS_DATA: bool = true;
164    const VALUE_CURVES: bool = true;
165    const INTERPOLATES: bool = true;
166    const OFFSETS: bool = true;
167}
168
169impl sealed::Sealed for crate::EffectValue {}
170impl AnimatedValue for crate::EffectValue {
171    const ACCEPTS_DATA: bool = true;
172    const VALUE_CURVES: bool = true;
173    const INTERPOLATES: bool = true;
174    const OFFSETS: bool = true;
175    const SPLIT: Option<(usize, usize)> = Some((2, MAX_SPLIT_CHANNELS));
176
177    fn takes_value_curve(&self) -> bool {
178        matches!(self, Self::Float(_))
179    }
180
181    fn extrapolates(&self, extrapolation: Extrapolation) -> bool {
182        match extrapolation {
183            Extrapolation::Hold | Extrapolation::Repeat | Extrapolation::PingPong => true,
184            Extrapolation::Linear => self.interpolates(),
185            Extrapolation::RepeatOffset => {
186                matches!(self, Self::Float(_) | Self::Vec2(_) | Self::Vec4(_))
187            }
188        }
189    }
190}
191
192impl sealed::Sealed for Vec2 {}
193impl AnimatedValue for Vec2 {
194    const ACCEPTS_DATA: bool = true;
195    const INTERPOLATES: bool = true;
196    const OFFSETS: bool = true;
197    const SPLIT: Option<(usize, usize)> = Some((2, 2));
198}
199
200animated_value!(data: false, interpolates: false, offsets: false; String, crate::TextContent);
201animated_value!(
202    data: false, interpolates: true, offsets: false;
203    crate::Paint,
204    crate::Rgba,
205    crate::Path,
206    crate::LayoutLength,
207    crate::LayoutSize,
208    crate::LayoutOffset,
209    crate::Insets
210);
211
212// The wire form of `Animated`, before the value type decides whether it takes data. Its doc
213// comment is the schema's description.
214/// A value that is constant, controlled by sorted keyframes, split into one animated number per
215/// component, or following a data set.
216#[derive(Deserialize)]
217#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
218#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
219#[cfg_attr(feature = "schema", schemars(rename = "Animated_{T}"))]
220#[cfg_attr(
221    feature = "schema",
222    schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
223)]
224enum AnimatedWire<T> {
225    /// A value without animation.
226    Constant {
227        /// Value used at every timestamp.
228        value: T,
229    },
230    /// Values evaluated from their keyframe sequence.
231    Keyframes {
232        /// Strictly ascending keyframes.
233        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
234        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
235        keyframes: Vec<Keyframe<T>>,
236        /// What the value does before the first keyframe.
237        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
238        #[cfg_attr(
239            feature = "schema",
240            schemars(schema_with = "extrapolation_schema::<T>")
241        )]
242        before: Extrapolation,
243        /// What the value does after the last keyframe.
244        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
245        #[cfg_attr(
246            feature = "schema",
247            schemars(schema_with = "extrapolation_schema::<T>")
248        )]
249        after: Extrapolation,
250    },
251    /// One animated number per component, each with its own keyframes, curves and
252    /// extrapolation, or its own data binding.
253    Split {
254        /// The components in order: `x` then `y`, or an effect vector's components.
255        #[serde(deserialize_with = "crate::bounded::seq::<_, _, MAX_SPLIT_CHANNELS>")]
256        channels: Vec<Animated<f32>>,
257    },
258    /// A channel of a data set, followed at render time.
259    Data(DataBinding),
260}
261
262#[cfg(feature = "schema")]
263fn extrapolation_schema<T: AnimatedValue>(
264    generator: &mut schemars::SchemaGenerator,
265) -> schemars::Schema {
266    match (T::INTERPOLATES, T::OFFSETS) {
267        (true, true) => generator.subschema_for::<Extrapolation>(),
268        (true, false) => generator.subschema_for::<ExtrapolationWithoutOffset>(),
269        (false, _) => generator.subschema_for::<HoldExtrapolation>(),
270    }
271}
272
273#[cfg(feature = "schema")]
274struct ExtrapolationWithoutOffset;
275
276#[cfg(feature = "schema")]
277impl schemars::JsonSchema for ExtrapolationWithoutOffset {
278    fn schema_name() -> std::borrow::Cow<'static, str> {
279        "ExtrapolationWithoutOffset".into()
280    }
281
282    fn schema_id() -> std::borrow::Cow<'static, str> {
283        "alpha2_model::ExtrapolationWithoutOffset".into()
284    }
285
286    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
287        let mut schema = Extrapolation::json_schema(generator);
288        crate::schema::drop_word(&mut schema, Extrapolation::RepeatOffset.word());
289        schema.insert(
290            "description".to_owned(),
291            "What a keyframed value that has no difference to add does before its first \
292             keyframe or after its\nlast: every choice but `repeat_offset`."
293                .into(),
294        );
295        schema
296    }
297}
298
299#[cfg(feature = "schema")]
300struct HoldExtrapolation;
301
302#[cfg(feature = "schema")]
303impl schemars::JsonSchema for HoldExtrapolation {
304    fn schema_name() -> std::borrow::Cow<'static, str> {
305        "HoldExtrapolation".into()
306    }
307
308    fn schema_id() -> std::borrow::Cow<'static, str> {
309        "alpha2_model::HoldExtrapolation".into()
310    }
311
312    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
313        let mut schema = Extrapolation::json_schema(generator);
314        for extrapolation in [Extrapolation::Linear, Extrapolation::RepeatOffset] {
315            crate::schema::drop_word(&mut schema, extrapolation.word());
316        }
317        schema.insert(
318            "description".to_owned(),
319            "What a keyframed value that only holds does before its first keyframe or after \
320             its last: `hold`,\n`repeat` or `ping_pong`."
321                .into(),
322        );
323        schema
324    }
325}
326
327impl<'de, T: Deserialize<'de> + AnimatedValue> Deserialize<'de> for Animated<T> {
328    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
329        Ok(match AnimatedWire::<T>::deserialize(deserializer)? {
330            AnimatedWire::Constant { value } => Self::Constant { value },
331            AnimatedWire::Keyframes {
332                keyframes,
333                before,
334                after,
335            } => {
336                if keyframes.iter().any(|keyframe| {
337                    matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
338                        && !keyframe.value.takes_value_curve()
339                }) {
340                    return Err(serde::de::Error::custom(if T::SPLIT.is_some() {
341                        "this value takes no `value_bezier`; split it or use a timing curve"
342                    } else {
343                        "this value takes no `value_bezier`; use a timing curve"
344                    }));
345                }
346                if let Some(refused) = [before, after].into_iter().find(|extrapolation| {
347                    !keyframes
348                        .iter()
349                        .all(|keyframe| keyframe.value.extrapolates(*extrapolation))
350                }) {
351                    return Err(serde::de::Error::custom(format_args!(
352                        "this value takes no `{}` extrapolation",
353                        refused.word()
354                    )));
355                }
356                Self::Keyframes {
357                    keyframes,
358                    before,
359                    after,
360                }
361            }
362            AnimatedWire::Split { channels } => match T::SPLIT {
363                Some((least, most)) if (least..=most).contains(&channels.len()) => {
364                    Self::Split { channels }
365                }
366                Some((least, most)) => {
367                    return Err(serde::de::Error::custom(format_args!(
368                        "a `split` of this value has {least} to {most} channels, not {}",
369                        channels.len()
370                    )));
371                }
372                None => {
373                    return Err(serde::de::Error::custom("this value takes no `split` mode"));
374                }
375            },
376            AnimatedWire::Data(binding) if T::ACCEPTS_DATA => Self::Data(Box::new(binding)),
377            AnimatedWire::Data(_) => {
378                return Err(serde::de::Error::custom(
379                    "this value takes no `data` mode; use `constant` or `keyframes`",
380                ));
381            }
382        })
383    }
384}
385
386#[cfg(feature = "schema")]
387impl<T: schemars::JsonSchema + AnimatedValue> schemars::JsonSchema for Animated<T> {
388    // Types without the data mode are a separate generic, `Keyframed_{T}`, for one shape each.
389    fn schema_name() -> std::borrow::Cow<'static, str> {
390        if T::ACCEPTS_DATA {
391            AnimatedWire::<T>::schema_name()
392        } else {
393            format!("Keyframed_{}", T::schema_name()).into()
394        }
395    }
396
397    fn schema_id() -> std::borrow::Cow<'static, str> {
398        if T::ACCEPTS_DATA {
399            AnimatedWire::<T>::schema_id()
400        } else {
401            format!("alpha2_model::Keyframed<{}>", T::schema_id()).into()
402        }
403    }
404
405    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
406        let mut schema = AnimatedWire::<T>::json_schema(generator);
407        match T::SPLIT {
408            Some((least, most)) => crate::schema::bound_split_channels(&mut schema, least, most),
409            None => crate::schema::drop_variant(&mut schema, "mode", "split"),
410        }
411        if !T::ACCEPTS_DATA {
412            crate::schema::drop_data_mode(&mut schema);
413            schema.insert(
414                "description".to_owned(),
415                "A value that is constant or controlled by sorted keyframes.".into(),
416            );
417        }
418        schema
419    }
420}
421
422impl<T> Animated<T> {
423    /// A value controlled by `keyframes`, holding before the first and after the last.
424    #[must_use]
425    pub const fn keyed(keyframes: Vec<Keyframe<T>>) -> Self {
426        Self::Keyframes {
427            keyframes,
428            before: Extrapolation::Hold,
429            after: Extrapolation::Hold,
430        }
431    }
432
433    /// The same animation with each value mapped by `map`, keeping times, interpolations and
434    /// extrapolation.
435    #[must_use]
436    pub fn map<U>(&self, map: impl Fn(&T) -> U) -> Animated<U> {
437        match self {
438            Self::Constant { value } => Animated::Constant { value: map(value) },
439            Self::Keyframes {
440                keyframes,
441                before,
442                after,
443            } => Animated::Keyframes {
444                keyframes: keyframes
445                    .iter()
446                    .map(|keyframe| Keyframe {
447                        time: keyframe.time,
448                        value: map(&keyframe.value),
449                        interpolation: keyframe.interpolation.clone(),
450                    })
451                    .collect(),
452                before: *before,
453                after: *after,
454            },
455            Self::Split { channels } => Animated::Split {
456                channels: channels.clone(),
457            },
458            Self::Data(binding) => Animated::Data(binding.clone()),
459        }
460    }
461
462    /// The data binding, when the whole value follows a data set. A `split` value's channels
463    /// hold their own.
464    #[must_use]
465    pub const fn data(&self) -> Option<&DataBinding> {
466        match self {
467            Self::Data(binding) => Some(binding),
468            Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } => None,
469        }
470    }
471
472    /// Whether the value can change over time: keyframes, split channels or data.
473    #[must_use]
474    pub const fn varies(&self) -> bool {
475        !matches!(self, Self::Constant { .. })
476    }
477}
478
479pub(crate) fn bindings_of<'a, T: Placed>(
480    at: &str,
481    animated: &'a Animated<T>,
482    visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
483) {
484    match animated {
485        Animated::Data(binding) => visit(at, binding, T::PLACE),
486        Animated::Split { channels } => channel_bindings(channels, at, visit),
487        Animated::Constant { .. } | Animated::Keyframes { .. } => {}
488    }
489}
490
491pub(crate) fn point_bindings_of<'a>(
492    at: &str,
493    animated: &'a AnimatedPoint,
494    visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
495) {
496    match animated {
497        AnimatedPoint::Data(binding) => visit(at, binding, PlaceType::Point),
498        AnimatedPoint::Split { channels } => channel_bindings(channels, at, visit),
499        AnimatedPoint::Path(motion) => {
500            bindings_of(&format!("{at}.distance"), &motion.distance, visit);
501        }
502        AnimatedPoint::Constant { .. } | AnimatedPoint::Keyframes { .. } => {}
503    }
504}
505
506fn channel_bindings<'a>(
507    channels: &'a [Animated<f32>],
508    at: &str,
509    visit: &mut dyn FnMut(&str, &'a DataBinding, PlaceType),
510) {
511    for (index, channel) in channels.iter().enumerate() {
512        if let Animated::Data(binding) = channel {
513            visit(&channel_path(at, index), binding, PlaceType::Scalar);
514        }
515    }
516}
517
518pub(crate) fn channel_path(at: &str, index: usize) -> String {
519    format!("{at}.channels[{index}]")
520}
521
522pub(crate) fn valid_channels(
523    channels: &[Animated<f32>],
524    count: std::ops::RangeInclusive<usize>,
525    check: impl Fn(f32) -> bool,
526) -> bool {
527    count.contains(&channels.len())
528        && channels
529            .iter()
530            .all(|channel| valid_scalar_values(channel, &check))
531}
532
533/// A position that can move along curves between its keyframes.
534///
535/// Its JSON is an `Animated<Vec2>` plus optional spatial tangents per keyframe. With them,
536/// the value travels the cubic Bezier through this keyframe's `out_tangent` and the next's
537/// `in_tangent`, at the speed its timing curve sets along the arc length. Without them it
538/// moves in a straight line.
539#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
540#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
541#[serde(deny_unknown_fields)]
542#[serde(tag = "mode", rename_all = "snake_case")]
543pub enum AnimatedPoint {
544    /// A value without animation.
545    Constant {
546        /// Value used at every timestamp.
547        value: Vec2,
548    },
549    /// Values evaluated from their keyframe sequence.
550    Keyframes {
551        /// Strictly ascending keyframes.
552        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
553        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
554        keyframes: Vec<PointKeyframe>,
555        /// What the value does before the first keyframe. `linear` continues along the path's
556        /// start tangent.
557        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
558        before: Extrapolation,
559        /// What the value does after the last keyframe. `linear` continues along the path's end
560        /// tangent.
561        #[serde(default, skip_serializing_if = "Extrapolation::is_hold")]
562        after: Extrapolation,
563    },
564    /// One animated number per axis, each with its own keyframes, curves and extrapolation, or
565    /// its own data binding. The value has no spatial path of its own: it is wherever the two
566    /// numbers put it.
567    Split {
568        /// The `x` value, then the `y` value.
569        #[serde(deserialize_with = "two_channels")]
570        #[cfg_attr(feature = "schema", schemars(length(min = 2, max = 2)))]
571        channels: Vec<Animated<f32>>,
572    },
573    /// A point a fraction of the way along a path.
574    Path(Box<MotionPath>),
575    /// A channel of a data set, followed at render time.
576    Data(Box<DataBinding>),
577}
578
579/// The most vertices the path of a `path` position has.
580pub const MAX_MOTION_PATH_VERTICES: usize = 256;
581
582/// A path and how far along it a position is.
583#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
584#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
585#[serde(deny_unknown_fields)]
586pub struct MotionPath {
587    /// The path, in the position's own space: one subpath of 2 to
588    /// [`MAX_MOTION_PATH_VERTICES`] vertices.
589    #[serde(deserialize_with = "motion_path")]
590    #[cfg_attr(feature = "schema", schemars(schema_with = "motion_path_schema"))]
591    pub path: crate::Path,
592    /// The fraction of the path's length travelled, measured as it shows on screen. Clamped to
593    /// `0..=1` on an open path; on a closed one it wraps, so 1.25 is a quarter of the way
594    /// round again.
595    pub distance: Animated<f32>,
596}
597
598fn motion_path<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<crate::Path, D::Error> {
599    let path = crate::Path::deserialize(deserializer)?;
600    let vertices = match path.subpaths.as_slice() {
601        [subpath] => subpath.vertices.len(),
602        subpaths => {
603            return Err(serde::de::Error::custom(format_args!(
604                "the path of a position has 1 subpath, not {}",
605                subpaths.len()
606            )));
607        }
608    };
609    if !(2..=MAX_MOTION_PATH_VERTICES).contains(&vertices) {
610        return Err(serde::de::Error::custom(format_args!(
611            "the path of a position has 2 to {MAX_MOTION_PATH_VERTICES} vertices, not {vertices}"
612        )));
613    }
614    Ok(path)
615}
616
617#[cfg(feature = "schema")]
618fn motion_path_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
619    let vertex = generator.subschema_for::<crate::PathVertex>();
620    schemars::json_schema!({
621        "description": "One subpath of 2 to `MAX_MOTION_PATH_VERTICES` vertices.",
622        "type": "object",
623        "properties": {
624            "subpaths": {
625                "type": "array",
626                "minItems": 1,
627                "maxItems": 1,
628                "items": {
629                    "type": "object",
630                    "properties": {
631                        "closed": {
632                            "description": "Whether a segment joins the last vertex back to the first.",
633                            "type": "boolean",
634                            "default": false
635                        },
636                        "vertices": {
637                            "description": "The vertices, in order.",
638                            "type": "array",
639                            "minItems": 2,
640                            "maxItems": MAX_MOTION_PATH_VERTICES,
641                            "items": vertex
642                        }
643                    },
644                    "required": ["vertices"],
645                    "additionalProperties": false
646                }
647            }
648        },
649        "required": ["subpaths"],
650        "additionalProperties": false
651    })
652}
653
654/// How a transform turns with its position.
655#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
656#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
657#[serde(rename_all = "snake_case")]
658pub enum Orient {
659    /// It does not.
660    #[default]
661    None,
662    /// The direction of the position's path where the position is, is added to the rotation:
663    /// that of its spatial curve between keyframes, or of the path of a `path` position. A
664    /// position with no path adds nothing.
665    Path,
666}
667
668impl Orient {
669    #[expect(
670        clippy::trivially_copy_pass_by_ref,
671        reason = "serde passes a field by reference"
672    )]
673    fn is_none(&self) -> bool {
674        *self == Self::None
675    }
676}
677
678fn two_channels<'de, D: serde::Deserializer<'de>>(
679    deserializer: D,
680) -> Result<Vec<Animated<f32>>, D::Error> {
681    let channels = crate::bounded::seq::<_, Animated<f32>, 2>(deserializer)?;
682    if channels.len() != 2 {
683        return Err(serde::de::Error::custom(format_args!(
684            "a `split` position has 2 channels, not {}",
685            channels.len()
686        )));
687    }
688    Ok(channels)
689}
690
691impl Default for AnimatedPoint {
692    fn default() -> Self {
693        Self::Constant {
694            value: Vec2::default(),
695        }
696    }
697}
698
699impl From<Animated<Vec2>> for AnimatedPoint {
700    fn from(animation: Animated<Vec2>) -> Self {
701        match animation {
702            Animated::Constant { value } => Self::Constant { value },
703            Animated::Keyframes {
704                keyframes,
705                before,
706                after,
707            } => Self::Keyframes {
708                keyframes: keyframes
709                    .into_iter()
710                    .map(|keyframe| PointKeyframe {
711                        time: keyframe.time,
712                        value: keyframe.value,
713                        interpolation: keyframe.interpolation,
714                        out_tangent: Vec2::default(),
715                        in_tangent: Vec2::default(),
716                    })
717                    .collect(),
718                before,
719                after,
720            },
721            Animated::Split { channels } => Self::Split { channels },
722            Animated::Data(binding) => Self::Data(binding),
723        }
724    }
725}
726
727impl Animated<f32> {
728    /// Whether a project can hold this number: finite values, and keyframes that ascend, stay
729    /// within [`MAX_KEYFRAMES`] and have valid interpolations. A `split` number is not valid.
730    #[must_use]
731    pub fn is_valid(&self) -> bool {
732        valid_scalar_values(self, |_| true)
733    }
734}
735
736impl AnimatedPoint {
737    /// Whether a project can hold this position: finite values and tangents, and keyframes that
738    /// ascend, stay within [`MAX_KEYFRAMES`] and have valid interpolations.
739    #[must_use]
740    pub fn is_valid(&self) -> bool {
741        valid_point_animation(self)
742    }
743
744    /// A position controlled by `keyframes`, holding before the first and after the last.
745    #[must_use]
746    pub const fn keyed(keyframes: Vec<PointKeyframe>) -> Self {
747        Self::Keyframes {
748            keyframes,
749            before: Extrapolation::Hold,
750            after: Extrapolation::Hold,
751        }
752    }
753
754    /// Whether the value changes over time: keyframes, split channels or data.
755    #[must_use]
756    pub const fn is_animated(&self) -> bool {
757        !matches!(self, Self::Constant { .. })
758    }
759
760    /// The data binding, when the whole value follows a data set. A `split` value's channels
761    /// hold their own.
762    #[must_use]
763    pub const fn data(&self) -> Option<&DataBinding> {
764        match self {
765            Self::Data(binding) => Some(binding),
766            Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } | Self::Path(_) => {
767                None
768            }
769        }
770    }
771}
772
773/// One keyframe of an [`AnimatedPoint`].
774#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
775#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
776#[serde(deny_unknown_fields)]
777pub struct PointKeyframe {
778    /// Timestamp of this value, as a [`Keyframe`]'s.
779    pub time: alpha2_time::MediaTime,
780    /// Value at `time`.
781    pub value: Vec2,
782    /// Interpolation from this keyframe to its successor: how fast the value travels along the
783    /// way.
784    #[serde(deserialize_with = "timing_interpolation")]
785    #[cfg_attr(feature = "schema", schemars(with = "TimingInterpolation"))]
786    pub interpolation: Interpolation,
787    /// The curve's first control point toward the next keyframe, relative to this value.
788    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
789    pub out_tangent: Vec2,
790    /// The curve's second control point from the previous keyframe, relative to this value.
791    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
792    pub in_tangent: Vec2,
793}
794
795/// One timestamped control value.
796#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
797#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
798#[serde(deny_unknown_fields)]
799#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
800#[cfg_attr(
801    feature = "schema",
802    schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
803)]
804pub struct Keyframe<T> {
805    /// Timestamp of this value. Timeline time, except composition time in a composition node's
806    /// settings and picture time in a shapes or layout generator's tree.
807    pub time: alpha2_time::MediaTime,
808    /// Value at `time`.
809    pub value: T,
810    /// Interpolation from this keyframe to its successor.
811    #[cfg_attr(
812        feature = "schema",
813        schemars(schema_with = "interpolation_schema::<T>")
814    )]
815    pub interpolation: Interpolation,
816}
817
818#[cfg(feature = "schema")]
819fn interpolation_schema<T: AnimatedValue>(
820    generator: &mut schemars::SchemaGenerator,
821) -> schemars::Schema {
822    if T::VALUE_CURVES {
823        generator.subschema_for::<Interpolation>()
824    } else {
825        generator.subschema_for::<TimingInterpolation>()
826    }
827}
828
829fn timing_interpolation<'de, D: serde::Deserializer<'de>>(
830    deserializer: D,
831) -> Result<Interpolation, D::Error> {
832    let interpolation = Interpolation::deserialize(deserializer)?;
833    if matches!(interpolation, Interpolation::ValueBezier(_)) {
834        return Err(serde::de::Error::custom(
835            "a position takes no `value_bezier`; split it or use a timing curve",
836        ));
837    }
838    Ok(interpolation)
839}
840
841/// Interpolation from one keyframe to the next.
842///
843/// Values interpolate numerically: a rotation from 0 to 720 degrees turns twice. A host that
844/// wants the shortest path normalizes its keyframe values.
845#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
846#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
847#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
848pub enum Interpolation {
849    /// Keep this keyframe's value until the next keyframe.
850    Hold,
851    /// Move to the next value at a constant rate.
852    Linear,
853    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
854    CubicBezier(CubicBezier),
855    /// Move to the next value along a value curve, which can move between equal values. Numbers
856    /// only: an animated number, or an effect parameter between `float` keyframes.
857    ValueBezier(ValueBezier),
858    /// Move to the next value in equal steps, as CSS `steps()`. A step starts on the first tick
859    /// at or after its exact time.
860    Steps(Steps),
861    /// Move to the next value along straight lines through a table of points, as CSS
862    /// `linear()`: from `(0, 0)` through each point to `(1, 1)`.
863    Points {
864        /// The points between the two ends, rising strictly in `x`; at most
865        /// [`crate::MAX_EASING_POINTS`].
866        points: Vec<EasingPoint>,
867    },
868}
869
870#[cfg(feature = "schema")]
871pub(crate) struct TimingInterpolation;
872
873#[cfg(feature = "schema")]
874impl schemars::JsonSchema for TimingInterpolation {
875    fn schema_name() -> std::borrow::Cow<'static, str> {
876        "TimingInterpolation".into()
877    }
878
879    fn schema_id() -> std::borrow::Cow<'static, str> {
880        "alpha2_model::TimingInterpolation".into()
881    }
882
883    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
884        let mut schema = InterpolationWire::json_schema(generator);
885        crate::schema::drop_variant(&mut schema, "type", "value_bezier");
886        schema.insert(
887            "description".to_owned(),
888            "Interpolation from one keyframe to the next for a value that is not a number: every \
889             kind but\nthe value curve."
890                .into(),
891        );
892        schema
893    }
894}
895
896/// The wire form of [`Interpolation`]; see `EasingWire` for why unit variants are empty
897/// structs.
898#[derive(Deserialize)]
899#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
900#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
901#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
902pub(crate) enum InterpolationWire {
903    /// Keep this keyframe's value until the next keyframe.
904    Hold {},
905    /// Move to the next value at a constant rate.
906    Linear {},
907    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
908    CubicBezier(CubicBezier),
909    /// Move to the next value along a value curve, which can move between equal values. Numbers
910    /// only: an animated number, or an effect parameter between `float` keyframes.
911    ValueBezier(ValueBezier),
912    /// Move to the next value in equal steps, as CSS `steps()`. A step starts on the first tick
913    /// at or after its exact time.
914    Steps(Steps),
915    /// Move to the next value along straight lines through a table of points, as CSS
916    /// `linear()`: from `(0, 0)` through each point to `(1, 1)`.
917    Points {
918        /// The points between the two ends, rising strictly in `x`; at most
919        /// `MAX_EASING_POINTS`.
920        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EASING_POINTS }>")]
921        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EASING_POINTS)))]
922        points: Vec<EasingPoint>,
923    },
924}
925
926impl From<InterpolationWire> for Interpolation {
927    fn from(wire: InterpolationWire) -> Self {
928        match wire {
929            InterpolationWire::Hold {} => Self::Hold,
930            InterpolationWire::Linear {} => Self::Linear,
931            InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
932            InterpolationWire::ValueBezier(curve) => Self::ValueBezier(curve),
933            InterpolationWire::Steps(steps) => Self::Steps(steps),
934            InterpolationWire::Points { points } => Self::Points { points },
935        }
936    }
937}
938
939impl From<Easing> for Interpolation {
940    fn from(easing: Easing) -> Self {
941        match easing {
942            Easing::Linear => Self::Linear,
943            Easing::CubicBezier(curve) => Self::CubicBezier(curve),
944            Easing::Steps(steps) => Self::Steps(steps),
945            Easing::Points { points } => Self::Points { points },
946        }
947    }
948}
949
950/// What a keyframe segment does at one progress.
951#[derive(Copy, Clone, Debug, PartialEq)]
952pub enum SegmentShape {
953    /// Keeps the left keyframe's value.
954    Hold,
955    /// This fraction of the way to the next value; may leave `0..=1`.
956    Amount(f64),
957    /// Follows a value curve between the two keyframes' values.
958    Value(ValueBezier),
959}
960
961impl Interpolation {
962    /// What the segment does at linear `progress` (clamped to `0..=1` for an amount). The
963    /// keyframe sampler places `steps` by whole ticks instead ([`Steps::index`]).
964    #[must_use]
965    #[inline]
966    pub fn shape(&self, progress: f64) -> SegmentShape {
967        match self {
968            Self::Hold => SegmentShape::Hold,
969            Self::Linear => SegmentShape::Amount(progress.clamp(0.0, 1.0)),
970            Self::CubicBezier(curve) => SegmentShape::Amount(curve.apply(progress)),
971            Self::ValueBezier(curve) => SegmentShape::Value(*curve),
972            Self::Steps(steps) => SegmentShape::Amount(steps.apply(progress)),
973            Self::Points { points } => {
974                SegmentShape::Amount(crate::easing_points_at(points, progress))
975            }
976        }
977    }
978
979    /// The slope of the amount where the segment starts (`at_end` false) or ends, which
980    /// `linear` extrapolation continues: 0 for `hold`. `None` for a value curve, which has no
981    /// amount; its slope is [`ValueBezier::end_slope`].
982    #[must_use]
983    pub fn end_slope(&self, at_end: bool) -> Option<f64> {
984        match self {
985            Self::Hold | Self::Steps(_) => Some(0.0),
986            Self::Linear => Some(1.0),
987            Self::CubicBezier(curve) => Some(curve.end_slope(at_end)),
988            Self::ValueBezier(_) => None,
989            Self::Points { points } => Some(crate::easing_points_slope(
990                points,
991                if at_end { 1.0 } else { 0.0 },
992            )),
993        }
994    }
995
996    /// Whether the interpolation's parameters are usable.
997    #[must_use]
998    pub fn is_valid(&self) -> bool {
999        match self {
1000            Self::Hold | Self::Linear => true,
1001            Self::CubicBezier(curve) => curve.is_valid(),
1002            Self::ValueBezier(curve) => curve.is_valid(),
1003            Self::Steps(steps) => steps.is_valid(),
1004            Self::Points { points } => crate::easing_points_valid(points),
1005        }
1006    }
1007}
1008
1009/// Resolution-independent visual presentation controls for a clip.
1010#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1011#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1012#[serde(deny_unknown_fields)]
1013///
1014/// Omitted fields default to the source centred on the canvas, unscaled, unrotated and opaque.
1015pub struct VisualProperties {
1016    /// Animated normalized canvas translation, along spatial curves where keyframes have
1017    /// tangents.
1018    #[serde(default = "centre_point")]
1019    pub position: AnimatedPoint,
1020    /// Unanimated normalized point within the source rectangle.
1021    #[serde(default = "centre")]
1022    pub anchor: Vec2,
1023    /// Animated per-axis scale.
1024    #[serde(default = "unit_scale")]
1025    pub scale: Animated<Vec2>,
1026    /// Animated clockwise rotation in degrees.
1027    #[serde(default = "no_rotation")]
1028    pub rotation_degrees: Animated<f32>,
1029    /// Animated opacity constrained to `0..=1`.
1030    #[serde(default = "opaque")]
1031    pub opacity: Animated<f32>,
1032    /// A `similarity` data set moving the clip's own picture, applied before this transform.
1033    /// Clip visuals only.
1034    #[serde(default, skip_serializing_if = "Option::is_none")]
1035    pub correction: Option<crate::CorrectionRef>,
1036    /// Whether the rotation follows the direction of the position's path.
1037    #[serde(default, skip_serializing_if = "Orient::is_none")]
1038    pub orient: Orient,
1039}
1040
1041impl Default for VisualProperties {
1042    fn default() -> Self {
1043        Self {
1044            position: centre_point(),
1045            anchor: centre(),
1046            scale: unit_scale(),
1047            rotation_degrees: no_rotation(),
1048            opacity: opaque(),
1049            correction: None,
1050            orient: Orient::None,
1051        }
1052    }
1053}
1054
1055const fn centre() -> Vec2 {
1056    Vec2::new(0.5, 0.5)
1057}
1058
1059const fn centre_point() -> AnimatedPoint {
1060    AnimatedPoint::Constant { value: centre() }
1061}
1062
1063pub(crate) const fn unit_scale() -> Animated<Vec2> {
1064    Animated::Constant {
1065        value: Vec2::new(1.0, 1.0),
1066    }
1067}
1068
1069const fn no_rotation() -> Animated<f32> {
1070    Animated::Constant { value: 0.0 }
1071}
1072
1073pub(crate) const fn opaque() -> Animated<f32> {
1074    Animated::Constant { value: 1.0 }
1075}
1076
1077/// What a walk over animated values meets at one value that is not constant.
1078pub(crate) enum Keyed<'a> {
1079    /// The times of its keyframes.
1080    Times(&'a [alpha2_time::MediaTime], Extrapolation, Extrapolation),
1081    /// Its data binding, with the type of the value bound.
1082    Data(&'a DataBinding, PlaceType),
1083}
1084
1085/// The value type a data binding sits on, which decides the kinds it can follow.
1086#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1087pub(crate) enum PlaceType {
1088    /// A point along spatial curves.
1089    Point,
1090    /// A two-component value.
1091    Vec2,
1092    /// A number.
1093    Scalar,
1094    /// An effect parameter, whose type its definition gives.
1095    Effect,
1096    /// A type that takes no data.
1097    Other,
1098}
1099
1100/// The [`PlaceType`] of each animatable type.
1101pub(crate) trait Placed {
1102    const PLACE: PlaceType;
1103}
1104
1105macro_rules! placed {
1106    ($place:ident: $($type:ty),+) => {
1107        $(impl Placed for $type {
1108            const PLACE: PlaceType = PlaceType::$place;
1109        })+
1110    };
1111}
1112
1113placed!(Scalar: f32);
1114placed!(Vec2: Vec2);
1115placed!(Effect: crate::EffectValue);
1116placed!(
1117    Other: String,
1118    crate::TextContent,
1119    crate::Paint,
1120    crate::Rgba,
1121    crate::Path,
1122    crate::LayoutLength,
1123    crate::LayoutSize,
1124    crate::LayoutOffset,
1125    crate::Insets
1126);
1127
1128/// Calls `visit` with `at` and the times of `animated`'s keyframes, or its data binding.
1129pub(crate) fn visit_keyed<T: Placed>(
1130    at: &str,
1131    animated: &Animated<T>,
1132    visit: &mut impl FnMut(&str, Keyed<'_>),
1133) {
1134    match animated {
1135        Animated::Keyframes {
1136            keyframes,
1137            before,
1138            after,
1139        } => {
1140            let times = keyframes
1141                .iter()
1142                .map(|keyframe| keyframe.time)
1143                .collect::<Vec<_>>();
1144            visit(at, Keyed::Times(&times, *before, *after));
1145        }
1146        Animated::Split { channels } => visit_keyed_channels(at, channels, visit),
1147        Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
1148        Animated::Constant { .. } => {}
1149    }
1150}
1151
1152fn visit_keyed_channels(
1153    at: &str,
1154    channels: &[Animated<f32>],
1155    visit: &mut impl FnMut(&str, Keyed<'_>),
1156) {
1157    for (index, channel) in channels.iter().enumerate() {
1158        match channel {
1159            Animated::Keyframes {
1160                keyframes,
1161                before,
1162                after,
1163            } => {
1164                let times = keyframes
1165                    .iter()
1166                    .map(|keyframe| keyframe.time)
1167                    .collect::<Vec<_>>();
1168                visit(
1169                    &channel_path(at, index),
1170                    Keyed::Times(&times, *before, *after),
1171                );
1172            }
1173            Animated::Data(binding) => visit(
1174                &channel_path(at, index),
1175                Keyed::Data(binding, PlaceType::Scalar),
1176            ),
1177            Animated::Constant { .. } | Animated::Split { .. } => {}
1178        }
1179    }
1180}
1181
1182/// [`visit_keyed`] for a point along a spatial curve.
1183pub(crate) fn visit_keyed_point(
1184    at: &str,
1185    animated: &AnimatedPoint,
1186    visit: &mut impl FnMut(&str, Keyed<'_>),
1187) {
1188    match animated {
1189        AnimatedPoint::Keyframes {
1190            keyframes,
1191            before,
1192            after,
1193        } => {
1194            let times = keyframes
1195                .iter()
1196                .map(|keyframe| keyframe.time)
1197                .collect::<Vec<_>>();
1198            visit(at, Keyed::Times(&times, *before, *after));
1199        }
1200        AnimatedPoint::Split { channels } => visit_keyed_channels(at, channels, visit),
1201        AnimatedPoint::Path(motion) => {
1202            visit_keyed(&format!("{at}.distance"), &motion.distance, visit);
1203        }
1204        AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
1205        AnimatedPoint::Constant { .. } => {}
1206    }
1207}
1208
1209impl VisualProperties {
1210    pub(crate) fn validate(&self) -> bool {
1211        self.anchor.is_finite()
1212            && valid_point_animation(&self.position)
1213            && valid_vec2_animation(&self.scale)
1214            && valid_scalar_animation(&self.rotation_degrees, false)
1215            && valid_scalar_animation(&self.opacity, true)
1216    }
1217}
1218
1219fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
1220    match animation {
1221        Animated::Constant { value } => value.is_finite(),
1222        Animated::Keyframes {
1223            keyframes,
1224            before,
1225            after,
1226        } => {
1227            valid_keyframes(keyframes, *before, *after)
1228                && keyframes.iter().all(|keyframe| keyframe.value.is_finite())
1229        }
1230        Animated::Split { channels } => valid_channels(channels, 2..=2, |_| true),
1231        Animated::Data(_) => true,
1232    }
1233}
1234
1235/// Valid keyframes (or a constant) whose values and tangents are finite.
1236pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
1237    match animation {
1238        AnimatedPoint::Constant { value } => value.is_finite(),
1239        AnimatedPoint::Data(_) => true,
1240        AnimatedPoint::Split { channels } => valid_channels(channels, 2..=2, |_| true),
1241        AnimatedPoint::Path(motion) => {
1242            let vertices = match motion.path.subpaths.as_slice() {
1243                [subpath] => subpath.vertices.as_slice(),
1244                _ => &[],
1245            };
1246            (2..=MAX_MOTION_PATH_VERTICES).contains(&vertices.len())
1247                && vertices.iter().all(|vertex| {
1248                    vertex.point.is_finite()
1249                        && vertex.in_tangent.is_finite()
1250                        && vertex.out_tangent.is_finite()
1251                })
1252                && valid_scalar_values(&motion.distance, |_| true)
1253        }
1254        AnimatedPoint::Keyframes { keyframes, .. } => {
1255            !keyframes.is_empty()
1256                && keyframes.len() <= MAX_KEYFRAMES
1257                && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
1258                && keyframes.iter().all(|keyframe| {
1259                    keyframe.interpolation.is_valid()
1260                        && !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
1261                        && keyframe.value.is_finite()
1262                        && keyframe.out_tangent.is_finite()
1263                        && keyframe.in_tangent.is_finite()
1264                })
1265        }
1266    }
1267}
1268
1269fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
1270    let domain = if unit_interval {
1271        crate::Domain::UNIT
1272    } else {
1273        crate::Domain::ANY
1274    };
1275    let valid_value = |value: f32| domain.contains(value);
1276    match animation {
1277        Animated::Constant { value } => valid_value(*value),
1278        Animated::Keyframes {
1279            keyframes,
1280            before,
1281            after,
1282        } => {
1283            valid_keyframes(keyframes, *before, *after)
1284                && keyframes.iter().all(|keyframe| valid_value(keyframe.value))
1285        }
1286        Animated::Split { .. } => false,
1287        Animated::Data(_) => true,
1288    }
1289}
1290
1291/// Valid keyframes (or a constant) whose every finite value passes `check`.
1292pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
1293    let valid = |value: f32| value.is_finite() && check(value);
1294    match animation {
1295        Animated::Constant { value } => valid(*value),
1296        Animated::Keyframes {
1297            keyframes,
1298            before,
1299            after,
1300        } => {
1301            valid_keyframes(keyframes, *before, *after)
1302                && keyframes.iter().all(|keyframe| valid(keyframe.value))
1303        }
1304        Animated::Split { .. } => false,
1305        Animated::Data(_) => true,
1306    }
1307}
1308
1309/// A non-empty, strictly ascending run of at most [`MAX_KEYFRAMES`] with usable interpolations.
1310pub(crate) fn valid_keyframes<T: AnimatedValue>(
1311    keyframes: &[Keyframe<T>],
1312    before: Extrapolation,
1313    after: Extrapolation,
1314) -> bool {
1315    !keyframes.is_empty()
1316        && keyframes.iter().all(|keyframe| {
1317            keyframe.value.extrapolates(before) && keyframe.value.extrapolates(after)
1318        })
1319        && keyframes.len() <= MAX_KEYFRAMES
1320        && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
1321        && keyframes
1322            .iter()
1323            .all(|keyframe| keyframe.interpolation.is_valid())
1324        && keyframes
1325            .iter()
1326            .zip(keyframes.iter().skip(1).map(Some).chain([None]))
1327            .all(|(keyframe, next)| {
1328                !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
1329                    || (keyframe.value.takes_value_curve()
1330                        && next.is_none_or(|next| next.value.takes_value_curve()))
1331            })
1332}