ferravex_core/lib.rs
1//! Small, platform-independent building blocks. Simulation time never comes from a wall clock.
2//!
3//! ```
4//! use ferravex_core::{FixedClock, World};
5//! let mut world = World::new();
6//! world.spawn((42_u32,));
7//! let mut clock = FixedClock::new(64.0, 8);
8//! let frame = clock.advance(1.0 / 60.0);
9//! for _ in 0..frame.steps { /* update systems with frame.dt */ }
10//! ```
11pub use ferravex_ecs as ecs;
12pub use ferravex_ecs::{Entity, World};
13pub mod collision;
14/// Shared lifecycle and fixed-timestep coordination for local games.
15pub mod session;
16pub mod telemetry;
17
18/// A fixed simulation step budget with a fractional render interpolation factor.
19#[derive(Debug, Clone, Copy)]
20pub struct FrameStep {
21 pub steps: u32,
22 pub dt: f32,
23 pub alpha: f32,
24 /// Whole steps intentionally discarded to prevent a spiral of death.
25 pub dropped_seconds: f64,
26}
27
28impl FrameStep {
29 /// Iterate over this frame's scheduled ticks, yielding the fixed `dt` for each.
30 ///
31 /// This iterator allocates nothing and excludes discarded catch-up time. It owns
32 /// a copy of the budget; iterating does not advance or otherwise mutate a clock.
33 /// Use [`Iterator::enumerate`] when an input edge should apply only on the first tick.
34 ///
35 /// ```
36 /// use ferravex_core::FixedClock;
37 ///
38 /// let mut clock = FixedClock::try_new(64.0, 8)?;
39 /// let frame = clock.advance(3.0 / 64.0);
40 /// let mut position = 0.0;
41 /// let mut jumps = 0;
42 /// for (index, dt) in frame.ticks().enumerate() {
43 /// position += 2.0 * dt;
44 /// if index == 0 { jumps += 1; } // Consume a pending jump edge once.
45 /// }
46 /// assert_eq!(position, 6.0 / 64.0);
47 /// assert_eq!(jumps, 1);
48 /// # Ok::<(), ferravex_core::FixedClockError>(())
49 /// ```
50 pub fn ticks(
51 self,
52 ) -> impl ExactSizeIterator<Item = f32> + DoubleEndedIterator + std::iter::FusedIterator {
53 std::iter::repeat_n(self.dt, self.steps as usize)
54 }
55}
56
57/// Context for one scheduled fixed update, produced by [`TickBatch::ticks`].
58///
59/// `tick` is the absolute scheduled count at this update, not an execution count.
60/// IDs begin at 1 after construction/reset and wrap from `u64::MAX` to 0. Reset
61/// reuses IDs; they are not globally unique or an execution/commit acknowledgment.
62/// See [`FixedClock::advance_batch`] for a runnable consumer.
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct TickContext {
65 /// Scheduled ID, including earlier issued work even if it was never executed.
66 pub tick: u64,
67 /// Zero-based position in the original batch, independent of iteration order.
68 pub batch_index: u32,
69 /// Fixed simulation delta in seconds, identical to the batch's [`FrameStep::dt`].
70 pub dt: f32,
71}
72
73/// An allocation-free snapshot of a frame budget and its scheduled tick IDs.
74///
75/// Created by [`FixedClock::advance_batch`], [`session::GameSession::advance_batch`]
76/// or [`session::GameSession::step_paused_batch`]. Scheduling already advanced the
77/// clock by the whole budget. Iterating, skipping, copying or dropping this value
78/// never advances or rolls back that clock and does not record actual execution.
79/// Track executed updates in your runner; an iterator yield alone is not an update.
80///
81/// A snapshot keeps its original IDs even after the clock advances or resets.
82/// Discard pending batches when resetting your simulation, since reset reuses IDs.
83/// See [`Self::ticks`] for an example of abandoning a batch early.
84#[derive(Debug, Clone, Copy)]
85pub struct TickBatch {
86 frame: FrameStep,
87 tick_before: u64,
88}
89
90impl TickBatch {
91 /// The unchanged timing budget, including zero-work and paused-step alpha.
92 ///
93 /// ```
94 /// use ferravex_core::FixedClock;
95 /// let batch = FixedClock::new(64.0, 2).advance_batch(3.5 / 64.0);
96 /// assert_eq!(batch.frame().steps, 2);
97 /// assert_eq!(batch.frame().alpha, 0.5);
98 /// assert_eq!(batch.frame().dropped_seconds, 1.0 / 64.0);
99 /// ```
100 pub fn frame(self) -> FrameStep {
101 self.frame
102 }
103
104 /// Iterate scheduled contexts without allocation or borrowing the clock.
105 ///
106 /// Each ID is `tick_before.wrapping_add(batch_index + 1)`. Discarded catch-up
107 /// time consumes no IDs. Empty budgets yield nothing. Every call produces the
108 /// same contexts, so executing a batch twice would repeat work with the same IDs.
109 /// Reverse/skip iteration preserves indices from the original forward order.
110 /// `nth`/`nth_back` skip in constant time, even for a maximum-sized budget.
111 ///
112 /// ```
113 /// use ferravex_core::FixedClock;
114 /// let mut clock = FixedClock::new(64.0, 8);
115 /// let batch = clock.advance_batch(3.0 / 64.0);
116 /// let mut executed = 0;
117 /// for context in batch.ticks().take(1) {
118 /// assert_eq!(context.tick, 1);
119 /// assert_eq!(context.batch_index, 0);
120 /// assert_eq!(context.dt, 1.0 / 64.0);
121 /// executed += 1; // Invoke the simulation here, then stop this batch.
122 /// }
123 /// assert_eq!(executed, 1);
124 /// assert_eq!(clock.tick(), 3); // Includes the two unexecuted scheduled IDs.
125 /// assert_eq!(clock.advance_batch(1.0 / 64.0).ticks().next().unwrap().tick, 4);
126 /// ```
127 pub fn ticks(
128 self,
129 ) -> impl ExactSizeIterator<Item = TickContext> + DoubleEndedIterator + std::iter::FusedIterator
130 {
131 TickContexts {
132 indices: 0..self.frame.steps as usize,
133 tick_before: self.tick_before,
134 dt: self.frame.dt,
135 }
136 }
137}
138
139// Map's default skipping can visit every skipped element. Keep range arithmetic
140// here so inspecting a large budget with nth/nth_back never executes that work.
141struct TickContexts {
142 indices: std::ops::Range<usize>,
143 tick_before: u64,
144 dt: f32,
145}
146
147impl TickContexts {
148 fn context(&self, index: usize) -> TickContext {
149 TickContext {
150 tick: self.tick_before.wrapping_add(index as u64 + 1),
151 batch_index: index as u32,
152 dt: self.dt,
153 }
154 }
155}
156
157impl Iterator for TickContexts {
158 type Item = TickContext;
159
160 fn next(&mut self) -> Option<Self::Item> {
161 self.indices.next().map(|index| self.context(index))
162 }
163
164 fn nth(&mut self, n: usize) -> Option<Self::Item> {
165 self.indices.nth(n).map(|index| self.context(index))
166 }
167
168 fn size_hint(&self) -> (usize, Option<usize>) {
169 self.indices.size_hint()
170 }
171
172 fn count(self) -> usize {
173 self.indices.len()
174 }
175
176 fn last(mut self) -> Option<Self::Item> {
177 self.next_back()
178 }
179}
180
181impl DoubleEndedIterator for TickContexts {
182 fn next_back(&mut self) -> Option<Self::Item> {
183 self.indices.next_back().map(|index| self.context(index))
184 }
185
186 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
187 self.indices.nth_back(n).map(|index| self.context(index))
188 }
189}
190
191impl ExactSizeIterator for TickContexts {}
192impl std::iter::FusedIterator for TickContexts {}
193
194/// Invalid configuration supplied to [`FixedClock::try_new`].
195///
196/// ```
197/// use ferravex_core::{FixedClock, FixedClockError};
198///
199/// let error = FixedClock::try_new(60.0, 0).unwrap_err();
200/// assert_eq!(error, FixedClockError::ZeroCatchUpBudget);
201/// assert!(error.to_string().contains("at least 1"));
202/// ```
203#[derive(Debug, Clone, Copy, PartialEq)]
204pub enum FixedClockError {
205 /// The rate must be finite and within the inclusive range `1..=1000` Hz.
206 InvalidTickRate { hz: f64 },
207 /// At least one simulation step must be permitted per frame.
208 ZeroCatchUpBudget,
209}
210
211impl std::fmt::Display for FixedClockError {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 match self {
214 Self::InvalidTickRate { hz } => write!(
215 f,
216 "tick rate must be in 1..=1000 Hz and finite; got {hz} Hz"
217 ),
218 Self::ZeroCatchUpBudget => write!(
219 f,
220 "catch-up budget must be nonzero; set max_steps to at least 1"
221 ),
222 }
223 }
224}
225
226impl std::error::Error for FixedClockError {}
227
228/// Frame-rate independent simulation with bounded catch-up work.
229///
230/// Supply elapsed seconds from your platform. Non-finite/negative durations are ignored.
231/// Over-budget whole steps are discarded; fractional remainder is retained for interpolation.
232#[derive(Debug, Clone)]
233pub struct FixedClock {
234 step: f64,
235 accumulator: f64,
236 max_steps: u32,
237 tick: u64,
238}
239
240impl FixedClock {
241 /// Create a clock with the given tick rate and maximum steps per frame.
242 ///
243 /// # Panics
244 ///
245 /// Panics unless `hz` is finite and in `1..=1000`, and `max_steps` is nonzero.
246 /// Use [`Self::try_new`] to report invalid user configuration without panicking.
247 pub fn new(hz: f64, max_steps: u32) -> Self {
248 Self::try_new(hz, max_steps).unwrap_or_else(|error| panic!("{error}"))
249 }
250
251 /// Create a clock, returning an actionable error for invalid configuration.
252 ///
253 /// `hz` must be finite and in `1..=1000`; `max_steps` must be at least one.
254 /// The tick rate is checked first if both values are invalid. Valid inputs have
255 /// exactly the same timing behavior as [`Self::new`].
256 ///
257 /// ```
258 /// use ferravex_core::FixedClock;
259 ///
260 /// let mut clock = FixedClock::try_new(60.0, 8)?;
261 /// assert_eq!(clock.advance(1.0 / 30.0).ticks().count(), 2);
262 /// # Ok::<(), ferravex_core::FixedClockError>(())
263 /// ```
264 pub fn try_new(hz: f64, max_steps: u32) -> Result<Self, FixedClockError> {
265 if !hz.is_finite() || !(1.0..=1000.0).contains(&hz) {
266 return Err(FixedClockError::InvalidTickRate { hz });
267 }
268 if max_steps == 0 {
269 return Err(FixedClockError::ZeroCatchUpBudget);
270 }
271 Ok(Self {
272 step: 1.0 / hz,
273 accumulator: 0.0,
274 max_steps,
275 tick: 0,
276 })
277 }
278
279 /// Schedule fixed ticks from elapsed platform time, preserving fractional time.
280 ///
281 /// Negative and non-finite durations are ignored. Finite durations are capped
282 /// at one hour before accumulation; time above that cap is ignored and is not
283 /// included in [`FrameStep::dropped_seconds`]. Within the cap, whole ticks beyond
284 /// the catch-up budget are discarded and reported in `dropped_seconds`.
285 pub fn advance(&mut self, frame_seconds: f64) -> FrameStep {
286 // Clamp absurd durations before addition to keep all arithmetic finite.
287 let elapsed = if frame_seconds.is_finite() {
288 frame_seconds.clamp(0.0, 3600.0)
289 } else {
290 0.0
291 };
292 self.accumulator += elapsed;
293 let available = ((self.accumulator + self.step * 1e-9) / self.step).floor() as u64;
294 let steps = available.min(self.max_steps as u64) as u32;
295 self.accumulator = (self.accumulator - available as f64 * self.step).max(0.0);
296 self.tick = self.tick.wrapping_add(steps as u64);
297 FrameStep {
298 steps,
299 dt: self.step as f32,
300 alpha: (self.accumulator / self.step).clamp(0.0, 1.0) as f32,
301 dropped_seconds: (available - steps as u64) as f64 * self.step,
302 }
303 }
304
305 /// Schedule the same work as [`Self::advance`], retaining per-update tick IDs.
306 ///
307 /// IDs start at 1, wrap through 0 and restart at 1 after [`Self::reset`]. They
308 /// count scheduled work, including any batch tail the caller does not execute.
309 /// No extra steps or time are consumed by constructing/iterating the batch.
310 ///
311 /// ```
312 /// use ferravex_core::{FixedClock, TickContext};
313 /// let mut clock = FixedClock::new(64.0, 4);
314 /// assert_eq!(clock.advance_batch(0.5 / 64.0).ticks().len(), 0);
315 /// let batch = clock.advance_batch(2.0 / 64.0);
316 /// let mut position = 0.0;
317 /// for TickContext { tick, batch_index, dt } in batch.ticks() {
318 /// assert_eq!(tick, u64::from(batch_index) + 1);
319 /// position += 2.0 * dt;
320 /// }
321 /// assert_eq!(position, 4.0 / 64.0);
322 /// assert_eq!(batch.frame().alpha, 0.5);
323 /// assert_eq!(clock.tick(), 2);
324 /// ```
325 pub fn advance_batch(&mut self, frame_seconds: f64) -> TickBatch {
326 let tick_before = self.tick;
327 let frame = self.advance(frame_seconds);
328 TickBatch { frame, tick_before }
329 }
330
331 /// Number of scheduled ticks since construction or reset, wrapping at `u64::MAX`.
332 /// Discarded catch-up ticks are not counted.
333 /// The whole batch is counted before execution; use [`Self::advance_batch`]
334 /// for individual IDs instead of reading this batch-end count inside a loop.
335 pub fn tick(&self) -> u64 {
336 self.tick
337 }
338 pub fn dt(&self) -> f32 {
339 self.step as f32
340 }
341 pub fn reset(&mut self) {
342 self.accumulator = 0.0;
343 self.tick = 0;
344 }
345}
346
347/// Allocation-free statistics over the most recent `N` accepted frame times.
348///
349/// Record elapsed **seconds**; diagnostics return **milliseconds**. During warm-up,
350/// only recorded samples contribute. Zero durations are valid, and `N == 0`
351/// creates a disabled, always-empty window. Invalid samples never evict history.
352/// Recording takes constant time; queries scan at most `N` samples. Percentile
353/// queries also copy the fixed array onto the stack and sort the populated part.
354///
355/// ```
356/// use ferravex_core::FrameStats;
357///
358/// let mut stats = FrameStats::<120>::default();
359/// stats.record(0.010);
360/// stats.record(0.030);
361/// assert_eq!(stats.sample_count(), 2);
362/// assert_eq!(stats.capacity(), 120);
363/// assert_eq!(stats.mean_ms(), 20.0);
364/// assert_eq!(stats.max_ms(), 30.0);
365/// assert_eq!(stats.percentile_ms(95.0), Some(30.0));
366/// assert_eq!(stats.jitter_ms(), 10.0);
367/// ```
368pub struct FrameStats<const N: usize = 120> {
369 samples: [f32; N],
370 cursor: usize,
371 len: usize,
372}
373impl<const N: usize> Default for FrameStats<N> {
374 fn default() -> Self {
375 Self {
376 samples: [0.0; N],
377 cursor: 0,
378 len: 0,
379 }
380 }
381}
382impl<const N: usize> FrameStats<N> {
383 /// Record elapsed seconds, silently ignoring invalid or disabled samples.
384 ///
385 /// See [`Self::try_record`] to learn whether a sample was accepted. Neither
386 /// method allocates, including during warm-up and when the window wraps.
387 pub fn record(&mut self, seconds: f32) {
388 self.try_record(seconds);
389 }
390
391 /// Record elapsed seconds, returning whether the sample was accepted.
392 ///
393 /// Returns `false` without changing the window if `N == 0`, `seconds` is
394 /// negative or non-finite, or converting to `f32` milliseconds overflows.
395 /// Zero (including negative zero) is accepted. When full, the oldest accepted
396 /// sample is replaced. This operation takes constant time and never allocates.
397 ///
398 /// ```
399 /// use ferravex_core::FrameStats;
400 ///
401 /// let mut stats = FrameStats::<2>::default();
402 /// assert!(stats.try_record(0.016));
403 /// assert!(!stats.try_record(f32::NAN));
404 /// assert!(!stats.try_record(f32::MAX)); // Milliseconds would overflow.
405 /// assert_eq!(stats.sample_count(), 1);
406 /// assert!(!FrameStats::<0>::default().try_record(0.016));
407 /// ```
408 pub fn try_record(&mut self, seconds: f32) -> bool {
409 let milliseconds = seconds * 1000.0;
410 if N == 0 || seconds < 0.0 || !milliseconds.is_finite() {
411 return false;
412 }
413 self.samples[self.cursor] = milliseconds;
414 self.cursor = (self.cursor + 1) % N;
415 self.len = (self.len + 1).min(N);
416 true
417 }
418
419 /// Number of accepted samples currently retained, at most [`Self::capacity`].
420 ///
421 /// This is a window count, not a lifetime counter. Compare it with capacity
422 /// to determine whether a nonzero window has completed warm-up.
423 ///
424 /// ```
425 /// use ferravex_core::FrameStats;
426 /// let mut stats = FrameStats::<2>::default();
427 /// assert_eq!(stats.sample_count(), 0);
428 /// for _ in 0..3 { stats.record(0.016); }
429 /// assert_eq!(stats.sample_count(), 2);
430 /// ```
431 pub const fn sample_count(&self) -> usize {
432 self.len
433 }
434
435 /// Maximum retained sample count; zero means recording is disabled.
436 ///
437 /// ```
438 /// use ferravex_core::FrameStats;
439 /// assert_eq!(FrameStats::<90>::default().capacity(), 90);
440 /// assert_eq!(FrameStats::<0>::default().capacity(), 0);
441 /// ```
442 pub const fn capacity(&self) -> usize {
443 N
444 }
445
446 /// Forget all samples and restart warm-up without allocating.
447 ///
448 /// ```
449 /// use ferravex_core::FrameStats;
450 /// let mut stats = FrameStats::<120>::default();
451 /// stats.record(0.016);
452 /// stats.clear();
453 /// assert_eq!(stats.sample_count(), 0);
454 /// assert_eq!(stats.mean_ms(), 0.0);
455 /// assert_eq!(stats.percentile_ms(95.0), None);
456 /// ```
457 pub fn clear(&mut self) {
458 self.cursor = 0;
459 self.len = 0;
460 }
461
462 /// Arithmetic mean in milliseconds, or zero when empty.
463 ///
464 /// Accumulates in `f64` so summing large accepted samples cannot overflow.
465 pub fn mean_ms(&self) -> f32 {
466 self.mean_ms_f64() as f32
467 }
468
469 fn mean_ms_f64(&self) -> f64 {
470 if self.len == 0 {
471 return 0.0;
472 }
473 self.samples[..self.len]
474 .iter()
475 .map(|&sample| f64::from(sample))
476 .sum::<f64>()
477 / self.len as f64
478 }
479
480 /// Largest retained frame time in milliseconds, or zero when empty.
481 pub fn max_ms(&self) -> f32 {
482 self.samples[..self.len].iter().copied().fold(0.0, f32::max)
483 }
484
485 /// Nearest-rank percentile in milliseconds, using a percentage in `0..=100`.
486 ///
487 /// Returns `None` for an empty window or a non-finite/out-of-range percentage.
488 /// For sorted samples, selects rank `ceil(percentile * sample_count / 100)`
489 /// (one-based), with percentile zero selecting the minimum. Percentile 100
490 /// selects the maximum. Small windows can therefore share several percentiles;
491 /// values are never interpolated and unused warm-up slots do not contribute.
492 ///
493 /// Does not change recording order or allocate on the heap. A query uses
494 /// `N * size_of::<f32>()` bytes of stack scratch space and sorts the `m`
495 /// retained samples in `O(m log m)` time. Choose `N` to fit your stack budget.
496 ///
497 /// ```
498 /// use ferravex_core::FrameStats;
499 /// let mut stats = FrameStats::<120>::default();
500 /// assert_eq!(stats.percentile_ms(99.0), None);
501 /// for seconds in [0.040, 0.010, 0.030, 0.020] { stats.record(seconds); }
502 /// assert_eq!(stats.percentile_ms(0.0), Some(10.0));
503 /// assert_eq!(stats.percentile_ms(50.0), Some(20.0));
504 /// assert_eq!(stats.percentile_ms(95.0), Some(40.0));
505 /// assert_eq!(stats.percentile_ms(101.0), None);
506 /// ```
507 pub fn percentile_ms(&self, percentile: f32) -> Option<f32> {
508 if self.len == 0 || !(0.0..=100.0).contains(&percentile) {
509 return None;
510 }
511 let mut sorted = self.samples;
512 sorted[..self.len].sort_unstable_by(f32::total_cmp);
513 let rank = (f64::from(percentile) * self.len as f64 / 100.0).ceil() as usize;
514 let index = rank.saturating_sub(1).min(self.len - 1);
515 Some(sorted[index])
516 }
517
518 /// Population standard deviation of retained frame times, in milliseconds.
519 ///
520 /// Jitter is `sqrt(sum((sample - mean)^2) / sample_count)`, measuring spread
521 /// around the mean, independent of sample order. It is not a difference between
522 /// consecutive frames. Empty, single-sample and constant windows return zero.
523 /// Uses two passes with `f64` arithmetic to avoid overflow and cancellation
524 /// from subtracting squared means. Never allocates.
525 ///
526 /// ```
527 /// use ferravex_core::FrameStats;
528 /// let mut stats = FrameStats::<120>::default();
529 /// assert_eq!(stats.jitter_ms(), 0.0);
530 /// stats.record(0.010);
531 /// assert_eq!(stats.jitter_ms(), 0.0);
532 /// stats.record(0.030);
533 /// assert_eq!(stats.jitter_ms(), 10.0);
534 /// ```
535 pub fn jitter_ms(&self) -> f32 {
536 if self.len < 2 {
537 return 0.0;
538 }
539 let mean = self.mean_ms_f64();
540 let squared_deviations = self.samples[..self.len]
541 .iter()
542 .map(|&sample| {
543 let deviation = f64::from(sample) - mean;
544 deviation * deviation
545 })
546 .sum::<f64>();
547 (squared_deviations / self.len as f64).sqrt() as f32
548 }
549}
550
551#[cfg(test)]
552mod tests {
553 use super::*;
554
555 #[test]
556 fn contextual_batches_preserve_legacy_timing_and_issued_ids() {
557 for hz in [1.0, 59.94, 64.0, 1000.0] {
558 for max_steps in [1, 4, u32::MAX] {
559 let mut clock = FixedClock::new(hz, max_steps);
560 let mut legacy = clock.clone();
561 for elapsed in [
562 0.0,
563 0.5 / hz,
564 0.5 / hz,
565 3.0 / hz,
566 10.25 / hz,
567 f64::NAN,
568 f64::INFINITY,
569 f64::NEG_INFINITY,
570 -1.0,
571 f64::MAX,
572 ] {
573 let before = clock.tick();
574 let expected = legacy.advance(elapsed);
575 let batch = clock.advance_batch(elapsed);
576 let frame = batch.frame();
577 assert_eq!(frame.steps, expected.steps);
578 assert_eq!(frame.dt, expected.dt);
579 assert_eq!(frame.alpha, expected.alpha);
580 assert_eq!(frame.dropped_seconds, expected.dropped_seconds);
581 assert_eq!(clock.tick(), legacy.tick());
582 let mut ticks = batch.ticks();
583 assert_eq!(ticks.len(), frame.steps as usize);
584 if frame.steps == 0 {
585 assert_eq!(ticks.next(), None);
586 assert_eq!(ticks.next_back(), None);
587 } else {
588 assert_eq!(
589 ticks.next(),
590 Some(TickContext {
591 tick: before.wrapping_add(1),
592 batch_index: 0,
593 dt: frame.dt,
594 })
595 );
596 if frame.steps > 1 {
597 assert_eq!(
598 ticks.next_back(),
599 Some(TickContext {
600 tick: clock.tick(),
601 batch_index: frame.steps - 1,
602 dt: frame.dt,
603 })
604 );
605 }
606 }
607 }
608 }
609 }
610 }
611
612 #[test]
613 fn contextual_batches_wrap_skip_and_retain_snapshot_ids_after_reset() {
614 let mut clock = FixedClock::new(64.0, 4);
615 clock.tick = u64::MAX - 1;
616 let batch = clock.advance_batch(10.5 / 64.0);
617 assert_eq!(batch.frame().dropped_seconds, 6.0 / 64.0);
618 assert_eq!(clock.tick(), 2);
619 let expected = [u64::MAX, 0, 1, 2];
620 for ((index, id), context) in expected.into_iter().enumerate().zip(batch.ticks()) {
621 assert_eq!(context.tick, id);
622 assert_eq!(context.batch_index, index as u32);
623 assert_eq!(context.dt, 1.0 / 64.0);
624 }
625 let mut ticks = batch.ticks();
626 assert_eq!(ticks.size_hint(), (4, Some(4)));
627 assert_eq!(ticks.next_back().unwrap().batch_index, 3);
628 assert_eq!(ticks.nth(1).unwrap().tick, 0);
629 assert_eq!(ticks.len(), 1);
630 assert_eq!(ticks.next().unwrap().tick, 1);
631 assert_eq!(ticks.next(), None);
632 assert_eq!(ticks.next_back(), None);
633 assert_eq!(ticks.next(), None);
634 assert_eq!(
635 clock.advance_batch(0.5 / 64.0).ticks().next().unwrap().tick,
636 3
637 );
638 clock.reset();
639 assert_eq!(clock.advance_batch(0.5 / 64.0).ticks().len(), 0);
640 assert_eq!(
641 clock.advance_batch(0.5 / 64.0).ticks().next().unwrap().tick,
642 1
643 );
644 assert_eq!(
645 batch
646 .ticks()
647 .map(|context| context.tick)
648 .collect::<Vec<_>>(),
649 expected
650 );
651 }
652
653 #[test]
654 fn contextual_iterator_supports_full_u32_budget_without_materializing_it() {
655 let frame = FrameStep {
656 steps: u32::MAX,
657 dt: 0.125,
658 alpha: 0.0,
659 dropped_seconds: 0.0,
660 };
661 let batch = TickBatch {
662 frame,
663 tick_before: u64::MAX,
664 };
665 let mut ticks = batch.ticks();
666 assert_eq!(ticks.len(), u32::MAX as usize);
667 let last = ticks.nth((u32::MAX - 1) as usize).unwrap();
668 assert_eq!(last.batch_index, u32::MAX - 1);
669 assert_eq!(last.tick, u64::from(u32::MAX - 1));
670 assert_eq!(ticks.next(), None);
671 assert_eq!(ticks.next_back(), None);
672 let mut reverse = batch.ticks();
673 assert_eq!(reverse.nth_back((u32::MAX - 1) as usize).unwrap().tick, 0);
674 assert_eq!(reverse.len(), 0);
675 assert_eq!(reverse.next(), None);
676 let mut skipped = batch.ticks();
677 assert_eq!(skipped.nth(usize::MAX), None);
678 assert_eq!(skipped.next_back(), None);
679 }
680
681 #[test]
682 fn abandoned_batch_tails_and_legacy_calls_still_consume_scheduled_ids() {
683 let mut clock = FixedClock::new(64.0, 4);
684 assert_eq!(clock.advance(2.0 / 64.0).steps, 2);
685 let batch = clock.advance_batch(4.0 / 64.0);
686 let mut executed = 0;
687 for context in batch.ticks() {
688 executed += 1;
689 assert_eq!(context.tick, 3);
690 if context.batch_index == 0 {
691 break;
692 }
693 }
694 assert_eq!(executed, 1);
695 assert_eq!(clock.tick(), 6);
696 let unused = clock.advance_batch(2.0 / 64.0);
697 assert_eq!(unused.frame().steps, 2);
698 assert_eq!(
699 clock.advance_batch(1.0 / 64.0).ticks().next().unwrap().tick,
700 9
701 );
702 }
703
704 #[test]
705 fn checked_clock_rejects_invalid_configuration_with_actionable_errors() {
706 for hz in [
707 0.0,
708 -0.0,
709 -60.0,
710 1.0 - f64::EPSILON,
711 1000.001,
712 f64::MAX,
713 f64::NAN,
714 f64::INFINITY,
715 f64::NEG_INFINITY,
716 ] {
717 let error = FixedClock::try_new(hz, 8).unwrap_err();
718 match error {
719 FixedClockError::InvalidTickRate { hz: actual } => {
720 assert_eq!(actual.to_bits(), hz.to_bits());
721 }
722 _ => panic!("expected an invalid tick rate"),
723 }
724 let message = error.to_string();
725 assert!(message.contains("1..=1000 Hz"));
726 assert!(message.contains("finite"));
727 assert!(message.contains(&hz.to_string()));
728 let source: &dyn std::error::Error = &error;
729 assert!(source.source().is_none());
730 }
731
732 let error = FixedClock::try_new(60.0, 0).unwrap_err();
733 assert_eq!(error, FixedClockError::ZeroCatchUpBudget);
734 assert!(error.to_string().contains("max_steps to at least 1"));
735 assert!(matches!(
736 FixedClock::try_new(0.0, 0),
737 Err(FixedClockError::InvalidTickRate { .. })
738 ));
739 }
740
741 #[test]
742 fn checked_clock_accepts_rate_and_budget_boundaries() {
743 for hz in [1.0, 59.94, 1000.0] {
744 for max_steps in [1, u32::MAX] {
745 let mut clock = FixedClock::try_new(hz, max_steps).unwrap();
746 assert_eq!(clock.tick(), 0);
747 assert_eq!(clock.dt(), (1.0 / hz) as f32);
748 let frame = clock.advance(1.0 / hz);
749 assert_eq!(frame.steps, 1);
750 assert_eq!(frame.alpha, 0.0);
751 assert_eq!(frame.dropped_seconds, 0.0);
752 assert_eq!(clock.tick(), 1);
753 }
754 }
755 }
756
757 #[test]
758 #[should_panic(expected = "tick rate must be in 1..=1000 Hz")]
759 fn original_constructor_still_panics_on_invalid_rate() {
760 FixedClock::new(f64::NAN, 8);
761 }
762
763 #[test]
764 #[should_panic(expected = "catch-up budget must be nonzero")]
765 fn original_constructor_still_panics_on_zero_budget() {
766 FixedClock::new(60.0, 0);
767 }
768
769 #[test]
770 fn frame_rate_independent() {
771 for hz in [30, 60, 64, 144] {
772 for fps in [30, 60, 144, 240] {
773 let mut clock = FixedClock::try_new(hz as f64, 8).unwrap();
774 let mut simulated_seconds = 0.0_f64;
775 for _ in 0..fps * 10 {
776 let frame = clock.advance(1.0 / fps as f64);
777 assert_eq!(frame.dropped_seconds, 0.0);
778 assert!((0.0..=1.0).contains(&frame.alpha));
779 for dt in frame.ticks() {
780 simulated_seconds += dt as f64;
781 }
782 }
783 assert_eq!(clock.tick(), hz * 10, "{hz} Hz at {fps} fps");
784 assert!((simulated_seconds - 10.0).abs() < 0.000001);
785 }
786 }
787 }
788
789 #[test]
790 fn catchup_is_bounded_and_fraction_retained() {
791 let mut clock = FixedClock::new(64.0, 4);
792 let f = clock.advance(10.5 / 64.0);
793 assert_eq!(f.steps, 4);
794 assert_eq!(f.ticks().count(), 4);
795 assert!((f.alpha - 0.5).abs() < 0.0001);
796 assert!((f.dropped_seconds - 6.0 / 64.0).abs() < 0.0001);
797 assert_eq!(clock.advance(0.5 / 64.0).steps, 1);
798 assert_eq!(clock.tick(), 5);
799 let idle = clock.advance(0.0);
800 assert_eq!(idle.steps, 0);
801 assert_eq!(idle.alpha, 0.0);
802 assert_eq!(idle.dropped_seconds, 0.0);
803 }
804
805 #[test]
806 fn invalid_durations_do_not_poison_clock() {
807 let mut c = FixedClock::new(64.0, 8);
808 assert_eq!(c.advance(0.25 / 64.0).steps, 0);
809 for dt in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -5.0] {
810 let frame = c.advance(dt);
811 assert_eq!(frame.steps, 0);
812 assert_eq!(frame.alpha, 0.25);
813 assert_eq!(frame.dropped_seconds, 0.0);
814 assert_eq!(c.tick(), 0);
815 }
816 assert_eq!(c.advance(0.75 / 64.0).steps, 1);
817 }
818
819 #[test]
820 fn ticks_preserve_struct_literals_and_iterator_bounds() {
821 let frame = FrameStep {
822 steps: 3,
823 dt: 0.125,
824 alpha: 0.75,
825 dropped_seconds: 8.0,
826 };
827 let mut ticks = frame.ticks();
828 assert_eq!(ticks.size_hint(), (3, Some(3)));
829 assert_eq!(ticks.next(), Some(0.125));
830 assert_eq!(ticks.len(), 2);
831 assert_eq!(ticks.next_back(), Some(0.125));
832 assert_eq!(ticks.next(), Some(0.125));
833 assert_eq!(ticks.len(), 0);
834 assert_eq!(ticks.next(), None);
835 assert_eq!(ticks.next_back(), None);
836 assert_eq!(ticks.next(), None);
837 assert_eq!(frame.ticks().sum::<f32>(), 0.375);
838
839 let mut empty = FrameStep { steps: 0, ..frame }.ticks();
840 assert_eq!(empty.len(), 0);
841 assert_eq!(empty.next(), None);
842 assert_eq!(empty.next_back(), None);
843
844 let mut largest = FrameStep {
845 steps: u32::MAX,
846 ..frame
847 }
848 .ticks();
849 assert_eq!(largest.len(), u32::MAX as usize);
850 assert_eq!(largest.nth((u32::MAX - 1) as usize), Some(frame.dt));
851 assert_eq!(largest.next(), None);
852 }
853
854 #[test]
855 fn finite_duration_cap_prevents_overflow_and_retains_fraction() {
856 for max_steps in [1, u32::MAX] {
857 let mut clock = FixedClock::try_new(1000.0, max_steps).unwrap();
858 clock.advance(0.00025);
859 let frame = clock.advance(f64::MAX);
860 let expected_steps = max_steps.min(3_600_000);
861 assert_eq!(frame.steps, expected_steps);
862 assert_eq!(frame.ticks().len(), expected_steps as usize);
863 assert_eq!(clock.tick(), expected_steps as u64);
864 assert!(frame.dt.is_finite());
865 assert!((frame.alpha - 0.25).abs() < 0.00001);
866 assert!(
867 (frame.dropped_seconds - (3_600_000 - expected_steps) as f64 / 1000.0).abs()
868 < 0.000001
869 );
870 assert_eq!(clock.advance(0.0).steps, 0);
871 assert_eq!(clock.advance(0.00075).steps, 1);
872 }
873 }
874
875 #[test]
876 fn tick_counter_wraps_only_scheduled_ticks() {
877 let mut clock = FixedClock::new(64.0, 4);
878 clock.tick = u64::MAX - 1;
879 let frame = clock.advance(10.5 / 64.0);
880 assert_eq!(frame.steps, 4);
881 assert_eq!(frame.dropped_seconds, 6.0 / 64.0);
882 assert_eq!(clock.tick(), 2);
883 assert_eq!(clock.advance(0.5 / 64.0).steps, 1);
884 assert_eq!(clock.tick(), 3);
885 }
886
887 #[test]
888 fn reset_clears_tick_and_fraction_without_changing_configuration() {
889 let mut clock = FixedClock::try_new(64.0, 2).unwrap();
890 assert_eq!(clock.advance(2.75 / 64.0).steps, 2);
891 clock.reset();
892 assert_eq!(clock.tick(), 0);
893 assert_eq!(clock.dt(), 1.0 / 64.0);
894 let frame = clock.advance(0.25 / 64.0);
895 assert_eq!(frame.steps, 0);
896 assert_eq!(frame.alpha, 0.25);
897 assert_eq!(frame.dropped_seconds, 0.0);
898 assert_eq!(clock.advance(4.0 / 64.0).steps, 2);
899 }
900
901 #[test]
902 fn stats_wrap_and_ignore_nan() {
903 let mut s = FrameStats::<2>::default();
904 for dt in [0.001, 0.003, 0.005, f32::NAN] {
905 s.record(dt);
906 }
907 assert!((s.mean_ms() - 4.0).abs() < 0.001);
908 assert_eq!(s.max_ms(), 5.0);
909 }
910}