awsm_web/tick/
timestamp.rs

1use super::Raf;
2use crate::errors::Error;
3///Simple struct for time, deltatime, and elapsed time
4#[derive(Copy, Clone, Debug)]
5pub struct Timestamp {
6    /// the current time
7    pub time: f64,
8    /// change in time since last tick
9    pub delta: f64,
10    /// total elapsed time since loop started
11    pub elapsed: f64,
12}
13
14pub struct TimestampLoop {
15    pub raf_loop: Raf,
16}
17
18impl TimestampLoop {
19    /// similar to the top-level start_raf_loop() but instead of a callback with the current time
20    /// it provides a Timestamp struct which contains commonly useful info
21    pub fn start<F>(mut on_tick: F) -> Result<Self, Error>
22    where
23        F: (FnMut(Timestamp) -> ()) + 'static,
24    {
25        let mut last_time: Option<f64> = None;
26        let mut first_time = 0f64;
27
28        let raf_loop = Raf::new(move |time| {
29            match last_time {
30                Some(last_time) => {
31                    on_tick(Timestamp {
32                        time,
33                        delta: time - last_time,
34                        elapsed: time - first_time,
35                    });
36                }
37                None => {
38                    on_tick(Timestamp {
39                        time,
40                        delta: 0.0,
41                        elapsed: 0.0,
42                    });
43                    first_time = time;
44                }
45            }
46            last_time = Some(time);
47        });
48
49        Ok(Self { raf_loop })
50    }
51}