From dbecd7fd9c2438f565dea4faa4a5ea2baa3a7781 Mon Sep 17 00:00:00 2001 From: Simon Gellis Date: Sat, 19 Oct 2024 21:05:56 -0400 Subject: [PATCH] Fix sleep timing --- game.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/game.c b/game.c index c9d9b0a..2555583 100644 --- a/game.c +++ b/game.c @@ -6,10 +6,16 @@ int sleepNanos(long int ns) { struct timespec time; + if (ns < 0) return; time.tv_sec = ns / 1000000000; time.tv_nsec = ns % 1000000000; return nanosleep(&time, NULL); } +long int tickNs() { + struct timespec time; + clock_gettime(CLOCK_MONOTONIC, &time); + return (time.tv_sec * 1000000000) + time.tv_nsec; +} typedef struct { GraphicsContext *gfx; @@ -46,17 +52,17 @@ int runGame(VB *sim, GraphicsContext *gfx) { gfxUpdateLeftEye(gfx, LEFT_EYE_DEFAULT); gfxUpdateRightEye(gfx, RIGHT_EYE_DEFAULT); - prevTicks = SDL_GetTicks64(); while (1) { clocks = MAX_STEP_CLOCKS; + prevTicks = tickNs(); vbEmulate(sim, &clocks); - ticks = SDL_GetTicks64(); + ticks = tickNs(); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { return 0; } } - sleepNanos(((MAX_STEP_CLOCKS - clocks) * 50) - (ticks - prevTicks) * 1000); + sleepNanos(((MAX_STEP_CLOCKS - clocks) * 50) - (ticks - prevTicks)); prevTicks = ticks; } }