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
48
49
50
51
use super::Raf;
use crate::errors::Error;
///Simple struct for time, deltatime, and elapsed time
#[derive(Copy, Clone, Debug)]
pub struct Timestamp {
    /// the current time
    pub time: f64,
    /// change in time since last tick
    pub delta: f64,
    /// total elapsed time since loop started
    pub elapsed: f64,
}

pub struct TimestampLoop {
    pub raf_loop: Raf,
}

impl TimestampLoop {
    /// similar to the top-level start_raf_loop() but instead of a callback with the current time
    /// it provides a Timestamp struct which contains commonly useful info
    pub fn start<F>(mut on_tick: F) -> Result<Self, Error>
    where
        F: (FnMut(Timestamp) -> ()) + 'static,
    {
        let mut last_time: Option<f64> = None;
        let mut first_time = 0f64;

        let raf_loop = Raf::new(move |time| {
            match last_time {
                Some(last_time) => {
                    on_tick(Timestamp {
                        time,
                        delta: time - last_time,
                        elapsed: time - first_time,
                    });
                }
                None => {
                    on_tick(Timestamp {
                        time,
                        delta: 0.0,
                        elapsed: 0.0,
                    });
                    first_time = time;
                }
            }
            last_time = Some(time);
        });

        Ok(Self { raf_loop })
    }
}