gizmo-core 0.10.0

A custom ECS and physics engine aimed for realistic simulations.
Documentation
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Frame timing: [`Time`], the variable render clock, and [`PhysicsTime`], the fixed-step
//! accumulator that drives the simulation.
//!
//! Neither type reads the system clock. Both are *fed* a delta measured by the caller
//! ([`Time::update`], [`PhysicsTime::accumulate`]), which is what makes a recorded or
//! replayed frame sequence reproduce the same stepping as the original run.
//!
//! The two types do not know about each other either: `accumulate` banks whatever delta it
//! is handed, and whether that is [`Time::dt`] — already multiplied by `time_scale` and
//! capped at `max_dt` — or an independently measured one is the caller's choice, not
//! something decided here.

/// Engine-wide time management.
///
/// # Usage
/// ```
/// use gizmo_core::time::Time;
///
/// let mut time = Time::new();
///
/// // At the start of every frame:
/// time.update(1.0 / 60.0);
///
/// assert_eq!(time.frame(), 1);
/// assert!((time.dt() - 1.0 / 60.0).abs() < 1e-6);
/// assert!((time.raw_dt() - 1.0 / 60.0).abs() < 1e-6);
///
/// // The time scale scales dt and does NOT affect raw_dt.
/// time.set_time_scale(0.5); // slow motion
/// time.update(1.0 / 60.0);
/// assert!((time.dt() - 0.5 / 60.0).abs() < 1e-6);
/// assert!((time.raw_dt() - 1.0 / 60.0).abs() < 1e-6);
///
/// time.set_time_scale(0.0); // pause: dt goes to zero, the frame counter keeps running
/// time.update(1.0 / 60.0);
/// assert_eq!(time.dt(), 0.0);
/// assert_eq!(time.frame(), 3);
///
/// // A long stall (spike) is clamped — so physics does not explode in a single frame.
/// time.set_time_scale(1.0);
/// time.update(5.0);
/// assert!(time.dt() <= 0.05 + 1e-6, "dt max_dt'ye clamp'lenmeli");
/// assert!((time.raw_dt() - 5.0).abs() < 1e-6, "raw_dt clamp'lenmez");
/// ```
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct Time {
    /// Clamped delta time (seconds). `time_scale` applied.
    dt: f32,
    /// Raw delta time — clamp and scale not applied.
    raw_dt: f32,
    /// Total elapsed time (seconds, at f64 precision).
    elapsed: f64,
    /// Frame counter.
    frame_count: u64,
    /// Time scale. 1.0 = normal, 0.5 = slow motion, 0.0 = pause.
    time_scale: f32,
    /// Maximum dt cap (seconds). Default: 1/20 = 50ms.
    max_dt: f32,
}

/// Default max dt: 50ms (20 FPS minimum).
const DEFAULT_MAX_DT: f32 = 1.0 / 20.0;

impl Time {
    /// Creates a clock sitting at frame 0, with `time_scale = 1.0` and the default 50 ms
    /// `max_dt` cap (equivalently, a 20 FPS floor on the simulated step).
    ///
    /// `dt`, `raw_dt` and `elapsed` all start at exactly zero. That is a deliberate value,
    /// not a placeholder: a system that runs before the first [`Time::update`] sees *no*
    /// time passing rather than a guessed frame duration, so it advances nothing instead of
    /// integrating a fabricated step.
    pub fn new() -> Self {
        Self {
            dt: 0.0,
            raw_dt: 0.0,
            elapsed: 0.0,
            frame_count: 0,
            time_scale: 1.0,
            max_dt: DEFAULT_MAX_DT,
        }
    }

    /// Takes the raw dt, applies clamp + scale and updates all time values.
    /// Must be called once at the start of every frame.
    pub fn update(&mut self, raw_dt: f32) {
        self.raw_dt = raw_dt.max(0.0); // Negatif dt'yi engelle
        self.dt = (self.raw_dt * self.time_scale).min(self.max_dt);
        self.elapsed += self.dt as f64;
        self.frame_count += 1;
    }

    // ──── Getter'lar ────

