-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoroutines.h
96 lines (80 loc) · 2.04 KB
/
coroutines.h
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
#ifndef HLAM_COROUTINES_H
#define HLAM_COROUTINES_H
#include <algorithm>
namespace hlam {
// Timer checks whether time is passed or not.
class Timer {
public:
float time;
Timer(float time, float elapsed = 0);
bool IsPassed() const;
void Update(float dt);
void Reset();
float Elapsed() const;
void Finish();
float Percentage() const;
private:
float elapsed;
};
// OneShot checks whether time is passed or not and returns true only once
class OneShot {
const float time;
float elapsed;
bool passed = false;
public:
OneShot(float time);
bool IsPassed();
void Update(float dt);
void Reset();
};
// Cooldown is a Timer with auto reset after passing
class Cooldown {
const float time;
float elapsed;
public:
Cooldown(float time, float init);
Cooldown(float time);
bool Invoke();
void Update(float dt);
void Reset();
};
} // namespace hlam
#endif // HLAM_COROUTINES_H
#ifdef HLAM_COROUTINES_IMPLEMENTATION
namespace hlam {
Timer::Timer(float time, float elapsed) : time(time), elapsed(elapsed) {}
bool Timer::IsPassed() const { return elapsed >= time; }
void Timer::Update(float dt) { elapsed += dt; }
void Timer::Reset() { elapsed = 0; }
float Timer::Elapsed() const { return elapsed; }
void Timer::Finish() { elapsed = time; }
float Timer::Percentage() const { return std::clamp(elapsed / time, 0.0f, 1.0f); }
OneShot::OneShot(float time) : time(time), elapsed(0.0f) {}
bool OneShot::IsPassed() {
if (passed) {
return false;
}
if (elapsed >= time) {
passed = true;
return true;
}
return false;
}
void OneShot::Update(float dt) { elapsed += dt; }
void OneShot::Reset() {
elapsed = 0.0f;
passed = false;
}
Cooldown::Cooldown(float time) : time(time), elapsed(0) {}
Cooldown::Cooldown(float time, float init) : time(time), elapsed(init) {}
bool Cooldown::Invoke() {
if (elapsed >= time) {
elapsed = 0;
return true;
}
return false;
}
void Cooldown::Update(float dt) { elapsed += dt; }
void Cooldown::Reset() { elapsed = 0; }
} // namespace hlam
#endif // HLAM_COROUTINES_IMPLEMENTATION