From 14829f827ce63a9fad915e54cc18f5e4bb35a9e4 Mon Sep 17 00:00:00 2001 From: Stepanov Igor Date: Sat, 18 Oct 2025 00:43:13 +0300 Subject: [PATCH] fix fps settings --- src/engine/Engine.cpp | 1 + src/window/detail/SDLWindow.cpp | 16 ++++++++++++++-- src/window/detail/SDLWindow.hpp | 3 +++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/engine/Engine.cpp b/src/engine/Engine.cpp index a977f354b..71bcd580f 100644 --- a/src/engine/Engine.cpp +++ b/src/engine/Engine.cpp @@ -308,6 +308,7 @@ void Engine::nextFrame() { : settings.display.framerate.get() ); window->swapBuffers(); + // todo: process it on another thread input->pollEvents(); } diff --git a/src/window/detail/SDLWindow.cpp b/src/window/detail/SDLWindow.cpp index 01be25cd9..7277c080e 100644 --- a/src/window/detail/SDLWindow.cpp +++ b/src/window/detail/SDLWindow.cpp @@ -18,6 +18,7 @@ #include "graphics/core/ImageData.hpp" #include "graphics/core/Texture.hpp" #include "settings.hpp" +#include "util/platform.hpp" #include "window/Window.hpp" #include "window/detail/SDLInput.hpp" @@ -231,6 +232,17 @@ SDLWindow::~SDLWindow() { } void SDLWindow::swapBuffers() noexcept { + if (framerate > 0) { + auto elapsedTime = time() - prevSwap; + auto frameTime = 1.0 / framerate; + if (elapsedTime < frameTime) { + platform::sleep( + static_cast((frameTime - elapsedTime) * 1000) + ); + } + prevSwap = time(); + } + if (!SDL_GL_SwapWindow(window)) [[unlikely]] { // C++20 needed logger.error() << "Cant swap buffer: " << SDL_GetError(); } @@ -425,10 +437,10 @@ double SDLWindow::time() { } void SDLWindow::setFramerate(int framerate) { - /*todo*/ - if (!SDL_GL_SetSwapInterval(framerate)) { + if (!SDL_GL_SetSwapInterval(framerate == -1)) { logger.error() << "Failed to set framerate: " << SDL_GetError(); } + this->framerate = framerate; } // todo: move somewhere diff --git a/src/window/detail/SDLWindow.hpp b/src/window/detail/SDLWindow.hpp index 8e9f23e8a..f1b32e837 100644 --- a/src/window/detail/SDLWindow.hpp +++ b/src/window/detail/SDLWindow.hpp @@ -47,6 +47,9 @@ private: bool toClose = false; bool fullscreen = false; + double framerate = -1; + double prevSwap = 0.0; + SDL_Window *window = nullptr; SDL_Renderer *renderer = nullptr; SDL_Cursor *cursor = nullptr;