cubik/
interpolation.rs

1pub trait Interpolate {
2	fn linear_interpolate(a: &Self, b: &Self, progress: f32) -> Self;
3}
4
5impl Interpolate for f32 {
6	fn linear_interpolate(a: &Self, b: &Self, progress: f32) -> Self {
7		*a + ((*b - *a) * progress)
8	}
9}
10
11impl Interpolate for (f32, f32) {
12	fn linear_interpolate(a: &Self, b: &Self, progress: f32) -> Self {
13		(
14			a.0 + ((b.0 - a.0) * progress),
15			a.1 + ((b.1 - a.1) * progress)
16		)
17	}
18}
19
20impl Interpolate for [f32; 3] {
21	fn linear_interpolate(a: &Self, b: &Self, progress: f32) -> Self {
22		[
23			a[0] + ((b[0] - a[0]) * progress),
24			a[1] + ((b[1] - a[1]) * progress),
25			a[2] + ((b[2] - a[2]) * progress),
26		]
27	}
28}
29
30pub struct InterpolationHelper<T: Interpolate + Copy> {
31	pub updates: Vec<T>,
32	last_update_duration: f32,
33	time_count: f32
34}
35
36impl<T: Interpolate + Copy> InterpolationHelper<T> {
37	pub fn new() -> Self {
38		Self {
39			updates: Vec::new(),
40			time_count: 0.,
41			last_update_duration: 0.
42		}
43	}
44
45	pub fn post_update(&mut self, update: T) {
46		self.updates.push(update);
47		if self.updates.len() > 2 {
48			self.updates.remove(0);
49		}
50		self.last_update_duration = self.time_count.max(0.1);
51		self.time_count = 0.
52	}
53
54	pub fn value(&mut self, time_delta: f32) -> Option<T> {
55		self.time_count += time_delta;
56		let len = self.updates.len();
57		match len {
58			0 => None,
59			1 => Some(*self.updates.first().unwrap()),
60			_ => {
61				let first = self.updates.first().unwrap();
62				let last = self.updates.last().unwrap();
63				Some(T::linear_interpolate(&first, &last, self.time_count / self.last_update_duration))
64			}
65		}
66	}
67}