50 lines
975 B
Rust
50 lines
975 B
Rust
|
use std::time::Instant;
|
||
|
|
||
|
pub struct TimeStep {
|
||
|
last_frame_time: Instant,
|
||
|
// Milliseconds
|
||
|
accum: u128,
|
||
|
fps_num: u16,
|
||
|
fps_den: u16,
|
||
|
}
|
||
|
|
||
|
impl TimeStep {
|
||
|
pub fn new (fps_num: u16, fps_den: u16) -> Self {
|
||
|
Self {
|
||
|
last_frame_time: Instant::now (),
|
||
|
accum: 0,
|
||
|
fps_num,
|
||
|
fps_den,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Automatically gets monotonic system time from Instant
|
||
|
// If you need something fancy just rewrite this.
|
||
|
// Returns: How many logics steps to run. Typically 0 or 1.
|
||
|
|
||
|
pub fn step (&mut self) -> u16 {
|
||
|
let frame_time = Instant::now ();
|
||
|
|
||
|
let fps_num_128: u128 = self.fps_num.into ();
|
||
|
let fps_den_128: u128 = self.fps_den.into ();
|
||
|
|
||
|
self.accum += (frame_time - self.last_frame_time).as_millis () * fps_num_128;
|
||
|
|
||
|
let mut result = 0;
|
||
|
const MAX_FRAMES: u16 = 4;
|
||
|
|
||
|
for _ in 0..MAX_FRAMES {
|
||
|
if self.accum > fps_den_128 {
|
||
|
result += 1;
|
||
|
self.accum -= fps_den_128;
|
||
|
}
|
||
|
else {
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
self.last_frame_time = frame_time;
|
||
|
result
|
||
|
}
|
||
|
}
|