Skip to content
systemcoding.dev
GPU

Implement a Fixed Timestep Game Loop With GLFW

Build a game loop in C with GLFW 3.4 that updates physics at a fixed 60 Hz step, renders at any rate, and interpolates between states for smooth motion.

7 min read
Summarize in AI
Flat illustration of a GPU die of compute units with one thread block lit, with the C, NVIDIA and Vulkan logos.

A bouncing ball moves 5 pixels per frame on your machine. On a friend's machine with a 144 Hz display it moves 5 pixels per frame, 144 times a second, and the ball is more than twice as fast. A loop that advances the simulation once per rendered frame ties the speed of your game to the speed of the hardware, and physics that depends on the frame rate also behaves differently from run to run. The standard cure is a fixed timestep: the simulation always advances in equal slices, and the renderer draws as often as it can. This post builds that loop in C with GLFW 3.4, explains the accumulator that makes it work, and adds interpolation so motion stays smooth when the two rates do not match. It continues from the basic GLFW window.

Three loops, in order of quality

The loops below differ in how they measure time. Each is wrong in a way that teaches the next one.

The first is the naive loop. It updates once per frame:

naive_loop.cc
while (!glfwWindowShouldClose(window)) {
    glfwPollEvents();
    x += 5.0f;          // 5 units per frame, however long the frame took
    render(x);
    glfwSwapBuffers(window);
}

The speed is 5 units times the frame rate. At 60 frames per second the object moves 300 units per second, and at 144 frames per second, 720.

The second scales by the elapsed time, the variable timestep:

variable_loop.cc
double previous = glfwGetTime();
while (!glfwWindowShouldClose(window)) {
    double now = glfwGetTime();
    double dt = now - previous;
    previous = now;

    glfwPollEvents();
    x += 300.0f * (float)dt;   // 300 units per second
    render(x);
    glfwSwapBuffers(window);
}

This fixes the speed. The object covers 300 units per second at any frame rate. It does not fix everything: physics that depends on dt in a nonlinear way, such as a spring or a jump arc computed by integrating velocity and gravity, gives slightly different results at different step sizes. A character that jumps 2.00 meters at 60 Hz may reach 1.96 at 30 Hz, and a collision test run once per large step can let a fast object tunnel through a thin wall. A rare long frame, say 200 ms after the window was dragged, injects one huge step.

The third is the fixed timestep, and it keeps the physics deterministic.

The accumulator

The idea: time arrives in uneven pieces, but the simulation consumes it in equal slices. Keep a variable, the accumulator, holding the time that has passed but has not been simulated yet. Each frame add the elapsed time to it. Then, while it holds at least one full step, run one simulation step and subtract the step from it. Whatever remains, less than one step, carries to the next frame.

fixed_loop.cc
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include <stdio.h>

typedef struct { float x, v; } State;

static void update(State* s, float dt) {
    s->x += s->v * dt;
    if (s->x > 10.0f) { s->x = 10.0f; s->v = -s->v; }
    if (s->x < 0.0f)  { s->x = 0.0f;  s->v = -s->v; }
}