    /// Clamped and scaled delta time (seconds).
    /// Systems such as physics, movement and animation should use this.
    #[inline]
    pub fn dt(&self) -> f32 {
        self.dt
    }

    /// Raw delta time — clamp and scale not applied.
    /// For systems that need real wall-clock time (e.g. the FPS counter).
    #[inline]
    pub fn raw_dt(&self) -> f32 {
        self.raw_dt
    }

    /// Total elapsed time (seconds, at f64 precision).
    /// Retains its precision even in long sessions.
    #[inline]
    pub fn elapsed(&self) -> f64 {
        self.elapsed
    }

    /// Total frame count.
    #[inline]
    pub fn frame(&self) -> u64 {
        self.frame_count
    }

    /// Current time scale.
    #[inline]
    pub fn time_scale(&self) -> f32 {
        self.time_scale
    }

    /// Current FPS (1/raw_dt). Returns 0.0 if raw_dt = 0.
    #[inline]
    pub fn fps(&self) -> f32 {
        if self.raw_dt > 0.0 {
            1.0 / self.raw_dt
        } else {
            0.0
        }
    }

    // ──── Setter'lar ────

    /// Sets the time scale. 0.0 = stop, 0.5 = slow motion, 1.0 = normal, 2.0 = fast.
    pub fn set_time_scale(&mut self, scale: f32) {
        self.time_scale = scale.max(0.0);
    }

    /// Sets the maximum dt cap (seconds).
    pub fn set_max_dt(&mut self, max: f32) {
        self.max_dt = max.max(0.001); // En az ~1ms
    }
}

impl Default for Time {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════
//  PhysicsTime — Sabit zaman adımlı fizik zamanlayıcı
//
//  Fizik motoru sabit dt'de çalışır (varsayılan 1/60s = 16.67ms).
//  Render frame'leri değişken hızda çalışırken, fizik her zaman aynı
//  dt ile güncellenir → determinizm + kararlılık.
//
//  Kullanım:
//    Frame başında `accumulate(render_dt)` çağrılır.
//    `should_step()` true döndüğü sürece fizik adımları çalıştırılır.
//    `consume_step()` ile accumulator azaltılır.
//    `alpha()` ile render interpolasyonu yapılır.
// ═══════════════════════════════════════════════════════════════════════
/// Fixed-timestep accumulator for the physics clock.
///
/// The render loop runs at whatever rate the machine manages; the solver must not. Per frame
/// the caller adds the elapsed render time with [`PhysicsTime::accumulate`], runs one physics
/// step for each [`PhysicsTime::should_step`] / [`PhysicsTime::consume_step`] pair, then calls
/// [`PhysicsTime::compute_alpha`] once before rendering:
///
/// ```text
/// accumulate(dt); while should_step() { step_physics(fixed_dt()); consume_step(); } compute_alpha();
/// ```
///
/// Every step advances the simulation by exactly [`PhysicsTime::fixed_dt`] seconds no matter
/// what the frame rate did, which is the property the determinism and stability guarantees
/// rest on. Leftover time below one step stays in the accumulator and surfaces as
/// [`PhysicsTime::alpha`] for render interpolation.
///
/// The accumulator is capped at 8 x `fixed_dt`, so however long a stall lasts (a breakpoint,
/// a swap-in, a stuttering frame) at most 8 steps are ever queued. Time past the cap is
/// **dropped**, not deferred: the simulation falls behind wall-clock rather than entering a
/// spiral of death where each catch-up frame costs more than it recovers.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct PhysicsTime {
    /// Fixed physics timestep (seconds). Default: 1/60.
    fixed_dt: f32,
    /// Accumulated time — time not yet spent as a physics step.
    accumulator: f32,
    /// Maximum accumulation limit (spiral of death protection).
    max_accumulator: f32,
    /// Total physics step count.
    step_count: u64,
    /// Total physics time (at f64 precision).
    physics_elapsed: f64,
    /// Interpolation coefficient: between 0.0..1.0.
    /// Used during rendering for `lerp(prev_state, curr_state, alpha)`.
    alpha: f32,
}

