60 lines
1.4 KiB
Rust
60 lines
1.4 KiB
Rust
use std::thread::sleep;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use self::input::InputState;
|
|
use self::screen::Screen;
|
|
|
|
type UpdateFn = fn(&mut Screen, &InputState) -> bool;
|
|
|
|
mod input;
|
|
mod screen;
|
|
|
|
pub struct Trekstor {
|
|
pub screen: Screen,
|
|
pub input: InputState,
|
|
accumulator: Duration,
|
|
last_time: Instant,
|
|
current_time: Instant,
|
|
update_timestep: Duration,
|
|
}
|
|
|
|
impl Trekstor {
|
|
pub fn new(update_fps: i32) -> Self {
|
|
let screen = Screen::new();
|
|
let input = InputState::new(&screen);
|
|
|
|
Self {
|
|
screen,
|
|
input,
|
|
accumulator: Duration::default(),
|
|
current_time: Instant::now(),
|
|
last_time: Instant::now(),
|
|
update_timestep: Duration::from_nanos(
|
|
(1_000_000_000f64 / update_fps as f64).round() as u64
|
|
),
|
|
}
|
|
}
|
|
|
|
pub fn update(&mut self, update: UpdateFn) {
|
|
loop {
|
|
self.input.handle_event();
|
|
self.current_time = Instant::now();
|
|
let dt = self.current_time - self.last_time;
|
|
self.last_time = self.current_time;
|
|
|
|
if dt < self.update_timestep {
|
|
sleep(self.update_timestep - dt);
|
|
}
|
|
|
|
// println!("FPS: {}", 1.0 / dt.as_secs_f64());
|
|
|
|
if !update(&mut self.screen, &self.input) {
|
|
return;
|
|
}
|
|
|
|
self.screen.flush();
|
|
self.input.finish();
|
|
}
|
|
}
|
|
}
|