Handmade Hero»Forums»Code»Days 013, 017 - swapping input buffers
20 posts
Days 013, 017 - swapping input buffers
1 week ago Edited by Joystick on June 28, 2020, 6:52 p.m.
Hey guys!

Could somebody elaborate on why does Casey use two input buffers and swaps between them at the end of every iteration of the game loop?
Does this technique have an impact on the responsiveness of the input?
Simon Anciaux
817 posts
Days 006, 017 - swapping input buffers
6 days, 9 hours ago
It's to handle controller state. Keyboard input messages allow you to know if the key was pressed before the current message. With controller input you can't know, so you need to rely on the previous frame state. You're not required to store it, you could just have a temporary copy while you're processing inputs.

You can see it here.

It doesn't have any impact on responsiveness.
20 posts
Days 013, 017 - swapping input buffers
6 days, 5 hours ago
Ah, I see!

But if that's the case then why does he also handle the keyboard state using those two buffers?

game_controller_input *OldKeyboardController = GetController(OldInput, 0);
game_controller_input *NewKeyboardController = GetController(NewInput, 0);
*NewKeyboardController = {};
NewKeyboardController->IsConnected = true;
for(int ButtonIndex = 0; ButtonIndex < ArrayCount(NewKeyboardController->Buttons); ++ButtonIndex) {
       NewKeyboardController->Buttons[ButtonIndex].EndedDown = OldKeyboardController->Buttons[ButtonIndex].EndedDown;


He's already checking whether any of the keys were pressed before the message in Win32ProcessPendingMessages(), doesn't he?

bool32 WasDown = ((Message.lParam & (1 << 30)) != 0);
bool32 IsDown = ((Message.lParam & (1 << 31)) == 0);
Simon Anciaux
817 posts
Days 013, 017 - swapping input buffers
6 days, 2 hours ago Edited by Simon Anciaux on June 28, 2020, 9:53 p.m.
I forgot about that.

To receive keyboard messages you need to press or release the key, or receive a "repeat" message. If you keep a key pressed, you'll only get a repeat message after a certain delay. Like in a text editor, if you press 'a' and keep the key pressed, you get 1 'a' directly, then after a few moment, you'll get a second 'a', and after that you'll get another 'a' more rapidly. Those message intervals are more than a frame time (configurable in windows settings), so in a game you can't rely on that and you use the last frame state to know if a key is still pressed.

There is another way to get key state: GetAsyncKeyState. This would always give you the key state. I don't know if there are downsides to using that.