aura-anim-core 0.3.0

Typed animation runtime and composable animation sources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Duration-based interpolation animations.

use crate::{
    timing::{Duration, Timing},
    traits::{Animatable, Animation, AnimationState},
};

/// The lifecycle state of a [`Tween`].
pub type TweenState = AnimationState;

/// An animation that interpolates between two values using [`Timing`].
///
/// # Examples
///
/// ```
/// use aura_anim_core::{Tween, timing::Timing};
/// use std::time::Duration;
///
/// let mut tween = Tween::between(0.0_f32, 10.0, Timing::new(100.0));
///
/// tween.tick(Duration::from_millis(50));
/// assert_eq!(*tween.value(), 5.0);
///
/// tween.tick(Duration::from_millis(50));
/// assert!(tween.is_completed());
/// assert_eq!(*tween.value(), 10.0);
/// ```
#[derive(Debug, Clone)]
pub struct Tween<T: Animatable> {
    from: T,
    to: T,
    current: T,
    elapsed: Duration,
    timing: Timing,
    state: AnimationState,
}

impl<T: Animatable> Tween<T> {
    /// Creates an idle tween with the default 200 millisecond timing.
    #[must_use]
    pub fn new(value: T) -> Self {
        Self::with_timing(value, Timing::new(200.0))
    }

    /// Creates an idle tween with the provided timing.
    #[must_use]
    pub fn with_timing(value: T, timing: Timing) -> Self {
        Self {
            from: value.clone(),
            to: value.clone(),
            current: value,
            elapsed: Duration::ZERO,
            timing,
            state: AnimationState::Idle,
        }
    }

    /// Creates a running tween from `from` to `to`.
    #[must_use]
    pub fn between(from: T, to: T, timing: Timing) -> Self {
        let mut tween = Self::with_timing(from, timing);
        tween.transition_to(to);
        tween
    }

    /// Returns the current interpolated value.
    #[must_use]
    pub fn value(&self) -> &T {
        &self.current
    }

    /// Returns the value at the start of the current transition.
    #[must_use]
    pub fn from(&self) -> &T {
        &self.from
    }

    /// Returns the target value of the current transition.
    #[must_use]
    pub fn target(&self) -> &T {
        &self.to
    }

    /// Returns the timing configuration.
    #[must_use]
    pub const fn timing(&self) -> Timing {
        self.timing
    }

    /// Returns the current lifecycle state.
    #[must_use]
    pub const fn state(&self) -> AnimationState {
        self.state
    }

