aboutsummaryrefslogtreecommitdiff
path: root/src/crepe/api/LoopTimer.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/crepe/api/LoopTimer.cpp')
-rw-r--r--src/crepe/api/LoopTimer.cpp37
1 files changed, 18 insertions, 19 deletions
diff --git a/src/crepe/api/LoopTimer.cpp b/src/crepe/api/LoopTimer.cpp
index 15a0e3a..d0a19d7 100644
--- a/src/crepe/api/LoopTimer.cpp
+++ b/src/crepe/api/LoopTimer.cpp
@@ -9,10 +9,6 @@ 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();
@@ -56,22 +52,25 @@ 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());
- }
- }
+ auto current_frame_time = std::chrono::steady_clock::now();
+ auto frame_duration = current_frame_time - this->last_frame_time;
- this->last_frame_time = current_frame_time;
+ if (frame_duration < this->frame_target_time) {
+ auto remaining_time = this->frame_target_time - frame_duration;
+
+ // Sleep for most of the remaining time using SDLContext
+ if (remaining_time > std::chrono::microseconds(2000)) { // 2ms threshold
+ SDLContext::get_instance().delay(
+ std::chrono::duration_cast<std::chrono::milliseconds>(remaining_time).count());
+ }
+
+ // Busy-wait for the last tiny remaining duration
+ while (std::chrono::steady_clock::now() - current_frame_time < remaining_time) {
+ // Busy wait
+ }
+ }
+
+ this->last_frame_time = std::chrono::steady_clock::now(); // Update frame time
}
double LoopTimer::get_lag() const {