Skip to main content

sciart_core/
clock.rs

1/// Fixed-timestep accumulator (ADR-0003, CORE-R9..R12).
2///
3/// The runtime feeds real elapsed time in; generators only ever see a constant `dt`.
4#[derive(Debug, Clone)]
5pub struct FixedStep {
6    dt: f64,
7    max_steps: u32,
8    acc: f64,
9}
10
11impl FixedStep {
12    /// `dt` must be positive and finite; `max_steps` is clamped to `>= 1`.
13    pub fn new(dt: f64, max_steps: u32) -> Self {
14        assert!(
15            dt.is_finite() && dt > 0.0,
16            "FixedStep dt must be > 0, got {dt}"
17        );
18        Self {
19            dt,
20            max_steps: max_steps.max(1),
21            acc: 0.0,
22        }
23    }
24
25    pub fn dt(&self) -> f64 {
26        self.dt
27    }
28
29    /// Add `elapsed` seconds and return how many `dt` steps to simulate now.
30    pub fn advance(&mut self, elapsed: f64) -> u32 {
31        if elapsed.is_finite() && elapsed > 0.0 {
32            self.acc += elapsed;
33        }
34        // Epsilon: 0.05 + 0.05 accumulates to 0.0999.. and would otherwise lose a step.
35        let due = (self.acc / self.dt + 1e-9).floor();
36        if due >= f64::from(self.max_steps) {
37            // Spiral-of-death guard: drop the backlog instead of catching up.
38            self.acc = 0.0;
39            return self.max_steps;
40        }
41        let steps = due as u32;
42        self.acc -= f64::from(steps) * self.dt;
43        // Guard float drift so alpha stays in [0, 1).
44        if self.acc < 0.0 || self.acc >= self.dt {
45            self.acc = 0.0;
46        }
47        steps
48    }
49
50    /// Fraction of the next step already accumulated, in `[0, 1)`.
51    pub fn alpha(&self) -> f64 {
52        self.acc / self.dt
53    }
54
55    pub fn reset(&mut self) {
56        self.acc = 0.0;
57    }
58}