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                "description": "The one subpath.",
626                "type": "array",
627                "minItems": 1,
628                "maxItems": 1,
629                "items": {
630                    "type": "object",
631                    "properties": {
632                        "closed": {
633                            "description": "Whether a segment joins the last vertex back to the first.",
634                            "type": "boolean",
635                            "default": false
636                        },
637                        "vertices": {
638                            "description": "The vertices, in order.",
639                            "type": "array",
640                            "minItems": 2,
641                            "maxItems": MAX_MOTION_PATH_VERTICES,
642                            "items": vertex
643                        }
644                    },
645                    "required": ["vertices"],
646                    "additionalProperties": false
647                }
648            }
649        },
650        "required": ["subpaths"],
651        "additionalProperties": false
652    })
653}
654
655/// How a transform turns with its position.
656#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
657#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
658#[serde(rename_all = "snake_case")]
659pub enum Orient {
660    /// It does not.
661    #[default]
662    None,
663    /// The direction of the position's path where the position is, is added to the rotation:
664    /// that of its spatial curve between keyframes, or of the path of a `path` position. A
665    /// position with no path adds nothing.
666    Path,
667}
668
669impl Orient {
670    #[expect(
671        clippy::trivially_copy_pass_by_ref,
672        reason = "serde passes a field by reference"
673    )]
674    fn is_none(&self) -> bool {
675        *self == Self::None
676    }
677}
678
679fn two_channels<'de, D: serde::Deserializer<'de>>(
680    deserializer: D,
681) -> Result<Vec<Animated<f32>>, D::Error> {
682    let channels = crate::bounded::seq::<_, Animated<f32>, 2>(deserializer)?;
683    if channels.len() != 2 {
684        return Err(serde::de::Error::custom(format_args!(
685            "a `split` position has 2 channels, not {}",
686            channels.len()
687        )));
688    }
689    Ok(channels)
690}
691
692impl Default for AnimatedPoint {
693    fn default() -> Self {
694        Self::Constant {
695            value: Vec2::default(),
696        }
697    }
698}
699
700impl From<Animated<Vec2>> for AnimatedPoint {
701    fn from(animation: Animated<Vec2>) -> Self {
702        match animation {
703            Animated::Constant { value } => Self::Constant { value },
704            Animated::Keyframes {
705                keyframes,
706                before,
707                after,
708            } => Self::Keyframes {
709                keyframes: keyframes
710                    .into_iter()
711                    .map(|keyframe| PointKeyframe {
712                        time: keyframe.time,
713                        value: keyframe.value,
714                        interpolation: keyframe.interpolation,
715                        out_tangent: Vec2::default(),
716                        in_tangent: Vec2::default(),
717                    })
718                    .collect(),
719                before,
720                after,
721            },
722            Animated::Split { channels } => Self::Split { channels },
723            Animated::Data(binding) => Self::Data(binding),
724        }
725    }
726}
727
728impl Animated<f32> {
729    /// Whether a project can hold this number: finite values, and keyframes that ascend, stay
730    /// within [`MAX_KEYFRAMES`] and have valid interpolations. A `split` number is not valid.
731    #[must_use]
732    pub fn is_valid(&self) -> bool {
733        valid_scalar_values(self, |_| true)
734    }
735}
736
737impl AnimatedPoint {
738    /// Whether a project can hold this position: finite values and tangents, and keyframes that
739    /// ascend, stay within [`MAX_KEYFRAMES`] and have valid interpolations.
740    #[must_use]
741    pub fn is_valid(&self) -> bool {
742        valid_point_animation(self)
743    }
744
745    /// A position controlled by `keyframes`, holding before the first and after the last.
746    #[must_use]
747    pub const fn keyed(keyframes: Vec<PointKeyframe>) -> Self {
748        Self::Keyframes {
749            keyframes,
750            before: Extrapolation::Hold,
751            after: Extrapolation::Hold,
752        }
753    }
754
755    /// Whether the value changes over time: keyframes, split channels or data.
756    #[must_use]
757    pub const fn is_animated(&self) -> bool {
758        !matches!(self, Self::Constant { .. })
759    }
760
761    /// The data binding, when the whole value follows a data set. A `split` value's channels
762    /// hold their own.
763    #[must_use]
764    pub const fn data(&self) -> Option<&DataBinding> {
765        match self {
766            Self::Data(binding) => Some(binding),
767            Self::Constant { .. } | Self::Keyframes { .. } | Self::Split { .. } | Self::Path(_) => {
768                None
769            }
770        }
771    }
772}
773
774/// One keyframe of an [`AnimatedPoint`].
775#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
776#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
777#[serde(deny_unknown_fields)]
778pub struct PointKeyframe {
779    /// Timestamp of this value, as a [`Keyframe`]'s.
780    pub time: alpha2_time::MediaTime,
781    /// Value at `time`.
782    pub value: Vec2,
783    /// Interpolation from this keyframe to its successor: how fast the value travels along the
784    /// way.
785    #[serde(deserialize_with = "timing_interpolation")]
786    #[cfg_attr(feature = "schema", schemars(with = "TimingInterpolation"))]
787    pub interpolation: Interpolation,
788    /// The curve's first control point toward the next keyframe, relative to this value.
789    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
790    pub out_tangent: Vec2,
791    /// The curve's second control point from the previous keyframe, relative to this value.
792    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
793    pub in_tangent: Vec2,
794}
795
796/// One timestamped control value.
797#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
798#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
799#[serde(deny_unknown_fields)]
800#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
801#[cfg_attr(
802    feature = "schema",
803    schemars(bound = "T: schemars::JsonSchema + AnimatedValue")
804)]
805pub struct Keyframe<T> {
806    /// Timestamp of this value. Timeline time, except composition time in a composition node's
807    /// settings and picture time in a shapes or layout generator's tree.
808    pub time: alpha2_time::MediaTime,
809    /// Value at `time`.
810    pub value: T,
811    /// Interpolation from this keyframe to its successor.
812    #[cfg_attr(
813        feature = "schema",
814        schemars(schema_with = "interpolation_schema::<T>")
815    )]
816    pub interpolation: Interpolation,
817}
818
819#[cfg(feature = "schema")]
820fn interpolation_schema<T: AnimatedValue>(
821    generator: &mut schemars::SchemaGenerator,
822) -> schemars::Schema {
823    if T::VALUE_CURVES {
824        generator.subschema_for::<Interpolation>()
825    } else {
826        generator.subschema_for::<TimingInterpolation>()
827    }
828}
829
830fn timing_interpolation<'de, D: serde::Deserializer<'de>>(
831    deserializer: D,
832) -> Result<Interpolation, D::Error> {
833    let interpolation = Interpolation::deserialize(deserializer)?;
834    if matches!(interpolation, Interpolation::ValueBezier(_)) {
835        return Err(serde::de::Error::custom(
836            "a position takes no `value_bezier`; split it or use a timing curve",
837        ));
838    }
839    Ok(interpolation)
840}
841
842/// Interpolation from one keyframe to the next.
843///
844/// Values interpolate numerically: a rotation from 0 to 720 degrees turns twice. A host that
845/// wants the shortest path normalizes its keyframe values.
846#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
847#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
848#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
849pub enum Interpolation {
850    /// Keep this keyframe's value until the next keyframe.
851    Hold,
852    /// Move to the next value at a constant rate.
853    Linear,
854    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
855    CubicBezier(CubicBezier),
856    /// Move to the next value along a value curve, which can move between equal values. Numbers
857    /// only: an animated number, or an effect parameter between `float` keyframes.
858    ValueBezier(ValueBezier),
859    /// Move to the next value in equal steps, as CSS `steps()`. A step starts on the first tick
860    /// at or after its exact time.
861    Steps(Steps),
862    /// Move to the next value along straight lines through a table of points, as CSS
863    /// `linear()`: from `(0, 0)` through each point to `(1, 1)`.
864    Points {
865        /// The points between the two ends, rising strictly in `x`; at most
866        /// [`crate::MAX_EASING_POINTS`].
867        points: Vec<EasingPoint>,
868    },
869}
870
871#[cfg(feature = "schema")]
872pub(crate) struct TimingInterpolation;
873
874#[cfg(feature = "schema")]
875impl schemars::JsonSchema for TimingInterpolation {
876    fn schema_name() -> std::borrow::Cow<'static, str> {
877        "TimingInterpolation".into()
878    }
879
880    fn schema_id() -> std::borrow::Cow<'static, str> {
881        "alpha2_model::TimingInterpolation".into()
882    }
883
884    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
885        let mut schema = InterpolationWire::json_schema(generator);
886        crate::schema::drop_variant(&mut schema, "type", "value_bezier");
887        schema.insert(
888            "description".to_owned(),
889            "Interpolation from one keyframe to the next for a value that is not a number: every \
890             kind but\nthe value curve."
891                .into(),
892        );
893        schema
894    }
895}
896
897/// The wire form of [`Interpolation`]; see `EasingWire` for why unit variants are empty
898/// structs.
899#[derive(Deserialize)]
900#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
901#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
902#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
903pub(crate) enum InterpolationWire {
904    /// Keep this keyframe's value until the next keyframe.
905    Hold {},
906    /// Move to the next value at a constant rate.
907    Linear {},
908    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
909    CubicBezier(CubicBezier),
910    /// Move to the next value along a value curve, which can move between equal values. Numbers
911    /// only: an animated number, or an effect parameter between `float` keyframes.
912    ValueBezier(ValueBezier),
913    /// Move to the next value in equal steps, as CSS `steps()`. A step starts on the first tick
914    /// at or after its exact time.
915    Steps(Steps),
916    /// Move to the next value along straight lines through a table of points, as CSS
917    /// `linear()`: from `(0, 0)` through each point to `(1, 1)`.
918    Points {
919        /// The points between the two ends, rising strictly in `x`; at most
920        /// `MAX_EASING_POINTS`.
921        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EASING_POINTS }>")]
922        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EASING_POINTS)))]
923        points: Vec<EasingPoint>,
924    },
925}
926
927impl From<InterpolationWire> for Interpolation {
928    fn from(wire: InterpolationWire) -> Self {
929        match wire {
930            InterpolationWire::Hold {} => Self::Hold,
931            InterpolationWire::Linear {} => Self::Linear,
932            InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
933            InterpolationWire::ValueBezier(curve) => Self::ValueBezier(curve),
934            InterpolationWire::Steps(steps) => Self::Steps(steps),
935            InterpolationWire::Points { points } => Self::Points { points },
936        }
937    }
938}
939
940impl From<Easing> for Interpolation {
941    fn from(easing: Easing) -> Self {
942        match easing {
943            Easing::Linear => Self::Linear,
944            Easing::CubicBezier(curve) => Self::CubicBezier(curve),
945            Easing::Steps(steps) => Self::Steps(steps),
946            Easing::Points { points } => Self::Points { points },
947        }
948    }
949}
950
951/// What a keyframe segment does at one progress.
952#[derive(Copy, Clone, Debug, PartialEq)]
953pub enum SegmentShape {
954    /// Keeps the left keyframe's value.
955    Hold,
956    /// This fraction of the way to the next value; may leave `0..=1`.
957    Amount(f64),
958    /// Follows a value curve between the two keyframes' values.
959    Value(ValueBezier),
960}
961
962impl Interpolation {
963    /// What the segment does at linear `progress` (clamped to `0..=1` for an amount). The
964    /// keyframe sampler places `steps` by whole ticks instead ([`Steps::index`]).
965    #[must_use]
966    #[inline]
967    pub fn shape(&self, progress: f64) -> SegmentShape {
968        match self {
969            Self::Hold => SegmentShape::Hold,
970            Self::Linear => SegmentShape::Amount(progress.clamp(0.0, 1.0)),
971            Self::CubicBezier(curve) => SegmentShape::Amount(curve.apply(progress)),
972            Self::ValueBezier(curve) => SegmentShape::Value(*curve),
973            Self::Steps(steps) => SegmentShape::Amount(steps.apply(progress)),
974            Self::Points { points } => {
975                SegmentShape::Amount(crate::easing_points_at(points, progress))
976            }
977        }
978    }
979
980    /// The slope of the amount where the segment starts (`at_end` false) or ends, which
981    /// `linear` extrapolation continues: 0 for `hold`. `None` for a value curve, which has no
982    /// amount; its slope is [`ValueBezier::end_slope`].
983    #[must_use]
984    pub fn end_slope(&self, at_end: bool) -> Option<f64> {
985        match self {
986            Self::Hold | Self::Steps(_) => Some(0.0),
987            Self::Linear => Some(1.0),
988            Self::CubicBezier(curve) => Some(curve.end_slope(at_end)),
989            Self::ValueBezier(_) => None,
990            Self::Points { points } => Some(crate::easing_points_slope(
991                points,
992                if at_end { 1.0 } else { 0.0 },
993            )),
994        }
995    }
996
997    /// Whether the interpolation's parameters are usable.
998    #[must_use]
999    pub fn is_valid(&self) -> bool {
1000        match self {
1001            Self::Hold | Self::Linear => true,
1002            Self::CubicBezier(curve) => curve.is_valid(),
1003            Self::ValueBezier(curve) => curve.is_valid(),
1004            Self::Steps(steps) => steps.is_valid(),
1005            Self::Points { points } => crate::easing_points_valid(points),
1006        }
1007    }
1008}
1009
1010/// Resolution-independent visual presentation controls for a clip.
1011#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1012#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1013#[serde(deny_unknown_fields)]
1014///
1015/// Omitted fields default to the source centred on the canvas, unscaled, unrotated and opaque.
1016pub struct VisualProperties {
1017    /// Animated normalized canvas translation, along spatial curves where keyframes have
1018    /// tangents.
1019    #[serde(default = "centre_point")]
1020    pub position: AnimatedPoint,
1021    /// Unanimated normalized point within the source rectangle.
1022    #[serde(default = "centre")]
1023    pub anchor: Vec2,
1024    /// Animated per-axis scale.
1025    #[serde(default = "unit_scale")]
1026    pub scale: Animated<Vec2>,
1027    /// Animated clockwise rotation in degrees.
1028    #[serde(default = "no_rotation")]
1029    pub rotation_degrees: Animated<f32>,
1030    /// Animated opacity constrained to `0..=1`.
1031    #[serde(default = "opaque")]
1032    pub opacity: Animated<f32>,
1033    /// A `similarity` data set moving the clip's own picture, applied before this transform.
1034    /// Clip visuals only.
1035    #[serde(default, skip_serializing_if = "Option::is_none")]
1036    pub correction: Option<crate::CorrectionRef>,
1037    /// Whether the rotation follows the direction of the position's path.
1038    #[serde(default, skip_serializing_if = "Orient::is_none")]
1039    pub orient: Orient,
1040}
1041
1042impl Default for VisualProperties {
1043    fn default() -> Self {
1044        Self {
1045            position: centre_point(),
1046            anchor: centre(),
1047            scale: unit_scale(),
1048            rotation_degrees: no_rotation(),
1049            opacity: opaque(),
1050            correction: None,
1051            orient: Orient::None,
1052        }
1053    }
1054}
1055
1056const fn centre() -> Vec2 {
1057    Vec2::new(0.5, 0.5)
1058}
1059
1060const fn centre_point() -> AnimatedPoint {
1061    AnimatedPoint::Constant { value: centre() }
1062}
1063
1064pub(crate) const fn unit_scale() -> Animated<Vec2> {
1065    Animated::Constant {
1066        value: Vec2::new(1.0, 1.0),
1067    }
1068}
1069
1070const fn no_rotation() -> Animated<f32> {
1071    Animated::Constant { value: 0.0 }
1072}
1073
1074pub(crate) const fn opaque() -> Animated<f32> {
1075    Animated::Constant { value: 1.0 }
1076}
1077
1078/// What a walk over animated values meets at one value that is not constant.
1079pub(crate) enum Keyed<'a> {
1080    /// The times of its keyframes.
1081    Times(&'a [alpha2_time::MediaTime], Extrapolation, Extrapolation),
1082    /// Its data binding, with the type of the value bound.
1083    Data(&'a DataBinding, PlaceType),
1084}
1085
1086/// The value type a data binding sits on, which decides the kinds it can follow.
1087#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1088pub(crate) enum PlaceType {
1089    /// A point along spatial curves.
1090    Point,
1091    /// A two-component value.
1092    Vec2,
1093    /// A number.
1094    Scalar,
1095    /// An effect parameter, whose type its definition gives.
1096    Effect,
1097    /// A type that takes no data.
1098    Other,
1099}
1100
1101/// The [`PlaceType`] of each animatable type.
1102pub(crate) trait Placed {
1103    const PLACE: PlaceType;
1104}
1105
1106macro_rules! placed {
1107    ($place:ident: $($type:ty),+) => {
1108        $(impl Placed for $type {
1109            const PLACE: PlaceType = PlaceType::$place;
1110        })+
1111    };
1112}
1113
1114placed!(Scalar: f32);
1115placed!(Vec2: Vec2);
1116placed!(Effect: crate::EffectValue);
1117placed!(
1118    Other: String,
1119    crate::TextContent,
1120    crate::Paint,
1121    crate::Rgba,
1122    crate::Path,
1123    crate::LayoutLength,
1124    crate::LayoutSize,
1125    crate::LayoutOffset,
1126    crate::Insets
1127);
1128
1129/// Calls `visit` with `at` and the times of `animated`'s keyframes, or its data binding.
1130pub(crate) fn visit_keyed<T: Placed>(
1131    at: &str,
1132    animated: &Animated<T>,
1133    visit: &mut impl FnMut(&str, Keyed<'_>),
1134) {
1135    match animated {
1136        Animated::Keyframes {
1137            keyframes,
1138            before,
1139            after,
1140        } => {
1141            let times = keyframes
1142                .iter()
1143                .map(|keyframe| keyframe.time)
1144                .collect::<Vec<_>>();
1145            visit(at, Keyed::Times(&times, *before, *after));
1146        }
1147        Animated::Split { channels } => visit_keyed_channels(at, channels, visit),
1148        Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
1149        Animated::Constant { .. } => {}
1150    }
1151}
1152
1153fn visit_keyed_channels(
1154    at: &str,
1155    channels: &[Animated<f32>],
1156    visit: &mut impl FnMut(&str, Keyed<'_>),
1157) {
1158    for (index, channel) in channels.iter().enumerate() {
1159        match channel {
1160            Animated::Keyframes {
1161                keyframes,
1162                before,
1163                after,
1164            } => {
1165                let times = keyframes
1166                    .iter()
1167                    .map(|keyframe| keyframe.time)
1168                    .collect::<Vec<_>>();
1169                visit(
1170                    &channel_path(at, index),
1171                    Keyed::Times(&times, *before, *after),
1172                );
1173            }
1174            Animated::Data(binding) => visit(
1175                &channel_path(at, index),
1176                Keyed::Data(binding, PlaceType::Scalar),
1177            ),
1178            Animated::Constant { .. } | Animated::Split { .. } => {}
1179        }
1180    }
1181}
1182
1183/// [`visit_keyed`] for a point along a spatial curve.
1184pub(crate) fn visit_keyed_point(
1185    at: &str,
1186    animated: &AnimatedPoint,
1187    visit: &mut impl FnMut(&str, Keyed<'_>),
1188) {
1189    match animated {
1190        AnimatedPoint::Keyframes {
1191            keyframes,
1192            before,
1193            after,
1194        } => {
1195            let times = keyframes
1196                .iter()
1197                .map(|keyframe| keyframe.time)
1198                .collect::<Vec<_>>();
1199            visit(at, Keyed::Times(&times, *before, *after));
1200        }
1201        AnimatedPoint::Split { channels } => visit_keyed_channels(at, channels, visit),
1202        AnimatedPoint::Path(motion) => {
1203            visit_keyed(&format!("{at}.distance"), &motion.distance, visit);
1204        }
1205        AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
1206        AnimatedPoint::Constant { .. } => {}
1207    }
1208}
1209
1210impl VisualProperties {
1211    pub(crate) fn validate(&self) -> bool {
1212        self.anchor.is_finite()
1213            && valid_point_animation(&self.position)
1214            && valid_vec2_animation(&self.scale)
1215            && valid_scalar_animation(&self.rotation_degrees, false)
1216            && valid_scalar_animation(&self.opacity, true)
1217    }
1218}
1219
1220fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
1221    match animation {
1222        Animated::Constant { value } => value.is_finite(),
1223        Animated::Keyframes {
1224            keyframes,
1225            before,
1226            after,
1227        } => {
1228            valid_keyframes(keyframes, *before, *after)
1229                && keyframes.iter().all(|keyframe| keyframe.value.is_finite())
1230        }
1231        Animated::Split { channels } => valid_channels(channels, 2..=2, |_| true),
1232        Animated::Data(_) => true,
1233    }
1234}
1235
1236/// Valid keyframes (or a constant) whose values and tangents are finite.
1237pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
1238    match animation {
1239        AnimatedPoint::Constant { value } => value.is_finite(),
1240        AnimatedPoint::Data(_) => true,
1241        AnimatedPoint::Split { channels } => valid_channels(channels, 2..=2, |_| true),
1242        AnimatedPoint::Path(motion) => {
1243            let vertices = match motion.path.subpaths.as_slice() {
1244                [subpath] => subpath.vertices.as_slice(),
1245                _ => &[],
1246            };
1247            (2..=MAX_MOTION_PATH_VERTICES).contains(&vertices.len())
1248                && vertices.iter().all(|vertex| {
1249                    vertex.point.is_finite()
1250                        && vertex.in_tangent.is_finite()
1251                        && vertex.out_tangent.is_finite()
1252                })
1253                && valid_scalar_values(&motion.distance, |_| true)
1254        }
1255        AnimatedPoint::Keyframes { keyframes, .. } => {
1256            !keyframes.is_empty()
1257                && keyframes.len() <= MAX_KEYFRAMES
1258                && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
1259                && keyframes.iter().all(|keyframe| {
1260                    keyframe.interpolation.is_valid()
1261                        && !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
1262                        && keyframe.value.is_finite()
1263                        && keyframe.out_tangent.is_finite()
1264                        && keyframe.in_tangent.is_finite()
1265                })
1266        }
1267    }
1268}
1269
1270fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
1271    let domain = if unit_interval {
1272        crate::Domain::UNIT
1273    } else {
1274        crate::Domain::ANY
1275    };
1276    let valid_value = |value: f32| domain.contains(value);
1277    match animation {
1278        Animated::Constant { value } => valid_value(*value),
1279        Animated::Keyframes {
1280            keyframes,
1281            before,
1282            after,
1283        } => {
1284            valid_keyframes(keyframes, *before, *after)
1285                && keyframes.iter().all(|keyframe| valid_value(keyframe.value))
1286        }
1287        Animated::Split { .. } => false,
1288        Animated::Data(_) => true,
1289    }
1290}
1291
1292/// Valid keyframes (or a constant) whose every finite value passes `check`.
1293pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
1294    let valid = |value: f32| value.is_finite() && check(value);
1295    match animation {
1296        Animated::Constant { value } => valid(*value),
1297        Animated::Keyframes {
1298            keyframes,
1299            before,
1300            after,
1301        } => {
1302            valid_keyframes(keyframes, *before, *after)
1303                && keyframes.iter().all(|keyframe| valid(keyframe.value))
1304        }
1305        Animated::Split { .. } => false,
1306        Animated::Data(_) => true,
1307    }
1308}
1309
1310/// A non-empty, strictly ascending run of at most [`MAX_KEYFRAMES`] with usable interpolations.
1311pub(crate) fn valid_keyframes<T: AnimatedValue>(
1312    keyframes: &[Keyframe<T>],
1313    before: Extrapolation,
1314    after: Extrapolation,
1315) -> bool {
1316    !keyframes.is_empty()
1317        && keyframes.iter().all(|keyframe| {
1318            keyframe.value.extrapolates(before) && keyframe.value.extrapolates(after)
1319        })
1320        && keyframes.len() <= MAX_KEYFRAMES
1321        && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
1322        && keyframes
1323            .iter()
1324            .all(|keyframe| keyframe.interpolation.is_valid())
1325        && keyframes
1326            .iter()
1327            .zip(keyframes.iter().skip(1).map(Some).chain([None]))
1328            .all(|(keyframe, next)| {
1329                !matches!(keyframe.interpolation, Interpolation::ValueBezier(_))
1330                    || (keyframe.value.takes_value_curve()
1331                        && next.is_none_or(|next| next.value.takes_value_curve()))
1332            })
1333}