    /// Returns whether the tween is currently running.
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.state == AnimationState::Running
    }

    /// Returns whether the tween has completed.
    #[must_use]
    pub fn is_completed(&self) -> bool {
        self.state == AnimationState::Completed
    }

    /// Starts a transition from the current value to `target`.
    pub fn transition_to(&mut self, target: T) {
        self.from = self.current.clone();
        self.to = target;
        self.elapsed = Duration::ZERO;
        self.state = AnimationState::Running;
        self.sample();
    }

    /// Advances the tween by `delta`.
    pub fn tick(&mut self, delta: impl Into<Duration>) {
        if self.state != AnimationState::Running {
            return;
        }

        self.elapsed += delta.into();
        self.sample();
    }

    fn remaining(&self) -> Option<Duration> {
        let total = self.timing.total_duration()?;
        Some(total.saturating_sub(self.elapsed))
    }

    /// Pauses the tween when it is running.
    pub fn pause(&mut self) {
        if self.state == AnimationState::Running {
            self.state = AnimationState::Paused;
        }
    }

    /// Resumes the tween when it is paused.
    pub fn resume(&mut self) {
        if self.state == AnimationState::Paused {
            self.state = AnimationState::Running;
        }
    }

    /// Cancels the tween unless it is already completed or canceled.
    pub fn cancel(&mut self) {
        if matches!(
            self.state,
            AnimationState::Running | AnimationState::Paused | AnimationState::Idle
        ) {
            self.state = AnimationState::Canceled;
        }
    }

    /// Seeks to normalized progress within the complete timing interval.
    pub fn seek(&mut self, progress: f32) {
        let progress = if progress.is_nan() {
            0.0
        } else {
            progress.clamp(0.0, 1.0)
        };
        self.state = AnimationState::Running;
        let total = self.timing.total_duration().unwrap_or_else(|| {
            Duration::from_millis(
                self.timing.delay().as_millis() + self.timing.duration().as_millis(),
            )
        });
        self.elapsed = Duration::from_millis(total.as_millis() * f64::from(progress));
        self.sample();
    }

    /// Moves the tween to its final value and completed state.
    #[allow(clippy::cast_possible_truncation)]
    pub fn finish(&mut self) {
        let progress = self
            .timing
            .iterations()
            .finite_count()
            .map_or(self.timing.direction().sample_progress(1, 1.0), |count| {
                self.timing.direction().end_progress(count)
            });
        self.current = T::interpolate(
            &self.from,
            &self.to,
            self.timing.easing().value(progress as f32),
        );
        self.state = AnimationState::Completed;
    }

    #[allow(clippy::cast_sign_loss)]
    #[allow(clippy::cast_possible_truncation)]
    fn sample(&mut self) {
        let Some(active_elapsed) = self.elapsed.checked_sub_delay(self.timing.delay()) else {
            self.current = self.from.clone();
            return;
        };

        let duration = self.timing.duration();
        if duration.is_zero() {
            self.finish();
            return;
        }

        if self
            .timing
            .active_duration()
            .is_some_and(|total| active_elapsed >= total)
        {
            self.finish();
            return;
        }

        let iteration_progress = active_elapsed.as_secs() / duration.as_secs();
        let iteration = iteration_progress.floor() as u32;
        let raw_progress = iteration_progress.fract();
        let progress = self
            .timing
            .direction()
            .sample_progress(iteration, raw_progress);
        let eased = self.timing.easing().value(progress as f32);
        self.current = T::interpolate(&self.from, &self.to, eased);
    }
}

impl<T: Animatable> Animation<T> for Tween<T> {
    fn value(&self) -> &T {
        self.value()
    }

    fn state(&self) -> AnimationState {
        self.state()
    }

    fn duration(&self) -> Option<Duration> {
        self.timing.total_duration()
    }

    fn tick(&mut self, delta: Duration) {
        self.tick(delta);
    }

    fn advance(&mut self, delta: Duration) -> Duration {
        if self.state != AnimationState::Running {
            return delta;
        }

        let Some(remaining) = self.remaining() else {
            self.tick(delta);
            return Duration::ZERO;
        };
        let consumed = delta.min(remaining);
        self.tick(consumed);
        delta.saturating_sub(consumed)
    }

    fn pause(&mut self) {
        self.pause();
    }

    fn resume(&mut self) {
        self.resume();
    }

    fn cancel(&mut self) {
        self.cancel();
    }

    fn seek(&mut self, progress: f32) {
        self.seek(progress);
    }

    fn finish(&mut self) {
        self.finish();
    }

    fn retarget(&mut self, target: &T) -> bool {
        self.transition_to(target.clone());
        true
    }

    fn set_rate(&mut self, rate: f64) {
        self.timing = self.timing.with_rate(rate);
    }

    fn into_value(self: Box<Self>) -> T {
        self.current
    }
}

#[cfg(test)]
mod tests {
    use super::Tween;
    use crate::{
        Animation, AnimationState,
        timing::{Delay, Direction, Duration, IterationCount, Timing},
    };
    use float_cmp::assert_approx_eq;

    #[test]
    fn new_tween_is_idle_with_matching_endpoints() {
        let tween = Tween::new(3.0_f32);

        assert_eq!(tween.state(), AnimationState::Idle);
        assert_approx_eq!(f32, *tween.value(), 3.0);
        assert_approx_eq!(f32, *tween.from(), 3.0);
        assert_approx_eq!(f32, *tween.target(), 3.0);
        assert_approx_eq!(f64, tween.timing().duration().as_millis(), 200.0);
    }

    #[test]
    fn transition_uses_current_value_as_new_start() {
        let mut tween = Tween::between(0.0_f32, 10.0, Timing::new(100.0));
        tween.tick(Duration::from_millis(40.0));
        tween.transition_to(20.0);

        assert_approx_eq!(f32, *tween.from(), 4.0);
        assert_approx_eq!(f32, *tween.value(), 4.0);
        assert_approx_eq!(f32, *tween.target(), 20.0);
    }

