diff options
-rw-r--r-- | engine/src/lib.rs | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/engine/src/lib.rs b/engine/src/lib.rs index ce953f8..bec1e30 100644 --- a/engine/src/lib.rs +++ b/engine/src/lib.rs @@ -1,6 +1,7 @@ #![deny(clippy::all, clippy::pedantic)] use std::collections::BTreeMap; +use std::time::{Duration, Instant}; use glfw::{Window, WindowBuilder}; @@ -29,6 +30,7 @@ pub struct Engine objects: BTreeMap<ObjectId, Object>, window: Window, camera: Camera, + delta_time: Duration, } impl Engine @@ -63,6 +65,7 @@ impl Engine window, objects: BTreeMap::new(), camera: Camera::new(), + delta_time: Duration::ZERO, }) } @@ -95,7 +98,11 @@ impl Engine /// Will return `Err` if updating the window fails. pub fn start(&mut self, mut func: impl FnMut(&mut Self)) -> Result<(), Error> { + let mut prev_frame_start: Option<Instant> = None; + while !self.window.should_close() { + self.update_delta_time(&mut prev_frame_start); + func(self); let window_size = self.window.size().map_err(Error::GetWindowSizeFailed)?; @@ -118,6 +125,25 @@ impl Engine { &mut self.camera } + + /// Returns the current delta time. Will be 0 if not called from the function + /// passed to [`start`]. + #[must_use] + pub fn delta_time(&self) -> &Duration + { + &self.delta_time + } + + fn update_delta_time(&mut self, prev_frame_start: &mut Option<Instant>) + { + let frame_start_time = Instant::now(); + + if let Some(last_frame_start) = prev_frame_start { + self.delta_time = frame_start_time.duration_since(*last_frame_start); + } + + *prev_frame_start = Some(frame_start_time); + } } /// Engine Error |