Improve loop with fps control

This commit is contained in:
2026-05-20 21:47:25 +01:00
parent 6ff16e3db4
commit 2bff3eb93f
5 changed files with 54 additions and 29 deletions
+23 -10
View File
@@ -252,26 +252,35 @@ struct App {
current_scene_id = scene_pool.acquire(loading_scene);
}
void loop() {
const uint64_t TARGET_NS = 1e9 / 60;
void set_fps(float fps) {
this->fps = fps;
target_frame_time = 1e9 / fps;
}
uint64_t time_a = window.get_time();
uint64_t time_b = window.get_time();
uint64_t get_fps() const {
return fps;
}
void loop() {
uint64_t frame_start = window.get_time();
uint64_t frame_end = window.get_time();
uint64_t previous_frame_end = 0;
while (running) {
time_a = window.get_time();
uint64_t frame_time = time_a - time_b;
frame_start = window.get_time();
uint64_t frame_time = frame_start - frame_end;
if (frame_time <= TARGET_NS) {
if (frame_time <= target_frame_time) {
struct timespec req;
req.tv_sec = 0;
req.tv_nsec = TARGET_NS - frame_time;
req.tv_nsec = target_frame_time - frame_time;
nanosleep(&req, nullptr);
}
time_b = window.get_time();
previous_frame_end = frame_end;
frame_end = window.get_time();
uint64_t dt = window.delta_time();
float dt = frame_end - previous_frame_end;
Scene *scene = scene_pool[current_scene_id];
@@ -329,6 +338,10 @@ struct App {
window.clear();
}
}
private:
uint64_t fps = 60;
uint64_t target_frame_time = 1e9 / fps;
};
} // namespace app