Skip to main content

alpha2_eval/
animation.rs

1use crate::keyed::{self, NumberSegment, Segment};
2use crate::{EvaluatedVisual, SampleContext};
3use alpha2_model::{
4    Animated, AnimatedPoint, EffectValue, Extrapolation, GradientStop, Insets, Interpolation,
5    Keyframe, LayoutLength, LayoutOffset, LayoutSize, MotionPath, Orient, Paint, Path,
6    PointKeyframe, Vec2, VisualProperties,
7};
8use alpha2_time::MediaTime;
9
10/// Evaluates visual properties at a timestamp. `aspect` is the canvas width over height, used
11/// to measure motion along spatial curves; `context` resolves data bindings.
12///
13/// Opacity is clamped to `0..=1`; position, scale and rotation keep curve overshoot.
14#[must_use]
15pub fn sample_visual(
16    properties: &VisualProperties,
17    time: MediaTime,
18    aspect: f64,
19    context: &SampleContext<'_>,
20) -> EvaluatedVisual {
21    let rotation = evaluate_scalar(&properties.rotation_degrees, time, context);
22    EvaluatedVisual {
23        position: sample_point(&properties.position, time, aspect, context),
24        anchor: properties.anchor,
25        scale: evaluate_vec2(&properties.scale, time, context),
26        rotation_degrees: match properties.orient {
27            Orient::None => rotation,
28            Orient::Path => finite_f32(
29                f64::from(rotation) + path_angle(&properties.position, time, aspect, context),
30            ),
31        },
32        opacity: evaluate_scalar(&properties.opacity, time, context).clamp(0.0, 1.0),
33    }
34}
35
36pub(crate) fn screen_aspect(aspect: f64) -> f64 {
37    if aspect.is_finite() && aspect > 0.0 {
38        aspect
39    } else {
40        1.0
41    }
42}
43
44pub(crate) fn motion_segments(
45    motion: &MotionPath,
46    aspect: f64,
47) -> (Vec<alpha2_geometry::kurbo::PathSeg>, bool) {
48    use alpha2_geometry::kurbo::{CubicBez, PathSeg, Point, Vec2 as Vector};
49    let Some(subpath) = motion.path.subpaths.first() else {
50        return (Vec::new(), false);
51    };
52    let point = |value: Vec2| Point::new(f64::from(value.x) * aspect, f64::from(value.y));
53    let vector = |value: Vec2| Vector::new(f64::from(value.x) * aspect, f64::from(value.y));
54    let vertices = &subpath.vertices;
55    let joined = vertices
56        .iter()
57        .zip(vertices.iter().skip(1).chain(vertices.first()))
58        .take(if subpath.closed {
59            vertices.len()
60        } else {
61            vertices.len().saturating_sub(1)
62        });
63    let segments = joined
64        .map(|(from, to)| {
65            PathSeg::Cubic(CubicBez::new(
66                point(from.point),
67                point(from.point) + vector(from.out_tangent),
68                point(to.point) + vector(to.in_tangent),
69                point(to.point),
70            ))
71        })
72        .collect();
73    (segments, subpath.closed)
74}
75
76fn degrees(direction: alpha2_geometry::kurbo::Vec2) -> f64 {
77    if direction.x == 0.0 && direction.y == 0.0 {
78        0.0
79    } else {
80        libm::atan2(direction.y, direction.x).to_degrees()
81    }
82}
83
84/// The clockwise angle in degrees of a position's path where the position is at `time`,
85/// measured from the positive x axis in a space `aspect` wide per unit high: the direction of
86/// its spatial curve between keyframes, or of the path of a `path` position. 0 for a position
87/// with no path.
88///
89/// It is the path's direction, not the travel's: a value that backs up along its path, by an
90/// overshooting curve or a mirrored `ping_pong` pass, keeps pointing forwards. While a keyed
91/// position holds or stands still it keeps the direction the next move starts with, or after
92/// the last move the one that move ended with.
93#[must_use]
94pub fn path_angle(
95    animation: &AnimatedPoint,
96    time: MediaTime,
97    aspect: f64,
98    context: &SampleContext<'_>,
99) -> f64 {
100    let aspect = screen_aspect(aspect);
101    match animation {
102        AnimatedPoint::Constant { .. } | AnimatedPoint::Data(_) | AnimatedPoint::Split { .. } => {
103            0.0
104        }
105        AnimatedPoint::Path(motion) => {
106            let (segments, closed) = motion_segments(motion, aspect);
107            let distance = f64::from(evaluate_scalar(&motion.distance, time, context));
108            degrees(alpha2_geometry::spatial::along_path(&segments, closed, distance).1)
109        }
110        AnimatedPoint::Keyframes {
111            keyframes,
112            before,
113            after,
114        } => {
115            let point = |value: Vec2| {
116                alpha2_geometry::kurbo::Point::new(f64::from(value.x) * aspect, f64::from(value.y))
117            };
118            let vector = |value: Vec2| {
119                alpha2_geometry::kurbo::Vec2::new(f64::from(value.x) * aspect, f64::from(value.y))
120            };
121            let direction = |index: usize, amount: f64| {
122                let (left, right) = (keyframes.get(index)?, keyframes.get(index + 1)?);
123                if matches!(left.interpolation, Interpolation::Hold) {
124                    return None;
125                }
126                alpha2_geometry::spatial::direction_along(
127                    point(left.value),
128                    vector(left.out_tangent),
129                    vector(right.in_tangent),
130                    point(right.value),
131                    amount,
132                )
133            };
134            let index_of =
135                |key: &PointKeyframe| keyframes.partition_point(|other| other.time < key.time);
136            let (segment, _) = keyed::read(keyframes, *before, *after, time);
137            let (at, own) = match segment.timed() {
138                Segment::Empty => return 0.0,
139                Segment::At(key) => (index_of(key), None),
140                Segment::Between(left, _, amount) => {
141                    let index = index_of(left);
142                    (index, direction(index, amount.clamp(0.0, 1.0)))
143                }
144            };
145            let found = own
146                .or_else(|| (at..keyframes.len()).find_map(|index| direction(index, 0.0)))
147                .or_else(|| (0..at).rev().find_map(|index| direction(index, 1.0)));
148            found.map_or(0.0, degrees)
149        }
150    }
151}
152
153fn evaluate_vec2(animation: &Animated<Vec2>, time: MediaTime, context: &SampleContext<'_>) -> Vec2 {
154    match animation {
155        Animated::Constant { value } => *value,
156        Animated::Data(binding) => {
157            crate::data::bound_vec2(binding, time, context).unwrap_or_default()
158        }
159        Animated::Split { channels } => {
160            let [x, y] = channel_values(channels, time, context);
161            Vec2::new(x, y)
162        }
163        Animated::Keyframes {
164            keyframes,
165            before,
166            after,
167        } => keyed_vec2(keyframes, *before, *after, time),
168    }
169}
170
171#[inline(never)]
172fn keyed_vec2(
173    keyframes: &[Keyframe<Vec2>],
174    before: Extrapolation,
175    after: Extrapolation,
176    time: MediaTime,
177) -> Vec2 {
178    let (segment, passes) = keyed::read(keyframes, before, after, time);
179    let (Some(first), Some(last)) = (keyframes.first(), keyframes.last()) else {
180        return Vec2::default();
181    };
182    match segment.timed() {
183        Segment::At(keyframe) if passes == 0 => keyframe.value,
184        segment => {
185            let component = |read: fn(&Vec2) -> f32| {
186                let wide = timed_number(&segment, read);
187                finite_f32(offset_by_passes(
188                    wide,
189                    passes,
190                    read(&first.value),
191                    read(&last.value),
192                ))
193            };
194            Vec2::new(component(|value| value.x), component(|value| value.y))
195        }
196    }
197}
198
199/// Samples an animated 2D value like [`sample_scalar`]. Use [`sample_point`] for positions that
200/// may follow spatial curves.
201#[must_use]
202pub fn sample_vec2(
203    animation: &Animated<Vec2>,
204    time: MediaTime,
205    context: &SampleContext<'_>,
206) -> Vec2 {
207    evaluate_vec2(animation, time, context)
208}
209
210/// Samples one animated scalar with the project's keyframe semantics.
211///
212/// Times outside the keyframes follow the value's `before` and `after`, which hold the first or
213/// last value unless set, and a [`alpha2_model::Interpolation::Hold`] segment keeps its left
214/// value. Interpolation is numeric, so a rotation from 0 to 720 degrees turns twice. A data
215/// binding reads its channel through `context`, and is zero without a value.
216#[must_use]
217pub fn sample_scalar(
218    animation: &Animated<f32>,
219    time: MediaTime,
220    context: &SampleContext<'_>,
221) -> f32 {
222    evaluate_scalar(animation, time, context)
223}
224
225fn evaluate_scalar(animation: &Animated<f32>, time: MediaTime, context: &SampleContext<'_>) -> f32 {
226    match animation {
227        Animated::Constant { value } => *value,
228        Animated::Data(binding) => crate::data::bound_scalar(binding, time, context).unwrap_or(0.0),
229        Animated::Split { .. } => 0.0,
230        Animated::Keyframes {
231            keyframes,
232            before,
233            after,
234        } => keyed_scalar(keyframes, *before, *after, time),
235    }
236}
237
238#[inline(never)]
239fn keyed_scalar(
240    keyframes: &[Keyframe<f32>],
241    before: Extrapolation,
242    after: Extrapolation,
243    time: MediaTime,
244) -> f32 {
245    let (segment, passes) = keyed::read(keyframes, before, after, time);
246    let (Some(first), Some(last)) = (keyframes.first(), keyframes.last()) else {
247        return 0.0;
248    };
249    match segment {
250        NumberSegment::Timed(Segment::At(keyframe)) if passes == 0 => keyframe.value,
251        segment => {
252            let wide = number(&segment, |value| *value);
253            finite_f32(offset_by_passes(wide, passes, first.value, last.value))
254        }
255    }
256}
257
258fn channel_values<const N: usize>(
259    channels: &[Animated<f32>],
260    time: MediaTime,
261    context: &SampleContext<'_>,
262) -> [f32; N] {
263    std::array::from_fn(|index| {
264        channels
265            .get(index)
266            .map_or(0.0, |channel| evaluate_scalar(channel, time, context))
267    })
268}
269
270fn timed_number<T>(segment: &Segment<'_, Keyframe<T>>, read: impl Fn(&T) -> f32) -> f64 {
271    match segment {
272        Segment::Empty => 0.0,
273        Segment::At(keyframe) => f64::from(read(&keyframe.value)),
274        Segment::Between(left, right, amount) => {
275            lerp(read(&left.value), read(&right.value), *amount)
276        }
277    }
278}
279
280fn number<T>(segment: &NumberSegment<'_, Keyframe<T>>, read: impl Fn(&T) -> f32) -> f64 {
281    match segment {
282        NumberSegment::Timed(segment) => timed_number(segment, read),
283        NumberSegment::Curve(left, right, curve, progress) => {
284            curve.value(read(&left.value), read(&right.value), *progress)
285        }
286        NumberSegment::Line {
287            left,
288            right,
289            curve,
290            at_end,
291            outside,
292        } => {
293            let (from, to) = (read(&left.value), read(&right.value));
294            f64::from(if *at_end { to } else { from })
295                + curve.end_slope(from, to, *at_end) * outside
296        }
297    }
298}
299
300fn lerp(start: f32, end: f32, amount: f64) -> f64 {
301    f64::from(start) + (f64::from(end) - f64::from(start)) * amount
302}
303
304fn offset_by_passes(value: f64, passes: i64, first: f32, last: f32) -> f64 {
305    if passes == 0 {
306        return value;
307    }
308    #[expect(clippy::cast_precision_loss, reason = "a count of passes")]
309    let passes = passes as f64;
310    value + passes * (f64::from(last) - f64::from(first))
311}
312
313/// Samples a position that may move along spatial curves.
314///
315/// With both facing tangents zero the value moves in a straight line like an `Animated<Vec2>`.
316/// Otherwise it follows the cubic Bezier, measured in a space `aspect` wide per unit high, and the
317/// eased amount is the fraction of arc length travelled. Overshoot continues along the end
318/// tangent.
319#[must_use]
320pub fn sample_point(
321    animation: &AnimatedPoint,
322    time: MediaTime,
323    aspect: f64,
324    context: &SampleContext<'_>,
325) -> Vec2 {
326    match animation {
327        AnimatedPoint::Constant { value } => *value,
328        moving => moving_point(moving, time, aspect, context),
329    }
330}
331
332#[inline(never)]
333fn moving_point(
334    animation: &AnimatedPoint,
335    time: MediaTime,
336    aspect: f64,
337    context: &SampleContext<'_>,
338) -> Vec2 {
339    match animation {
340        AnimatedPoint::Constant { value } => *value,
341        AnimatedPoint::Data(binding) => {
342            crate::data::bound_vec2(binding, time, context).unwrap_or_default()
343        }
344        AnimatedPoint::Split { channels } => {
345            let [x, y] = channel_values(channels, time, context);
346            Vec2::new(x, y)
347        }
348        AnimatedPoint::Path(motion) => {
349            let aspect = screen_aspect(aspect);
350            let (segments, closed) = motion_segments(motion, aspect);
351            let distance = f64::from(evaluate_scalar(&motion.distance, time, context));
352            let (at, _) = alpha2_geometry::spatial::along_path(&segments, closed, distance);
353            Vec2::new(finite_f32(at.x / aspect), finite_f32(at.y))
354        }
355        AnimatedPoint::Keyframes {
356            keyframes,
357            before,
358            after,
359        } => keyed_point(keyframes, *before, *after, time, aspect),
360    }
361}
362
363fn keyed_point(
364    keyframes: &[PointKeyframe],
365    before: Extrapolation,
366    after: Extrapolation,
367    time: MediaTime,
368    aspect: f64,
369) -> Vec2 {
370    let (segment, passes) = keyed::read(keyframes, before, after, time);
371    let (Some(first), Some(last)) = (keyframes.first(), keyframes.last()) else {
372        return Vec2::default();
373    };
374    let moved = |x: f64, y: f64| {
375        Vec2::new(
376            finite_f32(offset_by_passes(x, passes, first.value.x, last.value.x)),
377            finite_f32(offset_by_passes(y, passes, first.value.y, last.value.y)),
378        )
379    };
380    let (left, right, amount) = match segment.timed() {
381        Segment::Empty => return Vec2::default(),
382        Segment::At(keyframe) if passes == 0 => return keyframe.value,
383        Segment::At(keyframe) => {
384            return moved(f64::from(keyframe.value.x), f64::from(keyframe.value.y));
385        }
386        Segment::Between(left, right, amount) => (left, right, amount),
387    };
388    if left.out_tangent.is_zero() && right.in_tangent.is_zero() {
389        return moved(
390            lerp(left.value.x, right.value.x, amount),
391            lerp(left.value.y, right.value.y, amount),
392        );
393    }
394    let aspect = screen_aspect(aspect);
395    let point = |value: Vec2| {
396        alpha2_geometry::kurbo::Point::new(f64::from(value.x) * aspect, f64::from(value.y))
397    };
398    let vector = |value: Vec2| {
399        alpha2_geometry::kurbo::Vec2::new(f64::from(value.x) * aspect, f64::from(value.y))
400    };
401    let at = alpha2_geometry::spatial::point_along(
402        point(left.value),
403        vector(left.out_tangent),
404        vector(right.in_tangent),
405        point(right.value),
406        amount,
407    );
408    moved(at.x / aspect, at.y)
409}
410
411/// Nearest finite `f32`; NaN becomes zero.
412#[allow(clippy::cast_possible_truncation)]
413fn finite_f32(value: f64) -> f32 {
414    if value.is_nan() {
415        0.0
416    } else {
417        value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
418    }
419}
420
421/// Samples an animated path, interpolating points and tangents linearly in `f64`. Mismatched
422/// keyframe structures hold the left path.
423#[must_use]
424pub fn sample_path(animation: &Animated<Path>, time: MediaTime) -> alpha2_geometry::EvaluatedPath {
425    use alpha2_geometry::kurbo::{Point, Vec2 as Vector};
426    use alpha2_geometry::{EvaluatedPath, EvaluatedSubpath, EvaluatedVertex};
427    match animation {
428        Animated::Constant { value } => EvaluatedPath::from(value),
429        Animated::Data(_) | Animated::Split { .. } => EvaluatedPath::default(),
430        Animated::Keyframes {
431            keyframes,
432            before,
433            after,
434        } => match segment(keyframes, *before, *after, time) {
435            Segment::At(keyframe) => EvaluatedPath::from(&keyframe.value),
436            Segment::Empty => EvaluatedPath::default(),
437            Segment::Between(left, right, amount) => {
438                let structure = |path: &Path| {
439                    path.subpaths
440                        .iter()
441                        .map(|subpath| (subpath.closed, subpath.vertices.len()))
442                        .collect::<Vec<_>>()
443                };
444                if structure(&left.value) != structure(&right.value) {
445                    return EvaluatedPath::from(&left.value);
446                }
447                let lerp = |a: f32, b: f32| f64::from(a) + (f64::from(b) - f64::from(a)) * amount;
448                let point = |a: Vec2, b: Vec2| Point::new(lerp(a.x, b.x), lerp(a.y, b.y));
449                let vector = |a: Vec2, b: Vec2| Vector::new(lerp(a.x, b.x), lerp(a.y, b.y));
450                EvaluatedPath {
451                    subpaths: left
452                        .value
453                        .subpaths
454                        .iter()
455                        .zip(&right.value.subpaths)
456                        .map(|(from, to)| EvaluatedSubpath {
457                            closed: from.closed,
458                            vertices: from
459                                .vertices
460                                .iter()
461                                .zip(&to.vertices)
462                                .map(|(a, b)| EvaluatedVertex {
463                                    point: point(a.point, b.point),
464                                    in_tangent: vector(a.in_tangent, b.in_tangent),
465                                    out_tangent: vector(a.out_tangent, b.out_tangent),
466                                })
467                                .collect(),
468                        })
469                        .collect(),
470                }
471            }
472        },
473    }
474}
475
476/// Samples an animated paint. Colors interpolate premultiplied; gradient geometry and stop
477/// offsets interpolate numerically, then offsets are kept ordered in `0..=1` and radii positive.
478/// Mismatched keyframes hold the left paint.
479#[must_use]
480pub fn sample_paint(animation: &Animated<Paint>, time: MediaTime) -> Paint {
481    match animation {
482        Animated::Constant { value } => value.clone(),
483        Animated::Data(_) | Animated::Split { .. } => Paint::Solid {
484            color: alpha2_model::Rgba::new(0.0, 0.0, 0.0, 0.0),
485        },
486        Animated::Keyframes {
487            keyframes,
488            before,
489            after,
490        } => match segment(keyframes, *before, *after, time) {
491            Segment::At(keyframe) => keyframe.value.clone(),
492            Segment::Empty => Paint::Solid {
493                color: alpha2_model::Rgba::new(0.0, 0.0, 0.0, 0.0),
494            },
495            Segment::Between(left, right, amount) => {
496                interpolate_paint(&left.value, &right.value, amount)
497                    .unwrap_or_else(|| left.value.clone())
498            }
499        },
500    }
501}
502
503fn interpolate_paint(from: &Paint, to: &Paint, amount: f64) -> Option<Paint> {
504    let lerp = |a: f32, b: f32| interpolate_f32(a, b, amount);
505    let point = |a: Vec2, b: Vec2| Vec2::new(lerp(a.x, b.x), lerp(a.y, b.y));
506    let color = |a: alpha2_model::Rgba, b: alpha2_model::Rgba| {
507        let [red, green, blue, alpha] = interpolate_color(
508            [a.red, a.green, a.blue, a.alpha],
509            [b.red, b.green, b.blue, b.alpha],
510            amount,
511        );
512        alpha2_model::Rgba::new(red, green, blue, alpha)
513    };
514    let stops = |a: &[GradientStop], b: &[GradientStop]| -> Option<Vec<GradientStop>> {
515        if a.len() != b.len() {
516            return None;
517        }
518        let mut previous = 0.0_f32;
519        Some(
520            a.iter()
521                .zip(b)
522                .map(|(a, b)| {
523                    let offset = lerp(a.offset, b.offset).clamp(previous, 1.0);
524                    previous = offset;
525                    GradientStop {
526                        offset,
527                        color: color(a.color, b.color),
528                    }
529                })
530                .collect(),
531        )
532    };
533    Some(match (from, to) {
534        (Paint::Solid { color: a }, Paint::Solid { color: b }) => Paint::Solid {
535            color: color(*a, *b),
536        },
537        (
538            Paint::LinearGradient {
539                start: s0,
540                end: e0,
541                stops: a,
542                spread,
543            },
544            Paint::LinearGradient {
545                start: s1,
546                end: e1,
547                stops: b,
548                spread: other,
549            },
550        ) if spread == other => Paint::LinearGradient {
551            start: point(*s0, *s1),
552            end: point(*e0, *e1),
553            stops: stops(a, b)?,
554            spread: *spread,
555        },
556        (
557            Paint::RadialGradient {
558                center: c0,
559                radius: r0,
560                stops: a,
561                spread,
562            },
563            Paint::RadialGradient {
564                center: c1,
565                radius: r1,
566                stops: b,
567                spread: other,
568            },
569        ) if spread == other => Paint::RadialGradient {
570            center: point(*c0, *c1),
571            radius: lerp(*r0, *r1).max(f32::MIN_POSITIVE),
572            stops: stops(a, b)?,
573            spread: *spread,
574        },
575        (
576            Paint::ConicGradient {
577                center: c0,
578                angle_degrees: a0,
579                stops: a,
580            },
581            Paint::ConicGradient {
582                center: c1,
583                angle_degrees: a1,
584                stops: b,
585            },
586        ) => Paint::ConicGradient {
587            center: point(*c0, *c1),
588            angle_degrees: lerp(*a0, *a1),
589            stops: stops(a, b)?,
590        },
591        _ => return None,
592    })
593}
594
595/// One effect parameter's value at a timeline timestamp.
596#[derive(Copy, Clone, Debug, PartialEq)]
597pub struct EffectParamValue {
598    /// The sampled value.
599    pub value: EffectValue,
600    /// Whether `value` is interpolated rather than authored. Renderers clamp interpolated values
601    /// to the parameter range; an authored out-of-range value is an error.
602    pub interpolated: bool,
603}
604
605/// Samples one effect parameter with the project's keyframe semantics.
606///
607/// `Float` and `Vec2` interpolate component-wise. A straight sRGB `Color` interpolates
608/// premultiplied, as CSS does, to avoid a dark fringe when fading from transparent, then clamps
609/// to `0..=1`. `Enum` and `Bool` hold. A data binding gives a `Float` for scalars and a `Vec2`
610/// for points, marked interpolated so it is clamped to the parameter's range.
611#[must_use]
612pub fn sample_effect_param(
613    animation: &Animated<EffectValue>,
614    time: MediaTime,
615    context: &SampleContext<'_>,
616) -> EffectParamValue {
617    let authored = |value: EffectValue| EffectParamValue {
618        value,
619        interpolated: false,
620    };
621    let interpolated = |value: EffectValue| EffectParamValue {
622        value,
623        interpolated: true,
624    };
625    let between = |left: EffectValue, right: EffectValue, amount: f64| {
626        interpolate_value(left, right, amount).map_or_else(|| authored(left), interpolated)
627    };
628    match animation {
629        Animated::Data(binding) => {
630            let value = match crate::data::bound_vec2(binding, time, context) {
631                Some(point) if binding.remap.is_none() && is_points(binding, context) => {
632                    EffectValue::Vec2([point.x, point.y])
633                }
634                _ => EffectValue::Float(
635                    crate::data::bound_scalar(binding, time, context).unwrap_or(0.0),
636                ),
637            };
638            EffectParamValue {
639                value,
640                interpolated: true,
641            }
642        }
643        Animated::Constant { value } => authored(*value),
644        Animated::Split { channels } => interpolated(if channels.len() == 4 {
645            EffectValue::Vec4(channel_values(channels, time, context))
646        } else {
647            EffectValue::Vec2(channel_values(channels, time, context))
648        }),
649        Animated::Keyframes {
650            keyframes,
651            before,
652            after,
653        } => {
654            let (segment, passes) = keyed::read(keyframes, *before, *after, time);
655            if let Some(value) = repeat_offset_value(keyframes, &segment, passes) {
656                return interpolated(value);
657            }
658            match &segment {
659                NumberSegment::Curve(left, right, ..) | NumberSegment::Line { left, right, .. }
660                    if matches!(
661                        (left.value, right.value),
662                        (EffectValue::Float(_), EffectValue::Float(_))
663                    ) =>
664                {
665                    interpolated(EffectValue::Float(finite_f32(number(&segment, |value| {
666                        float(*value)
667                    }))))
668                }
669                _ => match segment.timed() {
670                    Segment::Between(left, right, amount) => {
671                        between(left.value, right.value, amount)
672                    }
673                    Segment::At(keyframe) => authored(keyframe.value),
674                    Segment::Empty => authored(EffectValue::Float(0.0)),
675                },
676            }
677        }
678    }
679}
680
681const fn float(value: EffectValue) -> f32 {
682    match value {
683        EffectValue::Float(value) => value,
684        _ => 0.0,
685    }
686}
687
688fn repeat_offset_value(
689    keyframes: &[Keyframe<EffectValue>],
690    segment: &NumberSegment<'_, Keyframe<EffectValue>>,
691    passes: i64,
692) -> Option<EffectValue> {
693    if passes == 0 {
694        return None;
695    }
696    let (first, last) = (keyframes.first()?.value, keyframes.last()?.value);
697    let component = |index: usize| {
698        let read = |value: &EffectValue| match value {
699            EffectValue::Float(value) => *value,
700            EffectValue::Vec2(values) => values.get(index).copied().unwrap_or_default(),
701            EffectValue::Vec4(values) => values.get(index).copied().unwrap_or_default(),
702            EffectValue::Color(_) | EffectValue::Enum(_) | EffectValue::Bool(_) => 0.0,
703        };
704        let wide = match first {
705            EffectValue::Float(_) => number(segment, read),
706            _ => timed_number(&segment.timed(), read),
707        };
708        finite_f32(offset_by_passes(wide, passes, read(&first), read(&last)))
709    };
710    match first {
711        EffectValue::Float(_) => Some(EffectValue::Float(component(0))),
712        EffectValue::Vec2(_) => Some(EffectValue::Vec2([component(0), component(1)])),
713        EffectValue::Vec4(_) => Some(EffectValue::Vec4(std::array::from_fn(component))),
714        EffectValue::Color(_) | EffectValue::Enum(_) | EffectValue::Bool(_) => None,
715    }
716}
717
718/// Whether `binding` follows a `points` data set.
719fn is_points(binding: &alpha2_model::DataBinding, context: &SampleContext<'_>) -> bool {
720    crate::data::bound_kind(binding, context) == Some(alpha2_model::DataKind::Points)
721}
722
723fn interpolate_value(start: EffectValue, end: EffectValue, amount: f64) -> Option<EffectValue> {
724    let lerp = |a: f32, b: f32| interpolate_f32(a, b, amount);
725    match (start, end) {
726        (EffectValue::Float(a), EffectValue::Float(b)) => Some(EffectValue::Float(lerp(a, b))),
727        (EffectValue::Vec2(a), EffectValue::Vec2(b)) => {
728            Some(EffectValue::Vec2([lerp(a[0], b[0]), lerp(a[1], b[1])]))
729        }
730        (EffectValue::Vec4(a), EffectValue::Vec4(b)) => {
731            Some(EffectValue::Vec4(std::array::from_fn(|index| {
732                lerp(a[index], b[index])
733            })))
734        }
735        (EffectValue::Color(a), EffectValue::Color(b)) => {
736            Some(EffectValue::Color(interpolate_color(a, b, amount)))
737        }
738        _ => None,
739    }
740}
741
742/// Samples an animated color, interpolated premultiplied.
743#[must_use]
744pub fn sample_rgba(
745    animation: &Animated<alpha2_model::Rgba>,
746    time: MediaTime,
747) -> alpha2_model::Rgba {
748    match animation {
749        Animated::Data(_) | Animated::Split { .. } => alpha2_model::Rgba::new(0.0, 0.0, 0.0, 0.0),
750        Animated::Constant { value } => *value,
751        Animated::Keyframes {
752            keyframes,
753            before,
754            after,
755        } => match segment(keyframes, *before, *after, time) {
756            Segment::At(keyframe) => keyframe.value,
757            Segment::Empty => alpha2_model::Rgba::new(0.0, 0.0, 0.0, 0.0),
758            Segment::Between(left, right, amount) => {
759                let (a, b) = (left.value, right.value);
760                let [red, green, blue, alpha] = interpolate_color(
761                    [a.red, a.green, a.blue, a.alpha],
762                    [b.red, b.green, b.blue, b.alpha],
763                    amount,
764                );
765                alpha2_model::Rgba::new(red, green, blue, alpha)
766            }
767        },
768    }
769}
770
771/// Interpolates straight colors premultiplied; returns straight, clamped to `0..=1`.
772#[allow(clippy::cast_possible_truncation)]
773fn interpolate_color(start: [f32; 4], end: [f32; 4], amount: f64) -> [f32; 4] {
774    let (start_alpha, end_alpha) = (f64::from(start[3]), f64::from(end[3]));
775    let alpha = (start_alpha + (end_alpha - start_alpha) * amount).clamp(0.0, 1.0);
776    let mut color = [0.0; 4];
777    for index in 0..3 {
778        let from = f64::from(start[index]) * start_alpha;
779        let to = f64::from(end[index]) * end_alpha;
780        let premultiplied = from + (to - from) * amount;
781        // Fully transparent has no color; keep straight interpolation so the value stays continuous.
782        let straight = if alpha > 0.0 {
783            premultiplied / alpha
784        } else {
785            f64::from(start[index]) + (f64::from(end[index]) - f64::from(start[index])) * amount
786        };
787        color[index] = straight.clamp(0.0, 1.0) as f32;
788    }
789    color[3] = alpha as f32;
790    color
791}
792
793fn segment<T>(
794    keyframes: &[Keyframe<T>],
795    before: Extrapolation,
796    after: Extrapolation,
797    time: MediaTime,
798) -> Segment<'_, Keyframe<T>> {
799    keyed::read(keyframes, before, after, time).0.timed()
800}
801
802#[allow(clippy::cast_precision_loss)]
803pub(crate) fn interpolation_amount(start: MediaTime, end: MediaTime, time: MediaTime) -> f64 {
804    let (start, end, time) = (start.ticks(), end.ticks(), time.ticks());
805    match (time.checked_sub(start), end.checked_sub(start)) {
806        (Some(elapsed), Some(length)) => elapsed as f64 / length as f64,
807        _ => {
808            (i128::from(time) - i128::from(start)) as f64
809                / (i128::from(end) - i128::from(start)) as f64
810        }
811    }
812}
813
814/// Linear interpolation clamped to finite `f32`, since overshoot can exceed its range.
815#[allow(clippy::cast_possible_truncation)]
816pub(crate) fn interpolate_f32(start: f32, end: f32, amount: f64) -> f32 {
817    (f64::from(start) + (f64::from(end) - f64::from(start)) * amount)
818        .clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
819}
820
821/// Samples per-side lengths like `sample_size`.
822#[must_use]
823pub fn sample_insets(animation: &Animated<Insets>, time: MediaTime) -> [f32; 4] {
824    match animation {
825        Animated::Constant { value } => value.sides().map(LayoutSize::value),
826        Animated::Data(_) | Animated::Split { .. } => [0.0; 4],
827        Animated::Keyframes {
828            keyframes,
829            before,
830            after,
831        } => match segment(keyframes, *before, *after, time) {
832            Segment::Between(left, right, amount) => {
833                let (from, to) = (left.value.sides(), right.value.sides());
834                std::array::from_fn(|side| {
835                    interpolate_f32(from[side].value(), to[side].value(), amount)
836                })
837            }
838            Segment::At(keyframe) => keyframe.value.sides().map(LayoutSize::value),
839            Segment::Empty => [0.0; 4],
840        },
841    }
842}
843
844/// Samples a layout size like [`sample_scalar`]. Plan sizes are fractions.
845#[must_use]
846pub fn sample_size(animation: &Animated<LayoutSize>, time: MediaTime) -> f32 {
847    match animation {
848        Animated::Constant { value } => value.value(),
849        Animated::Data(_) | Animated::Split { .. } => 0.0,
850        Animated::Keyframes {
851            keyframes,
852            before,
853            after,
854        } => match segment(keyframes, *before, *after, time) {
855            Segment::Between(left, right, amount) => {
856                interpolate_f32(left.value.value(), right.value.value(), amount)
857            }
858            Segment::At(keyframe) => keyframe.value.value(),
859            Segment::Empty => 0.0,
860        },
861    }
862}
863
864/// Samples a layout offset per axis like [`sample_size`].
865#[must_use]
866pub fn sample_offset(animation: &Animated<LayoutOffset>, time: MediaTime) -> Vec2 {
867    let vector = |offset: &LayoutOffset| Vec2::new(offset.x.value(), offset.y.value());
868    match animation {
869        Animated::Constant { value } => vector(value),
870        Animated::Data(_) | Animated::Split { .. } => Vec2::default(),
871        Animated::Keyframes {
872            keyframes,
873            before,
874            after,
875        } => match segment(keyframes, *before, *after, time) {
876            Segment::Between(left, right, amount) => Vec2::new(
877                interpolate_f32(left.value.x.value(), right.value.x.value(), amount),
878                interpolate_f32(left.value.y.value(), right.value.y.value(), amount),
879            ),
880            Segment::At(keyframe) => vector(&keyframe.value),
881            Segment::Empty => Vec2::default(),
882        },
883    }
884}
885
886/// Samples a layout length. Mismatched keyframe kinds keep the left kind.
887#[must_use]
888pub fn sample_length(animation: &Animated<LayoutLength>, time: MediaTime) -> LayoutLength {
889    match animation {
890        Animated::Constant { value } => *value,
891        Animated::Data(_) | Animated::Split { .. } => LayoutLength::Fraction(0.0),
892        Animated::Keyframes {
893            keyframes,
894            before,
895            after,
896        } => match segment(keyframes, *before, *after, time) {
897            Segment::Between(left, right, amount) => left.value.with_value(interpolate_f32(
898                left.value.value(),
899                right.value.value(),
900                amount,
901            )),
902            Segment::At(keyframe) => keyframe.value,
903            Segment::Empty => LayoutLength::Fraction(0.0),
904        },
905    }
906}
907
908/// Samples a non-interpolating value: the last keyframe at or before `time`, else the first.
909/// Outside the keyframes `time` is first mapped by the value's `before` and `after`.
910#[must_use]
911pub fn sample_hold<T: Clone + Default>(animation: &Animated<T>, time: MediaTime) -> T {
912    match animation {
913        Animated::Constant { value } => value.clone(),
914        Animated::Data(_) | Animated::Split { .. } => T::default(),
915        Animated::Keyframes {
916            keyframes,
917            before,
918            after,
919        } => keyed::held(keyframes, *before, *after, time)
920            .map(|keyframe| keyframe.value.clone())
921            .unwrap_or_default(),
922    }
923}
924
925#[cfg(test)]
926#[path = "animation_tests.rs"]
927mod tests;