diff --git a/CMakeLists.txt b/CMakeLists.txt index 2106e3a..843c367 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,6 +19,7 @@ add_executable(breakhack src/map src/map_lua src/camera + src/timer ) target_link_libraries(breakhack diff --git a/src/main.c b/src/main.c index fce230f..a62daf5 100644 --- a/src/main.c +++ b/src/main.c @@ -10,6 +10,7 @@ #include "camera.h" #include "map.h" #include "map_lua.h" +#include "timer.h" #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 768 @@ -123,10 +124,11 @@ static void run() { bool quit = false; + Timer* fpsTimer = timer_create(); while (!quit) { - int ticks = SDL_GetTicks(); + timer_start(fpsTimer); quit = handle_events(); @@ -137,10 +139,13 @@ void run() SDL_RenderPresent(gRenderer); - ticks = SDL_GetTicks() - ticks; + int ticks = timer_get_ticks(fpsTimer); if (ticks < 1000/60) SDL_Delay((1000/60) - ticks); + timer_stop(fpsTimer); } + + timer_destroy(fpsTimer); } static diff --git a/src/timer.c b/src/timer.c new file mode 100644 index 0000000..db9b68d --- /dev/null +++ b/src/timer.c @@ -0,0 +1,33 @@ +#include +#include "util.h" +#include "timer.h" + +Timer* timer_create() +{ + Timer *t = ec_malloc(sizeof(Timer)); + t->startTime = 0; + return t; +} + +void timer_start(Timer *t) +{ + t->startTime = SDL_GetTicks(); +} + +void timer_stop(Timer *t) +{ + t->startTime = 0; +} + +unsigned int timer_get_ticks(Timer *t) +{ + if (!t->startTime) + return 0; + + return SDL_GetTicks() - t->startTime; +} + +void timer_destroy(Timer *t) +{ + free(t); +} diff --git a/src/timer.h b/src/timer.h new file mode 100644 index 0000000..32f4624 --- /dev/null +++ b/src/timer.h @@ -0,0 +1,14 @@ +#ifndef TIMER_H_ +#define TIMER_H_ + +typedef struct { + unsigned int startTime; +} Timer; + +Timer* timer_create(); +void timer_start(Timer*); +void timer_stop(Timer*); +unsigned int timer_get_ticks(Timer*); +void timer_destroy(Timer*); + +#endif // TIMER_H_