impl PhysicsTime {
    /// Creates a new PhysicsTime. `hz` = physics update rate (e.g. 60, 120, 240).
    pub fn new(hz: u32) -> Self {
        let fixed_dt = 1.0 / hz as f32;
        Self {
            fixed_dt,
            accumulator: 0.0,
            max_accumulator: fixed_dt * 8.0, // En fazla 8 fizik adımı birikebilir
            step_count: 0,
            physics_elapsed: 0.0,
            alpha: 0.0,
        }
    }

    /// Adds the render frame dt to the accumulator.
    /// Called once at the start of every frame.
    pub fn accumulate(&mut self, render_dt: f32) {
        self.accumulator += render_dt;
        // Spiral of death koruması
        if self.accumulator > self.max_accumulator {
            self.accumulator = self.max_accumulator;
        }
    }

    /// Has enough time accumulated for one physics step?
    #[inline]
    pub fn should_step(&self) -> bool {
        self.accumulator >= self.fixed_dt
    }

    /// "Consumes" one physics step — subtracts fixed_dt from the accumulator.
    /// Called after every physics step.
    pub fn consume_step(&mut self) {
        self.accumulator -= self.fixed_dt;
        self.step_count += 1;
        self.physics_elapsed += self.fixed_dt as f64;
    }

    /// Computes the interpolation alpha.
    /// Called after all physics steps are finished, before rendering.
    pub fn compute_alpha(&mut self) {
        self.alpha = self.accumulator / self.fixed_dt;
    }

    // ──── Getter'lar ────

    /// Fixed physics dt (seconds).
    #[inline]
    pub fn fixed_dt(&self) -> f32 {
        self.fixed_dt
    }

    /// Interpolation coefficient (0.0 .. 1.0).
    /// `render_pos = lerp(prev_physics_pos, curr_physics_pos, alpha)`
    #[inline]
    pub fn alpha(&self) -> f32 {
        self.alpha
    }

    /// Total physics step count.
    #[inline]
    pub fn step_count(&self) -> u64 {
        self.step_count
    }

    /// Total physics time (at f64 precision).
    #[inline]
    pub fn physics_elapsed(&self) -> f64 {
        self.physics_elapsed
    }

    /// Accumulated time (for debugging purposes).
    #[inline]
    pub fn accumulator(&self) -> f32 {
        self.accumulator
    }

    // ──── Setter'lar ────

    /// Changes the physics rate (Hz). Caution: accumulated time is not reset.
    pub fn set_hz(&mut self, hz: u32) {
        self.fixed_dt = 1.0 / hz.max(1) as f32;
        self.max_accumulator = self.fixed_dt * 8.0;
    }
}

