blob: f94e24b529525b793b13f6d481c09400603b25d2 (
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
|
#include <chrono>
#include "../facade/SDLContext.h"
#include "../util/Log.h"
#include "LoopTimer.h"
using namespace crepe;
LoopTimer::LoopTimer() { dbg_trace(); }
LoopTimer & LoopTimer::get_instance() {
static LoopTimer instance;
return instance;
}
void LoopTimer::start() {
this->last_frame_time = std::chrono::steady_clock::now();
this->elapsed_time = std::chrono::milliseconds(0);
this->elapsed_fixed_time = std::chrono::milliseconds(0);
this->delta_time = std::chrono::milliseconds(0);
}
void LoopTimer::update() {
auto current_frame_time = std::chrono::steady_clock::now();
// Convert to duration in seconds for delta time
this->delta_time = std::chrono::duration_cast<std::chrono::duration<double>>(
current_frame_time - last_frame_time);
if (this->delta_time > this->maximum_delta_time) {
this->delta_time = this->maximum_delta_time;
}
this->actual_fps = 1.0 / this->delta_time.count();
this->delta_time *= this->game_scale;
this->elapsed_time += this->delta_time;
this->last_frame_time = current_frame_time;
}
double LoopTimer::get_delta_time() const { return this->delta_time.count(); }
double LoopTimer::get_current_time() const { return this->elapsed_time.count(); }
void LoopTimer::advance_fixed_update() { this->elapsed_fixed_time += this->fixed_delta_time; }
double LoopTimer::get_fixed_delta_time() const { return this->fixed_delta_time.count(); }
void LoopTimer::set_target_fps(int fps) {
this->target_fps = fps;
// target time per frame in seconds
this->frame_target_time = std::chrono::duration<double>(1.0) / target_fps;
}
int LoopTimer::get_fps() const { return this->actual_fps; }
void LoopTimer::set_game_scale(double value) { this->game_scale = value; }
double LoopTimer::get_game_scale() const { return this->game_scale; }
void LoopTimer::enforce_frame_rate() {
std::chrono::steady_clock::time_point current_frame_time
= std::chrono::steady_clock::now();
std::chrono::milliseconds frame_duration
= std::chrono::duration_cast<std::chrono::milliseconds>(current_frame_time
- this->last_frame_time);
if (frame_duration < this->frame_target_time) {
std::chrono::milliseconds delay_time
= std::chrono::duration_cast<std::chrono::milliseconds>(this->frame_target_time
- frame_duration);
if (delay_time.count() > 0) {
SDLContext::get_instance().delay(delay_time.count());
}
}
}
double LoopTimer::get_lag() const {
return (this->elapsed_time - this->elapsed_fixed_time).count();
}
|