-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimer.cc
89 lines (69 loc) · 1.46 KB
/
timer.cc
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
#include "timer.hh"
#include <iostream>
#include <algorithm>
vector<Timer*> Timer::timers;
Timer::Timer(timer_callback callback) :
callback(callback),
expired(true)
{
timers.push_back(this);
}
Timer::~Timer() {
timers.erase(find(timers.begin(), timers.end(), this));
}
void Timer::Set(float timeout, bool periodic) {
this->startTime = SDL_GetTicks();
this->timeout = timeout;
this->periodic = periodic;
this->expired = false;
}
void Timer::Check() {
if (this->expired || this->paused)
return;
float elapsed = (SDL_GetTicks() - this->startTime) / 1000.0;
if (elapsed >= this->timeout) {
if (this->periodic)
this->startTime = SDL_GetTicks();
this->callback(elapsed);
this->expired = !this->periodic;
}
}
void Timer::Pause() {
if (expired)
return;
this->pauseTime = SDL_GetTicks();
this->paused = true;
}
void Timer::Unpause() {
if (this->expired)
return;
if (this->paused)
this->startTime += SDL_GetTicks() - this->pauseTime;
this->paused = false;
}
bool Timer::TogglePause() {
if (this->paused)
this->Unpause();
else
this->Pause();
return this->paused;
}
bool Timer::IsPaused() {
return this->paused;
}
void Timer::CheckAll() {
for (auto t : timers)
t->Check();
}
void Timer::PauseAll() {
for (auto t : timers)
t->Pause();
}
void Timer::UnpauseAll() {
for (auto t : timers)
t->Unpause();
}
void Timer::TogglePauseAll() {
for (auto t : timers)
t->TogglePause();
}