impl Default for PhysicsTime {
    fn default() -> Self {
        Self::new(60) // 60 Hz fizik
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_update() {
        let mut time = Time::new();
        time.update(0.016);

        assert!((time.dt() - 0.016).abs() < 0.0001);
        assert!((time.raw_dt() - 0.016).abs() < 0.0001);
        assert!((time.elapsed() - 0.016).abs() < 0.001);
        assert_eq!(time.frame(), 1);
    }

    #[test]
    fn test_dt_clamp() {
        let mut time = Time::new();
        time.update(1.0); // 1 saniye spike

        assert!(time.dt() <= DEFAULT_MAX_DT + 0.0001);
        assert!((time.raw_dt() - 1.0).abs() < 0.0001);
    }

    #[test]
    fn test_negative_dt_clamped_to_zero() {
        let mut time = Time::new();
        time.update(-0.5);

        assert_eq!(time.dt(), 0.0);
        assert_eq!(time.raw_dt(), 0.0);
    }

    #[test]
    fn test_time_scale() {
        let mut time = Time::new();
        time.set_time_scale(0.5);
        time.update(0.016);

        assert!((time.dt() - 0.008).abs() < 0.0001); // 0.016 * 0.5
        assert!((time.raw_dt() - 0.016).abs() < 0.0001);
    }

    #[test]
    fn test_time_scale_zero_is_pause() {
        let mut time = Time::new();
        time.set_time_scale(0.0);
        time.update(0.016);

        assert_eq!(time.dt(), 0.0);
        assert_eq!(time.elapsed(), 0.0);
        assert_eq!(time.frame(), 1); // Frame hâlâ sayılır
    }

    #[test]
    fn test_elapsed_accumulates() {
        let mut time = Time::new();
        for _ in 0..100 {
            time.update(0.01);
        }

        assert!((time.elapsed() - 1.0).abs() < 0.01);
        assert_eq!(time.frame(), 100);
    }

    #[test]
    fn test_fps() {
        let mut time = Time::new();
        time.update(1.0 / 60.0);
        assert!((time.fps() - 60.0).abs() < 1.0);

        time.update(0.0);
        assert_eq!(time.fps(), 0.0); // Division by zero koruması
    }

    #[test]
    fn test_custom_max_dt() {
        let mut time = Time::new();
        time.set_max_dt(1.0 / 10.0); // 100ms
        time.update(0.5);

        assert!((time.dt() - 0.1).abs() < 0.0001); // 100ms cap
    }

    #[test]
    fn test_serde_derive() {
        // serde derive doğru çalışıyor — serialize/deserialize uygulanmış
        let mut time = Time::new();
        time.update(0.016);
        time.update(0.016);

        // Clone ile roundtrip kontrolü (serde_json bağımlılık gerektirmeden)
        let cloned = time;
        assert_eq!(cloned.frame(), time.frame());
        assert!((cloned.elapsed() - time.elapsed()).abs() < 0.001);
    }

    // ─── PhysicsTime Testleri ───

    #[test]
    fn test_physics_time_basic_step() {
        let mut pt = PhysicsTime::new(60);
        assert!(!pt.should_step()); // Henüz birikim yok

        pt.accumulate(1.0 / 60.0); // Tam bir fizik adımı
        assert!(pt.should_step());

        pt.consume_step();
        assert!(!pt.should_step());
        assert_eq!(pt.step_count(), 1);
    }

    #[test]
    fn test_physics_time_multiple_steps() {
        let mut pt = PhysicsTime::new(60);
        let fixed_dt = pt.fixed_dt();
        // 3.5 adıma yetecek birikim (FP hassasiyeti için margin)
        pt.accumulate(fixed_dt * 3.5);

        let mut steps = 0;
        while pt.should_step() {
            pt.consume_step();
            steps += 1;
        }
        assert_eq!(steps, 3);
        assert_eq!(pt.step_count(), 3);
    }

    #[test]
    fn test_physics_time_spiral_of_death() {
        let mut pt = PhysicsTime::new(60);
        // 1 saniyelik spike — max 8 adım birikebilir
        pt.accumulate(1.0);

        let mut steps = 0;
        while pt.should_step() {
            pt.consume_step();
            steps += 1;
        }
        assert!(
            steps <= 8,
            "Spiral koruması: max 8 adım, bulundu: {}",
            steps
        );
    }

    #[test]
    fn test_physics_time_alpha() {
        let mut pt = PhysicsTime::new(60);
        let fixed_dt = 1.0 / 60.0;

        // 1.5 fizik adımı birikim
        pt.accumulate(fixed_dt * 1.5);
        pt.consume_step(); // 1 adım tüket
        pt.compute_alpha();

        // Kalan 0.5 adım → alpha ≈ 0.5
        assert!(
            (pt.alpha() - 0.5).abs() < 0.01,
            "Alpha ≈ 0.5: {}",
            pt.alpha()
        );
    }

    #[test]
    fn test_physics_time_elapsed() {
        let mut pt = PhysicsTime::new(60);
        for _ in 0..60 {
            pt.accumulate(1.0 / 60.0);
            while pt.should_step() {
                pt.consume_step();
            }
        }
        // 60 adım × 1/60 = 1.0s
        assert!((pt.physics_elapsed() - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_physics_time_set_hz() {
        let mut pt = PhysicsTime::new(60);
        pt.set_hz(120);
        assert!((pt.fixed_dt() - 1.0 / 120.0).abs() < 1e-6);
    }
}