summaryrefslogtreecommitdiff
path: root/engine-ecs/src/time.rs
blob: 3f888cbf99d5f5fd56cfd0ea25f0e8e4ce185bf4 (plain)
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
use std::ops::Deref;
use std::time::{Duration, Instant};

use engine_ecs_macros::Sole;

use crate::sole::Single;

#[derive(Debug, Sole)]
#[non_exhaustive]
pub struct Time
{
    /// Time passed since the beginning of the previous tick.
    pub delta_time: Duration,

    /// Time at the beginning of the current tick.
    pub tick_begin: Option<Instant>,
}

impl Deref for Single<'_, Time>
{
    type Target = Time;

    fn deref(&self) -> &Self::Target
    {
        let Ok(time) = self.get() else {
            // Time is always created by World::new
            unreachable!();
        };

        time
    }
}

pub(crate) fn update(time: &mut Time)
{
    let current_time = Instant::now();

    let tick_begin = time.tick_begin.get_or_insert(current_time);

    time.delta_time = current_time.duration_since(*tick_begin);

    time.tick_begin = Some(current_time);
}