gameprogcpp / code

Game Programming in C++ Code
Other
1.01k stars 354 forks source link

SDL_GetKeyboardState called every frame #69

Open nickenchev opened 1 month ago

nickenchev commented 1 month ago

Very minor detail.

The SDL documentation states the following: "The pointer returned is a pointer to an internal SDL array. It will be valid for the whole lifetime of the application and should not be freed by the caller." https://wiki.libsdl.org/SDL2/SDL_GetKeyboardState

This is very common as most SDL tutorials seem to want to call it every iteration of the game-loop, so the idea of having to constantly call it keeps getting propagated into every single SDL tutorial. If the SDL team decides to perform some more work in this function, I bet a whole bunch of SDL based applications would feel a performance hit.

chalonverse commented 1 month ago

That’s true — the funny thing is that other parts of the SDL implementation actually also just goes ahead and calls SDL_GetKeyboardState repeatedly, like: https://github.com/libsdl-org/SDL/blob/fdc04708f1950ad76eff16fd47ffe67dcdc5ba04/src/video/windows/SDL_windowsevents.c#L1270

Haruu000 commented 1 month ago

Contributor

Hey can you look at the Linux makefile issue

nickenchev commented 1 month ago

I'm assuming its because the call itself looks pretty inexpensive when you check the .c file its defined in. Though, the example you sent only occurs on key-up events, so so it wouldn't end up being a part of every loop iteration, it would likely only happen once at the end of a key-press/hold. Whereas the example I noticed it in the book gets called inside ProcessInput(), so its happening on absolutely every single pass of the game loop. Again, not really a big deal, its just something I notice in every sample SDL2 code, and considering how much gamedevs go out of their way to micro-optimize, I always wonder why stuff like this ends up everywhere.


void Game::ProcessInput()
{
...
    // Get state of keyboard
    const Uint8* state = SDL_GetKeyboardState(NULL);
    // If escape is pressed, also end loop
    if (state[SDL_SCANCODE_ESCAPE])
    {
        mIsRunning = false;
    }
}
`