Skip to main content

euv_core/game/clock/
impl.rs

1use super::*;
2
3/// Default 60Hz fixed-timestep `FrameClock` with 8-substep safety cap.
4impl Default for FrameClock {
5    /// Creates a `FrameClock` configured for 60Hz fixed simulation steps.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default 60Hz game clock.
10    fn default() -> Self {
11        Self::new(1.0 / 60.0, 8)
12    }
13}
14
15/// Simulation step scheduling and frame telemetry updates for `FrameClock`.
16impl FrameClock {
17    /// Advances the clock by `raw_dt_secs` and returns how many fixed simulation steps to execute.
18    ///
19    /// # Arguments
20    ///
21    /// - `&Self` - Mutable frame clock.
22    /// - `f32` - Unclamped elapsed seconds since the previous frame.
23    ///
24    /// # Returns
25    ///
26    /// - `u32` - Number of fixed-timestep updates to run this frame.
27    pub fn tick(&mut self, raw_dt_secs: f32) -> u32 {
28        let safe_fixed: f32 = self.get_fixed_dt().max(0.000_1);
29        let dt: f32 = if raw_dt_secs.is_finite() {
30            raw_dt_secs.clamp(0.0, 0.25)
31        } else {
32            0.0
33        };
34        self.set_delta_secs(dt);
35        self.set_elapsed_secs(self.get_elapsed_secs() + (dt as f64));
36        self.set_frame_count(self.get_frame_count().saturating_add(1));
37        if dt > 0.0 {
38            let inst_fps: f32 = 1.0 / dt;
39            let prev_fps: f32 = self.get_fps();
40            let smoothed: f32 = if prev_fps <= 0.0 {
41                inst_fps
42            } else {
43                prev_fps * 0.85 + inst_fps * 0.15
44            };
45            self.set_fps(smoothed);
46        }
47        let mut acc: f32 = self.get_accumulator() + dt;
48        let max_steps: u32 = self.get_max_substeps().max(1);
49        let mut steps: u32 = 0;
50        while acc >= safe_fixed && steps < max_steps {
51            acc -= safe_fixed;
52            steps += 1;
53        }
54        if steps == max_steps && acc >= safe_fixed {
55            acc = 0.0;
56        }
57        self.set_accumulator(acc);
58        self.set_alpha((acc / safe_fixed).clamp(0.0, 1.0));
59        self.set_fixed_step_count(self.get_fixed_step_count().saturating_add(steps as u64));
60        steps
61    }
62}