I am making a C++ SDL based game engine, I am finishing the InputManager, let know what…
- User
I am making a C++ SDL based game engine, I am finishing the InputManager, let know what you think about it and what fixes can I make? Take into account:
- It is a singleton, and is called once, but I don't need to explicitly do anything for thread safe because it is already.
- There is a TODO I didn't know if I should implement it or not, because I think I deal with that in two other methods: GamepadButtonPressed and GamepadButtonReleased., help me decide this.
- Yes it is a big mess of Update() but I will be improving upon this when I deal with the EventManager
class InputManager { public: ~InputManager(); InputManager(const InputManager&) = delete; InputManager operator=(const InputManager&) = delete; static InputManager& GetInstance() noexcept; void Update(); bool IsKeyPressed(Input::KeyCode key) const; bool IsKeyReleased(Input::KeyCode key) const; bool IsMouseButtonPressed(Input::MouseButton button) const; Point GetMousePosition() const; bool IsGamepadButtonPressed(Input::GamepadButton button, int gamepadIndex) const; bool IsGamepadButtonReleased(Input::GamepadButton button, int gamepadIndex) const;
private: InputManager(); void UpdateKeyboardState(); void SetMouseState(uint8_t mouseButton, bool pressed); SDL_GameController* GetGamepad(int index); void GamepadButtonPressed(uint8_t button, int gamepadIndex); void GamepadButtonReleased(uint8_t button, int gamepadIndex); void GamepadOpen(int gamepadIndex); void GamepadClose(int gamepadIndex);
std::unordered_map<Input::KeyCode, bool> currentKeyboardState; std::unordered_map<Input::KeyCode, bool> previousKeyboardState; std::unordered_map<Input::MouseButton, bool> mouseButtonsState; std::vector<SDL_GameController*> gamepads; std::vector<std::unordered_map<Input::GamepadButton, bool>> currentGamepadState; std::vector<std::unordered_map<Input::GamepadButton, bool>> previousGamepadState; };
uint8_t KeyToSDL(Input::KeyCode keyCode); Input::KeyCode KeyFromSDL(uint8_t sdlKeyCode); uint8_t MouseButtonToSDL(Input::MouseButton mouseButton); Input::MouseButton MouseButtonFromSDL(uint8_t sdlMouseButton); SDL_GameControllerButton GamepadButtonToSDL(Input::GamepadButton gamepadButton); Input::GamepadButton GamepadButtonFromSDL(SDL_GameControllerButton sdlGamepadButton);
InputManager::InputManager() { }
InputManager::~InputManager() { for (SDL_GameController* gamepad : gamepads) { if (gamepad) { SDL_GameControllerClose(gamepad); } } }
InputManager& InputManager::GetInstance() noexcept { static InputManager instance;
return instance; }
void InputManager::Update() { previousKeyboardState = currentKeyboardState;
SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_MOUSEBUTTONUP: { SetMouseState(event.button.button, false); break; } case SDL_MOUSEBUTTONDOWN: { SetMouseState(event.button.button, true); break; } case SDL_CONTROLLERDEVICEADDED: { GamepadOpen(event.cdevice.which); break; } case SDL_CONTROLLERDEVICEREMOVED: { GamepadClose(event.cdevice.which); break; } case SDL_CONTROLLERBUTTONDOWN: { GamepadButtonPressed(event.cbutton.button, event.cbutton.which); break; } case SDL_CONTROLLERBUTTONUP: { GamepadButtonReleased(event.cbutton.button, event.cbutton.which); break; } } }
- Assistant
- User
Ok I see, now let's start doing the fixes.
First, make the code for the TODO, and initialize the gamepad state, although I find it unnecesary since I do that at button pressed and button released with the resizing and the bool by default have a false value.
Second, make the code fix for the state checking logic of the gamepad buttons, I thought mine was correct but I guess I was wrong.
- Assistant
- User
This line: for(auto& button : Input::AllGamepadButtons) is giving me this error: error: expected primary-expression before ')' token, in my code I have this
for(auto& button : Input::GamepadButton) { currentGamepadState[gamepadIndex][button] = false; previousGamepadState[gamepadIndex][button] = false; }
struct Input { enum class GamepadButton { Invalid = -1, South, // Cross, A East, // Circle, B ... } }
- Assistant
- User
Perfect, got it to compile correctly, now since the initialization is done in the GamepadOpen method, should I take that from the pressed or released methods?
void InputManager::GamepadButtonPressed(uint8_t button, int gamepadIndex) { if (gamepadIndex >= 0) { if (gamepadIndex >= static_cast(currentGamepadState.size())) // remove this part? { currentGamepadState.resize(gamepadIndex + 1); previousGamepadState.resize(gamepadIndex + 1); }
Input::GamepadButton gamepadButton = GamepadButtonFromSDL(static_cast<SDL_GameControllerButton>(button)); previousGamepadState[gamepadIndex][gamepadButton] = currentGamepadState[gamepadIndex][gamepadButton]; currentGamepadState[gamepadIndex][gamepadButton] = true; }}
- Assistant
Yes, if you've already handled the initialization of the and in the method, you can safely remove the resizing logic from the and methods. This removal is based on the assumption that any button press or release event will only come from an already-open and therefore initialized gamepad controller.
- User
OK now that we have every wrong thing fixed, and since I don't plan to support other controller types yet, like josticks, what else can we do now to improve it? Should we move the Gamepad logic into its own class? What do you think about what is left?
- Assistant
- User
- Assistant
- User
OK I fixed some of your corncerns:
First I solved 2) and 3) by fixing the index and throwing an exception, then I catch it in the Update method:
Gamepad::Gamepad(int index) { gamepad = SDL_GameControllerOpen(index); if (gamepad) { //... } else { std::string errorMsg = SDL_GetError(); SDL_LogError(SDL_LOG_CATEGORY_ERROR, errorMsg.c_str());
throw std::runtime_error(errorMsg); } gamepadIndex = index;}
InputManager::Update() { //... case SDL_CONTROLLERDEVICEADDED: { try { gamepads.push_back(Gamepad(event.cdevice.which)); } catch (std::runtime_error& e) { std::string errorMsg = "ERROR: Gamepad " + std::to_string(event.cdevice.which) + " could not be open: " + e.what(); SDL_LogError(SDL_LOG_CATEGORY_ERROR, errorMsg.c_str()); } break; }
Second I need help with your points 1) and 4): How can I make it more robust? You are right the index will be deleted and reallocated and I haven't though that very well, I thought the index was unique by device, but if connecting and re-connecting can land the same device in the same index or the same index but with an already a device mapped there.
- Assistant
- User
OK I did the changes but now I am having errors here:
bool InputManager::IsGamepadButtonPressed(Input::GamepadButton button, int gamepadID) const { return gamepads[gamepadID].IsButtonPressed(button); }
bool InputManager::IsGamepadButtonReleased(Input::GamepadButton button, int gamepadID) const { return gamepads[gamepadID].IsButtonReleased(button); }
Also since I don't need the gamepad index for anything, should I take it out from the Gamepad class?
- Assistant
The errors you're encountering in the
IsGamepadButtonPressedandIsGamepadButtonReleasedmethods could stem from multiple causes, depending on the specific error messages you're seeing. However, one potential issue arises from directly accessing elements in a using the . Using on a with a key that doesn't exist will try to create a default object for that key, which isn't valid if you're trying to simply query or check the status and the map has non-default constructible objects or if you don't want to mutate the map. In a const method context, like yours, using is also not possible because it potentially modifies the map. - User
- Assistant
- User
I found the error, and changed them like this:
-
Changed this: Gamepad newGamepad(instanceID); gamepads[instanceID] = std::move(newGamepad); to this: Gamepad newGamepad(instanceID); gamepads.insert({ instanceID, newGamepad });
-
Changed this: int instanceID = event.cdevice.which; gamepads[instanceID].Update(event); to this: int instanceID = event.cdevice.which; auto it = gamepads.find(instanceID); if(it != gamepads.end()) { return it->second.Update(event); }
-
- Assistant
I'm glad you found the source of the error, and your adjustments look good! Here's a bit of feedback on the changes you made to ensure everything aligns well with best practices and the intended behavior:
- User
Great, it compiles correctly now. I wanted to ask you, since we change vector from a map, will this destructor work the same as with the vector, that is calling each Gamepad destructor to close each opened Gamepad?
InputManager::~InputManager() { gamepads.clear(); }
Gamepad::~Gamepad() { SDL_GameControllerClose(gamepad); gamepad = nullptr; }
- Assistant
Yes, your approach to managing
Gamepaddestruction will still work correctly with astd::unordered_mapas it did with astd::vector.When you call
gamepads.clear()on yourstd::unordered_map, it will indeed destroy all of theGamepadobjects stored in the map, which in turn calls the destructor for eachGamepadinstance. This is because containers likestd::vector,std::map, , and so on, manage the lifetime of the objects they contain. When these containers are cleared or destroyed (such as when they go out of scope or are explicitly cleared with methods like ), they automatically call the destructor for each object they contain. - User
OK, now that everything is already done, let's discuss about your last concern:
- Gamepad Feature Expansion:
- With gamepad handling now encapsulated in its own class, it’s easier to extend functionality. Consider adding support for analog stick inputs, trigger buttons, or even force feedback (vibration) if your game could benefit from those.
What should we do about it? If we need to do something, how can we deal with it?
- Assistant
- User
I will keep this for a future release, but thanks for giving me the idea, I think I will start small now, with what I have and then adding more things in a future release. Before closing this, since we moved the gamepad out of the InputManager, should the Mouse and/or the Keyboard be moved out as well or they are not really needed outside or making no sense outside?
- Assistant