perigee/
time.rs

1use std::cmp::{PartialEq, PartialOrd};
2use std::time::Duration;
3
4use serde::{Deserialize, Serialize};
5
6/// A clock that passes time whenever it's
7/// ticked. This clock is great for pure simulation
8/// timekeeping as it doesn't need access to system-native
9/// clocks and only ticks through the provided `tick()` function.
10#[derive(
11    Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
12)]
13pub struct PassiveClock(Duration);
14
15impl PassiveClock {
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    pub fn set_seconds(&mut self, seconds: f32) {
21        self.0 = Duration::from_secs_f32(seconds);
22    }
23
24    pub fn tick(&mut self, delta_seconds: f32) {
25        self.0 = self
26            .0
27            .saturating_add(Duration::from_secs_f32(delta_seconds));
28    }
29
30    pub fn tick_reverse(&mut self, delta_seconds: f32) {
31        self.0 = self
32            .0
33            .saturating_sub(Duration::from_secs_f32(delta_seconds));
34    }
35
36    pub fn reset(&mut self) {
37        self.0 = Duration::default();
38    }
39
40    pub fn elapsed(&self) -> Duration {
41        self.0
42    }
43}