Skip to content

Instantly share code, notes, and snippets.

@pabloasanchez
Created January 10, 2025 11:20
Show Gist options
  • Save pabloasanchez/b8882d8020b72a695c3f7f8cc25ad9b1 to your computer and use it in GitHub Desktop.
Save pabloasanchez/b8882d8020b72a695c3f7f8cc25ad9b1 to your computer and use it in GitHub Desktop.
SDL2/C frame limiter
// From: https://cplusplus.com/forum/beginner/94946/
// By: https://cplusplus.com/user/Disch/
#define FPS 60
int frame_length = 1000 / FPS; // Number of ms between frames. 17 gives you approx 60 FPS (1000 / 60)
Uint32 next_frame; // Timestamp that next frame is to occur
int skipped_frames; // Number of frames we have skipped
// Configurable (optionally const) value to determine when to start "skipping" frames.
// I.e., we'll start skipping after we fall this many frames behind
int skip_frames_behind = 5;
// Configurable (optionally const) value to determine how many frames we allow it to
// "fall behind" before we give up and resync.
// Higher values = Game opts to run 'slower'
// Lower values = Game opts to run 'choppier'
int max_frame_skip = 5;
void sdl_frame_limit(void (*fn)(bool)) {
Sint32 delta = (Sint32) (SDL_GetTicks() - next_frame); // get time between next frame and now
if (delta < 0) { // if it's not yet time for the next frame... wait and sleep for a bit
SDL_Delay(1);
return;
}
next_frame += frame_length; // otherwise, we're going to do at least 1 frame. increment our time counter
if (delta >= (frame_length * skip_frames_behind)) { // if we have fallen too far behind.. we need to start skipping frames to catch up
if (skipped_frames >= max_frame_skip) { // if we have already skipped the maximum number of times. "Give up" and just resync
next_frame = SDL_GetTicks();
skipped_frames = 0;
} else {
++skipped_frames; // otherwise, skip this frame
fn(false); // by "skip", I mean "run logic, but don't draw".
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment