diff options
author | WBoerenkamps <wrj.boerenkamps@student.avans.nl> | 2024-12-04 10:26:32 +0100 |
---|---|---|
committer | WBoerenkamps <wrj.boerenkamps@student.avans.nl> | 2024-12-04 10:26:32 +0100 |
commit | c7c4cc0e3b1a3152256bc8ebf6494c19519538db (patch) | |
tree | 9c7a2201d94c8a51bb93de7cea45a9f14e2da5ea /src/crepe/api/LoopTimer.cpp | |
parent | f137451d0edb13543919cf2d1a3af379cb3a1485 (diff) |
looptimer no singleton
Diffstat (limited to 'src/crepe/api/LoopTimer.cpp')
-rw-r--r-- | src/crepe/api/LoopTimer.cpp | 37 |
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 { |