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