Skip to main content

game_toolkit_core/
time.rs

1use std::time::{Duration, Instant};
2
3pub struct Time {
4    pub elapsed: Duration,
5    pub delta: Duration,
6    pub frame: u64,
7    pub fps: f32,
8    start: Instant,
9    last_frame: Instant,
10    fps_accum: f32,
11}
12
13impl Time {
14    pub fn new() -> Self {
15        let now = Instant::now();
16        Self {
17            elapsed: Duration::ZERO,
18            delta: Duration::ZERO,
19            frame: 0,
20            fps: 0.0,
21            start: now,
22            last_frame: now,
23            fps_accum: 0.0,
24        }
25    }
26
27    pub fn tick(&mut self) {
28        let now = Instant::now();
29        self.delta = now - self.last_frame;
30        self.elapsed = now - self.start;
31        self.last_frame = now;
32        self.frame += 1;
33        let inst = 1.0 / self.delta.as_secs_f32().max(1e-6);
34        self.fps_accum = self.fps_accum * 0.95 + inst * 0.05;
35        self.fps = self.fps_accum;
36    }
37}
38
39impl Default for Time {
40    fn default() -> Self {
41        Self::new()
42    }
43}