int main(void) {
    if (!glfwInit()) return 1;
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    GLFWwindow* window = glfwCreateWindow(800, 600, "Fixed step", NULL, NULL);
    if (!window) { glfwTerminate(); return 1; }
    glfwMakeContextCurrent(window);
    gladLoadGL(glfwGetProcAddress);
    glfwSwapInterval(1);

    const double step = 1.0 / 60.0;
    double accumulator = 0.0;
    double previous = glfwGetTime();

    State state = { 0.0f, 4.0f };
    unsigned long updates = 0;

    while (!glfwWindowShouldClose(window)) {
        double now = glfwGetTime();
        double frame = now - previous;
        previous = now;
        if (frame > 0.25) frame = 0.25;
        accumulator += frame;

        glfwPollEvents();

        while (accumulator >= step) {
            update(&state, (float)step);
            accumulator -= step;
            updates++;
        }

        glClearColor(0.1f, 0.1f, 0.15f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(window);
    }

    printf("simulated %lu steps, x = %.3f\n", updates, state.x);
    glfwTerminate();
    return 0;
}

Two lines deserve attention. The clamp if (frame > 0.25) frame = 0.25 prevents the spiral of death: if one frame takes a long time, the accumulator would hold many steps, the inner loop would run all of them, and that slow catch-up would make the next frame even longer. Capping the incoming time throws away time rather than falling behind forever. And the inner while can run zero, one or several times per frame, which is how a fixed 60 Hz simulation coexists with a 144 Hz renderer, where most frames run zero steps, or with a 30 Hz renderer, where each frame runs two.

Work an example. The step is 1/60 s, about 0.01667 s, and the display runs at 144 Hz, so frames arrive about every 0.00694 s. Over one second there are 144 frames and the inner loop runs exactly 60 times in total, regardless of how those 60 steps distribute across the frames. A 4 units per second ball therefore advances 4 units in one second whichever display it runs on. If the program runs for exactly 10 seconds, it prints something close to the following, and the exact count depends on when the window was closed:

Text
simulated 600 steps, x = 0.000

The numbers vary with timing, but updates divided by elapsed seconds is always about 60, which is the point.

Interpolation removes the stutter

One flaw remains. At the end of a frame the accumulator holds a fraction of a step, between 0 and step, time that has passed but is not reflected in the state. If the renderer draws the state as it is, motion stutters: at 144 Hz, some frames show a new simulation step and others repeat the previous picture, and the on-screen position advances in jumps of uneven spacing.

The cure is to render a position between the previous and the current state, weighted by how far through the next step you are. That weight is alpha = accumulator / step, a value from 0 to 1.

interpolate.cc
State previous_state = state;

while (accumulator >= step) {
    previous_state = state;
    update(&state, (float)step);
    accumulator -= step;
}

float alpha = (float)(accumulator / step);
float render_x = previous_state.x * (1.0f - alpha) + state.x * alpha;
draw_ball(render_x);

Keep the last two states. Interpolating between them means the picture lags the simulation by up to one step, about 16 ms, and in exchange moves smoothly at any display rate. With the ball at 2.0 in the previous state and 2.0667 in the current one, drawn when the accumulator holds a quarter of a step, the render position is 2.0 * 0.75 + 2.0667 * 0.25 = 2.0167.

The alternative to interpolating is extrapolating, drawing ahead of the state using the velocity. It removes the lag and introduces overshoot when the object turns around. Interpolation is the safer default.

Input and the fixed step

Input events arrive between frames, but the simulation advances in steps. Sample input once per frame, before the inner loop, and use the same sampled value for every step in that frame. Poll with glfwPollEvents() at the top, as above, and read key state inside update, or copy it into the state struct first. A one-shot action, such as a jump press, should be latched by a key callback and consumed by the first step that runs, or a frame that runs zero steps would drop it. A flag set by the callback and cleared by update does that:

latch.cc
static bool jump_requested = false;

static void on_key(GLFWwindow* w, int key, int sc, int action, int mods) {
    if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) jump_requested = true;
}

static void update(State* s, float dt) {
    if (jump_requested) { s->v += 5.0f; jump_requested = false; }
    // ...
}

Without the latch, a tap on a frame that ran no step is lost.

Choosing the step

60 Hz is a convention that suits most games, since it matches the common display refresh and divides evenly into 30. A physics-heavy game may choose 120 Hz or higher for stability, and a slow strategy game may choose 20. The step is a design decision about accuracy, not a measurement, so pick the largest step at which your fastest object cannot cross your thinnest wall in one step. If a bullet moves 600 units per second and walls are 5 units thick, a step of 1/60 s moves it 10 units, which skips the wall, and a step of 1/240 s moves it 2.5 units. A larger step is cheaper and a smaller one is more accurate, and the accumulator lets you change the number in one line.

Timing source

glfwGetTime returns seconds since glfwInit as a double, measured with the highest resolution timer the platform offers. It is monotonic in practice, so it never goes backward when the system clock changes, which is why a loop should use it and not the wall clock from time(). If you need the raw counter, glfwGetTimerValue and glfwGetTimerFrequency return a 64-bit tick count and its rate in ticks per second, so subtract tick values before converting to avoid losing precision on long sessions.

The loop is described in more detail by the GLFW time documentation for the clock functions used here.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.