Skip to main content

alpha2_eval/curves/
materialize.rs

1//! A repeating or continued curve spelled out as keyframes.
2
3use super::{CurveError, part_keys, stepped};
4use crate::{SampleContext, sample_scalar};
5use alpha2_model::{Animated, Extrapolation, Interpolation, Keyframe, MAX_KEYFRAMES};
6use alpha2_time::{MediaTime, TimeRange};
7
8struct Spelled {
9    keys: Vec<(i128, Interpolation, Option<f32>)>,
10}
11
12impl Spelled {
13    fn push(&mut self, time: i128, interpolation: Interpolation) -> Result<(), CurveError> {
14        self.write(time, interpolation, None)
15    }
16
17    fn write(
18        &mut self,
19        time: i128,
20        interpolation: Interpolation,
21        value: Option<f32>,
22    ) -> Result<(), CurveError> {
23        if self.keys.len() >= MAX_KEYFRAMES {
24            return Err(CurveError::TooManyKeys);
25        }
26        self.keys.push((time, interpolation, value));
27        Ok(())
28    }
29
30    fn forward(
31        &mut self,
32        keyframes: &[Keyframe<f32>],
33        shift: i128,
34        wraps: bool,
35    ) -> Result<(), CurveError> {
36        let count = keyframes.len();
37        for (index, keyframe) in keyframes[..count - 1].iter().enumerate() {
38            let time = i128::from(keyframe.time.ticks()) + shift;
39            if !wraps || index + 2 < count {
40                self.push(time, keyframe.interpolation.clone())?;
41                continue;
42            }
43            let last = &keyframes[count - 1];
44            let length = i128::from(last.time.ticks()) - i128::from(keyframe.time.ticks());
45            if length == 1 {
46                self.push(time, Interpolation::Hold)?;
47                continue;
48            }
49            for part in part_keys(keyframe, last, keyframe.time.ticks(), last.time.ticks() - 1) {
50                self.push(i128::from(part.time.ticks()) + shift, part.interpolation)?;
51            }
52            self.push(time + length - 1, Interpolation::Hold)?;
53        }
54        Ok(())
55    }
56
57    fn mirrored(&mut self, keyframes: &[Keyframe<f32>], base: i128) -> Result<(), CurveError> {
58        let end = i128::from(keyframes[keyframes.len() - 1].time.ticks());
59        for pair in keyframes.windows(2).rev() {
60            let (left, right) = (&pair[0], &pair[1]);
61            let time = base + end - i128::from(right.time.ticks());
62            match left.interpolation {
63                Interpolation::Hold => {
64                    self.push(time, Interpolation::Hold)?;
65                    if right.time.ticks() - left.time.ticks() > 1 {
66                        self.push(time + 1, Interpolation::Hold)?;
67                    }
68                }
69                Interpolation::Steps(steps) => {
70                    self.push(time, Interpolation::Hold)?;
71                    let risers = stepped(left, right, steps, left.time.ticks(), right.time.ticks());
72                    let mut next = right.time.ticks();
73                    for riser in risers.iter().rev() {
74                        let shown = base + end - i128::from(next) + 1;
75                        if shown < base + end - i128::from(left.time.ticks()) {
76                            self.push(shown, Interpolation::Hold)?;
77                        }
78                        next = riser.time.ticks();
79                    }
80                }
81                Interpolation::Points { ref points } => self.push(
82                    time,
83                    Interpolation::Points {
84                        points: alpha2_model::easing_points_reversed(points),
85                    },
86                )?,
87                Interpolation::Linear => self.push(time, Interpolation::Linear)?,
88                Interpolation::CubicBezier(curve) => {
89                    self.push(time, Interpolation::CubicBezier(curve.reversed()))?;
90                }
91                Interpolation::ValueBezier(curve) => {
92                    self.push(time, Interpolation::ValueBezier(curve.reversed()))?;
93                }
94            }
95        }
96        Ok(())
97    }
98
99    fn pass(
100        &mut self,
101        keyframes: &[Keyframe<f32>],
102        mode: Extrapolation,
103        pass: i128,
104        start: i128,
105        period: i128,
106    ) -> Result<(), CurveError> {
107        if mode == Extrapolation::PingPong && pass.rem_euclid(2) == 1 {
108            self.mirrored(keyframes, start + pass * period)
109        } else {
110            self.forward(keyframes, pass * period, mode == Extrapolation::Repeat)
111        }
112    }
113}
114
115/// Spells out as keyframes what the value's `before` and `after` show over `range`, and sets
116/// each side the range reaches to `hold`: copies of the keyframes for every pass of a repeating
117/// mode that meets the range, and one keyframe at the range's edge for `linear`.
118///
119/// Every keyframe written holds the value the evaluator gives at its tick (the last keyframe of
120/// a side left as it is keeps its own, which a wrap there does not show). Between them the
121/// curve is the same, with two exceptions that stay within rounding: the last segment of a
122/// `repeat` pass, which ends one tick early and holds across the wrap, and a mirrored
123/// `ping_pong` pass, whose curves are written reversed. A value that is not keyed is left
124/// alone.
125///
126/// The result shows the old curve inside `range` only. Past the range a spelled side holds,
127/// and a repeating side the range does not reach repeats all the keyframes there now are.
128///
129/// # Errors
130///
131/// [`CurveError::TooManyKeys`] when the result would hold more than [`MAX_KEYFRAMES`]
132/// keyframes; the value is then left as it was.
133pub fn materialize(animation: &mut Animated<f32>, range: TimeRange) -> Result<(), CurveError> {
134    let live = animation.clone();
135    let Animated::Keyframes {
136        keyframes,
137        before,
138        after,
139    } = animation
140    else {
141        return Ok(());
142    };
143    let [first, .., last] = keyframes.as_slice() else {
144        return Ok(());
145    };
146    let (start, end) = (
147        i128::from(first.time.ticks()),
148        i128::from(last.time.ticks()),
149    );
150    let period = end - start;
151    let (from, to) = (
152        i128::from(range.start().ticks()),
153        i128::from(range.end().ticks()) - 1,
154    );
155    if to < from {
156        return Ok(());
157    }
158    let wraps = matches!(after, Extrapolation::Repeat | Extrapolation::RepeatOffset);
159    let reaches_before = from < start && *before != Extrapolation::Hold;
160    let reaches_after = *after != Extrapolation::Hold && (to > end || (to == end && wraps));
161    let pass_of = |tick: i128| (tick - start).div_euclid(period);
162    let count = keyframes.len();
163    let mut spelled = Spelled { keys: Vec::new() };
164
165    if reaches_before {
166        if *before == Extrapolation::Linear {
167            spelled.push(from, Interpolation::Linear)?;
168        } else {
169            for pass in pass_of(from)..0 {
170                spelled.pass(keyframes, *before, pass, start, period)?;
171            }
172        }
173    }
174    if reaches_after && *after != Extrapolation::Linear {
175        spelled.pass(keyframes, *after, 0, start, period)?;
176        for pass in 1..=pass_of(to) {
177            spelled.pass(keyframes, *after, pass, start, period)?;
178        }
179        if *after != Extrapolation::Repeat {
180            spelled.push(start + (pass_of(to) + 1) * period, Interpolation::Linear)?;
181        }
182    } else {
183        for keyframe in &keyframes[..count - 1] {
184            spelled.push(
185                i128::from(keyframe.time.ticks()),
186                keyframe.interpolation.clone(),
187            )?;
188        }
189        if reaches_after {
190            spelled.push(end, Interpolation::Linear)?;
191            spelled.push(to + 1, Interpolation::Linear)?;
192        } else {
193            spelled.write(end, last.interpolation.clone(), Some(last.value))?;
194        }
195    }
196
197    let written = spelled
198        .keys
199        .into_iter()
200        .filter_map(|(time, interpolation, value)| {
201            let time = MediaTime(i64::try_from(time).ok()?);
202            Some(Keyframe {
203                time,
204                value: value.unwrap_or_else(|| sample_scalar(&live, time, &SampleContext::NONE)),
205                interpolation,
206            })
207        })
208        .collect();
209    *keyframes = written;
210    if reaches_before {
211        *before = Extrapolation::Hold;
212    }
213    if reaches_after {
214        *after = Extrapolation::Hold;
215    }
216    Ok(())
217}