Handmade Hero»Forums»Code
23 posts
Days 013, 017 - swapping input buffers
Edited by Joystick on
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
1337 posts
Days 013, 017 - swapping input buffers
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.
23 posts
Days 013, 017 - swapping input buffers
Ah, I see!

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

1
2
3
4
5
6
7
8
9
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;
}

Win32ProcessPendingMessages(NewKeyboardController);


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

1
2
bool32 WasDown = ((Message.lParam & (1 << 30)) != 0);
bool32 IsDown = ((Message.lParam & (1 << 31)) == 0);
Simon Anciaux
1337 posts
Days 013, 017 - swapping input buffers
Edited by Simon Anciaux on
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.