-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameLoop.cpp
More file actions
82 lines (63 loc) · 1.85 KB
/
GameLoop.cpp
File metadata and controls
82 lines (63 loc) · 1.85 KB
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
#include "GameLoop.hpp"
#include <algorithm>
namespace Caffeine {
GameLoop::GameLoop(const GameLoopConfig& config)
: m_config(config) {
}
GameLoop::~GameLoop() {
}
void GameLoop::init() {
if (m_state != GameState::Init) return;
m_state = GameState::Running;
m_accumulator = 0.0;
m_elapsedTime = 0.0;
m_alpha = 0.0;
m_frameCount = 0;
}
void GameLoop::tick(f64 deltaTime) {
if (m_state != GameState::Running && m_state != GameState::Paused) return;
if (m_callbacks) m_callbacks->onBeginFrame();
if (onBeginFrame) onBeginFrame();
deltaTime = std::min(deltaTime, m_config.maxFrameTime);
m_elapsedTime += deltaTime;
if (m_state == GameState::Running) {
m_accumulator += deltaTime;
while (m_accumulator >= m_config.fixedDeltaTime) {
processFixedUpdate(m_config.fixedDeltaTime);
m_accumulator -= m_config.fixedDeltaTime;
}
if (m_config.interpolation) {
m_alpha = m_accumulator / m_config.fixedDeltaTime;
} else {
m_alpha = 0.0;
}
}
if (m_callbacks) m_callbacks->onRender(m_alpha);
if (onRender) onRender(m_alpha);
if (m_callbacks) m_callbacks->onEndFrame();
if (onEndFrame) onEndFrame();
m_frameCount++;
}
void GameLoop::pause() {
if (m_state == GameState::Running) {
m_state = GameState::Paused;
}
}
void GameLoop::resume() {
if (m_state == GameState::Paused) {
m_state = GameState::Running;
}
}
void GameLoop::shutdown() {
if (m_state == GameState::Running || m_state == GameState::Paused) {
m_state = GameState::Shutdown;
}
}
void GameLoop::setCallbacks(IGameCallbacks* callbacks) {
m_callbacks = callbacks;
}
void GameLoop::processFixedUpdate(f64 dt) {
if (m_callbacks) m_callbacks->onFixedUpdate(dt);
if (onFixedUpdate) onFixedUpdate(dt);
}
}