summaryrefslogtreecommitdiffhomepage
path: root/StarsEx/Clock.cpp
blob: 60e6f67a98777e269614b6f13b77908faa728bf1 (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
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
/*  Starshatter: The Open Source Project
    Copyright (c) 2021-2024, Starshatter: The Open Source Project Contributors
    Copyright (c) 2011-2012, Starshatter OpenSource Distribution Contributors
    Copyright (c) 1997-2006, Destroyer Studios LLC.
*/

#include "Clock.h"

#include <chrono>

static constexpr double NO_COMPRESSION {1.0};
static constexpr double STARTING_DELTA {1.0 / 60.0};

Clock* Clock::instance = nullptr;


Clock*
Clock::GetInstance()
{
    return instance;
}


bool
Clock::Init()
{
    if (instance == nullptr) {
        instance = new Clock();
        return instance != nullptr;
    }
    return false;
}


void
Clock::Close()
{
    if (instance != nullptr) {
        delete instance;
        instance = nullptr;
    }
}


Clock::Clock() :
    m_point {inner_clock::now()},
    m_game_elapsed {inner_clock::duration::zero()},
    m_real_elapsed {inner_clock::duration::zero()},
    m_compression {NO_COMPRESSION},
    m_delta {STARTING_DELTA},
    m_gui_delta {STARTING_DELTA},
    m_rate {0.0}
{
}


void
Clock::Set()
{
    m_point = inner_clock::now();
    m_delta = STARTING_DELTA;
    m_gui_delta = STARTING_DELTA;
}


double
Clock::Step()
{
    const auto next = inner_clock::now();
    const auto delta = next - m_point;
    m_game_elapsed += std::chrono::duration_cast<inner_clock::duration>(delta * m_compression);
    m_real_elapsed += delta;
    const std::chrono::duration<double> seconds = delta;
    m_delta = seconds.count() * m_compression;
    m_gui_delta = seconds.count();
    m_point = next;
    m_rate = 1 / m_gui_delta;
    return m_delta;
}


void
Clock::ResetGameTime()
{
    m_game_elapsed = inner_clock::duration::zero();
}


void
Clock::SkipGameTime(double seconds)
{
    const std::chrono::duration<double> skip {seconds};
    m_game_elapsed += std::chrono::duration_cast<inner_clock::duration>(skip);
}


double
Clock::Delta() const
{
    return m_delta;
}


double
Clock::GuiDelta() const
{
    return m_gui_delta;
}


double
Clock::Rate() const
{
    return m_rate;
}


double
Clock::TimeCompression() const
{
    return m_compression;
}


void
Clock::SetTimeCompression(double compression)
{
    m_compression = compression;
}