    #[test]
    fn rate_changes_tween_playback_duration() {
        let mut faster = Tween::between(0.0_f32, 10.0, Timing::new(100.0)).rate(2.0);
        let mut slower = Tween::between(0.0_f32, 10.0, Timing::new(100.0)).rate(0.5);

        faster.tick(Duration::from_millis(50.0));
        slower.tick(Duration::from_millis(50.0));

        assert_eq!(faster.state(), AnimationState::Completed);
        assert_approx_eq!(f32, *faster.value(), 10.0);
        assert_eq!(slower.state(), AnimationState::Running);
        assert_approx_eq!(f32, *slower.value(), 2.5);
    }

    #[test]
    fn paused_and_canceled_tweens_do_not_tick() {
        let mut tween = Tween::between(0.0_f32, 10.0, Timing::new(100.0));
        tween.pause();
        tween.tick(Duration::from_millis(50.0));
        assert_approx_eq!(f32, *tween.value(), 0.0);

        tween.resume();
        tween.tick(Duration::from_millis(25.0));
        assert_approx_eq!(f32, *tween.value(), 2.5);

        tween.cancel();
        tween.tick(Duration::from_millis(75.0));
        assert_eq!(tween.state(), AnimationState::Canceled);
        assert_approx_eq!(f32, *tween.value(), 2.5);
    }

    #[test]
    fn advance_returns_unconsumed_duration() {
        let mut tween = Tween::between(0.0_f32, 1.0, Timing::new(100.0));

        let overflow = Animation::advance(&mut tween, Duration::from_millis(125.0));

        assert_eq!(overflow, Duration::from_millis(25.0));
        assert_eq!(tween.state(), AnimationState::Completed);
    }

    #[test]
    fn infinite_tween_consumes_all_advanced_time() {
        let timing = Timing::new(100.0).with_iterations(IterationCount::INFINITE);
        let mut tween = Tween::between(0.0_f32, 1.0, timing);

        let overflow = Animation::advance(&mut tween, Duration::from_millis(250.0));

        assert_eq!(overflow, Duration::ZERO);
        assert_eq!(tween.state(), AnimationState::Running);
        assert_approx_eq!(f32, *tween.value(), 0.5);
    }

    #[test]
    fn delay_and_submillisecond_progress_preserve_duration_precision() {
        let timing = Timing::new(0.5).with_delay(Delay::from_millis(0.25));
        let mut tween = Tween::between(0.0_f32, 10.0, timing);

        tween.tick(std::time::Duration::from_micros(250));
        assert_approx_eq!(f32, *tween.value(), 0.0);

        tween.tick(std::time::Duration::from_micros(125));
        assert_approx_eq!(f32, *tween.value(), 2.5);
    }

    #[test]
    fn repeated_tween_samples_progress_within_alternate_iteration() {
        let timing = Timing::new(100.0)
            .with_iterations(2)
            .with_direction(Direction::Alternate);
        let mut tween = Tween::between(0.0_f32, 10.0, timing);

        tween.tick(Duration::from_millis(150.0));

        assert_eq!(tween.state(), AnimationState::Running);
        assert_approx_eq!(f32, *tween.value(), 5.0);
    }

    #[test]
    fn finish_respects_repeated_direction() {
        let timing = Timing::new(100.0)
            .with_iterations(2)
            .with_direction(Direction::Alternate);
        let mut tween = Tween::between(0.0_f32, 10.0, timing);

        tween.finish();

        assert_eq!(tween.state(), AnimationState::Completed);
        assert_approx_eq!(f32, *tween.value(), 0.0);
    }

    #[test]
    fn zero_duration_tween_finishes_on_tick() {
        let mut tween = Tween::between(0.0_f32, 10.0, Timing::new(0.0));

        tween.tick(Duration::ZERO);

        assert_eq!(tween.state(), AnimationState::Completed);
        assert_approx_eq!(f32, *tween.value(), 10.0);
    }
}