use std::{error::Error, fmt, time::Duration};
use crate::{easing::Easing, math::Vec2};
pub trait Interpolate: Copy {
fn interpolate(self, end: Self, amount: f32) -> Self;
fn is_valid_interpolation_value(self) -> bool;
}
impl Interpolate for f32 {
fn interpolate(self, end: Self, amount: f32) -> Self {
finite_f32_lerp(self, end, amount)
}
fn is_valid_interpolation_value(self) -> bool {
self.is_finite()
}
}
impl Interpolate for Vec2 {
fn interpolate(self, end: Self, amount: f32) -> Self {
Self::new(
finite_f32_lerp(self.x, end.x, amount),
finite_f32_lerp(self.y, end.y, amount),
)
}
fn is_valid_interpolation_value(self) -> bool {
self.is_finite()
}
}
fn finite_f32_lerp(start: f32, end: f32, amount: f32) -> f32 {
if !start.is_finite() || !end.is_finite() || !amount.is_finite() {
return start;
}
let value = f64::from(start) + (f64::from(end) - f64::from(start)) * f64::from(amount);
value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TweenError {
InvalidValue,
InvalidInterpolatedValue,
}
impl fmt::Display for TweenError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidValue => write!(
formatter,
"tween values must satisfy their interpolation contract"
),
Self::InvalidInterpolatedValue => {
write!(formatter, "tween interpolation produced an invalid value")
}
}
}
}
impl Error for TweenError {}
#[derive(Debug, Clone)]
pub struct Tween<T: Interpolate> {
start: T,
current: T,
target: T,
elapsed: Duration,
duration: Duration,
easing: Easing,
active: bool,
}
impl<T: Interpolate> Tween<T> {
pub fn new(initial: T) -> Result<Self, TweenError> {
if !initial.is_valid_interpolation_value() {
return Err(TweenError::InvalidValue);
}
Ok(Self {
start: initial,
current: initial,
target: initial,
elapsed: Duration::ZERO,
duration: Duration::ZERO,
easing: Easing::Linear,
active: false,
})
}
pub fn to(mut self, target: T, duration: Duration, easing: Easing) -> Result<Self, TweenError> {
self.set_target(target, duration, easing)?;
Ok(self)
}
pub fn value(&self) -> T {
self.current
}
pub fn target(&self) -> T {
self.target
}
pub fn is_active(&self) -> bool {
self.active
}
pub fn set_target(
&mut self,
target: T,
duration: Duration,
easing: Easing,
) -> Result<(), TweenError> {
if !target.is_valid_interpolation_value() {
return Err(TweenError::InvalidValue);
}
self.start = self.current;
self.target = target;
self.elapsed = Duration::ZERO;
self.duration = duration;
self.easing = easing;
self.active = duration > Duration::ZERO;
if !self.active {
self.current = target;
}
Ok(())
}
pub fn snap(&mut self, value: T) -> Result<(), TweenError> {
if !value.is_valid_interpolation_value() {
return Err(TweenError::InvalidValue);
}
self.start = value;
self.current = value;
self.target = value;
self.elapsed = Duration::ZERO;
self.duration = Duration::ZERO;
self.active = false;
Ok(())
}
pub fn update(&mut self, dt: Duration) -> Result<T, TweenError> {
if !self.active {
return Ok(self.current);
}
let elapsed = self.elapsed.saturating_add(dt);
let amount = if elapsed >= self.duration {
1.0
} else {
(elapsed.as_secs_f64() / self.duration.as_secs_f64()) as f32
};
let current = self
.start
.interpolate(self.target, self.easing.sample(amount));
if !current.is_valid_interpolation_value() {
return Err(TweenError::InvalidInterpolatedValue);
}
self.elapsed = elapsed;
self.current = current;
if amount >= 1.0 {
self.current = self.target;
self.active = false;
}
Ok(self.current)
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use crate::{Easing, Interpolate, Tween, TweenError};
#[test]
fn tween_reaches_target() {
let mut tween = Tween::new(0.0)
.unwrap()
.to(10.0, Duration::from_millis(100), Easing::Linear)
.unwrap();
assert_eq!(tween.update(Duration::from_millis(50)), Ok(5.0));
assert_eq!(tween.update(Duration::from_millis(50)), Ok(10.0));
assert!(!tween.is_active());
}
#[test]
fn maximum_duration_completes_with_maximum_update() {
let mut tween = Tween::new(2.0)
.unwrap()
.to(9.0, Duration::MAX, Easing::Linear)
.unwrap();
assert_eq!(tween.update(Duration::MAX), Ok(9.0));
assert!(!tween.is_active());
}
#[test]
fn retarget_uses_current_value_as_new_start() {
let mut tween = Tween::new(0.0)
.unwrap()
.to(10.0, Duration::from_secs(2), Easing::Linear)
.unwrap();
assert_eq!(tween.update(Duration::from_secs(1)), Ok(5.0));
tween
.set_target(9.0, Duration::from_secs(1), Easing::Linear)
.unwrap();
assert_eq!(tween.update(Duration::from_millis(500)), Ok(7.0));
assert_eq!(tween.update(Duration::from_millis(500)), Ok(9.0));
}
#[test]
fn extreme_finite_values_do_not_overflow_during_interpolation() {
let mut scalar = Tween::new(f32::MAX)
.unwrap()
.to(-f32::MAX, Duration::from_secs(2), Easing::Linear)
.unwrap();
let midpoint = scalar.update(Duration::from_secs(1)).unwrap();
assert!(midpoint.is_finite());
assert_eq!(midpoint, 0.0);
let mut vector = Tween::new(crate::Vec2::splat(f32::MAX))
.unwrap()
.to(
crate::Vec2::splat(-f32::MAX),
Duration::from_secs(2),
Easing::Linear,
)
.unwrap();
assert!(vector.update(Duration::from_secs(1)).unwrap().is_finite());
}
#[derive(Clone, Copy)]
struct InvalidIntermediate(f32);
impl Interpolate for InvalidIntermediate {
fn interpolate(self, _end: Self, _amount: f32) -> Self {
Self(f32::NAN)
}
fn is_valid_interpolation_value(self) -> bool {
self.0.is_finite()
}
}
#[test]
fn tween_rejects_invalid_values_and_is_atomic_on_bad_interpolation() {
assert!(matches!(
Tween::new(f32::NAN),
Err(TweenError::InvalidValue)
));
let mut tween = Tween::new(InvalidIntermediate(1.0))
.unwrap()
.to(
InvalidIntermediate(2.0),
Duration::from_secs(2),
Easing::Linear,
)
.unwrap();
assert!(matches!(
tween.update(Duration::from_secs(1)),
Err(TweenError::InvalidInterpolatedValue)
));
assert_eq!(tween.value().0, 1.0);
assert_eq!(tween.elapsed, Duration::ZERO);
assert!(tween.is_active());
assert_eq!(
tween.set_target(
InvalidIntermediate(f32::NAN),
Duration::ZERO,
Easing::Linear,
),
Err(TweenError::InvalidValue)
);
}
}