Skip to main content

elevator_core/
time.rs

1//! Tick-to-wall-clock time conversion.
2
3use std::time::Duration;
4
5/// Converts between simulation ticks and wall-clock time.
6///
7/// The core simulation is purely tick-based for determinism.
8/// Game integrations use `TimeAdapter` to display real-time
9/// values and schedule events in human-readable units.
10#[derive(Debug, Clone, Copy)]
11pub struct TimeAdapter {
12    /// Ticks per real-time second.
13    ticks_per_second: f64,
14}
15
16impl TimeAdapter {
17    /// Create a new adapter with the given tick rate.
18    #[must_use]
19    pub const fn new(ticks_per_second: f64) -> Self {
20        Self { ticks_per_second }
21    }
22
23    /// Convert ticks to seconds.
24    #[allow(clippy::cast_precision_loss)] // tick counts within f64 range
25    #[must_use]
26    pub fn ticks_to_seconds(&self, ticks: u64) -> f64 {
27        ticks as f64 / self.ticks_per_second
28    }
29
30    /// Convert seconds to ticks, rounded to nearest.
31    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // intentional rounding
32    #[must_use]
33    pub fn seconds_to_ticks(&self, seconds: f64) -> u64 {
34        (seconds * self.ticks_per_second).round() as u64
35    }
36
37    /// Convert a `Duration` to ticks, rounded to nearest.
38    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // intentional rounding
39    #[must_use]
40    pub fn duration_to_ticks(&self, duration: Duration) -> u64 {
41        (duration.as_secs_f64() * self.ticks_per_second).round() as u64
42    }
43
44    /// Convert ticks to a `Duration`.
45    #[allow(clippy::cast_precision_loss)] // tick counts within f64 range
46    #[must_use]
47    pub fn ticks_to_duration(&self, ticks: u64) -> Duration {
48        Duration::from_secs_f64(ticks as f64 / self.ticks_per_second)
49    }
50
51    /// The configured tick rate.
52    #[must_use]
53    pub const fn ticks_per_second(&self) -> f64 {
54        self.ticks_per_second
55    }
56}