treball en curs: correccions de tidy

This commit is contained in:
2026-05-16 15:49:21 +02:00
parent 18cd287808
commit 3421f34a84
18 changed files with 658 additions and 651 deletions
+166 -169
View File
@@ -45,8 +45,8 @@ static void installWebStandardMapping(SDL_JoystickID jid) {
Input *Input::instance = nullptr;
// Singleton API
void Input::init(const std::string &gameControllerDbPath) {
Input::instance = new Input(gameControllerDbPath);
void Input::init(const std::string &game_controller_db_path) {
Input::instance = new Input(game_controller_db_path);
}
void Input::destroy() {
@@ -60,111 +60,99 @@ auto Input::get() -> Input * {
// Constructor
Input::Input(std::string file)
: dbPath(std::move(file)) {
: db_path_(std::move(file)) {
// Inicializa las variables
KeyBindings kb;
kb.scancode = 0;
kb.active = false;
keyBindings.resize(input_number_of_inputs, kb);
key_bindings_.resize(NUMBER_OF_INPUTS, kb);
GameControllerBindings gcb;
gcb.button = SDL_GAMEPAD_BUTTON_INVALID;
gcb.active = false;
gameControllerBindings.resize(input_number_of_inputs, gcb);
game_controller_bindings_.resize(NUMBER_OF_INPUTS, gcb);
}
// Destructor
Input::~Input() {
for (auto *pad : connectedControllers) {
for (auto *pad : connected_controllers_) {
if (pad != nullptr) {
SDL_CloseGamepad(pad);
}
}
connectedControllers.clear();
connectedControllerIds.clear();
controllerNames.clear();
numGamepads = 0;
connected_controllers_.clear();
connected_controller_ids_.clear();
controller_names_.clear();
num_gamepads_ = 0;
}
// Actualiza el estado del objeto
void Input::update() {
if (disabledUntil == d_keyPressed && !checkAnyInput()) {
if (disabled_until_ == KEY_PRESSED && !checkAnyInput()) {
enable();
}
}
// Asigna inputs a teclas
void Input::bindKey(Uint8 input, SDL_Scancode code) {
keyBindings[input].scancode = code;
key_bindings_[input].scancode = code;
}
// Asigna inputs a botones del mando
void Input::bindGameControllerButton(Uint8 input, SDL_GamepadButton button) {
gameControllerBindings[input].button = button;
game_controller_bindings_[input].button = button;
}
// Comprueba si un input esta activo
auto Input::checkInput(Uint8 input, bool repeat, int device, int index) -> bool {
if (!enabled) {
if (!enabled_) {
return false;
}
bool successKeyboard = false;
bool successGameController = false;
if (device == INPUT_USE_ANY) {
index = 0;
}
bool success_keyboard = false;
if (device == INPUT_USE_KEYBOARD || device == INPUT_USE_ANY) {
const bool *keyStates = SDL_GetKeyboardState(nullptr);
if (repeat) {
successKeyboard = keyStates[keyBindings[input].scancode];
} else {
if (!keyBindings[input].active) {
if (keyStates[keyBindings[input].scancode]) {
keyBindings[input].active = true;
successKeyboard = true;
} else {
successKeyboard = false;
}
} else {
if (!keyStates[keyBindings[input].scancode]) {
keyBindings[input].active = false;
successKeyboard = false;
} else {
successKeyboard = false;
}
}
}
success_keyboard = checkKeyboardInput(input, repeat);
}
if (gameControllerFound() && index >= 0 && index < (int)connectedControllers.size()) {
if ((device == INPUT_USE_GAMECONTROLLER) || (device == INPUT_USE_ANY)) {
if (repeat) {
successGameController = SDL_GetGamepadButton(connectedControllers[index], gameControllerBindings[input].button);
} else {
if (!gameControllerBindings[input].active) {
if (SDL_GetGamepadButton(connectedControllers[index], gameControllerBindings[input].button)) {
gameControllerBindings[input].active = true;
successGameController = true;
} else {
successGameController = false;
}
} else {
if (!SDL_GetGamepadButton(connectedControllers[index], gameControllerBindings[input].button)) {
gameControllerBindings[input].active = false;
successGameController = false;
} else {
successGameController = false;
}
}
}
}
bool success_game_controller = false;
if ((device == INPUT_USE_GAMECONTROLLER || device == INPUT_USE_ANY) && gameControllerFound() && index >= 0 && index < (int)connected_controllers_.size()) {
success_game_controller = checkGameControllerInput(input, repeat, index);
}
return (successKeyboard || successGameController);
return success_keyboard || success_game_controller;
}
// Helper de checkInput: comprueba el estado de una tecla
auto Input::checkKeyboardInput(Uint8 input, bool repeat) -> bool {
const bool *key_states = SDL_GetKeyboardState(nullptr);
const bool IS_DOWN = key_states[key_bindings_[input].scancode];
if (repeat) {
return IS_DOWN;
}
// Modo edge-trigger: éxito sólo en el frame en que la tecla pasa de up a down
const bool PRESS_EDGE = IS_DOWN && !key_bindings_[input].active;
key_bindings_[input].active = IS_DOWN;
return PRESS_EDGE;
}
// Helper de checkInput: comprueba el estado de un botón de mando
auto Input::checkGameControllerInput(Uint8 input, bool repeat, int index) -> bool {
const bool IS_DOWN = SDL_GetGamepadButton(connected_controllers_[index], game_controller_bindings_[input].button);
if (repeat) {
return IS_DOWN;
}
// Modo edge-trigger: éxito sólo en el frame en que el botón pasa de up a down
const bool PRESS_EDGE = IS_DOWN && !game_controller_bindings_[input].active;
game_controller_bindings_[input].active = IS_DOWN;
return PRESS_EDGE;
}
// Comprueba si hay almenos un input activo
@@ -174,19 +162,19 @@ auto Input::checkAnyInput(int device, int index) -> bool {
}
if (device == INPUT_USE_KEYBOARD || device == INPUT_USE_ANY) {
const bool *mKeystates = SDL_GetKeyboardState(nullptr);
const bool *key_states = SDL_GetKeyboardState(nullptr);
for (auto &keyBinding : keyBindings) {
if (mKeystates[keyBinding.scancode]) {
for (auto &key_binding : key_bindings_) {
if (key_states[key_binding.scancode]) {
return true;
}
}
}
if (gameControllerFound() && index >= 0 && index < (int)connectedControllers.size()) {
if (gameControllerFound() && index >= 0 && index < (int)connected_controllers_.size()) {
if (device == INPUT_USE_GAMECONTROLLER || device == INPUT_USE_ANY) {
for (auto &gameControllerBinding : gameControllerBindings) {
if (SDL_GetGamepadButton(connectedControllers[index], gameControllerBinding.button)) {
for (auto &game_controller_binding : game_controller_bindings_) {
if (SDL_GetGamepadButton(connected_controllers_[index], game_controller_binding.button)) {
return true;
}
}
@@ -199,13 +187,13 @@ auto Input::checkAnyInput(int device, int index) -> bool {
// Construye el nombre visible de un mando.
// Recorta des del primer '(' o '[' (per a evitar coses tipus
// "Retroid Controller (vendor: 1001) ...") i talla a 25 caràcters.
auto Input::buildControllerName(SDL_Gamepad *pad, int padIndex) -> std::string {
(void)padIndex;
const char *padName = SDL_GetGamepadName(pad);
std::string name = (padName != nullptr) ? padName : "Unknown";
const auto pos = name.find_first_of("([");
if (pos != std::string::npos) {
name.erase(pos);
auto Input::buildControllerName(SDL_Gamepad *pad, int pad_index) -> std::string {
(void)pad_index;
const char *pad_name = SDL_GetGamepadName(pad);
std::string name = (pad_name != nullptr) ? pad_name : "Unknown";
const auto POS = name.find_first_of("([");
if (POS != std::string::npos) {
name.erase(POS);
}
while (!name.empty() && name.back() == ' ') {
name.pop_back();
@@ -219,136 +207,145 @@ auto Input::buildControllerName(SDL_Gamepad *pad, int padIndex) -> std::string {
// Busca si hay un mando conectado. Cierra y limpia el estado previo para
// que la función sea idempotente si se invoca más de una vez.
auto Input::discoverGameController() -> bool {
// Cierra los mandos ya abiertos y limpia los vectores paralelos
for (auto *pad : connectedControllers) {
resetGameControllerState();
ensureGamepadSubsystem();
int num_joysticks = 0;
SDL_JoystickID *joysticks = SDL_GetJoysticks(&num_joysticks);
if (joysticks == nullptr) {
return false;
}
int gamepad_count = 0;
for (int i = 0; i < num_joysticks; ++i) {
if (SDL_IsGamepad(joysticks[i])) {
gamepad_count++;
}
}
if (verbose_) {
std::cout << "\nChecking for game controllers...\n";
std::cout << num_joysticks << " joysticks found, " << gamepad_count << " are gamepads\n";
}
bool found = false;
if (gamepad_count > 0) {
found = true;
int pad_index = 0;
for (int i = 0; i < num_joysticks; i++) {
if (!SDL_IsGamepad(joysticks[i])) {
continue;
}
if (openGamepad(joysticks[i], pad_index)) {
pad_index++;
}
}
SDL_SetGamepadEventsEnabled(true);
}
SDL_free(joysticks);
return found;
}
// Helper de discoverGameController: cierra mandos previos y limpia vectores paralelos
void Input::resetGameControllerState() {
for (auto *pad : connected_controllers_) {
if (pad != nullptr) {
SDL_CloseGamepad(pad);
}
}
connectedControllers.clear();
connectedControllerIds.clear();
controllerNames.clear();
numGamepads = 0;
bool found = false;
connected_controllers_.clear();
connected_controller_ids_.clear();
controller_names_.clear();
num_gamepads_ = 0;
}
// Helper de discoverGameController: inicializa el subsystem de gamepad y carga el mapping
void Input::ensureGamepadSubsystem() {
if (SDL_WasInit(SDL_INIT_GAMEPAD) != SDL_INIT_GAMEPAD) {
SDL_InitSubSystem(SDL_INIT_GAMEPAD);
}
if (SDL_AddGamepadMappingsFromFile(db_path_.c_str()) < 0 && verbose_) {
std::cout << "Error, could not load " << db_path_.c_str() << " file: " << SDL_GetError() << '\n';
}
}
if (SDL_AddGamepadMappingsFromFile(dbPath.c_str()) < 0) {
if (verbose) {
std::cout << "Error, could not load " << dbPath.c_str() << " file: " << SDL_GetError() << '\n';
// Helper de discoverGameController: abre y registra un mando. Devuelve true si tuvo éxito.
auto Input::openGamepad(SDL_JoystickID joystick_id, int pad_index) -> bool {
installWebStandardMapping(joystick_id);
SDL_Gamepad *pad = SDL_OpenGamepad(joystick_id);
if (pad == nullptr) {
if (verbose_) {
std::cout << "SDL_GetError() = " << SDL_GetError() << '\n';
}
return false;
}
int nJoysticks = 0;
SDL_JoystickID *joysticks = SDL_GetJoysticks(&nJoysticks);
if (joysticks != nullptr) {
int gamepadCount = 0;
for (int i = 0; i < nJoysticks; ++i) {
if (SDL_IsGamepad(joysticks[i])) {
gamepadCount++;
}
}
if (verbose) {
std::cout << "\nChecking for game controllers...\n";
std::cout << nJoysticks << " joysticks found, " << gamepadCount << " are gamepads\n";
}
if (gamepadCount > 0) {
found = true;
int padIndex = 0;
for (int i = 0; i < nJoysticks; i++) {
if (!SDL_IsGamepad(joysticks[i])) {
continue;
}
installWebStandardMapping(joysticks[i]);
SDL_Gamepad *pad = SDL_OpenGamepad(joysticks[i]);
if (pad != nullptr) {
const std::string name = buildControllerName(pad, padIndex);
connectedControllers.push_back(pad);
connectedControllerIds.push_back(joysticks[i]);
controllerNames.push_back(name);
numGamepads++;
padIndex++;
if (verbose) {
std::cout << name << '\n';
}
} else {
if (verbose) {
std::cout << "SDL_GetError() = " << SDL_GetError() << '\n';
}
}
}
SDL_SetGamepadEventsEnabled(true);
}
SDL_free(joysticks);
const std::string NAME = buildControllerName(pad, pad_index);
connected_controllers_.push_back(pad);
connected_controller_ids_.push_back(joystick_id);
controller_names_.push_back(NAME);
num_gamepads_++;
if (verbose_) {
std::cout << NAME << '\n';
}
return found;
return true;
}
// Procesa un evento SDL_EVENT_GAMEPAD_ADDED
auto Input::handleGamepadAdded(SDL_JoystickID jid, std::string &outName) -> bool {
auto Input::handleGamepadAdded(SDL_JoystickID jid, std::string &out_name) -> bool {
if (!SDL_IsGamepad(jid)) {
return false;
}
// Si el mando ya está registrado no hace nada (ej. evento retroactivo tras el scan inicial)
if (std::ranges::any_of(connectedControllerIds, [jid](SDL_JoystickID existing) { return existing == jid; })) {
if (std::ranges::any_of(connected_controller_ids_, [jid](SDL_JoystickID existing) { return existing == jid; })) {
return false;
}
installWebStandardMapping(jid);
SDL_Gamepad *pad = SDL_OpenGamepad(jid);
if (pad == nullptr) {
if (verbose) {
if (verbose_) {
std::cout << "Failed to open gamepad " << jid << ": " << SDL_GetError() << '\n';
}
return false;
}
const int padIndex = (int)connectedControllers.size();
const std::string name = buildControllerName(pad, padIndex);
connectedControllers.push_back(pad);
connectedControllerIds.push_back(jid);
controllerNames.push_back(name);
numGamepads++;
const int PAD_INDEX = (int)connected_controllers_.size();
const std::string NAME = buildControllerName(pad, PAD_INDEX);
connected_controllers_.push_back(pad);
connected_controller_ids_.push_back(jid);
controller_names_.push_back(NAME);
num_gamepads_++;
if (verbose) {
std::cout << "Gamepad connected: " << name << '\n';
if (verbose_) {
std::cout << "Gamepad connected: " << NAME << '\n';
}
outName = name;
out_name = NAME;
return true;
}
// Procesa un evento SDL_EVENT_GAMEPAD_REMOVED
auto Input::handleGamepadRemoved(SDL_JoystickID jid, std::string &outName) -> bool {
for (size_t i = 0; i < connectedControllerIds.size(); ++i) {
if (connectedControllerIds[i] != jid) {
auto Input::handleGamepadRemoved(SDL_JoystickID jid, std::string &out_name) -> bool {
for (size_t i = 0; i < connected_controller_ids_.size(); ++i) {
if (connected_controller_ids_[i] != jid) {
continue;
}
outName = controllerNames[i];
if (connectedControllers[i] != nullptr) {
SDL_CloseGamepad(connectedControllers[i]);
out_name = controller_names_[i];
if (connected_controllers_[i] != nullptr) {
SDL_CloseGamepad(connected_controllers_[i]);
}
connectedControllers.erase(connectedControllers.begin() + i);
connectedControllerIds.erase(connectedControllerIds.begin() + i);
controllerNames.erase(controllerNames.begin() + i);
numGamepads--;
numGamepads = std::max(numGamepads, 0);
connected_controllers_.erase(connected_controllers_.begin() + i);
connected_controller_ids_.erase(connected_controller_ids_.begin() + i);
controller_names_.erase(controller_names_.begin() + i);
num_gamepads_--;
num_gamepads_ = std::max(num_gamepads_, 0);
if (verbose) {
std::cout << "Gamepad disconnected: " << outName << '\n';
if (verbose_) {
std::cout << "Gamepad disconnected: " << out_name << '\n';
}
return true;
@@ -358,35 +355,35 @@ auto Input::handleGamepadRemoved(SDL_JoystickID jid, std::string &outName) -> bo
// Comprueba si hay algun mando conectado
auto Input::gameControllerFound() const -> bool {
return numGamepads > 0;
return num_gamepads_ > 0;
}
// Obten el nombre de un mando de juego
auto Input::getControllerName(int index) -> std::string {
if (numGamepads > 0) {
return controllerNames[index];
if (num_gamepads_ > 0) {
return controller_names_[index];
}
return "";
}
// Obten el numero de mandos conectados
auto Input::getNumControllers() const -> int {
return numGamepads;
return num_gamepads_;
}
// Establece si ha de mostrar mensajes
void Input::setVerbose(bool value) {
verbose = value;
verbose_ = value;
}
// Deshabilita las entradas durante un periodo de tiempo
void Input::disableUntil(InputDisable value) {
disabledUntil = value;
enabled = false;
disabled_until_ = value;
enabled_ = false;
}
// Hablita las entradas
void Input::enable() {
enabled = true;
disabledUntil = d_notDisabled;
enabled_ = true;
disabled_until_ = NOT_DISABLED;
}