1use std::{error::Error, fmt, time::Duration};
2
3use crate::{easing::Easing, math::Vec2};
4
5pub trait Interpolate: Copy {
11 fn interpolate(self, end: Self, amount: f32) -> Self;
13
14 fn is_valid_interpolation_value(self) -> bool;
19}
20
21impl Interpolate for f32 {
22 fn interpolate(self, end: Self, amount: f32) -> Self {
23 finite_f32_lerp(self, end, amount)
24 }
25
26 fn is_valid_interpolation_value(self) -> bool {
27 self.is_finite()
28 }
29}
30
31impl Interpolate for Vec2 {
32 fn interpolate(self, end: Self, amount: f32) -> Self {
33 Self::new(
34 finite_f32_lerp(self.x, end.x, amount),
35 finite_f32_lerp(self.y, end.y, amount),
36 )
37 }
38
39 fn is_valid_interpolation_value(self) -> bool {
40 self.is_finite()
41 }
42}
43
44fn finite_f32_lerp(start: f32, end: f32, amount: f32) -> f32 {
45 if !start.is_finite() || !end.is_finite() || !amount.is_finite() {
46 return start;
47 }
48 let value = f64::from(start) + (f64::from(end) - f64::from(start)) * f64::from(amount);
49 value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum TweenError {
55 InvalidValue,
57 InvalidInterpolatedValue,
59}
60
61impl fmt::Display for TweenError {
62 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63 match self {
64 Self::InvalidValue => write!(
65 formatter,
66 "tween values must satisfy their interpolation contract"
67 ),
68 Self::InvalidInterpolatedValue => {
69 write!(formatter, "tween interpolation produced an invalid value")
70 }
71 }
72 }
73}
74
75impl Error for TweenError {}
76
77#[derive(Debug, Clone)]
82pub struct Tween<T: Interpolate> {
83 start: T,
84 current: T,
85 target: T,
86 elapsed: Duration,
87 duration: Duration,
88 easing: Easing,
89 active: bool,
90}
91
92impl<T: Interpolate> Tween<T> {
93 pub fn new(initial: T) -> Result<Self, TweenError> {
95 if !initial.is_valid_interpolation_value() {
96 return Err(TweenError::InvalidValue);
97 }
98 Ok(Self {
99 start: initial,
100 current: initial,
101 target: initial,
102 elapsed: Duration::ZERO,
103 duration: Duration::ZERO,
104 easing: Easing::Linear,
105 active: false,
106 })
107 }
108
109 pub fn to(mut self, target: T, duration: Duration, easing: Easing) -> Result<Self, TweenError> {
111 self.set_target(target, duration, easing)?;
112 Ok(self)
113 }
114
115 pub fn value(&self) -> T {
117 self.current
118 }
119
120 pub fn target(&self) -> T {
122 self.target
123 }
124
125 pub fn is_active(&self) -> bool {
127 self.active
128 }
129
130 pub fn set_target(
134 &mut self,
135 target: T,
136 duration: Duration,
137 easing: Easing,
138 ) -> Result<(), TweenError> {
139 if !target.is_valid_interpolation_value() {
140 return Err(TweenError::InvalidValue);
141 }
142 self.start = self.current;
143 self.target = target;
144 self.elapsed = Duration::ZERO;
145 self.duration = duration;
146 self.easing = easing;
147 self.active = duration > Duration::ZERO;
148 if !self.active {
149 self.current = target;
150 }
151 Ok(())
152 }
153
154 pub fn snap(&mut self, value: T) -> Result<(), TweenError> {
156 if !value.is_valid_interpolation_value() {
157 return Err(TweenError::InvalidValue);
158 }
159 self.start = value;
160 self.current = value;
161 self.target = value;
162 self.elapsed = Duration::ZERO;
163 self.duration = Duration::ZERO;
164 self.active = false;
165 Ok(())
166 }
167
168 pub fn update(&mut self, dt: Duration) -> Result<T, TweenError> {
172 if !self.active {
173 return Ok(self.current);
174 }
175
176 let elapsed = self.elapsed.saturating_add(dt);
177 let amount = if elapsed >= self.duration {
178 1.0
179 } else {
180 (elapsed.as_secs_f64() / self.duration.as_secs_f64()) as f32
181 };
182 let current = self
183 .start
184 .interpolate(self.target, self.easing.sample(amount));
185 if !current.is_valid_interpolation_value() {
186 return Err(TweenError::InvalidInterpolatedValue);
187 }
188
189 self.elapsed = elapsed;
190 self.current = current;
191 if amount >= 1.0 {
192 self.current = self.target;
193 self.active = false;
194 }
195
196 Ok(self.current)
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use std::time::Duration;
203
204 use crate::{Easing, Interpolate, Tween, TweenError};
205
206 #[test]
207 fn tween_reaches_target() {
208 let mut tween = Tween::new(0.0)
209 .unwrap()
210 .to(10.0, Duration::from_millis(100), Easing::Linear)
211 .unwrap();
212
213 assert_eq!(tween.update(Duration::from_millis(50)), Ok(5.0));
214 assert_eq!(tween.update(Duration::from_millis(50)), Ok(10.0));
215 assert!(!tween.is_active());
216 }
217
218 #[test]
219 fn maximum_duration_completes_with_maximum_update() {
220 let mut tween = Tween::new(2.0)
221 .unwrap()
222 .to(9.0, Duration::MAX, Easing::Linear)
223 .unwrap();
224
225 assert_eq!(tween.update(Duration::MAX), Ok(9.0));
226 assert!(!tween.is_active());
227 }
228
229 #[test]
230 fn retarget_uses_current_value_as_new_start() {
231 let mut tween = Tween::new(0.0)
232 .unwrap()
233 .to(10.0, Duration::from_secs(2), Easing::Linear)
234 .unwrap();
235 assert_eq!(tween.update(Duration::from_secs(1)), Ok(5.0));
236
237 tween
238 .set_target(9.0, Duration::from_secs(1), Easing::Linear)
239 .unwrap();
240
241 assert_eq!(tween.update(Duration::from_millis(500)), Ok(7.0));
242 assert_eq!(tween.update(Duration::from_millis(500)), Ok(9.0));
243 }
244
245 #[test]
246 fn extreme_finite_values_do_not_overflow_during_interpolation() {
247 let mut scalar = Tween::new(f32::MAX)
248 .unwrap()
249 .to(-f32::MAX, Duration::from_secs(2), Easing::Linear)
250 .unwrap();
251 let midpoint = scalar.update(Duration::from_secs(1)).unwrap();
252 assert!(midpoint.is_finite());
253 assert_eq!(midpoint, 0.0);
254
255 let mut vector = Tween::new(crate::Vec2::splat(f32::MAX))
256 .unwrap()
257 .to(
258 crate::Vec2::splat(-f32::MAX),
259 Duration::from_secs(2),
260 Easing::Linear,
261 )
262 .unwrap();
263 assert!(vector.update(Duration::from_secs(1)).unwrap().is_finite());
264 }
265
266 #[derive(Clone, Copy)]
267 struct InvalidIntermediate(f32);
268
269 impl Interpolate for InvalidIntermediate {
270 fn interpolate(self, _end: Self, _amount: f32) -> Self {
271 Self(f32::NAN)
272 }
273
274 fn is_valid_interpolation_value(self) -> bool {
275 self.0.is_finite()
276 }
277 }
278
279 #[test]
280 fn tween_rejects_invalid_values_and_is_atomic_on_bad_interpolation() {
281 assert!(matches!(
282 Tween::new(f32::NAN),
283 Err(TweenError::InvalidValue)
284 ));
285
286 let mut tween = Tween::new(InvalidIntermediate(1.0))
287 .unwrap()
288 .to(
289 InvalidIntermediate(2.0),
290 Duration::from_secs(2),
291 Easing::Linear,
292 )
293 .unwrap();
294 assert!(matches!(
295 tween.update(Duration::from_secs(1)),
296 Err(TweenError::InvalidInterpolatedValue)
297 ));
298 assert_eq!(tween.value().0, 1.0);
299 assert_eq!(tween.elapsed, Duration::ZERO);
300 assert!(tween.is_active());
301 assert_eq!(
302 tween.set_target(
303 InvalidIntermediate(f32::NAN),
304 Duration::ZERO,
305 Easing::Linear,
306 ),
307 Err(TweenError::InvalidValue)
308 );
309 }
310}