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