From 3d0de3f951ec2da7a2d41c6958d0d3583a7832a0 Mon Sep 17 00:00:00 2001 From: HampusM Date: Tue, 24 Oct 2023 21:44:56 +0200 Subject: feat(engine): add delta time --- engine/src/lib.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) 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, 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 = 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) + { + 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 -- cgit v1.2.3-18-g5258