Skip to main content

alpha2_model/
animation.rs

1use crate::{CubicBezier, DataBinding, Easing};
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/// A value that is constant, controlled by sorted keyframes, or following a data set.
37///
38/// Only value types whose [`AnimatedValue::ACCEPTS_DATA`] is true (`f32`, [`Vec2`] and
39/// [`crate::EffectValue`]) read or offer the `data` mode; for the others it fails to
40/// deserialize and the schema leaves it out.
41#[derive(Clone, Debug, PartialEq, Serialize)]
42#[serde(tag = "mode", rename_all = "snake_case")]
43pub enum Animated<T> {
44    /// A value without animation.
45    Constant {
46        /// Value used at every timestamp.
47        value: T,
48    },
49    /// Values evaluated from their keyframe sequence.
50    Keyframes {
51        /// Strictly ascending keyframes. The evaluator clamps outside the sequence.
52        keyframes: Vec<Keyframe<T>>,
53    },
54    /// A channel of a data set, followed at render time.
55    Data(Box<DataBinding>),
56}
57
58mod sealed {
59    pub trait Sealed {}
60}
61
62/// A type an [`Animated`] value can hold. Sealed: implemented for the model's animatable types.
63pub trait AnimatedValue: sealed::Sealed {
64    /// Whether the type takes the `data` value mode.
65    const ACCEPTS_DATA: bool;
66}
67
68macro_rules! animated_value {
69    ($accepts:literal: $($type:ty),+) => {
70        $(
71            impl sealed::Sealed for $type {}
72            impl AnimatedValue for $type {
73                const ACCEPTS_DATA: bool = $accepts;
74            }
75        )+
76    };
77}
78
79animated_value!(true: f32, Vec2, crate::EffectValue);
80animated_value!(
81    false: String,
82    crate::TextContent,
83    crate::Paint,
84    crate::Rgba,
85    crate::Path,
86    crate::LayoutLength,
87    crate::LayoutSize,
88    crate::LayoutOffset,
89    crate::Insets
90);
91
92// The wire form of `Animated`, before the value type decides whether it takes data. Its doc
93// comment is the schema's description.
94/// A value that is constant, controlled by sorted keyframes, or following a data set.
95#[derive(Deserialize)]
96#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
97#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
98#[cfg_attr(feature = "schema", schemars(rename = "Animated_{T}"))]
99enum AnimatedWire<T> {
100    /// A value without animation.
101    Constant {
102        /// Value used at every timestamp.
103        value: T,
104    },
105    /// Values evaluated from their keyframe sequence.
106    Keyframes {
107        /// Strictly ascending keyframes. The evaluator clamps outside the sequence.
108        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
109        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
110        keyframes: Vec<Keyframe<T>>,
111    },
112    /// A channel of a data set, followed at render time.
113    Data(DataBinding),
114}
115
116impl<'de, T: Deserialize<'de> + AnimatedValue> Deserialize<'de> for Animated<T> {
117    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
118        Ok(match AnimatedWire::<T>::deserialize(deserializer)? {
119            AnimatedWire::Constant { value } => Self::Constant { value },
120            AnimatedWire::Keyframes { keyframes } => Self::Keyframes { keyframes },
121            AnimatedWire::Data(binding) if T::ACCEPTS_DATA => Self::Data(Box::new(binding)),
122            AnimatedWire::Data(_) => {
123                return Err(serde::de::Error::custom(
124                    "this value takes no `data` mode; use `constant` or `keyframes`",
125                ));
126            }
127        })
128    }
129}
130
131#[cfg(feature = "schema")]
132impl<T: schemars::JsonSchema + AnimatedValue> schemars::JsonSchema for Animated<T> {
133    // Types without the data mode are a separate generic, `Keyframed_{T}`, for one shape each.
134    fn schema_name() -> std::borrow::Cow<'static, str> {
135        if T::ACCEPTS_DATA {
136            AnimatedWire::<T>::schema_name()
137        } else {
138            format!("Keyframed_{}", T::schema_name()).into()
139        }
140    }
141
142    fn schema_id() -> std::borrow::Cow<'static, str> {
143        if T::ACCEPTS_DATA {
144            AnimatedWire::<T>::schema_id()
145        } else {
146            format!("alpha2_model::Keyframed<{}>", T::schema_id()).into()
147        }
148    }
149
150    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
151        let mut schema = AnimatedWire::<T>::json_schema(generator);
152        if !T::ACCEPTS_DATA {
153            crate::schema::drop_data_mode(&mut schema);
154            schema.insert(
155                "description".to_owned(),
156                "A value that is constant or controlled by sorted keyframes.".into(),
157            );
158        }
159        schema
160    }
161}
162
163impl<T> Animated<T> {
164    /// The same animation with each value mapped by `map`, keeping times and interpolations.
165    #[must_use]
166    pub fn map<U>(&self, map: impl Fn(&T) -> U) -> Animated<U> {
167        match self {
168            Self::Constant { value } => Animated::Constant { value: map(value) },
169            Self::Keyframes { keyframes } => Animated::Keyframes {
170                keyframes: keyframes
171                    .iter()
172                    .map(|keyframe| Keyframe {
173                        time: keyframe.time,
174                        value: map(&keyframe.value),
175                        interpolation: keyframe.interpolation,
176                    })
177                    .collect(),
178            },
179            Self::Data(binding) => Animated::Data(binding.clone()),
180        }
181    }
182
183    /// The data binding, when the value follows a data set.
184    #[must_use]
185    pub const fn data(&self) -> Option<&DataBinding> {
186        match self {
187            Self::Data(binding) => Some(binding),
188            Self::Constant { .. } | Self::Keyframes { .. } => None,
189        }
190    }
191
192    /// Whether the value can change over time: keyframes or data.
193    #[must_use]
194    pub const fn varies(&self) -> bool {
195        !matches!(self, Self::Constant { .. })
196    }
197}
198
199/// A position that can move along curves between its keyframes.
200///
201/// Its JSON is an `Animated<Vec2>` plus optional spatial tangents per keyframe. With them,
202/// the value travels the cubic Bezier through this keyframe's `out_tangent` and the next's
203/// `in_tangent`, at the speed its timing curve sets along the arc length. Without them it
204/// moves in a straight line.
205#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
206#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
207#[serde(deny_unknown_fields)]
208#[serde(tag = "mode", rename_all = "snake_case")]
209pub enum AnimatedPoint {
210    /// A value without animation.
211    Constant {
212        /// Value used at every timestamp.
213        value: Vec2,
214    },
215    /// Values evaluated from their keyframe sequence.
216    Keyframes {
217        /// Strictly ascending keyframes. The evaluator clamps outside the sequence.
218        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_KEYFRAMES }>")]
219        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_KEYFRAMES)))]
220        keyframes: Vec<PointKeyframe>,
221    },
222    /// A channel of a data set, followed at render time.
223    Data(Box<DataBinding>),
224}
225
226impl Default for AnimatedPoint {
227    fn default() -> Self {
228        Self::Constant {
229            value: Vec2::default(),
230        }
231    }
232}
233
234impl From<Animated<Vec2>> for AnimatedPoint {
235    fn from(animation: Animated<Vec2>) -> Self {
236        match animation {
237            Animated::Constant { value } => Self::Constant { value },
238            Animated::Keyframes { keyframes } => Self::Keyframes {
239                keyframes: keyframes
240                    .into_iter()
241                    .map(|keyframe| PointKeyframe {
242                        time: keyframe.time,
243                        value: keyframe.value,
244                        interpolation: keyframe.interpolation,
245                        out_tangent: Vec2::default(),
246                        in_tangent: Vec2::default(),
247                    })
248                    .collect(),
249            },
250            Animated::Data(binding) => Self::Data(binding),
251        }
252    }
253}
254
255impl AnimatedPoint {
256    /// Whether the value changes over time: keyframes or data.
257    #[must_use]
258    pub const fn is_animated(&self) -> bool {
259        !matches!(self, Self::Constant { .. })
260    }
261
262    /// The data binding, when the value follows a data set.
263    #[must_use]
264    pub const fn data(&self) -> Option<&DataBinding> {
265        match self {
266            Self::Data(binding) => Some(binding),
267            Self::Constant { .. } | Self::Keyframes { .. } => None,
268        }
269    }
270}
271
272/// One keyframe of an [`AnimatedPoint`].
273#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
274#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
275#[serde(deny_unknown_fields)]
276pub struct PointKeyframe {
277    /// Timestamp of this value, as a [`Keyframe`]'s.
278    pub time: alpha2_time::MediaTime,
279    /// Value at `time`.
280    pub value: Vec2,
281    /// Interpolation from this keyframe to its successor: how fast the value travels along the
282    /// way.
283    pub interpolation: Interpolation,
284    /// The curve's first control point toward the next keyframe, relative to this value.
285    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
286    pub out_tangent: Vec2,
287    /// The curve's second control point from the previous keyframe, relative to this value.
288    #[serde(default, skip_serializing_if = "Vec2::is_zero")]
289    pub in_tangent: Vec2,
290}
291
292/// One timestamped control value.
293#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
294#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
295#[serde(deny_unknown_fields)]
296#[cfg_attr(feature = "schema", schemars(rename = "Keyframe_{T}"))]
297pub struct Keyframe<T> {
298    /// Timestamp of this value. Timeline time, except composition time in a composition node's
299    /// settings and picture time in a shapes or layout generator's tree.
300    pub time: alpha2_time::MediaTime,
301    /// Value at `time`.
302    pub value: T,
303    /// Interpolation from this keyframe to its successor.
304    pub interpolation: Interpolation,
305}
306
307/// Interpolation from one keyframe to the next.
308///
309/// Values interpolate numerically: a rotation from 0 to 720 degrees turns twice. A host that
310/// wants the shortest path normalizes its keyframe values.
311#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
312#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
313#[serde(tag = "type", rename_all = "snake_case", from = "InterpolationWire")]
314pub enum Interpolation {
315    /// Keep this keyframe's value until the next keyframe.
316    Hold,
317    /// Move to the next value at a constant rate.
318    Linear,
319    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
320    CubicBezier(CubicBezier),
321}
322
323/// The wire form of [`Interpolation`]; see `EasingWire` for why unit variants are empty
324/// structs.
325#[derive(Deserialize)]
326#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
327#[cfg_attr(feature = "schema", schemars(rename = "Interpolation"))]
328#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
329pub(crate) enum InterpolationWire {
330    /// Keep this keyframe's value until the next keyframe.
331    Hold {},
332    /// Move to the next value at a constant rate.
333    Linear {},
334    /// Move to the next value along a CSS `cubic-bezier()` timing curve.
335    CubicBezier(CubicBezier),
336}
337
338impl From<InterpolationWire> for Interpolation {
339    fn from(wire: InterpolationWire) -> Self {
340        match wire {
341            InterpolationWire::Hold {} => Self::Hold,
342            InterpolationWire::Linear {} => Self::Linear,
343            InterpolationWire::CubicBezier(curve) => Self::CubicBezier(curve),
344        }
345    }
346}
347
348impl Interpolation {
349    /// The fraction of the way to the next value at linear segment `progress` (clamped to
350    /// `0..=1`), or `None` while holding. A cubic Bezier may overshoot `0..=1`.
351    #[must_use]
352    pub fn amount(self, progress: f64) -> Option<f64> {
353        match self {
354            Self::Hold => None,
355            Self::Linear => Some(Easing::Linear.apply(progress)),
356            Self::CubicBezier(curve) => Some(curve.apply(progress)),
357        }
358    }
359
360    /// Whether the interpolation's parameters are usable.
361    #[must_use]
362    pub fn is_valid(self) -> bool {
363        match self {
364            Self::Hold | Self::Linear => true,
365            Self::CubicBezier(curve) => curve.is_valid(),
366        }
367    }
368}
369
370/// Resolution-independent visual presentation controls for a clip.
371#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
372#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
373#[serde(deny_unknown_fields)]
374///
375/// Omitted fields default to the source centred on the canvas, unscaled, unrotated and opaque.
376pub struct VisualProperties {
377    /// Animated normalized canvas translation, along spatial curves where keyframes have
378    /// tangents.
379    #[serde(default = "centre_point")]
380    pub position: AnimatedPoint,
381    /// Unanimated normalized point within the source rectangle.
382    #[serde(default = "centre")]
383    pub anchor: Vec2,
384    /// Animated per-axis scale.
385    #[serde(default = "unit_scale")]
386    pub scale: Animated<Vec2>,
387    /// Animated clockwise rotation in degrees.
388    #[serde(default = "no_rotation")]
389    pub rotation_degrees: Animated<f32>,
390    /// Animated opacity constrained to `0..=1`.
391    #[serde(default = "opaque")]
392    pub opacity: Animated<f32>,
393    /// A `similarity` data set moving the clip's own picture, applied before this transform.
394    /// Clip visuals only.
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub correction: Option<crate::CorrectionRef>,
397}
398
399impl Default for VisualProperties {
400    fn default() -> Self {
401        Self {
402            position: centre_point(),
403            anchor: centre(),
404            scale: unit_scale(),
405            rotation_degrees: no_rotation(),
406            opacity: opaque(),
407            correction: None,
408        }
409    }
410}
411
412const fn centre() -> Vec2 {
413    Vec2::new(0.5, 0.5)
414}
415
416const fn centre_point() -> AnimatedPoint {
417    AnimatedPoint::Constant { value: centre() }
418}
419
420pub(crate) const fn unit_scale() -> Animated<Vec2> {
421    Animated::Constant {
422        value: Vec2::new(1.0, 1.0),
423    }
424}
425
426const fn no_rotation() -> Animated<f32> {
427    Animated::Constant { value: 0.0 }
428}
429
430pub(crate) const fn opaque() -> Animated<f32> {
431    Animated::Constant { value: 1.0 }
432}
433
434/// What a walk over animated values meets at one value that is not constant.
435pub(crate) enum Keyed<'a> {
436    /// The times of its keyframes.
437    Times(&'a [alpha2_time::MediaTime]),
438    /// Its data binding, with the type of the value bound.
439    Data(&'a DataBinding, PlaceType),
440}
441
442/// The value type a data binding sits on, which decides the kinds it can follow.
443#[derive(Copy, Clone, Debug, Eq, PartialEq)]
444pub(crate) enum PlaceType {
445    /// A point along spatial curves.
446    Point,
447    /// A two-component value.
448    Vec2,
449    /// A number.
450    Scalar,
451    /// An effect parameter, whose type its definition gives.
452    Effect,
453    /// A type that takes no data.
454    Other,
455}
456
457/// The [`PlaceType`] of each animatable type.
458pub(crate) trait Placed {
459    const PLACE: PlaceType;
460}
461
462macro_rules! placed {
463    ($place:ident: $($type:ty),+) => {
464        $(impl Placed for $type {
465            const PLACE: PlaceType = PlaceType::$place;
466        })+
467    };
468}
469
470placed!(Scalar: f32);
471placed!(Vec2: Vec2);
472placed!(Effect: crate::EffectValue);
473placed!(
474    Other: String,
475    crate::TextContent,
476    crate::Paint,
477    crate::Rgba,
478    crate::Path,
479    crate::LayoutLength,
480    crate::LayoutSize,
481    crate::LayoutOffset,
482    crate::Insets
483);
484
485/// Calls `visit` with `at` and the times of `animated`'s keyframes, or its data binding.
486pub(crate) fn visit_keyed<T: Placed>(
487    at: &str,
488    animated: &Animated<T>,
489    visit: &mut impl FnMut(&str, Keyed<'_>),
490) {
491    match animated {
492        Animated::Keyframes { keyframes } => {
493            let times = keyframes
494                .iter()
495                .map(|keyframe| keyframe.time)
496                .collect::<Vec<_>>();
497            visit(at, Keyed::Times(&times));
498        }
499        Animated::Data(binding) => visit(at, Keyed::Data(binding, T::PLACE)),
500        Animated::Constant { .. } => {}
501    }
502}
503
504/// [`visit_keyed`] for a point along a spatial curve.
505pub(crate) fn visit_keyed_point(
506    at: &str,
507    animated: &AnimatedPoint,
508    visit: &mut impl FnMut(&str, Keyed<'_>),
509) {
510    match animated {
511        AnimatedPoint::Keyframes { keyframes } => {
512            let times = keyframes
513                .iter()
514                .map(|keyframe| keyframe.time)
515                .collect::<Vec<_>>();
516            visit(at, Keyed::Times(&times));
517        }
518        AnimatedPoint::Data(binding) => visit(at, Keyed::Data(binding, PlaceType::Point)),
519        AnimatedPoint::Constant { .. } => {}
520    }
521}
522
523impl VisualProperties {
524    pub(crate) fn validate(&self) -> bool {
525        self.anchor.is_finite()
526            && valid_point_animation(&self.position)
527            && valid_vec2_animation(&self.scale)
528            && valid_scalar_animation(&self.rotation_degrees, false)
529            && valid_scalar_animation(&self.opacity, true)
530    }
531}
532
533fn valid_vec2_animation(animation: &Animated<Vec2>) -> bool {
534    match animation {
535        Animated::Constant { value } => value.is_finite(),
536        Animated::Keyframes { keyframes } => {
537            valid_keyframes(keyframes)
538                && keyframes.iter().all(|keyframe| keyframe.value.is_finite())
539        }
540        Animated::Data(_) => true,
541    }
542}
543
544/// Valid keyframes (or a constant) whose values and tangents are finite.
545pub(crate) fn valid_point_animation(animation: &AnimatedPoint) -> bool {
546    match animation {
547        AnimatedPoint::Constant { value } => value.is_finite(),
548        AnimatedPoint::Data(_) => true,
549        AnimatedPoint::Keyframes { keyframes } => {
550            !keyframes.is_empty()
551                && keyframes.len() <= MAX_KEYFRAMES
552                && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
553                && keyframes.iter().all(|keyframe| {
554                    keyframe.interpolation.is_valid()
555                        && keyframe.value.is_finite()
556                        && keyframe.out_tangent.is_finite()
557                        && keyframe.in_tangent.is_finite()
558                })
559        }
560    }
561}
562
563fn valid_scalar_animation(animation: &Animated<f32>, unit_interval: bool) -> bool {
564    let domain = if unit_interval {
565        crate::Domain::UNIT
566    } else {
567        crate::Domain::ANY
568    };
569    let valid_value = |value: f32| domain.contains(value);
570    match animation {
571        Animated::Constant { value } => valid_value(*value),
572        Animated::Keyframes { keyframes } => {
573            valid_keyframes(keyframes)
574                && keyframes.iter().all(|keyframe| valid_value(keyframe.value))
575        }
576        Animated::Data(_) => true,
577    }
578}
579
580/// Valid keyframes (or a constant) whose every finite value passes `check`.
581pub(crate) fn valid_scalar_values(animation: &Animated<f32>, check: impl Fn(f32) -> bool) -> bool {
582    let valid = |value: f32| value.is_finite() && check(value);
583    match animation {
584        Animated::Constant { value } => valid(*value),
585        Animated::Keyframes { keyframes } => {
586            valid_keyframes(keyframes) && keyframes.iter().all(|keyframe| valid(keyframe.value))
587        }
588        Animated::Data(_) => true,
589    }
590}
591
592/// A non-empty, strictly ascending run of at most [`MAX_KEYFRAMES`] with usable interpolations.
593pub(crate) fn valid_keyframes<T>(keyframes: &[Keyframe<T>]) -> bool {
594    !keyframes.is_empty()
595        && keyframes.len() <= MAX_KEYFRAMES
596        && keyframes.windows(2).all(|pair| pair[0].time < pair[1].time)
597        && keyframes
598            .iter()
599            .all(|keyframe| keyframe.interpolation.is_valid())
600}