Files
coffee_crisis_arcade_edition/source/input.cpp

461 lines
14 KiB
C++

#include "input.h"
#include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_init.h> // Para SDL_INIT_GAMEPAD, SDL_InitSubSystem
#include <SDL3/SDL_keyboard.h> // Para SDL_GetKeyboardState
#include <SDL3/SDL_log.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_Log...
#include <algorithm> // Para find
#include <iterator> // Para distance
#include <unordered_map> // Para unordered_map, operator==, _Node_cons...
#include <utility> // Para pair
// Singleton
Input *Input::instance_ = nullptr;
// Inicializa la instancia única del singleton
void Input::init(const std::string &game_controller_db_path) { Input::instance_ = new Input(game_controller_db_path); }
// Libera la instancia
void Input::destroy() { delete Input::instance_; }
// Obtiene la instancia
Input *Input::get() { return Input::instance_; }
// Constructor
Input::Input(const std::string &game_controller_db_path)
: game_controller_db_path_(game_controller_db_path)
{
// Inicializa el subsistema SDL_INIT_GAMEPAD
initSDLGamePad();
// Inicializa los vectores
key_bindings_.resize(static_cast<int>(InputAction::SIZE), KeyBindings());
controller_bindings_.resize(num_gamepads_, std::vector<ControllerBindings>(static_cast<int>(InputAction::SIZE), ControllerBindings()));
// Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
button_inputs_ = {InputAction::FIRE_LEFT, InputAction::FIRE_CENTER, InputAction::FIRE_RIGHT, InputAction::START};
}
// Asigna inputs a teclas
void Input::bindKey(InputAction input, SDL_Scancode code)
{
key_bindings_.at(static_cast<int>(input)).scancode = code;
}
// Asigna inputs a botones del mando
void Input::bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button)
{
if (controller_index < num_gamepads_)
{
controller_bindings_.at(controller_index).at(static_cast<int>(input)).button = button;
}
}
// Asigna inputs a botones del mando
void Input::bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source)
{
if (controller_index < num_gamepads_)
{
controller_bindings_.at(controller_index).at(static_cast<int>(input_target)).button = controller_bindings_.at(controller_index).at(static_cast<int>(input_source)).button;
}
}
// Comprueba si un input esta activo
bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index)
{
bool success_keyboard = false;
bool success_controller = false;
const int input_index = static_cast<int>(input);
if (device == InputDevice::KEYBOARD || device == InputDevice::ANY)
{
if (repeat)
{ // El usuario quiere saber si está pulsada (estado mantenido)
success_keyboard = key_bindings_[input_index].is_held;
}
else
{ // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
success_keyboard = key_bindings_[input_index].just_pressed;
}
}
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_)
{
if ((device == InputDevice::CONTROLLER) || (device == InputDevice::ANY))
{
success_controller = checkAxisInput(input, controller_index, repeat);
if (!success_controller)
{
if (repeat)
{ // El usuario quiere saber si está pulsada (estado mantenido)
success_controller = controller_bindings_.at(controller_index).at(input_index).is_held;
}
else
{ // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
success_controller = controller_bindings_.at(controller_index).at(input_index).just_pressed;
}
}
}
}
return (success_keyboard || success_controller);
}
// Comprueba si hay almenos un input activo
bool Input::checkAnyInput(InputDevice device, int controller_index)
{
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
const int num_actions = static_cast<int>(InputAction::SIZE);
// --- Comprobación del Teclado ---
if (device == InputDevice::KEYBOARD || device == InputDevice::ANY)
{
for (int i = 0; i < num_actions; ++i)
{
// Simplemente leemos el estado pre-calculado por Input::update().
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
if (key_bindings_.at(i).just_pressed)
{
return true; // Se encontró una acción recién pulsada.
}
}
}
// --- Comprobación del Mando ---
// Comprobamos si hay mandos y si el índice solicitado es válido.
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_)
{
if (device == InputDevice::CONTROLLER || device == InputDevice::ANY)
{
// Bucle CORREGIDO: Iteramos sobre todas las acciones, no sobre el número de mandos.
for (int i = 0; i < num_actions; ++i)
{
// Leemos el estado pre-calculado para el mando y la acción específicos.
if (controller_bindings_.at(controller_index).at(i).just_pressed)
{
return true; // Se encontró una acción recién pulsada en el mando.
}
}
}
}
// Si llegamos hasta aquí, no se detectó ninguna nueva pulsación.
return false;
}
// Comprueba si hay algún botón pulsado. Devuelve 0 en caso de no encontrar nada o el indice del dispositivo + 1. Se hace así para poder gastar el valor devuelto como un valor "booleano"
int Input::checkAnyButton(bool repeat)
{
// Solo comprueba los botones definidos previamente
for (auto bi : button_inputs_)
{
// Comprueba el teclado
if (checkInput(bi, repeat, InputDevice::KEYBOARD))
{
return 1;
}
// Comprueba los mandos
for (int i = 0; i < num_gamepads_; ++i)
{
if (checkInput(bi, repeat, InputDevice::CONTROLLER, i))
{
return i + 1;
}
}
}
return 0;
}
// Busca si hay mandos conectados
bool Input::discoverGameControllers()
{
bool found = false;
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: could not load %s file: %s", game_controller_db_path_.c_str(), SDL_GetError());
}
// 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)
{
// Usar el ID del joystick, no el índice
auto joy = SDL_OpenJoystick(joystick_ids[i]);
joysticks_.push_back(joy);
// En SDL3, SDL_IsGamepad toma un SDL_JoystickID, no un índice
if (SDL_IsGamepad(joystick_ids[i]))
{
num_gamepads_++;
}
}
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> LOOKING FOR GAME CONTROLLERS");
if (num_joysticks_ != num_gamepads_)
{
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Joysticks found: %d", num_joysticks_);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Gamepads found : %d", num_gamepads_);
}
else
{
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Gamepads found: %d", num_gamepads_);
}
if (num_gamepads_ > 0)
{
found = true;
// Recorrer los joysticks y abrir solo los que son gamepads
for (int i = 0; i < num_joysticks_; i++)
{
if (SDL_IsGamepad(joystick_ids[i]))
{
// 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;
}
// Comprueba si hay algun mando conectado
bool Input::gameControllerFound() { return num_gamepads_ > 0 ? true : false; }
// Obten el nombre de un mando de juego
std::string Input::getControllerName(int controller_index) const { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
// Obten el número de mandos conectados
int Input::getNumControllers() const { return num_gamepads_; }
// Obtiene el indice del controlador a partir de un event.id
int Input::getJoyIndex(SDL_JoystickID id) const
{
for (int i = 0; i < num_joysticks_; ++i)
{
if (SDL_GetJoystickID(joysticks_[i]) == id)
{
return i;
}
}
return -1;
}
// Muestra por consola los controles asignados
void Input::printBindings(InputDevice device, int controller_index) const
{
if (device == InputDevice::ANY || device == InputDevice::KEYBOARD)
{
return;
}
if (device == InputDevice::CONTROLLER)
{
if (controller_index >= num_gamepads_)
{
return;
}
// Muestra el nombre del mando
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n%s", controller_names_.at(controller_index).c_str());
// Muestra los botones asignados
for (auto bi : button_inputs_)
{
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s : %d", to_string(bi).c_str(), controller_bindings_.at(controller_index).at(static_cast<int>(bi)).button);
}
}
}
// Obtiene el SDL_GamepadButton asignado a un input
SDL_GamepadButton Input::getControllerBinding(int controller_index, InputAction input) const
{
return controller_bindings_[controller_index][static_cast<int>(input)].button;
}
// Obtiene el indice a partir del nombre del mando
int Input::getIndexByName(const std::string &name) const
{
auto it = std::find(controller_names_.begin(), controller_names_.end(), name);
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
}
// Convierte un InputAction a std::string
std::string Input::to_string(InputAction input) const
{
switch (input)
{
case InputAction::FIRE_LEFT:
return "input_fire_left";
case InputAction::FIRE_CENTER:
return "input_fire_center";
case InputAction::FIRE_RIGHT:
return "input_fire_right";
case InputAction::START:
return "input_start";
case InputAction::SERVICE:
return "input_service";
default:
return "";
}
}
// Convierte un std::string a InputAction
InputAction Input::to_inputs_e(const std::string &name) const
{
static const std::unordered_map<std::string, InputAction> inputMap = {
{"input_fire_left", InputAction::FIRE_LEFT},
{"input_fire_center", InputAction::FIRE_CENTER},
{"input_fire_right", InputAction::FIRE_RIGHT},
{"input_start", InputAction::START},
{"input_service", InputAction::SERVICE}};
auto it = inputMap.find(name);
return it != inputMap.end() ? it->second : InputAction::NONE;
}
// Comprueba el eje del mando
bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
{
// Umbral para considerar el eje como activo
bool axis_active_now = false;
switch (input)
{
case InputAction::LEFT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD_;
break;
case InputAction::RIGHT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD_;
break;
case InputAction::UP:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -AXIS_THRESHOLD_;
break;
case InputAction::DOWN:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > AXIS_THRESHOLD_;
break;
default:
return false;
}
// Referencia al binding correspondiente
auto &binding = controller_bindings_.at(controller_index).at(static_cast<int>(input));
if (repeat)
{
// Si se permite repetir, simplemente devolvemos el estado actual
return axis_active_now;
}
else
{
// Si no se permite repetir, aplicamos la lógica de transición
if (axis_active_now && !binding.axis_active)
{
// Transición de inactivo a activo
binding.axis_active = true;
return true;
}
else if (!axis_active_now && binding.axis_active)
{
// Transición de activo a inactivo
binding.axis_active = false;
}
// Mantener el estado actual
return false;
}
}
void Input::initSDLGamePad()
{
if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1)
{
if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD))
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GAMEPAD could not initialize! SDL Error: %s", SDL_GetError());
}
else
{
SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "\n** SDL_GAMEPAD: INITIALIZING");
discoverGameControllers();
SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "** SDL_GAMEPAD: INITIALIZATION COMPLETE\n");
}
}
}
void Input::resetInputStates()
{
// Resetear todos los KeyBindings.active a false
for (auto &key : key_bindings_)
{
key.is_held = false;
key.just_pressed = false;
}
// Resetear todos los ControllerBindings.active a false
for (auto &controller_vec : controller_bindings_)
{
for (auto &binding : controller_vec)
{
binding.is_held = false;
binding.just_pressed = false;
}
}
}
void Input::update()
{
// --- TECLADO ---
const bool *key_states = SDL_GetKeyboardState(nullptr);
for (size_t i = 0; i < key_bindings_.size(); ++i)
{
bool key_is_down_now = key_states[key_bindings_[i].scancode];
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
key_bindings_[i].just_pressed = key_is_down_now && !key_bindings_[i].is_held;
key_bindings_[i].is_held = key_is_down_now;
}
// --- MANDOS ---
for (int c = 0; c < num_gamepads_; ++c)
{
for (size_t i = 0; i < controller_bindings_[c].size(); ++i)
{
bool button_is_down_now = SDL_GetGamepadButton(connected_controllers_.at(c), controller_bindings_.at(c).at(i).button) != 0;
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
controller_bindings_[c][i].just_pressed = button_is_down_now && !controller_bindings_[c][i].is_held;
controller_bindings_[c][i].is_held = button_is_down_now;
}
}
}