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
use super::*;
/// Default 60Hz integer-nanosecond fixed-timestep `FrameClock` with 8-substep safety cap.
impl Default for FrameClock {
/// Creates a `FrameClock` configured for 60Hz (`16_666_667 ns`) fixed simulation steps.
///
/// # Returns
///
/// - `Self` - Default 60Hz game clock.
fn default() -> Self {
Self::from_fixed_step_ns(CLOCK_DEFAULT_FIXED_STEP_NS, CLOCK_DEFAULT_MAX_SUBSTEPS)
}
}
/// Nanosecond fixed-step accumulation, VSync hysteresis snapping, and dt-invariant FPS telemetry for `FrameClock`.
impl FrameClock {
/// Constructs a `FrameClock` from a fixed timestep in seconds and substep cap.
///
/// # Arguments
///
/// - `f32` - Fixed simulation timestep in seconds (e.g. `1.0 / 60.0`).
/// - `u32` - Upper cap on fixed substeps executed per rendered frame.
///
/// # Returns
///
/// - `Self` - Configured integer-nanosecond frame clock.
#[must_use]
pub fn new(fixed_dt: f32, max_substeps: u32) -> Self {
let safe_dt: f32 = if fixed_dt.is_finite() {
fixed_dt.max(0.000_1)
} else {
1.0 / 60.0
};
let step_ns: u64 = ((safe_dt as f64) * CLOCK_NS_PER_SEC_F64)
.round()
.max(CLOCK_MIN_FIXED_STEP_NS as f64) as u64;
Self::from_fixed_step_ns(step_ns, max_substeps)
}
/// Constructs a `FrameClock` directly from an exact integer-nanosecond simulation period.
///
/// # Arguments
///
/// - `u64` - Fixed simulation step duration in nanoseconds (`16_666_667` for 60Hz, `8_333_333` for 120Hz).
/// - `u32` - Upper cap on fixed substeps executed per rendered frame.
///
/// # Returns
///
/// - `Self` - Configured integer-nanosecond frame clock.
#[must_use]
pub fn from_fixed_step_ns(fixed_step_ns: u64, max_substeps: u32) -> Self {
let safe_ns: u64 = fixed_step_ns.max(CLOCK_MIN_FIXED_STEP_NS);
Self {
fixed_dt: ((safe_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32,
fixed_step_ns: safe_ns,
max_substeps: max_substeps.max(1),
accumulator_ns: 0,
accumulator: 0.0,
delta_ns: 0,
delta_secs: 0.0,
elapsed_ns: 0,
elapsed_secs: 0.0,
alpha: 0.0,
fps: 0.0,
frame_count: 0,
fixed_step_count: 0,
}
}
/// Constructs a `FrameClock` for an integer simulation frequency in Hertz (e.g. `60` or `120`).
///
/// # Arguments
///
/// - `u32` - Simulation tick frequency in Hertz (`1..=1000`).
/// - `u32` - Upper cap on fixed substeps executed per rendered frame.
///
/// # Returns
///
/// - `Self` - Configured integer-nanosecond frame clock.
#[must_use]
pub fn for_sim_hz(sim_hz: u32, max_substeps: u32) -> Self {
let clamped_hz: u64 = (sim_hz.clamp(1, 1000)) as u64;
let step_ns: u64 = (CLOCK_NS_PER_SEC + clamped_hz / 2) / clamped_hz;
Self::from_fixed_step_ns(step_ns, max_substeps)
}
/// Returns the ±0.5% VSync-boundary hysteresis snap window in nanoseconds (`±83_333 ns` at 60Hz).
///
/// # Arguments
///
/// - `&Self` - Frame clock reference.
///
/// # Returns
///
/// - `u64` - Hysteresis tolerance window in nanoseconds.
#[must_use]
pub fn hysteresis_window_ns(&self) -> u64 {
let safe_fixed_ns: u64 = self.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
(safe_fixed_ns / CLOCK_HYSTERESIS_DIVISOR).max(1)
}
/// Advances the clock by `raw_dt_ns` nanoseconds using ±0.5% VSync-boundary hysteresis snapping and dt-invariant FPS smoothing.
///
/// # Arguments
///
/// - `&Self` - Mutable frame clock.
/// - `u64` - Unclamped elapsed nanoseconds since the previous frame.
///
/// # Returns
///
/// - `u32` - Number of fixed-timestep simulation updates to execute this frame.
pub fn tick_ns(&mut self, raw_dt_ns: u64) -> u32 {
let mut safe_fixed_ns: u64 = self.get_fixed_step_ns().max(CLOCK_MIN_FIXED_STEP_NS);
let expected_dt_f32: f32 = ((safe_fixed_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32;
if (self.get_fixed_dt() - expected_dt_f32).abs() > 1e-5 && self.get_fixed_dt().is_finite() {
let safe_dt: f32 = self.get_fixed_dt().max(0.000_1);
safe_fixed_ns = ((safe_dt as f64) * CLOCK_NS_PER_SEC_F64)
.round()
.max(CLOCK_MIN_FIXED_STEP_NS as f64) as u64;
self.set_fixed_step_ns(safe_fixed_ns);
}
let dt_ns: u64 = raw_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
let dt_secs: f32 = ((dt_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32;
self.set_delta_ns(dt_ns);
self.set_delta_secs(dt_secs);
let next_elapsed_ns: u64 = self.get_elapsed_ns().saturating_add(dt_ns);
self.set_elapsed_ns(next_elapsed_ns);
self.set_elapsed_secs((next_elapsed_ns as f64) / CLOCK_NS_PER_SEC_F64);
self.set_frame_count(self.get_frame_count().saturating_add(1));
if dt_ns > 0 {
let inst_fps: f32 = (CLOCK_NS_PER_SEC_F64 / (dt_ns as f64)) as f32;
let prev_fps: f32 = self.get_fps();
let smoothed: f32 = if prev_fps <= 0.0 {
inst_fps
} else {
let ema_alpha: f32 =
(1.0 - (-dt_secs / CLOCK_FPS_EMA_TAU_SECS).exp()).clamp(0.0, 1.0);
prev_fps + (inst_fps - prev_fps) * ema_alpha
};
self.set_fps(smoothed);
}
let snap_window_ns: u64 = (safe_fixed_ns / CLOCK_HYSTERESIS_DIVISOR).max(1);
let mut acc_ns: u64 = self.get_accumulator_ns().saturating_add(dt_ns);
let rem_before: u64 = acc_ns % safe_fixed_ns;
if rem_before > 0 && safe_fixed_ns - rem_before <= snap_window_ns {
acc_ns = acc_ns.saturating_add(safe_fixed_ns - rem_before);
}
let max_steps: u32 = self.get_max_substeps().max(1);
let mut steps: u32 = 0;
while acc_ns >= safe_fixed_ns && steps < max_steps {
acc_ns -= safe_fixed_ns;
steps += 1;
}
if (steps == max_steps && acc_ns >= safe_fixed_ns)
|| (steps > 0 && acc_ns <= snap_window_ns)
{
acc_ns = 0;
}
self.set_accumulator_ns(acc_ns);
self.set_accumulator(((acc_ns as f64) / CLOCK_NS_PER_SEC_F64) as f32);
self.set_alpha(((acc_ns as f64) / (safe_fixed_ns as f64)).clamp(0.0, 1.0) as f32);
self.set_fixed_step_count(self.get_fixed_step_count().saturating_add(steps as u64));
steps
}
/// Advances the clock by `raw_dt_secs` seconds (converted to integer nanoseconds) and returns how many fixed simulation steps to execute.
///
/// # Arguments
///
/// - `&Self` - Mutable frame clock.
/// - `f32` - Unclamped elapsed seconds since the previous frame.
///
/// # Returns
///
/// - `u32` - Number of fixed-timestep updates to run this frame.
pub fn tick(&mut self, raw_dt_secs: f32) -> u32 {
let dt_ns: u64 = if raw_dt_secs.is_finite() && raw_dt_secs > 0.0 {
((raw_dt_secs.clamp(0.0, 0.25) as f64) * CLOCK_NS_PER_SEC_F64).round() as u64
} else {
0
};
self.tick_ns(dt_ns)
}
}
/// Default 60Hz fixed simulation / 60Hz presentation `FixedTimestep3DSession`.
impl Default for FixedTimestep3DSession {
/// Creates a `FixedTimestep3DSession` with 60Hz fixed simulation, 8 max substeps, and 60Hz presentation cadence.
///
/// # Returns
///
/// - `Self` - Default decoupled 3D simulation session.
fn default() -> Self {
Self::new(60, CLOCK_DEFAULT_MAX_SUBSTEPS, 60.0)
}
}
/// Decoupled fixed-timestep simulation stepping and render interpolation helpers for `FixedTimestep3DSession`.
impl FixedTimestep3DSession {
/// Constructs a `FixedTimestep3DSession` with explicit fixed simulation frequency, substep cap, and presentation cadence.
///
/// # Arguments
///
/// - `u32` - Fixed simulation frequency in Hertz (`1..=1000`).
/// - `u32` - Maximum fixed substeps allowed per presentation frame to prevent spiral-of-death stalls.
/// - `f32` - Display presentation cadence in Hertz (e.g. `60.0`, `120.0`, `144.0`, `240.0`).
///
/// # Returns
///
/// - `Self` - Configured decoupled 3D simulation session.
#[must_use]
pub fn new(sim_hz: u32, max_substeps: u32, present_hz: f32) -> Self {
let safe_present_hz: f32 = if present_hz.is_finite() {
present_hz.clamp(1.0, 1000.0)
} else {
60.0
};
Self {
clock: FrameClock::for_sim_hz(sim_hz, max_substeps),
present_hz: safe_present_hz,
sim_steps_total: 0,
present_frames_total: 0,
interpolated_only_frames: 0,
clamped_stall_frames: 0,
last_alpha: 0.0,
last_steps: 0,
}
}
/// Updates the display presentation cadence in Hertz without altering the fixed simulation timestep or accumulator.
///
/// # Arguments
///
/// - `&Self` - Mutable simulation session.
/// - `f32` - New presentation cadence in Hertz (`1.0..=1000.0`).
pub fn set_present_cadence_hz(&mut self, present_hz: f32) {
if present_hz.is_finite() {
self.set_present_hz(present_hz.clamp(1.0, 1000.0));
}
}
/// Advances the decoupled loop by `present_dt_ns` nanoseconds, executing only the required fixed simulation steps and returning render interpolation `alpha`.
///
/// # Arguments
///
/// - `&Self` - Mutable simulation session.
/// - `u64` - Elapsed presentation interval in integer nanoseconds.
/// - `F` - Fixed-timestep simulation callback invoked once per fixed substep with `fixed_dt_secs`.
///
/// # Returns
///
/// - `SimPresentFrame` - Per-present step count, interpolation alpha, and clamp flags.
pub fn advance_present_ns<F>(&mut self, present_dt_ns: u64, mut step_sim: F) -> SimPresentFrame
where
F: FnMut(f32),
{
let fixed_ns: u64 = self
.get_clock()
.get_fixed_step_ns()
.max(CLOCK_MIN_FIXED_STEP_NS);
let max_substeps: u32 = self.get_clock().get_max_substeps().max(1);
let pre_acc_ns: u64 = self.get_clock().get_accumulator_ns();
let clamped_dt_ns: u64 = present_dt_ns.min(CLOCK_MAX_FRAME_DT_NS);
let uncapped_steps: u64 = pre_acc_ns.saturating_add(clamped_dt_ns) / fixed_ns;
let hit_clamp: bool =
present_dt_ns > CLOCK_MAX_FRAME_DT_NS || uncapped_steps > (max_substeps as u64);
let steps: u32 = self.get_mut_clock().tick_ns(present_dt_ns);
let fixed_dt: f32 = self.get_clock().get_fixed_dt();
let alpha: f32 = self.get_clock().get_alpha();
let present_dt_secs: f32 = self.get_clock().get_delta_secs();
for _ in 0..steps {
step_sim(fixed_dt);
}
let interpolated_only: bool = steps == 0;
self.set_sim_steps_total(self.get_sim_steps_total().saturating_add(steps as u64));
self.set_present_frames_total(self.get_present_frames_total().saturating_add(1));
if interpolated_only {
self.set_interpolated_only_frames(
self.get_interpolated_only_frames().saturating_add(1),
);
}
if hit_clamp {
self.set_clamped_stall_frames(self.get_clamped_stall_frames().saturating_add(1));
}
self.set_last_alpha(alpha);
self.set_last_steps(steps);
SimPresentFrame::new(
steps,
alpha,
fixed_dt,
present_dt_secs,
interpolated_only,
hit_clamp,
)
}
/// Advances the decoupled loop by `present_dt_secs` seconds (converted to integer nanoseconds) and returns render interpolation metadata.
///
/// # Arguments
///
/// - `&Self` - Mutable simulation session.
/// - `f32` - Elapsed presentation interval in seconds.
/// - `F` - Fixed-timestep simulation callback invoked once per fixed substep with `fixed_dt_secs`.
///
/// # Returns
///
/// - `SimPresentFrame` - Per-present step count, interpolation alpha, and clamp flags.
pub fn advance_present<F>(&mut self, present_dt_secs: f32, step_sim: F) -> SimPresentFrame
where
F: FnMut(f32),
{
let dt_ns: u64 = if present_dt_secs.is_finite() && present_dt_secs > 0.0 {
((present_dt_secs.min(1.0) as f64) * CLOCK_NS_PER_SEC_F64).round() as u64
} else {
0
};
self.advance_present_ns(dt_ns, step_sim)
}
/// Linearly interpolates between `prev` and `next` simulation scalar values using `alpha` clamped to `[0.0, 1.0]`.
///
/// # Arguments
///
/// - `f32` - Previous fixed simulation scalar value.
/// - `f32` - Latest fixed simulation scalar value.
/// - `f32` - Render interpolation factor in `[0.0, 1.0]`.
///
/// # Returns
///
/// - `f32` - Smoothly interpolated render scalar value.
#[must_use]
pub fn interpolate_scalar(prev: f32, next: f32, alpha: f32) -> f32 {
let t: f32 = if alpha.is_finite() {
alpha.clamp(0.0, 1.0)
} else {
1.0
};
prev + (next - prev) * t
}
}