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