diff --git a/src/Application.cpp b/src/Application.cpp index 8e7457e..e287eb0 100644 --- a/src/Application.cpp +++ b/src/Application.cpp @@ -17,6 +17,10 @@ Application Application::app; void Application::run() { bool quit {false}; while (!quit) { + // measure start time for this tick + auto start = SDL_GetTicks(); + + // handle events SDL_Event event; if (SDL_PollEvent(&event)) { switch (event.type) { @@ -30,12 +34,29 @@ void Application::run() { quit = handle_event(event); } } + + // update windows for (const Window& window : Window::windows()) { window.update(); } + + // run any custom actions for (RunLoopAction action : _actions) { action(); } + + // measure end time for this tick + auto end = SDL_GetTicks(); + + // calculate how long this tick took, and how much is left + // if we want to maintain a steady fps + auto elapsed = end - start; + auto available = 1000 / _fps - elapsed; + + // if there's any time left, sleep that much + if (available > 0) { + // SDL_Delay(available); + } } } diff --git a/src/Application.hpp b/src/Application.hpp index c5015a2..d84972d 100644 --- a/src/Application.hpp +++ b/src/Application.hpp @@ -36,11 +36,15 @@ namespace sc { void add_run_loop_action(RunLoopAction action); void remove_run_loop_action(RunLoopAction action); + int fps() const { return _fps; } + void fps(int fps) { _fps = fps; } + private: static Application app; std::map> _event_handlers; std::vector _actions; + int _fps {60}; bool handle_event(const SDL_Event& event); };