Skip to main content

euv_core/game/clock/
impl.rs

1use super::*;
2
3/// Default 60Hz integer-nanosecond fixed-timestep `FrameClock` with 8-substep safety cap.
4impl Default for FrameClock {
5    /// Creates a `FrameClock` configured for 60Hz (`16_666_667 ns`) fixed simulation steps.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default 60Hz game clock.
10    fn default() -> Self {
11        Self::from_fixed_step_ns(CLOCK_DEFAULT_FIXED_STEP_NS, CLOCK_DEFAULT_MAX_SUBSTEPS)
12    }
13}
14
15/// Nanosecond fixed-step accumulation, VSync hysteresis snapping, and dt-invariant FPS telemetry for `FrameClock`.
16impl FrameClock {
17    /// Constructs a `FrameClock` from a fixed timestep in seconds and substep cap.
18    ///
19    /// # Arguments
20    ///
21    /// - `f32` - Fixed simulation timestep in seconds (e.g. `1.0 / 60.0`).
22    /// - `u32` - Upper cap on fixed substeps executed per rendered frame.
23    ///
24    /// # Returns
25    ///
26    /// - `Self` - Configured integer-nanosecond frame clock.
27    #[must_use]
28    pub fn new(fixed_dt: f32, max_substeps: u32) -> Self {
29        let safe_dt: f32 = if fixed_dt.is_finite() {
30            fixed_dt.max(0.000_1)
31        } else {
32            1.0 / 60.0
33        };
34        let step_ns: u64 = ((safe_dt as f64) * CLOCK_NS_PER_SEC_F64)
35            .round()
36            .max(CLOCK_MIN_FIXED_STEP_NS as f64) as u64;
37        Self::from_fixed_step_ns(step_ns, max_substeps)
38    }
39
40    /// Constructs a `FrameClock` directly from an exact integer-nanosecond simulation period.
41    ///
42    /// # Arguments
43    ///
44    /// - `u64` - Fixed simulation step duration in nanoseconds (`16_666_667` for 60Hz, `8_333_333` for 120Hz).
45    /// - `u32` - Upper cap on fixed substeps executed per rendered frame.
46    ///
47    /// # Returns
48    ///
49    /// - `Self` - Configured integer-nanosecond frame clock.
50    #[must_use]
51    pub fn from_fixed_step_ns(fixed_step_ns: u64, max_substeps: u32) -> Self {
52        let safe_ns: u64 = fixed_step_ns.max(CLOCK_MIN_FIXED_STEP_NS);
53        Self {
54            fixed_dt: ((safe_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32,
55            fixed_step_ns: safe_ns,
56            max_substeps: max_substeps.max(1),
57            accumulator_ns: 0,
58            accumulator: 0.0,
59            delta_ns: 0,
60            delta_secs: 0.0,
61            elapsed_ns: 0,
62            elapsed_secs: 0.0,
63            alpha: 0.0,
64            fps: 0.0,
65            frame_count: 0,
66            fixed_step_count: 0,
67        }
68    }
69
70    /// Constructs a `FrameClock` for an integer simulation frequency in Hertz (e.g. `60` or `120`).
71    ///
72    /// # Arguments
73    ///
74    /// - `u32` - Simulation tick frequency in Hertz (`1..=1000`).
75    /// - `u32` - Upper cap on fixed substeps executed per rendered frame.
76    ///
77    /// # Returns
78    ///
79    /// - `Self` - Configured integer-nanosecond frame clock.
80    #[must_use]
81    pub fn for_sim_hz(sim_hz: u32, max_substeps: u32) -> Self {
82        let clamped_hz: u64 = (sim_hz.clamp(1, 1000)) as u64;
83        let step_ns: u64 = (CLOCK_NS_PER_SEC + clamped_hz / 2) / clamped_hz;
84        Self::from_fixed_step_ns(step_ns, max_substeps)
85    }
86
87    /// Returns the ±0.5% VSync-boundary hysteresis snap window in nanoseconds (`±83_333 ns` at 60Hz).
88    ///
89    /// # Arguments
90    ///
91    /// - `&Self` - Frame clock reference.
92    ///
93    /// # Returns
94    ///
95    /// - `u64` - Hysteresis tolerance window in nanoseconds.
96    #[must_use]
97    pub fn hysteresis_window_ns(&self) -> u64 {
98        let safe_fixed_ns: u64 = self.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
99        (safe_fixed_ns / CLOCK_HYSTERESIS_DIVISOR).max(1)
100    }
101
102    /// Advances the clock by `raw_dt_ns` nanoseconds using ±0.5% VSync-boundary hysteresis snapping and dt-invariant FPS smoothing.
103    ///
104    /// # Arguments
105    ///
106    /// - `&Self` - Mutable frame clock.
107    /// - `u64` - Unclamped elapsed nanoseconds since the previous frame.
108    ///
109    /// # Returns
110    ///
111    /// - `u32` - Number of fixed-timestep simulation updates to execute this frame.
112    pub fn tick_ns(&mut self, raw_dt_ns: u64) -> u32 {
113        let mut safe_fixed_ns: u64 = self.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
114        let expected_dt_f32: f32 = ((safe_fixed_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32;
115        if (self.get_fixed_dt() - expected_dt_f32).abs() > 1e-5 && self.get_fixed_dt().is_finite() {
116            let safe_dt: f32 = self.get_fixed_dt().max(0.000_1);
117            safe_fixed_ns = ((safe_dt as f64) * CLOCK_NS_PER_SEC_F64)
118                .round()
119                .max(CLOCK_MIN_FIXED_STEP_NS as f64) as u64;
120            self.set_fixed_step_ns(safe_fixed_ns);
121        }
122        let dt_ns: u64 = raw_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
123        let dt_secs: f32 = ((dt_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32;
124        self.set_delta_ns(dt_ns);
125        self.set_delta_secs(dt_secs);
126        let next_elapsed_ns: u64 = self.get_elapsed_ns().saturating_add(dt_ns);
127        self.set_elapsed_ns(next_elapsed_ns);
128        self.set_elapsed_secs((next_elapsed_ns as f64) / CLOCK_NS_PER_SEC_F64);
129        self.set_frame_count(self.get_frame_count().saturating_add(1));
130        if dt_ns > 0 {
131            let inst_fps: f32 = (CLOCK_NS_PER_SEC_F64 / (dt_ns as f64)) as f32;
132            let prev_fps: f32 = self.get_fps();
133            let smoothed: f32 = if prev_fps <= 0.0 {
134                inst_fps
135            } else {
136                let ema_alpha: f32 =
137                    (1.0 - (-dt_secs / CLOCK_FPS_EMA_TAU_SECS).exp()).clamp(0.0, 1.0);
138                prev_fps + (inst_fps - prev_fps) * ema_alpha
139            };
140            self.set_fps(smoothed);
141        }
142        let snap_window_ns: u64 = (safe_fixed_ns / CLOCK_HYSTERESIS_DIVISOR).max(1);
143        let mut acc_ns: u64 = self.get_accumulator_ns().saturating_add(dt_ns);
144        let rem_before: u64 = acc_ns % safe_fixed_ns;
145        if rem_before > 0 && safe_fixed_ns - rem_before <= snap_window_ns {
146            acc_ns = acc_ns.saturating_add(safe_fixed_ns - rem_before);
147        }
148        let max_steps: u32 = self.get_max_substeps().max(1);
149        let mut steps: u32 = 0;
150        while acc_ns >= safe_fixed_ns && steps < max_steps {
151            acc_ns -= safe_fixed_ns;
152            steps += 1;
153        }
154        if (steps == max_steps && acc_ns >= safe_fixed_ns)
155            || (steps > 0 && acc_ns <= snap_window_ns)
156        {
157            acc_ns = 0;
158        }
159        self.set_accumulator_ns(acc_ns);
160        self.set_accumulator(((acc_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32);
161        self.set_alpha(((acc_ns as f64) / (safe_fixed_ns as f64)).clamp(0.0, 1.0) as f32);
162        self.set_fixed_step_count(self.get_fixed_step_count().saturating_add(steps as u64));
163        steps
164    }
165
166    /// Advances the clock by `raw_dt_secs` seconds (converted to integer nanoseconds) and returns how many fixed simulation steps to execute.
167    ///
168    /// # Arguments
169    ///
170    /// - `&Self` - Mutable frame clock.
171    /// - `f32` - Unclamped elapsed seconds since the previous frame.
172    ///
173    /// # Returns
174    ///
175    /// - `u32` - Number of fixed-timestep updates to run this frame.
176    pub fn tick(&mut self, raw_dt_secs: f32) -> u32 {
177        let dt_ns: u64 = if raw_dt_secs.is_finite() && raw_dt_secs > 0.0 {
178            ((raw_dt_secs.clamp(0.0, 0.25) as f64) * CLOCK_NS_PER_SEC_F64).round() as u64
179        } else {
180            0
181        };
182        self.tick_ns(dt_ns)
183    }
184}