Skip to main content

tweener/
lib.rs

1#![doc = include_str!("../README.md")]
2
3#[cfg(test)]
4mod test;
5
6use std::f64::consts::PI;
7use std::time::Duration;
8
9use num_traits::{Float, NumCast};
10
11/// Converts an `f64` constant into the generic float type.
12#[inline]
13fn lit<T: Float>(v: f64) -> T {
14    <T as NumCast>::from(v).unwrap()
15}
16
17/// Converts a [`Duration`] into seconds as the generic float type.
18#[inline]
19fn secs<T: Float>(d: Duration) -> T {
20    lit(d.as_secs_f64())
21}
22
23/// Interpolates a value from `begin` to `end` over `duration` using the easing function `func`.
24///
25/// Generic over the float type (`f32` or `f64`); defaults to `f64`.
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct Tween<T = f64> {
28    /// Current interpolated value.
29    pub value: T,
30    /// Starting value of the tween.
31    pub begin: T,
32    /// Target value of the tween.
33    pub end: T,
34    /// Total time the tween takes to go from `begin` to `end`.
35    pub duration: Duration,
36    /// Easing function that shapes the progress curve.
37    pub func: Easing,
38    /// When `true`, the tween plays back in the opposite direction on reaching the end instead of finishing.
39    pub yoyo: bool,
40    /// Time elapsed so far in the current run.
41    pub time: Duration,
42    /// Time left over after `time` passes `duration` in the last update, carried into the next cycle or step.
43    pub overflow: Duration,
44    /// When `true`, the tween is currently playing backwards, from `end` to `begin`.
45    pub reversed: bool,
46}
47
48impl<T: Float> Tween<T> {
49    /// Creates a new tween from `begin` to `end` over `duration` using the easing function `func`.
50    pub fn new(begin: T, end: T, duration: Duration, func: Easing, yoyo: bool) -> Self {
51        Self {
52            value: begin,
53            begin,
54            end,
55            duration,
56            func,
57            yoyo,
58            time: Duration::ZERO,
59            overflow: Duration::ZERO,
60            reversed: false,
61        }
62    }
63
64    /// Sets the elapsed time directly, clamping to `duration` and updating `value` and `overflow` accordingly.
65    pub fn set_time(&mut self, current: Duration) {
66        if current >= self.duration {
67            self.overflow = current - self.duration;
68            self.time = self.duration;
69            self.value = self.end;
70        } else if current.is_zero() {
71            self.overflow = Duration::ZERO;
72            self.time = Duration::ZERO;
73            self.value = self.begin;
74        } else {
75            self.overflow = Duration::ZERO;
76            self.time = current;
77            self.value = self.func.apply(
78                secs(self.time),
79                self.begin,
80                self.change(),
81                secs(self.duration),
82            );
83        }
84    }
85
86    /// Returns the total distance between `begin` and `end`.
87    pub fn change(&self) -> T {
88        self.end - self.begin
89    }
90
91    /// Returns `true` once the tween has reached its end point in the current playback direction.
92    pub fn is_finished(&self) -> bool {
93        if self.reversed {
94            self.time.is_zero()
95        } else {
96            self.time >= self.duration
97        }
98    }
99
100    /// Advances the tween by `dt` in the current direction, flipping direction and carrying over the remainder when `yoyo` is enabled.
101    pub fn update(&mut self, dt: Duration) {
102        let prev = self.time;
103        if self.reversed {
104            match prev.checked_sub(dt) {
105                Some(t) => self.set_time(t),
106                None => {
107                    self.set_time(Duration::ZERO);
108                    self.overflow = dt - prev;
109                }
110            }
111        } else {
112            self.set_time(prev + dt);
113        }
114
115        while self.yoyo && !self.duration.is_zero() && self.is_finished() {
116            let over = self.overflow;
117            self.reversed = !self.reversed;
118            if self.reversed {
119                if over <= self.duration {
120                    self.set_time(self.duration - over);
121                } else {
122                    self.set_time(Duration::ZERO);
123                    self.overflow = over - self.duration;
124                }
125            } else {
126                self.set_time(over);
127            }
128        }
129    }
130}
131
132// Easing functions
133
134const BACK_S: f64 = 1.70158;
135
136/// The enum that holds the easing methods allows the [`Tween`] struct to be serialized.
137#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub enum Easing {
140    Linear,
141    InQuad,
142    OutQuad,
143    InOutQuad,
144    OutInQuad,
145    InCubic,
146    OutCubic,
147    InOutCubic,
148    OutInCubic,
149    InQuart,
150    OutQuart,
151    InOutQuart,
152    OutInQuart,
153    InQuint,
154    OutQuint,
155    InOutQuint,
156    OutInQuint,
157    InSine,
158    OutSine,
159    InOutSine,
160    OutInSine,
161    InExpo,
162    OutExpo,
163    InOutExpo,
164    OutInExpo,
165    InCirc,
166    OutCirc,
167    InOutCirc,
168    OutInCirc,
169    InElastic,
170    OutElastic,
171    InOutElastic,
172    OutInElastic,
173    InBack,
174    OutBack,
175    InOutBack,
176    OutInBack,
177    InBounce,
178    OutBounce,
179    InOutBounce,
180    OutInBounce,
181}
182
183impl Easing {
184    pub(crate) fn apply<T: Float>(self, t: T, b: T, c: T, d: T) -> T {
185        use Easing::*;
186        match self {
187            Linear => linear(t, b, c, d),
188            InQuad => in_quad(t, b, c, d),
189            OutQuad => out_quad(t, b, c, d),
190            InOutQuad => in_out_quad(t, b, c, d),
191            OutInQuad => out_in_quad(t, b, c, d),
192            InCubic => in_cubic(t, b, c, d),
193            OutCubic => out_cubic(t, b, c, d),
194            InOutCubic => in_out_cubic(t, b, c, d),
195            OutInCubic => out_in_cubic(t, b, c, d),
196            InQuart => in_quart(t, b, c, d),
197            OutQuart => out_quart(t, b, c, d),
198            InOutQuart => in_out_quart(t, b, c, d),
199            OutInQuart => out_in_quart(t, b, c, d),
200            InQuint => in_quint(t, b, c, d),
201            OutQuint => out_quint(t, b, c, d),
202            InOutQuint => in_out_quint(t, b, c, d),
203            OutInQuint => out_in_quint(t, b, c, d),
204            InSine => in_sine(t, b, c, d),
205            OutSine => out_sine(t, b, c, d),
206            InOutSine => in_out_sine(t, b, c, d),
207            OutInSine => out_in_sine(t, b, c, d),
208            InExpo => in_expo(t, b, c, d),
209            OutExpo => out_expo(t, b, c, d),
210            InOutExpo => in_out_expo(t, b, c, d),
211            OutInExpo => out_in_expo(t, b, c, d),
212            InCirc => in_circ(t, b, c, d),
213            OutCirc => out_circ(t, b, c, d),
214            InOutCirc => in_out_circ(t, b, c, d),
215            OutInCirc => out_in_circ(t, b, c, d),
216            InElastic => in_elastic(t, b, c, d),
217            OutElastic => out_elastic(t, b, c, d),
218            InOutElastic => in_out_elastic(t, b, c, d),
219            OutInElastic => out_in_elastic(t, b, c, d),
220            InBack => in_back(t, b, c, d),
221            OutBack => out_back(t, b, c, d),
222            InOutBack => in_out_back(t, b, c, d),
223            OutInBack => out_in_back(t, b, c, d),
224            InBounce => in_bounce(t, b, c, d),
225            OutBounce => out_bounce(t, b, c, d),
226            InOutBounce => in_out_bounce(t, b, c, d),
227            OutInBounce => out_in_bounce(t, b, c, d),
228        }
229    }
230}
231
232type EaseFn<T> = fn(T, T, T, T) -> T;
233
234/// Shared shape of every `OutIn*` easing: the first half plays `out`, the second half plays `inn`.
235fn out_in<T: Float>(t: T, b: T, c: T, d: T, out: EaseFn<T>, inn: EaseFn<T>) -> T {
236    let two = lit::<T>(2.0);
237    if t < d / two {
238        return out(t * two, b, c / two, d);
239    }
240    inn((t * two) - d, b + c / two, c / two, d)
241}
242
243fn linear<T: Float>(t: T, b: T, c: T, d: T) -> T {
244    c * t / d + b
245}
246
247fn in_quad<T: Float>(t: T, b: T, c: T, d: T) -> T {
248    c * (t / d).powi(2) + b
249}
250
251fn out_quad<T: Float>(t: T, b: T, c: T, d: T) -> T {
252    let two = lit::<T>(2.0);
253    let t = t / d;
254    -c * t * (t - two) + b
255}
256
257fn in_out_quad<T: Float>(t: T, b: T, c: T, d: T) -> T {
258    let (one, two) = (T::one(), lit::<T>(2.0));
259    let t = t / d * two;
260    if t < one {
261        return c / two * t.powi(2) + b;
262    }
263    -c / two * ((t - one) * (t - lit::<T>(3.0)) - one) + b
264}
265
266fn out_in_quad<T: Float>(t: T, b: T, c: T, d: T) -> T {
267    out_in(t, b, c, d, out_quad, in_quad)
268}
269
270fn in_cubic<T: Float>(t: T, b: T, c: T, d: T) -> T {
271    c * (t / d).powi(3) + b
272}
273
274fn out_cubic<T: Float>(t: T, b: T, c: T, d: T) -> T {
275    c * ((t / d - T::one()).powi(3) + T::one()) + b
276}
277
278fn in_out_cubic<T: Float>(t: T, b: T, c: T, d: T) -> T {
279    let two = lit::<T>(2.0);
280    let mut t = t / d * two;
281    if t < T::one() {
282        return c / two * t * t * t + b;
283    }
284    t = t - two;
285    c / two * (t * t * t + two) + b
286}
287
288fn out_in_cubic<T: Float>(t: T, b: T, c: T, d: T) -> T {
289    out_in(t, b, c, d, out_cubic, in_cubic)
290}
291
292fn in_quart<T: Float>(t: T, b: T, c: T, d: T) -> T {
293    c * (t / d).powi(4) + b
294}
295
296fn out_quart<T: Float>(t: T, b: T, c: T, d: T) -> T {
297    let one = T::one();
298    -c * ((t / d - one).powi(4) - one) + b
299}
300
301fn in_out_quart<T: Float>(t: T, b: T, c: T, d: T) -> T {
302    let two = lit::<T>(2.0);
303    let t = t / d * two;
304    if t < T::one() {
305        return c / two * t.powi(4) + b;
306    }
307    -c / two * ((t - two).powi(4) - two) + b
308}
309
310fn out_in_quart<T: Float>(t: T, b: T, c: T, d: T) -> T {
311    out_in(t, b, c, d, out_quart, in_quart)
312}
313
314fn in_quint<T: Float>(t: T, b: T, c: T, d: T) -> T {
315    c * (t / d).powi(5) + b
316}
317
318fn out_quint<T: Float>(t: T, b: T, c: T, d: T) -> T {
319    c * ((t / d - T::one()).powi(5) + T::one()) + b
320}
321
322fn in_out_quint<T: Float>(t: T, b: T, c: T, d: T) -> T {
323    let two = lit::<T>(2.0);
324    let t = t / d * two;
325    if t < T::one() {
326        return c / two * t.powi(5) + b;
327    }
328    c / two * ((t - two).powi(5) + two) + b
329}
330
331fn out_in_quint<T: Float>(t: T, b: T, c: T, d: T) -> T {
332    out_in(t, b, c, d, out_quint, in_quint)
333}
334
335fn in_sine<T: Float>(t: T, b: T, c: T, d: T) -> T {
336    -c * (t / d * lit::<T>(PI / 2.0)).cos() + c + b
337}
338
339fn out_sine<T: Float>(t: T, b: T, c: T, d: T) -> T {
340    c * (t / d * lit::<T>(PI / 2.0)).sin() + b
341}
342
343fn in_out_sine<T: Float>(t: T, b: T, c: T, d: T) -> T {
344    -c / lit::<T>(2.0) * ((lit::<T>(PI) * t / d).cos() - T::one()) + b
345}
346
347fn out_in_sine<T: Float>(t: T, b: T, c: T, d: T) -> T {
348    out_in(t, b, c, d, out_sine, in_sine)
349}
350
351fn in_expo<T: Float>(t: T, b: T, c: T, d: T) -> T {
352    if t == T::zero() {
353        return b;
354    }
355    c * lit::<T>(2.0).powf(lit::<T>(10.0) * (t / d - T::one())) + b - c * lit::<T>(0.001)
356}
357
358fn out_expo<T: Float>(t: T, b: T, c: T, d: T) -> T {
359    if t == d {
360        return b + c;
361    }
362    c * lit::<T>(1.001) * (-(lit::<T>(2.0).powf(lit::<T>(-10.0) * t / d)) + T::one()) + b
363}
364
365fn in_out_expo<T: Float>(t: T, b: T, c: T, d: T) -> T {
366    if t == T::zero() {
367        return b;
368    }
369    if t == d {
370        return b + c;
371    }
372    let (one, two) = (T::one(), lit::<T>(2.0));
373    let t = t / d * two;
374    if t < one {
375        return c / two * two.powf(lit::<T>(10.0) * (t - one)) + b - c * lit::<T>(0.0005);
376    }
377    c / two * lit::<T>(1.0005) * (-(two.powf(lit::<T>(-10.0) * (t - one))) + two) + b
378}
379
380fn out_in_expo<T: Float>(t: T, b: T, c: T, d: T) -> T {
381    out_in(t, b, c, d, out_expo, in_expo)
382}
383
384fn in_circ<T: Float>(t: T, b: T, c: T, d: T) -> T {
385    let one = T::one();
386    -c * ((one - (t / d).powi(2)).sqrt() - one) + b
387}
388
389fn out_circ<T: Float>(t: T, b: T, c: T, d: T) -> T {
390    c * (T::one() - (t / d - T::one()).powi(2)).sqrt() + b
391}
392
393fn in_out_circ<T: Float>(t: T, b: T, c: T, d: T) -> T {
394    let (one, two) = (T::one(), lit::<T>(2.0));
395    let mut t = t / d * two;
396    if t < one {
397        return -c / two * ((one - t * t).sqrt() - one) + b;
398    }
399    t = t - two;
400    c / two * ((one - t * t).sqrt() + one) + b
401}
402
403fn out_in_circ<T: Float>(t: T, b: T, c: T, d: T) -> T {
404    out_in(t, b, c, d, out_circ, in_circ)
405}
406
407fn in_elastic<T: Float>(t: T, b: T, c: T, d: T) -> T {
408    if t == T::zero() {
409        return b;
410    }
411    let mut t = t / d;
412    if t == T::one() {
413        return b + c;
414    }
415    let (p, a, s) = calculate_pas(c, d);
416    t = t - T::one();
417    -(a * lit::<T>(2.0).powf(lit::<T>(10.0) * t) * ((t * d - s) * lit::<T>(2.0 * PI) / p).sin()) + b
418}
419
420fn out_elastic<T: Float>(t: T, b: T, c: T, d: T) -> T {
421    if t == T::zero() {
422        return b;
423    }
424    let t = t / d;
425    if t == T::one() {
426        return b + c;
427    }
428    let (p, a, s) = calculate_pas(c, d);
429    a * lit::<T>(2.0).powf(lit::<T>(-10.0) * t) * ((t * d - s) * lit::<T>(2.0 * PI) / p).sin()
430        + c
431        + b
432}
433
434fn in_out_elastic<T: Float>(t: T, b: T, c: T, d: T) -> T {
435    if t == T::zero() {
436        return b;
437    }
438    let (two, half) = (lit::<T>(2.0), lit::<T>(0.5));
439    let mut t = t / d * two;
440    if t == two {
441        return b + c;
442    }
443    let (p, a, s) = calculate_pas(c, d);
444    let tau = lit::<T>(2.0 * PI);
445    t = t - T::one();
446    if t < T::zero() {
447        return -half * (a * two.powf(lit::<T>(10.0) * t) * ((t * d - s) * tau / p).sin()) + b;
448    }
449    a * two.powf(lit::<T>(-10.0) * t) * ((t * d - s) * tau / p).sin() * half + c + b
450}
451
452fn out_in_elastic<T: Float>(t: T, b: T, c: T, d: T) -> T {
453    out_in(t, b, c, d, out_elastic, in_elastic)
454}
455
456fn in_back<T: Float>(t: T, b: T, c: T, d: T) -> T {
457    let s = lit::<T>(BACK_S);
458    let t = t / d;
459    c * t * t * ((s + T::one()) * t - s) + b
460}
461
462fn out_back<T: Float>(t: T, b: T, c: T, d: T) -> T {
463    let (one, s) = (T::one(), lit::<T>(BACK_S));
464    let t = t / d - one;
465    c * (t * t * ((s + one) * t + s) + one) + b
466}
467
468fn in_out_back<T: Float>(t: T, b: T, c: T, d: T) -> T {
469    let (one, two) = (T::one(), lit::<T>(2.0));
470    let s = lit::<T>(BACK_S * 1.525);
471    let mut t = t / d * two;
472    if t < one {
473        return c / two * (t * t * ((s + one) * t - s)) + b;
474    }
475    t = t - two;
476    c / two * (t * t * ((s + one) * t + s) + two) + b
477}
478
479fn out_in_back<T: Float>(t: T, b: T, c: T, d: T) -> T {
480    out_in(t, b, c, d, out_back, in_back)
481}
482
483fn out_bounce<T: Float>(t: T, b: T, c: T, d: T) -> T {
484    let k = lit::<T>(7.5625);
485    let mut t = t / d;
486    if t < lit::<T>(1.0 / 2.75) {
487        return c * (k * t * t) + b;
488    }
489    if t < lit::<T>(2.0 / 2.75) {
490        t = t - lit::<T>(1.5 / 2.75);
491        return c * (k * t * t + lit::<T>(0.75)) + b;
492    } else if t < lit::<T>(2.5 / 2.75) {
493        t = t - lit::<T>(2.25 / 2.75);
494        return c * (k * t * t + lit::<T>(0.9375)) + b;
495    }
496    t = t - lit::<T>(2.625 / 2.75);
497    c * (k * t * t + lit::<T>(0.984375)) + b
498}
499
500fn in_bounce<T: Float>(t: T, b: T, c: T, d: T) -> T {
501    c - out_bounce(d - t, T::zero(), c, d) + b
502}
503
504fn in_out_bounce<T: Float>(t: T, b: T, c: T, d: T) -> T {
505    let (two, half) = (lit::<T>(2.0), lit::<T>(0.5));
506    if t < d / two {
507        return in_bounce(t * two, T::zero(), c, d) * half + b;
508    }
509    out_bounce(t * two - d, T::zero(), c, d) * half + c * half + b
510}
511
512fn out_in_bounce<T: Float>(t: T, b: T, c: T, d: T) -> T {
513    out_in(t, b, c, d, out_bounce, in_bounce)
514}
515
516fn calculate_pas<T: Float>(c: T, d: T) -> (T, T, T) {
517    let p = d * lit::<T>(0.3);
518    (p, c, p / lit::<T>(4.0))
519}