From 324ddd04164deb70be921d67dc1d7b918e0b9d3c Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Sat, 21 Jun 2025 13:20:05 +0200 Subject: [PATCH] fix Input: migrat correctament a SDL3 discoverGameControllers() --- source/input.cpp | 48 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/source/input.cpp b/source/input.cpp index 69462ef..2cdab8a 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -217,16 +217,20 @@ bool Input::discoverGameControllers() SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: could not load %s file: %s", game_controller_db_path_.c_str(), SDL_GetError()); } - SDL_GetJoysticks(&num_joysticks_); + // En SDL3, SDL_GetJoysticks devuelve un array de IDs, no un contador + SDL_JoystickID* joystick_ids = SDL_GetJoysticks(&num_joysticks_); num_gamepads_ = 0; // Cuenta el número de mandos joysticks_.clear(); for (int i = 0; i < num_joysticks_; ++i) { - auto joy = SDL_OpenJoystick(i); + // Usar el ID del joystick, no el índice + auto joy = SDL_OpenJoystick(joystick_ids[i]); joysticks_.push_back(joy); - if (SDL_IsGamepad(i)) + + // En SDL3, SDL_IsGamepad toma un SDL_JoystickID, no un índice + if (SDL_IsGamepad(joystick_ids[i])) { num_gamepads_++; } @@ -247,26 +251,40 @@ bool Input::discoverGameControllers() { found = true; - for (int i = 0; i < num_gamepads_; i++) + // Recorrer los joysticks y abrir solo los que son gamepads + for (int i = 0; i < num_joysticks_; i++) { - // Abre el mando y lo añade a la lista - auto pad = SDL_OpenGamepad(i); - if (SDL_GamepadConnected(pad) == 1) + if (SDL_IsGamepad(joystick_ids[i])) { - connected_controllers_.push_back(pad); - const std::string name = SDL_GetGamepadNameForID(i); - SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "#%d: %s", i, name.c_str()); - controller_names_.push_back(name); - } - else - { - SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GetError() = %s", SDL_GetError()); + // Abre el mando usando el ID del joystick + auto pad = SDL_OpenGamepad(joystick_ids[i]); + if (pad != nullptr) + { + connected_controllers_.push_back(pad); + + // Obtener el nombre usando el ID del joystick + const char* name_cstr = SDL_GetGamepadNameForID(joystick_ids[i]); + std::string name = name_cstr ? name_cstr : "Unknown Gamepad"; + + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "#%d: %s", i, name.c_str()); + controller_names_.push_back(name); + } + else + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to open gamepad %d: %s", joystick_ids[i], SDL_GetError()); + } } } SDL_SetGamepadEventsEnabled(true); } + // Liberar el array de IDs + if (joystick_ids) + { + SDL_free(joystick_ids); + } + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> FINISHED LOOKING FOR GAME CONTROLLERS"); return found; }