1#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
6pub enum Easing {
7 Linear,
9 SmoothStep,
11 EaseInCubic,
13 EaseOutCubic,
15 #[default]
17 EaseInOutCubic,
18 EaseOutExpo,
20 EaseOutBack,
22}
23
24impl Easing {
25 pub fn sample(self, amount: f32) -> f32 {
30 let t = if amount.is_finite() {
31 amount.clamp(0.0, 1.0)
32 } else {
33 0.0
34 };
35 match self {
36 Self::Linear => t,
37 Self::SmoothStep => t * t * (3.0 - 2.0 * t),
38 Self::EaseInCubic => t * t * t,
39 Self::EaseOutCubic => 1.0 - (1.0 - t).powi(3),
40 Self::EaseInOutCubic if t < 0.5 => 4.0 * t * t * t,
41 Self::EaseInOutCubic => 1.0 - (-2.0 * t + 2.0).powi(3) * 0.5,
42 Self::EaseOutExpo if t >= 1.0 => 1.0,
43 Self::EaseOutExpo => 1.0 - 2.0_f32.powf(-10.0 * t),
44 Self::EaseOutBack => {
45 let c1 = 1.70158;
46 let c3 = c1 + 1.0;
47 1.0 + c3 * (t - 1.0).powi(3) + c1 * (t - 1.0).powi(2)
48 }
49 }
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 use super::Easing;
56
57 #[test]
58 fn easing_clamps_input() {
59 assert_eq!(Easing::Linear.sample(-1.0), 0.0);
60 assert_eq!(Easing::Linear.sample(2.0), 1.0);
61 assert_eq!(Easing::Linear.sample(f32::NAN), 0.0);
62 }
63
64 #[test]
65 fn every_curve_has_exact_finite_endpoints() {
66 let curves = [
67 Easing::Linear,
68 Easing::SmoothStep,
69 Easing::EaseInCubic,
70 Easing::EaseOutCubic,
71 Easing::EaseInOutCubic,
72 Easing::EaseOutExpo,
73 Easing::EaseOutBack,
74 ];
75 for curve in curves {
76 assert_eq!(curve.sample(0.0), 0.0, "{curve:?} start");
77 assert_eq!(curve.sample(1.0), 1.0, "{curve:?} end");
78 assert!(curve.sample(0.5).is_finite(), "{curve:?} midpoint");
79 assert!(
80 curve.sample(f32::INFINITY).is_finite(),
81 "{curve:?} infinity"
82 );
83 }
84 }
85}