My game loop currently looks something like this:
while (!quit) {
takeInput(); // Input is sampled however fast loop can run
time_now = get_time()
time_passed += (time_now - time_prev);
time_prev = time_now;
while (time_passed > SOME_TIME) {
update(); // Update is done over fixed time-step for determinism
time_passed -= SOME_TIME_STEP; // This time step is less than or equal to SOME_TIME
}
render(time_passed); // Render using interpolation from previously updated position and velocity
}
Basically, I take input as fast as I can, run the movement and physics only in discreet chunks of time after certain period and interpolate the difference in the renderer. The renderer is set to draw at Vsync (using SDL_GL_SetSwapInterval(-1)
) and currently, the value of SOME_TIME is set so that update()
runs at half of display's refresh frequency (but with a minimum bound of SOME_TIME_STEP which is set to 5 millisecond).
The problem is that I am running the renderer as fast as I can which is submitting frames continuously. Because I am currently loading a test level, the game loop is basically finishing up in a few microseconds (unless there is something wrong with how I am calculating time too). As far as I understand, my program will submit frames to the driver way faster than it is going to draw (because of Vsync) and this should lead to some type of periodic locking up/lagging.
So my question is, how to I prevent this? Should I put the render call in a time bound loop too just like update()
? Should I call sleep()
manually instead of relying on graphics driver for Vsync?
sleep
guarantees that the thread will sleep at least the amount of time you ask for, not exactly the amount of time you ask for. The delay is generally longer than what you ask for, so it should not be used. Perhaps limiting the amount of render call to one very 1/60 th of a second would be enough? \$\endgroup\$