#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum TweenEase {
Linear,
Power2Out,
#[default]
Power3Out,
ExpoOut,
SineInOut,
CubicBezier(crate::CubicBezier),
}
impl TweenEase {
pub fn sample(self, t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
match self {
Self::Linear => t,
Self::Power2Out => 1.0 - (1.0 - t).powi(3),
Self::Power3Out => 1.0 - (1.0 - t).powi(4),
Self::ExpoOut => {
if t >= 1.0 {
1.0
} else {
1.0 - 2.0_f32.powf(-10.0 * t)
}
}
Self::SineInOut => (1.0 - (std::f32::consts::PI * t).cos()) * 0.5,
Self::CubicBezier(curve) => curve.sample(t),
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct ScalarTween {
from: f32,
target: f32,
start: f64,
duration: f64,
ease: TweenEase,
}
impl ScalarTween {
pub fn new(value: f32) -> Self {
Self {
from: value,
target: value,
start: 0.0,
duration: 0.0,
ease: TweenEase::default(),
}
}
pub fn sample(&self, now: f64) -> f32 {
if self.duration <= 0.0 {
return self.target;
}
let t = ((now - self.start) / self.duration).clamp(0.0, 1.0) as f32;
self.from + (self.target - self.from) * self.ease.sample(t)
}
pub fn settled(&self, now: f64) -> bool {
self.from == self.target || now >= self.start + self.duration
}
pub fn target(&self) -> f32 {
self.target
}
pub fn retarget(
&mut self,
target: f32,
now: f64,
duration: f32,
delay: f32,
ease: TweenEase,
reduced: bool,
) {
if reduced || duration <= 0.0 {
*self = Self::new(target);
} else if target != self.target {
self.from = self.sample(now);
self.target = target;
self.start = now + f64::from(delay.max(0.0));
self.duration = f64::from(duration.max(0.0));
self.ease = ease;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exact_gsap_curves_and_endpoints() {
assert!((TweenEase::Power3Out.sample(0.5) - 0.9375).abs() < 1e-6);
for ease in [
TweenEase::Linear,
TweenEase::Power2Out,
TweenEase::Power3Out,
TweenEase::ExpoOut,
TweenEase::SineInOut,
] {
assert_eq!(ease.sample(0.0), 0.0);
assert_eq!(ease.sample(1.0), 1.0);
}
}
#[test]
fn css_bezier_tween_matches_shared_solver() {
let curve = crate::CubicBezier::new(0.23, 1., 0.32, 1.);
let mut t = ScalarTween::new(0.);
t.retarget(1., 0., 1., 0., TweenEase::CubicBezier(curve), false);
for time in [0., 0.1, 0.3, 0.5, 0.8, 1.] {
assert!((t.sample(time as f64) - curve.sample(time)).abs() < 1e-6);
}
}
#[test]
fn interruption_delay_and_reduced_motion() {
let mut t = ScalarTween::new(0.0);
t.retarget(1.0, 0.0, 1.0, 0.2, TweenEase::Linear, false);
assert_eq!(t.sample(0.1), 0.0);
let current = t.sample(0.7);
t.retarget(0.0, 0.7, 0.6, 0.0, TweenEase::Power3Out, false);
assert_eq!(t.sample(0.7), current);
assert!(t.settled(1.4));
t.retarget(1.0, 1.4, 1.0, 0.2, TweenEase::Linear, true);
assert_eq!(t.sample(1.4), 1.0);
}
}