Skip to main content

euv_core/game/pacing/
impl.rs

1use super::*;
2
3/// Default high-refresh native-VSync-driven `FramePacingController`.
4impl Default for FramePacingController {
5    /// Creates a `FramePacingController` configured for the default display refresh rate (`120Hz`) with native VSync and bounded in-flight frames.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default frame pacing controller.
10    fn default() -> Self {
11        Self::for_display_hz(PACING_DEFAULT_DISPLAY_HZ)
12    }
13}
14
15/// Unified VSync pacing, double-gate elimination, clock rebasing, and in-flight tracking for `FramePacingController`.
16impl FramePacingController {
17    /// Constructs a native-VSync `FramePacingController` tracking `display_hz` uncapped with bounded in-flight frames.
18    ///
19    /// # Arguments
20    ///
21    /// - `f32` - Active hardware display refresh rate in Hertz.
22    ///
23    /// # Returns
24    ///
25    /// - `Self` - Uncapped display-synchronized frame pacing controller.
26    #[must_use]
27    pub fn for_display_hz(display_hz: f32) -> Self {
28        Self::new(display_hz, true, None, PACING_DEFAULT_MAX_IN_FLIGHT)
29    }
30
31    /// Constructs a `FramePacingController` with explicit display rate, VSync ownership, optional user FPS cap, and in-flight bound.
32    ///
33    /// # Arguments
34    ///
35    /// - `f32` - Active display refresh rate in Hertz.
36    /// - `bool` - Whether native platform VSync already throttles presentation.
37    /// - `Option<u32>` - Optional explicit user FPS cap.
38    /// - `u32` - Maximum concurrent in-flight frames (`1..=4`).
39    ///
40    /// # Returns
41    ///
42    /// - `Self` - Configured frame pacing controller.
43    #[must_use]
44    pub fn new(
45        display_hz: f32,
46        native_vsync_active: bool,
47        user_fps_cap: Option<u32>,
48        max_in_flight_frames: u32,
49    ) -> Self {
50        Self {
51            display_hz: display_hz.clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ),
52            native_vsync_active,
53            user_fps_cap: user_fps_cap.filter(|cap: &u32| *cap > 0),
54            max_in_flight_frames: max_in_flight_frames.clamp(1, 4),
55            in_flight_frames: 0,
56            last_vsync_ns: 0,
57            last_submitted_vsync_ns: 0,
58            last_present_ns: 0,
59            fixed_step_ns: PACING_DEFAULT_FIXED_STEP_NS,
60            oldest_pending_input_ns: 0,
61            pending_input_dirty: false,
62            pending_layout_dirty: false,
63            stats: FramePacingStats::default(),
64        }
65    }
66
67    /// Returns the optional explicit user FPS cap.
68    ///
69    /// # Arguments
70    ///
71    /// - `&Self` - Pacing controller reference.
72    ///
73    /// # Returns
74    ///
75    /// - `Option<u32>` - Active user FPS cap if set.
76    #[must_use]
77    pub const fn active_user_fps_cap(&self) -> Option<u32> {
78        let Self { user_fps_cap, .. } = *self;
79        user_fps_cap
80    }
81
82    /// Returns `true` when software sleep/deadline gating should be bypassed because native VSync already paces presentation at or below the target rate.
83    ///
84    /// # Arguments
85    ///
86    /// - `&Self` - Pacing controller reference.
87    ///
88    /// # Returns
89    ///
90    /// - `bool` - `true` when software waiting must be skipped to avoid double-gating.
91    #[must_use]
92    pub fn should_bypass_software_gate(&self) -> bool {
93        if !self.get_native_vsync_active() {
94            return false;
95        }
96        match self.active_user_fps_cap() {
97            None => true,
98            Some(cap) => (cap as f32) >= self.get_display_hz() - 0.5,
99        }
100    }
101
102    /// Returns the nominal display refresh period in nanoseconds.
103    ///
104    /// # Arguments
105    ///
106    /// - `&Self` - Pacing controller reference.
107    ///
108    /// # Returns
109    ///
110    /// - `u64` - Nominal VSync period in nanoseconds.
111    #[must_use]
112    pub fn display_period_ns(&self) -> u64 {
113        let hz: f64 = self
114            .get_display_hz()
115            .clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ) as f64;
116        (NS_PER_SEC_F64 / hz).round() as u64
117    }
118
119    /// Updates the display refresh rate mode and rebases the monotonic clock to avoid synthetic dt spikes.
120    ///
121    /// # Arguments
122    ///
123    /// - `&Self` - Mutable pacing controller.
124    /// - `f32` - New active hardware refresh rate in Hertz.
125    /// - `u64` - Current monotonic timestamp in nanoseconds.
126    pub fn set_display_mode(&mut self, display_hz: f32, timestamp_ns: u64) {
127        self.set_display_hz(display_hz.clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ));
128        self.rebase_clock(timestamp_ns);
129    }
130
131    /// Handles a dynamic OS display refresh-rate switch (e.g. ProMotion or multi-monitor drag) by clamping `new_hz` and resetting the monotonic timebase cleanly.
132    ///
133    /// # Arguments
134    ///
135    /// - `&Self` - Mutable pacing controller.
136    /// - `f32` - Newly reported hardware display refresh rate in Hertz.
137    pub fn on_display_mode_changed(&mut self, new_hz: f32) {
138        self.set_display_hz(new_hz.clamp(PACING_MIN_DISPLAY_HZ, PACING_MAX_DISPLAY_HZ));
139        self.rebase_clock(0);
140    }
141
142    /// Handles application foreground resume by clearing stale VSync timestamps, resetting in-flight backpressure, and preventing post-suspend missed-VSync or dt spikes.
143    ///
144    /// # Arguments
145    ///
146    /// - `&Self` - Mutable pacing controller.
147    pub fn on_resume(&mut self) {
148        self.set_in_flight_frames(0);
149        self.set_oldest_pending_input_ns(0);
150        self.set_pending_input_dirty(false);
151        self.set_pending_layout_dirty(true);
152        self.rebase_clock(0);
153    }
154
155    /// Rebases the monotonic VSync reference timestamp (e.g. after foreground resume or refresh-rate switch).
156    ///
157    /// # Arguments
158    ///
159    /// - `&Self` - Mutable pacing controller.
160    /// - `u64` - Current monotonic timestamp in nanoseconds.
161    pub fn rebase_clock(&mut self, timestamp_ns: u64) {
162        self.set_last_vsync_ns(timestamp_ns);
163        self.set_last_submitted_vsync_ns(0);
164        self.set_last_present_ns(0);
165        let mut stats: FramePacingStats = self.get_stats();
166        stats.set_timebase_rebases(stats.get_timebase_rebases().saturating_add(1));
167        self.set_stats(stats);
168    }
169
170    /// Notifies the controller that one submitted frame finished presenting, freeing an in-flight slot.
171    ///
172    /// # Arguments
173    ///
174    /// - `&Self` - Mutable pacing controller.
175    pub fn notify_present_completed(&mut self) {
176        let next: u32 = self.get_in_flight_frames().saturating_sub(1);
177        self.set_in_flight_frames(next);
178    }
179
180    /// Evaluates a scheduling `trigger` at monotonic `timestamp_ns` and returns a single authoritative `PacingDecision`.
181    ///
182    /// # Arguments
183    ///
184    /// - `&Self` - Mutable pacing controller.
185    /// - `FramePacingTrigger` - Incoming scheduling event kind.
186    /// - `u64` - Monotonic clock timestamp in nanoseconds.
187    ///
188    /// # Returns
189    ///
190    /// - `PacingDecision` - Whether to step simulation, render, wait in flight, or defer to VSync.
191    pub fn evaluate(&mut self, trigger: FramePacingTrigger, timestamp_ns: u64) -> PacingDecision {
192        match trigger {
193            FramePacingTrigger::InputEvent => {
194                self.set_pending_input_dirty(true);
195                if self.get_oldest_pending_input_ns() == 0 {
196                    self.set_oldest_pending_input_ns(timestamp_ns);
197                }
198                let mut stats: FramePacingStats = self.get_stats();
199                stats.set_deferred_non_vsync_events(
200                    stats.get_deferred_non_vsync_events().saturating_add(1),
201                );
202                self.set_stats(stats);
203                PacingDecision::new(
204                    PacingAction::DeferToNextVsync,
205                    0.0,
206                    0,
207                    timestamp_ns,
208                    0.0,
209                    false,
210                    false,
211                )
212            }
213            FramePacingTrigger::SafeAreaChanged | FramePacingTrigger::FullscreenChanged => {
214                self.set_pending_layout_dirty(true);
215                let mut stats: FramePacingStats = self.get_stats();
216                stats.set_deferred_non_vsync_events(
217                    stats.get_deferred_non_vsync_events().saturating_add(1),
218                );
219                self.set_stats(stats);
220                PacingDecision::new(
221                    PacingAction::DeferToNextVsync,
222                    0.0,
223                    0,
224                    timestamp_ns,
225                    0.0,
226                    false,
227                    false,
228                )
229            }
230            FramePacingTrigger::TimebaseReset => {
231                self.rebase_clock(timestamp_ns);
232                PacingDecision::new(
233                    PacingAction::DeferToNextVsync,
234                    0.0,
235                    0,
236                    timestamp_ns,
237                    0.0,
238                    false,
239                    false,
240                )
241            }
242            FramePacingTrigger::LifecycleFirstFrame => {
243                self.set_pending_layout_dirty(false);
244                PacingDecision::new(
245                    PacingAction::RenderWithoutSimAdvance,
246                    0.0,
247                    0,
248                    timestamp_ns,
249                    0.0,
250                    true,
251                    false,
252                )
253            }
254            FramePacingTrigger::Vsync => self.evaluate_vsync(timestamp_ns),
255        }
256    }
257
258    /// Evaluates an authoritative VSync opportunity at monotonic `timestamp_ns`.
259    ///
260    /// # Arguments
261    ///
262    /// - `&Self` - Mutable pacing controller.
263    /// - `u64` - Monotonic VSync timestamp in nanoseconds.
264    ///
265    /// # Returns
266    ///
267    /// - `PacingDecision` - Pacing verdict for this VSync interval.
268    fn evaluate_vsync(&mut self, timestamp_ns: u64) -> PacingDecision {
269        let mut stats: FramePacingStats = self.get_stats();
270        stats.set_vsync_signals(stats.get_vsync_signals().saturating_add(1));
271        let period_ns: u64 = self.display_period_ns().max(1);
272        let prev_vsync_ns: u64 = self.get_last_vsync_ns();
273        let raw_vsync_dt_ns: u64 = if prev_vsync_ns == 0 || timestamp_ns <= prev_vsync_ns {
274            period_ns
275        } else {
276            timestamp_ns - prev_vsync_ns
277        };
278        if prev_vsync_ns != 0 && raw_vsync_dt_ns > (period_ns.saturating_mul(3) / 2) {
279            let missed: u64 = (raw_vsync_dt_ns / period_ns).saturating_sub(1);
280            stats.set_missed_vsync_intervals(
281                stats.get_missed_vsync_intervals().saturating_add(missed),
282            );
283        }
284        self.set_last_vsync_ns(timestamp_ns);
285        if self.get_in_flight_frames() >= self.get_max_in_flight_frames() {
286            stats.set_in_flight_waits(stats.get_in_flight_waits().saturating_add(1));
287            self.set_stats(stats);
288            return PacingDecision::new(
289                PacingAction::WaitInFlight,
290                0.0,
291                0,
292                timestamp_ns,
293                0.0,
294                false,
295                false,
296            );
297        }
298        let prev_submitted_ns: u64 = self.get_last_submitted_vsync_ns();
299        if !self.should_bypass_software_gate()
300            && let Some(cap_hz) = self.active_user_fps_cap()
301            && prev_submitted_ns != 0
302        {
303            let cap_period_ns: u64 = (NS_PER_SEC_F64 / (cap_hz as f64)).round() as u64;
304            let elapsed_present: u64 = timestamp_ns.saturating_sub(prev_submitted_ns);
305            if elapsed_present.saturating_add(period_ns / 4) < cap_period_ns {
306                stats.set_user_cap_skips(stats.get_user_cap_skips().saturating_add(1));
307                self.set_stats(stats);
308                return PacingDecision::new(
309                    PacingAction::SkipUserCap,
310                    0.0,
311                    0,
312                    timestamp_ns,
313                    0.0,
314                    false,
315                    false,
316                );
317            }
318        }
319        let raw_sim_dt_ns: u64 = if prev_submitted_ns != 0 && timestamp_ns > prev_submitted_ns {
320            timestamp_ns - prev_submitted_ns
321        } else {
322            raw_vsync_dt_ns
323        };
324        let fixed_ns: u64 = self.get_fixed_step_ns().max(PACING_MIN_FIXED_STEP_NS);
325        let max_sim_dt_ns: u64 = fixed_ns
326            .saturating_mul(PACING_MAX_SIM_DT_MULT)
327            .min(PACING_MAX_FRAME_DT_NS);
328        let sim_dt_ns: u64 = raw_sim_dt_ns.min(max_sim_dt_ns);
329        let sim_dt_secs: f32 = ((sim_dt_ns as f64) / NS_PER_SEC_F64)
330            .clamp(0.0, PACING_MAX_FRAME_DT_SECS as f64) as f32;
331        let input_age_ms: f32 = if self.get_oldest_pending_input_ns() != 0
332            && timestamp_ns >= self.get_oldest_pending_input_ns()
333        {
334            ((timestamp_ns - self.get_oldest_pending_input_ns()) as f64 / 1_000_000.0) as f32
335        } else {
336            0.0
337        };
338        self.set_last_submitted_vsync_ns(timestamp_ns);
339        self.set_last_present_ns(timestamp_ns);
340        self.set_oldest_pending_input_ns(0);
341        self.set_pending_input_dirty(false);
342        self.set_pending_layout_dirty(false);
343        self.set_in_flight_frames(self.get_in_flight_frames().saturating_add(1));
344        stats.set_frames_submitted(stats.get_frames_submitted().saturating_add(1));
345        self.set_stats(stats);
346        PacingDecision::new(
347            PacingAction::StepAndRender,
348            sim_dt_secs,
349            sim_dt_ns,
350            timestamp_ns,
351            input_age_ms,
352            true,
353            true,
354        )
355    }
356}