2020-08-29 04:33:20 +00:00
|
|
|
use crate::span;
|
2019-01-12 15:57:19 +00:00
|
|
|
use std::{
|
|
|
|
thread,
|
2019-06-09 18:14:02 +00:00
|
|
|
time::{Duration, Instant},
|
2019-01-12 15:57:19 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
const CLOCK_SMOOTHING: f64 = 0.9;
|
|
|
|
|
|
|
|
pub struct Clock {
|
2019-06-09 18:14:02 +00:00
|
|
|
last_sys_time: Instant,
|
2019-01-12 15:57:19 +00:00
|
|
|
last_delta: Option<Duration>,
|
|
|
|
running_tps_average: f64,
|
2019-06-09 18:14:02 +00:00
|
|
|
compensation: f64,
|
2019-01-12 15:57:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Clock {
|
2019-07-01 20:42:43 +00:00
|
|
|
pub fn start() -> Self {
|
2019-01-12 15:57:19 +00:00
|
|
|
Self {
|
2019-06-09 18:14:02 +00:00
|
|
|
last_sys_time: Instant::now(),
|
2019-01-12 15:57:19 +00:00
|
|
|
last_delta: None,
|
|
|
|
running_tps_average: 0.0,
|
2019-06-09 18:14:02 +00:00
|
|
|
compensation: 1.0,
|
2019-01-12 15:57:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn get_tps(&self) -> f64 { 1.0 / self.running_tps_average }
|
2019-01-12 15:57:19 +00:00
|
|
|
|
2019-04-29 20:37:19 +00:00
|
|
|
pub fn get_last_delta(&self) -> Duration {
|
2019-07-01 20:42:43 +00:00
|
|
|
self.last_delta.unwrap_or_else(|| Duration::new(0, 0))
|
2019-04-29 20:37:19 +00:00
|
|
|
}
|
2019-01-12 15:57:19 +00:00
|
|
|
|
2020-02-01 20:39:39 +00:00
|
|
|
pub fn get_avg_delta(&self) -> Duration { Duration::from_secs_f64(self.running_tps_average) }
|
2019-01-12 15:57:19 +00:00
|
|
|
|
|
|
|
pub fn tick(&mut self, tgt: Duration) {
|
2020-09-07 04:59:16 +00:00
|
|
|
span!(_guard, "tick", "Clock::tick");
|
2019-06-09 18:14:02 +00:00
|
|
|
let delta = Instant::now().duration_since(self.last_sys_time);
|
2019-01-12 15:57:19 +00:00
|
|
|
|
2019-05-17 09:22:32 +00:00
|
|
|
// Attempt to sleep to fill the gap.
|
2019-01-12 15:57:19 +00:00
|
|
|
if let Some(sleep_dur) = tgt.checked_sub(delta) {
|
2019-06-09 18:14:02 +00:00
|
|
|
if self.running_tps_average != 0.0 {
|
|
|
|
self.compensation =
|
|
|
|
(self.compensation + (tgt.as_secs_f64() / self.running_tps_average) - 1.0)
|
|
|
|
.max(0.0)
|
|
|
|
}
|
|
|
|
|
|
|
|
let sleep_secs = sleep_dur.as_secs_f64() * self.compensation;
|
|
|
|
if sleep_secs > 0.0 {
|
|
|
|
thread::sleep(Duration::from_secs_f64(sleep_secs));
|
|
|
|
}
|
2019-01-12 15:57:19 +00:00
|
|
|
}
|
|
|
|
|
2019-06-09 18:14:02 +00:00
|
|
|
let delta = Instant::now().duration_since(self.last_sys_time);
|
2019-01-12 15:57:19 +00:00
|
|
|
|
2019-06-09 18:14:02 +00:00
|
|
|
self.last_sys_time = Instant::now();
|
2019-01-12 15:57:19 +00:00
|
|
|
self.last_delta = Some(delta);
|
2019-04-22 16:50:15 +00:00
|
|
|
self.running_tps_average = if self.running_tps_average == 0.0 {
|
|
|
|
delta.as_secs_f64()
|
|
|
|
} else {
|
2019-04-29 20:37:19 +00:00
|
|
|
CLOCK_SMOOTHING * self.running_tps_average
|
|
|
|
+ (1.0 - CLOCK_SMOOTHING) * delta.as_secs_f64()
|
2019-04-22 16:50:15 +00:00
|
|
|
};
|
2019-01-12 15:57:19 +00:00
|
|
|
}
|
|
|
|
}
|