1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use chrono::Utc;
use crate::IntoF32;
const SEC: f32 = 1_000.0;
#[derive(Default, Debug)]
pub struct Animation {
start: f32,
span: f32,
duration: f32,
stamp: i64,
}
impl Animation {
pub fn new(start: impl IntoF32, end: impl IntoF32, duration: impl IntoF32) -> Self {
let start = start.into_f32() * SEC;
let end = end.into_f32() * SEC;
Self {
start,
span: end - start,
duration: duration.into_f32() * SEC,
stamp: Utc::now().timestamp_millis(),
}
}
pub fn finished(&self) -> bool {
Utc::now().timestamp_millis() >= self.stamp + self.duration as i64
}
pub fn value(&self) -> f32 {
debug_assert!(self.span != 0.0);
let now = Utc::now().timestamp_millis();
let delta = (now - self.stamp) as f32;
let passed = (delta / self.duration) as u64;
let even = passed % 2 == 0;
let passed = passed as f32;
let delta = delta - (passed * self.duration);
let ratio = delta / (self.duration);
let span = if even {
self.span * ratio
} else {
self.span - self.span * ratio
};
(self.start + span) / SEC
}
}