Search code examples
c++ceventssdl

Using SDL_PollEvent vs SDL_PumpEvents


I've been using SDL for a while now, but now it seems I've been doing things the wrong way when working with keyboard events.

Normally my main loop looks something like this:

int main() {
    SDL_Init(SDL_INIT_VIDEO);
    /* Some video system initializations */

    /* Main loop */
    for(;;) {
        SDL_PumpEvents();
        const unsigned char *key = SDL_GetKeyboardState(nullptr);

        /* Do something with the keys pressed */
    }
}

... and this has worked fine for me. But I've recently looked at some code examples, and technically all of them use a different pattern:

int main() {
    SDL_Init(SDL_INIT_VIDEO);
    /* Some video system initializations */

    /* Main loop */
    for(;;) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            /* switch/case to know keys pressed */
        }
    }
}

So looking at SDL documentation I found that SDL_PollEvent does call SDL_PumpEvents. SDL_PollEvent reference

And what SDL_PumpEvents does is to gather the state of all input devices to generate event objets. SDL_PumpEvents reference

So in the first example, I'm not flushing the event queue, so why does it works without crashing? Is the second pattern the correct way of getting input state?


Solution

  • While PumpEvents modifies the global keyboard and mouse state, its precision may be not enough. Consider what happens when you have the mouse pressed, moved and released all in single frame - with PumpEvents you'll get the last position and 'released' state, but not the position of the first click or even the click event itself. It's the same for the keyboard - you get the 'latest' state but not the previous states of the keys in the order they were pressed/released. There are also a lot of 'special' events like window events, joysticks (SDL has an optional high-frequency background thread to poll the joystick and place events in the queue) and even hotplug events for audio devices and joysticks - you can't get that without inspecting the event queue.

    Your program doesn't crash on overflow because SDL has an upper limit on how many events it can store in the queue - currently 65535.