Skip to main content

alpha2_eval/
animation.rs

1use crate::{EvaluatedVisual, SampleContext};
2use alpha2_model::{
3    Animated, AnimatedPoint, EffectValue, GradientStop, Insets, Keyframe, LayoutLength,
4    LayoutOffset, LayoutSize, Paint, Path, PointKeyframe, Vec2, VisualProperties,
5};
6use alpha2_time::MediaTime;
7
8/// Evaluates visual properties at a timestamp. `aspect` is the canvas width over height, used
9/// to measure motion along spatial curves; `context` resolves data bindings.
10///
11/// Opacity is clamped to `0..=1`; position, scale and rotation keep curve overshoot.
12#[must_use]
13pub fn sample_visual(
14    properties: &VisualProperties,
15    time: MediaTime,
16    aspect: f64,
17    context: &SampleContext<'_>,
18) -> EvaluatedVisual {
19    EvaluatedVisual {
20        position: sample_point(&properties.position, time, aspect, context),
21        anchor: properties.anchor,
22        scale: evaluate_vec2(&properties.scale, time, context),
23        rotation_degrees: evaluate_scalar(&properties.rotation_degrees, time, context),
24        opacity: evaluate_scalar(&properties.opacity, time, context).clamp(0.0, 1.0),
25    }
26}
27
28fn evaluate_vec2(animation: &Animated<Vec2>, time: MediaTime, context: &SampleContext<'_>) -> Vec2 {
29    match animation {
30        Animated::Constant { value } => *value,
31        Animated::Data(binding) => {
32            crate::data::bound_vec2(binding, time, context).unwrap_or_default()
33        }
34        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
35            Segment::Between(left, right, amount) => Vec2::new(
36                interpolate_f32(left.value.x, right.value.x, amount),
37                interpolate_f32(left.value.y, right.value.y, amount),
38            ),
39            Segment::At(keyframe) => keyframe.value,
40            Segment::Empty => Vec2::default(),
41        },
42    }
43}
44
45/// Samples an animated 2D value like [`sample_scalar`]. Use [`sample_point`] for positions that
46/// may follow spatial curves.
47#[must_use]
48pub fn sample_vec2(
49    animation: &Animated<Vec2>,
50    time: MediaTime,
51    context: &SampleContext<'_>,
52) -> Vec2 {
53    evaluate_vec2(animation, time, context)
54}
55
56/// Samples one animated scalar with the project's keyframe semantics.
57///
58/// Times outside the keyframes clamp to the first or last value, and a
59/// [`alpha2_model::Interpolation::Hold`] segment keeps its left value. Interpolation is numeric,
60/// so a rotation from 0 to 720 degrees turns twice. A data binding reads its channel through
61/// `context`, and is zero without a value.
62#[must_use]
63pub fn sample_scalar(
64    animation: &Animated<f32>,
65    time: MediaTime,
66    context: &SampleContext<'_>,
67) -> f32 {
68    evaluate_scalar(animation, time, context)
69}
70
71fn evaluate_scalar(animation: &Animated<f32>, time: MediaTime, context: &SampleContext<'_>) -> f32 {
72    match animation {
73        Animated::Constant { value } => *value,
74        Animated::Data(binding) => crate::data::bound_scalar(binding, time, context).unwrap_or(0.0),
75        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
76            Segment::Between(left, right, amount) => {
77                interpolate_f32(left.value, right.value, amount)
78            }
79            Segment::At(keyframe) => keyframe.value,
80            Segment::Empty => 0.0,
81        },
82    }
83}
84
85/// Samples a position that may move along spatial curves.
86///
87/// With both facing tangents zero the value moves in a straight line like an `Animated<Vec2>`.
88/// Otherwise it follows the cubic Bezier, measured in a space `aspect` wide per unit high, and the
89/// eased amount is the fraction of arc length travelled. Overshoot continues along the end
90/// tangent.
91#[must_use]
92pub fn sample_point(
93    animation: &AnimatedPoint,
94    time: MediaTime,
95    aspect: f64,
96    context: &SampleContext<'_>,
97) -> Vec2 {
98    match animation {
99        AnimatedPoint::Constant { value } => *value,
100        AnimatedPoint::Data(binding) => {
101            crate::data::bound_vec2(binding, time, context).unwrap_or_default()
102        }
103        AnimatedPoint::Keyframes { keyframes } => match point_segment(keyframes, time) {
104            PointSegment::At(value) => value,
105            PointSegment::Between(left, right, amount) => {
106                if left.out_tangent.is_zero() && right.in_tangent.is_zero() {
107                    return Vec2::new(
108                        interpolate_f32(left.value.x, right.value.x, amount),
109                        interpolate_f32(left.value.y, right.value.y, amount),
110                    );
111                }
112                let aspect = if aspect.is_finite() && aspect > 0.0 {
113                    aspect
114                } else {
115                    1.0
116                };
117                let point = |value: Vec2| {
118                    alpha2_geometry::kurbo::Point::new(
119                        f64::from(value.x) * aspect,
120                        f64::from(value.y),
121                    )
122                };
123                let vector = |value: Vec2| {
124                    alpha2_geometry::kurbo::Vec2::new(
125                        f64::from(value.x) * aspect,
126                        f64::from(value.y),
127                    )
128                };
129                let at = alpha2_geometry::spatial::point_along(
130                    point(left.value),
131                    vector(left.out_tangent),
132                    vector(right.in_tangent),
133                    point(right.value),
134                    amount,
135                );
136                Vec2::new(finite_f32(at.x / aspect), finite_f32(at.y))
137            }
138        },
139    }
140}
141
142enum PointSegment<'a> {
143    At(Vec2),
144    Between(&'a PointKeyframe, &'a PointKeyframe, f64),
145}
146
147fn point_segment(keyframes: &[PointKeyframe], time: MediaTime) -> PointSegment<'_> {
148    let next = keyframes.partition_point(|keyframe| keyframe.time <= time);
149    if next == 0 {
150        return PointSegment::At(
151            keyframes
152                .first()
153                .map_or_else(Vec2::default, |key| key.value),
154        );
155    }
156    let left = &keyframes[next - 1];
157    let Some(right) = keyframes.get(next) else {
158        return PointSegment::At(left.value);
159    };
160    if time == left.time {
161        return PointSegment::At(left.value);
162    }
163    let progress = interpolation_amount(left.time, right.time, time);
164    match left.interpolation.amount(progress) {
165        Some(amount) => PointSegment::Between(left, right, amount),
166        None => PointSegment::At(left.value),
167    }
168}
169
170/// Nearest finite `f32`; NaN becomes zero.
171#[allow(clippy::cast_possible_truncation)]
172fn finite_f32(value: f64) -> f32 {
173    if value.is_nan() {
174        0.0
175    } else {
176        value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
177    }
178}
179
180/// Samples an animated path, interpolating points and tangents linearly in `f64`. Mismatched
181/// keyframe structures hold the left path.
182#[must_use]
183pub fn sample_path(animation: &Animated<Path>, time: MediaTime) -> alpha2_geometry::EvaluatedPath {
184    use alpha2_geometry::kurbo::{Point, Vec2 as Vector};
185    use alpha2_geometry::{EvaluatedPath, EvaluatedSubpath, EvaluatedVertex};
186    match animation {
187        Animated::Constant { value } => EvaluatedPath::from(value),
188        Animated::Data(_) => EvaluatedPath::default(),
189        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
190            Segment::At(keyframe) => EvaluatedPath::from(&keyframe.value),
191            Segment::Empty => EvaluatedPath::default(),
192            Segment::Between(left, right, amount) => {
193                let structure = |path: &Path| {
194                    path.subpaths
195                        .iter()
196                        .map(|subpath| (subpath.closed, subpath.vertices.len()))
197                        .collect::<Vec<_>>()
198                };
199                if structure(&left.value) != structure(&right.value) {
200                    return EvaluatedPath::from(&left.value);
201                }
202                let lerp = |a: f32, b: f32| f64::from(a) + (f64::from(b) - f64::from(a)) * amount;
203                let point = |a: Vec2, b: Vec2| Point::new(lerp(a.x, b.x), lerp(a.y, b.y));
204                let vector = |a: Vec2, b: Vec2| Vector::new(lerp(a.x, b.x), lerp(a.y, b.y));
205                EvaluatedPath {
206                    subpaths: left
207                        .value
208                        .subpaths
209                        .iter()
210                        .zip(&right.value.subpaths)
211                        .map(|(from, to)| EvaluatedSubpath {
212                            closed: from.closed,
213                            vertices: from
214                                .vertices
215                                .iter()
216                                .zip(&to.vertices)
217                                .map(|(a, b)| EvaluatedVertex {
218                                    point: point(a.point, b.point),
219                                    in_tangent: vector(a.in_tangent, b.in_tangent),
220                                    out_tangent: vector(a.out_tangent, b.out_tangent),
221                                })
222                                .collect(),
223                        })
224                        .collect(),
225                }
226            }
227        },
228    }
229}
230
231/// Samples an animated paint. Colors interpolate premultiplied; gradient geometry and stop
232/// offsets interpolate numerically, then offsets are kept ordered in `0..=1` and radii positive.
233/// Mismatched keyframes hold the left paint.
234#[must_use]
235pub fn sample_paint(animation: &Animated<Paint>, time: MediaTime) -> Paint {
236    match animation {
237        Animated::Constant { value } => value.clone(),
238        Animated::Data(_) => Paint::Solid {
239            color: alpha2_model::Rgba::new(0.0, 0.0, 0.0, 0.0),
240        },
241        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
242            Segment::At(keyframe) => keyframe.value.clone(),
243            Segment::Empty => Paint::Solid {
244                color: alpha2_model::Rgba::new(0.0, 0.0, 0.0, 0.0),
245            },
246            Segment::Between(left, right, amount) => {
247                interpolate_paint(&left.value, &right.value, amount)
248                    .unwrap_or_else(|| left.value.clone())
249            }
250        },
251    }
252}
253
254fn interpolate_paint(from: &Paint, to: &Paint, amount: f64) -> Option<Paint> {
255    let lerp = |a: f32, b: f32| interpolate_f32(a, b, amount);
256    let point = |a: Vec2, b: Vec2| Vec2::new(lerp(a.x, b.x), lerp(a.y, b.y));
257    let color = |a: alpha2_model::Rgba, b: alpha2_model::Rgba| {
258        let [red, green, blue, alpha] = interpolate_color(
259            [a.red, a.green, a.blue, a.alpha],
260            [b.red, b.green, b.blue, b.alpha],
261            amount,
262        );
263        alpha2_model::Rgba::new(red, green, blue, alpha)
264    };
265    let stops = |a: &[GradientStop], b: &[GradientStop]| -> Option<Vec<GradientStop>> {
266        if a.len() != b.len() {
267            return None;
268        }
269        let mut previous = 0.0_f32;
270        Some(
271            a.iter()
272                .zip(b)
273                .map(|(a, b)| {
274                    let offset = lerp(a.offset, b.offset).clamp(previous, 1.0);
275                    previous = offset;
276                    GradientStop {
277                        offset,
278                        color: color(a.color, b.color),
279                    }
280                })
281                .collect(),
282        )
283    };
284    Some(match (from, to) {
285        (Paint::Solid { color: a }, Paint::Solid { color: b }) => Paint::Solid {
286            color: color(*a, *b),
287        },
288        (
289            Paint::LinearGradient {
290                start: s0,
291                end: e0,
292                stops: a,
293                spread,
294            },
295            Paint::LinearGradient {
296                start: s1,
297                end: e1,
298                stops: b,
299                spread: other,
300            },
301        ) if spread == other => Paint::LinearGradient {
302            start: point(*s0, *s1),
303            end: point(*e0, *e1),
304            stops: stops(a, b)?,
305            spread: *spread,
306        },
307        (
308            Paint::RadialGradient {
309                center: c0,
310                radius: r0,
311                stops: a,
312                spread,
313            },
314            Paint::RadialGradient {
315                center: c1,
316                radius: r1,
317                stops: b,
318                spread: other,
319            },
320        ) if spread == other => Paint::RadialGradient {
321            center: point(*c0, *c1),
322            radius: lerp(*r0, *r1).max(f32::MIN_POSITIVE),
323            stops: stops(a, b)?,
324            spread: *spread,
325        },
326        (
327            Paint::ConicGradient {
328                center: c0,
329                angle_degrees: a0,
330                stops: a,
331            },
332            Paint::ConicGradient {
333                center: c1,
334                angle_degrees: a1,
335                stops: b,
336            },
337        ) => Paint::ConicGradient {
338            center: point(*c0, *c1),
339            angle_degrees: lerp(*a0, *a1),
340            stops: stops(a, b)?,
341        },
342        _ => return None,
343    })
344}
345
346/// One effect parameter's value at a timeline timestamp.
347#[derive(Copy, Clone, Debug, PartialEq)]
348pub struct EffectParamValue {
349    /// The sampled value.
350    pub value: EffectValue,
351    /// Whether `value` is interpolated rather than authored. Renderers clamp interpolated values
352    /// to the parameter range; an authored out-of-range value is an error.
353    pub interpolated: bool,
354}
355
356/// Samples one effect parameter with the project's keyframe semantics.
357///
358/// `Float` and `Vec2` interpolate component-wise. A straight sRGB `Color` interpolates
359/// premultiplied, as CSS does, to avoid a dark fringe when fading from transparent, then clamps
360/// to `0..=1`. `Enum` and `Bool` hold. A data binding gives a `Float` for scalars and a `Vec2`
361/// for points, marked interpolated so it is clamped to the parameter's range.
362#[must_use]
363pub fn sample_effect_param(
364    animation: &Animated<EffectValue>,
365    time: MediaTime,
366    context: &SampleContext<'_>,
367) -> EffectParamValue {
368    let authored = |value: EffectValue| EffectParamValue {
369        value,
370        interpolated: false,
371    };
372    match animation {
373        Animated::Data(binding) => {
374            let value = match crate::data::bound_vec2(binding, time, context) {
375                Some(point) if binding.remap.is_none() && is_points(binding, context) => {
376                    EffectValue::Vec2([point.x, point.y])
377                }
378                _ => EffectValue::Float(
379                    crate::data::bound_scalar(binding, time, context).unwrap_or(0.0),
380                ),
381            };
382            EffectParamValue {
383                value,
384                interpolated: true,
385            }
386        }
387        Animated::Constant { value } => authored(*value),
388        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
389            Segment::Between(left, right, amount) => {
390                interpolate_value(left.value, right.value, amount).map_or_else(
391                    || authored(left.value),
392                    |value| EffectParamValue {
393                        value,
394                        interpolated: true,
395                    },
396                )
397            }
398            Segment::At(keyframe) => authored(keyframe.value),
399            Segment::Empty => authored(EffectValue::Float(0.0)),
400        },
401    }
402}
403
404/// Whether `binding` follows a `points` data set.
405fn is_points(binding: &alpha2_model::DataBinding, context: &SampleContext<'_>) -> bool {
406    crate::data::bound_kind(binding, context) == Some(alpha2_model::DataKind::Points)
407}
408
409fn interpolate_value(start: EffectValue, end: EffectValue, amount: f64) -> Option<EffectValue> {
410    let lerp = |a: f32, b: f32| interpolate_f32(a, b, amount);
411    match (start, end) {
412        (EffectValue::Float(a), EffectValue::Float(b)) => Some(EffectValue::Float(lerp(a, b))),
413        (EffectValue::Vec2(a), EffectValue::Vec2(b)) => {
414            Some(EffectValue::Vec2([lerp(a[0], b[0]), lerp(a[1], b[1])]))
415        }
416        (EffectValue::Vec4(a), EffectValue::Vec4(b)) => {
417            Some(EffectValue::Vec4(std::array::from_fn(|index| {
418                lerp(a[index], b[index])
419            })))
420        }
421        (EffectValue::Color(a), EffectValue::Color(b)) => {
422            Some(EffectValue::Color(interpolate_color(a, b, amount)))
423        }
424        _ => None,
425    }
426}
427
428/// Samples an animated color, interpolated premultiplied.
429#[must_use]
430pub fn sample_rgba(
431    animation: &Animated<alpha2_model::Rgba>,
432    time: MediaTime,
433) -> alpha2_model::Rgba {
434    match animation {
435        Animated::Data(_) => alpha2_model::Rgba::new(0.0, 0.0, 0.0, 0.0),
436        Animated::Constant { value } => *value,
437        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
438            Segment::At(keyframe) => keyframe.value,
439            Segment::Empty => alpha2_model::Rgba::new(0.0, 0.0, 0.0, 0.0),
440            Segment::Between(left, right, amount) => {
441                let (a, b) = (left.value, right.value);
442                let [red, green, blue, alpha] = interpolate_color(
443                    [a.red, a.green, a.blue, a.alpha],
444                    [b.red, b.green, b.blue, b.alpha],
445                    amount,
446                );
447                alpha2_model::Rgba::new(red, green, blue, alpha)
448            }
449        },
450    }
451}
452
453/// Interpolates straight colors premultiplied; returns straight, clamped to `0..=1`.
454#[allow(clippy::cast_possible_truncation)]
455fn interpolate_color(start: [f32; 4], end: [f32; 4], amount: f64) -> [f32; 4] {
456    let (start_alpha, end_alpha) = (f64::from(start[3]), f64::from(end[3]));
457    let alpha = (start_alpha + (end_alpha - start_alpha) * amount).clamp(0.0, 1.0);
458    let mut color = [0.0; 4];
459    for index in 0..3 {
460        let from = f64::from(start[index]) * start_alpha;
461        let to = f64::from(end[index]) * end_alpha;
462        let premultiplied = from + (to - from) * amount;
463        // Fully transparent has no color; keep straight interpolation so the value stays continuous.
464        let straight = if alpha > 0.0 {
465            premultiplied / alpha
466        } else {
467            f64::from(start[index]) + (f64::from(end[index]) - f64::from(start[index])) * amount
468        };
469        color[index] = straight.clamp(0.0, 1.0) as f32;
470    }
471    color[3] = alpha as f32;
472    color
473}
474
475enum Segment<'a, T> {
476    /// Before the first, after the last, or inside a held segment.
477    At(&'a Keyframe<T>),
478    /// Inside an interpolated segment, this fraction of the way to the right.
479    Between(&'a Keyframe<T>, &'a Keyframe<T>, f64),
480    /// No keyframes; validation rejects this.
481    Empty,
482}
483
484fn segment<T>(keyframes: &[Keyframe<T>], time: MediaTime) -> Segment<'_, T> {
485    let next = keyframes.partition_point(|keyframe| keyframe.time <= time);
486    if next == 0 {
487        return keyframes.first().map_or(Segment::Empty, Segment::At);
488    }
489    let left = &keyframes[next - 1];
490    let Some(right) = keyframes.get(next) else {
491        return Segment::At(left);
492    };
493    // On a keyframe the value is the authored one, whatever the curve.
494    if time == left.time {
495        return Segment::At(left);
496    }
497    let progress = interpolation_amount(left.time, right.time, time);
498    match left.interpolation.amount(progress) {
499        Some(amount) => Segment::Between(left, right, amount),
500        None => Segment::At(left),
501    }
502}
503
504#[allow(clippy::cast_precision_loss)]
505pub(crate) fn interpolation_amount(start: MediaTime, end: MediaTime, time: MediaTime) -> f64 {
506    (i128::from(time.ticks()) - i128::from(start.ticks())) as f64
507        / (i128::from(end.ticks()) - i128::from(start.ticks())) as f64
508}
509
510/// Linear interpolation clamped to finite `f32`, since overshoot can exceed its range.
511#[allow(clippy::cast_possible_truncation)]
512pub(crate) fn interpolate_f32(start: f32, end: f32, amount: f64) -> f32 {
513    (f64::from(start) + (f64::from(end) - f64::from(start)) * amount)
514        .clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
515}
516
517/// Samples per-side lengths like `sample_size`.
518#[must_use]
519pub fn sample_insets(animation: &Animated<Insets>, time: MediaTime) -> [f32; 4] {
520    match animation {
521        Animated::Constant { value } => value.sides().map(LayoutSize::value),
522        Animated::Data(_) => [0.0; 4],
523        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
524            Segment::Between(left, right, amount) => {
525                let (from, to) = (left.value.sides(), right.value.sides());
526                std::array::from_fn(|side| {
527                    interpolate_f32(from[side].value(), to[side].value(), amount)
528                })
529            }
530            Segment::At(keyframe) => keyframe.value.sides().map(LayoutSize::value),
531            Segment::Empty => [0.0; 4],
532        },
533    }
534}
535
536/// Samples a layout size like [`sample_scalar`]. Plan sizes are fractions.
537#[must_use]
538pub fn sample_size(animation: &Animated<LayoutSize>, time: MediaTime) -> f32 {
539    match animation {
540        Animated::Constant { value } => value.value(),
541        Animated::Data(_) => 0.0,
542        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
543            Segment::Between(left, right, amount) => {
544                interpolate_f32(left.value.value(), right.value.value(), amount)
545            }
546            Segment::At(keyframe) => keyframe.value.value(),
547            Segment::Empty => 0.0,
548        },
549    }
550}
551
552/// Samples a layout offset per axis like [`sample_size`].
553#[must_use]
554pub fn sample_offset(animation: &Animated<LayoutOffset>, time: MediaTime) -> Vec2 {
555    let vector = |offset: &LayoutOffset| Vec2::new(offset.x.value(), offset.y.value());
556    match animation {
557        Animated::Constant { value } => vector(value),
558        Animated::Data(_) => Vec2::default(),
559        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
560            Segment::Between(left, right, amount) => Vec2::new(
561                interpolate_f32(left.value.x.value(), right.value.x.value(), amount),
562                interpolate_f32(left.value.y.value(), right.value.y.value(), amount),
563            ),
564            Segment::At(keyframe) => vector(&keyframe.value),
565            Segment::Empty => Vec2::default(),
566        },
567    }
568}
569
570/// Samples a layout length. Mismatched keyframe kinds keep the left kind.
571#[must_use]
572pub fn sample_length(animation: &Animated<LayoutLength>, time: MediaTime) -> LayoutLength {
573    match animation {
574        Animated::Constant { value } => *value,
575        Animated::Data(_) => LayoutLength::Fraction(0.0),
576        Animated::Keyframes { keyframes } => match segment(keyframes, time) {
577            Segment::Between(left, right, amount) => left.value.with_value(interpolate_f32(
578                left.value.value(),
579                right.value.value(),
580                amount,
581            )),
582            Segment::At(keyframe) => keyframe.value,
583            Segment::Empty => LayoutLength::Fraction(0.0),
584        },
585    }
586}
587
588/// Samples a non-interpolating value: the last keyframe at or before `time`, else the first.
589#[must_use]
590pub fn sample_hold<T: Clone + Default>(animation: &Animated<T>, time: MediaTime) -> T {
591    match animation {
592        Animated::Constant { value } => value.clone(),
593        Animated::Data(_) => T::default(),
594        Animated::Keyframes { keyframes } => {
595            let next = keyframes.partition_point(|keyframe| keyframe.time <= time);
596            keyframes
597                .get(next.saturating_sub(1))
598                .map(|keyframe| keyframe.value.clone())
599                .unwrap_or_default()
600        }
601    }
602}