463 lines
16 KiB
C++
463 lines
16 KiB
C++
#include "input.h"
|
|
|
|
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_GetGamepa...
|
|
|
|
#include <algorithm> // Para find
|
|
#include <cstddef> // Para size_t
|
|
#include <iterator> // Para distance
|
|
#include <memory> // Para std::unique_ptr
|
|
#include <unordered_map> // Para unordered_map, _Node_const_iterator, operat...
|
|
#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, const std::string &gamepad_configs_file) {
|
|
Input::instance = new Input(game_controller_db_path, gamepad_configs_file);
|
|
}
|
|
|
|
// Libera la instancia
|
|
void Input::destroy() { delete Input::instance; }
|
|
|
|
// Obtiene la instancia
|
|
auto Input::get() -> Input * { return Input::instance; }
|
|
|
|
// Constructor
|
|
Input::Input(std::string game_controller_db_path, std::string gamepad_configs_file)
|
|
: gamepad_mappings_file_(std::move(game_controller_db_path)),
|
|
gamepad_configs_file_(std::move(gamepad_configs_file)) {
|
|
// Inicializa el subsistema SDL_INIT_GAMEPAD
|
|
initSDLGamePad();
|
|
|
|
// Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
|
|
button_inputs_ = {Action::FIRE_LEFT, Action::FIRE_CENTER, Action::FIRE_RIGHT, Action::START};
|
|
}
|
|
|
|
// Asigna inputs a teclas
|
|
void Input::bindKey(Action action, SDL_Scancode code) {
|
|
keyboard_.bindings[action].scancode = code;
|
|
}
|
|
|
|
// Asigna inputs a botones del mando
|
|
void Input::bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action action, SDL_GamepadButton button) {
|
|
if (gamepad != nullptr) {
|
|
gamepad->bindings[action].button = button;
|
|
}
|
|
}
|
|
|
|
// Asigna inputs a botones del mando
|
|
void Input::bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action input_target, Action input_source) {
|
|
if (gamepad != nullptr) {
|
|
gamepad->bindings[input_target].button = gamepad->bindings[input_source].button;
|
|
}
|
|
}
|
|
|
|
// Comprueba si un input esta activo
|
|
auto Input::checkAction(Action action, bool repeat, bool check_keyboard, std::shared_ptr<Gamepad> gamepad) -> bool {
|
|
bool success_keyboard = false;
|
|
bool success_controller = false;
|
|
|
|
if (check_keyboard) {
|
|
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
|
success_keyboard = keyboard_.bindings[action].is_held;
|
|
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
|
success_keyboard = keyboard_.bindings[action].just_pressed;
|
|
}
|
|
}
|
|
|
|
if (gamepad != nullptr) {
|
|
success_controller = checkAxisInput(action, gamepad, repeat);
|
|
|
|
if (!success_controller) {
|
|
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
|
success_controller = gamepad->bindings[action].is_held;
|
|
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
|
success_controller = gamepad->bindings[action].just_pressed;
|
|
}
|
|
}
|
|
}
|
|
|
|
return (success_keyboard || success_controller);
|
|
}
|
|
|
|
// Comprueba si hay almenos un input activo
|
|
auto Input::checkAnyInput(bool check_keyboard, std::shared_ptr<Gamepad> gamepad) -> bool {
|
|
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
|
|
|
|
// --- Comprobación del Teclado ---
|
|
if (check_keyboard) {
|
|
for (const auto &pair : keyboard_.bindings) {
|
|
// Simplemente leemos el estado pre-calculado por Input::update().
|
|
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
|
|
if (pair.second.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 (gamepad != nullptr) {
|
|
// Iteramos sobre todas las acciones, no sobre el número de mandos.
|
|
for (const auto &pair : gamepad->bindings) {
|
|
// Leemos el estado pre-calculado para el mando y la acción específicos.
|
|
if (pair.second.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
|
|
auto Input::checkAnyButton(bool repeat) -> bool {
|
|
// Solo comprueba los botones definidos previamente
|
|
for (auto bi : button_inputs_) {
|
|
// Comprueba el teclado
|
|
if (checkAction(bi, repeat, CHECK_KEYBOARD)) {
|
|
return true;
|
|
}
|
|
|
|
// Comprueba los mandos
|
|
for (auto gamepad : gamepads_) {
|
|
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
// Comprueba si hay algun mando conectado
|
|
auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); }
|
|
|
|
// Obten el nombre de un mando de juego
|
|
auto Input::getControllerName(std::shared_ptr<Gamepad> gamepad) const -> std::string { return gamepad == nullptr ? std::string() : gamepad->name; }
|
|
|
|
// Obten el número de mandos conectados
|
|
auto Input::getNumGamepads() const -> int { return gamepads_.size(); }
|
|
|
|
// Obtiene el indice del controlador a partir de un event.id
|
|
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
|
|
// for (int i = 0; i < num_joysticks_; ++i) {
|
|
// if (SDL_GetJoystickID(joysticks_[i]) == id) {
|
|
// return i;
|
|
// }
|
|
// }
|
|
return -1;
|
|
}
|
|
|
|
// Obtiene el SDL_GamepadButton asignado a un input
|
|
auto Input::getControllerBinding(std::shared_ptr<Gamepad> gamepad, Action input) const -> SDL_GamepadButton {
|
|
return gamepad->bindings[input].button;
|
|
}
|
|
|
|
// Convierte un InputAction a std::string
|
|
auto Input::inputToString(Action input) -> std::string {
|
|
switch (input) {
|
|
case Action::FIRE_LEFT:
|
|
return "input_fire_left";
|
|
case Action::FIRE_CENTER:
|
|
return "input_fire_center";
|
|
case Action::FIRE_RIGHT:
|
|
return "input_fire_right";
|
|
case Action::START:
|
|
return "input_start";
|
|
case Action::SERVICE:
|
|
return "input_service";
|
|
default:
|
|
return "";
|
|
}
|
|
}
|
|
|
|
// Convierte un std::string a InputAction
|
|
auto Input::stringToInput(const std::string &name) -> Action {
|
|
static const std::unordered_map<std::string, Action> INPUT_MAP = {
|
|
{"input_fire_left", Action::FIRE_LEFT},
|
|
{"input_fire_center", Action::FIRE_CENTER},
|
|
{"input_fire_right", Action::FIRE_RIGHT},
|
|
{"input_start", Action::START},
|
|
{"input_service", Action::SERVICE}};
|
|
|
|
auto it = INPUT_MAP.find(name);
|
|
return it != INPUT_MAP.end() ? it->second : Action::NONE;
|
|
}
|
|
|
|
// Comprueba el eje del mando
|
|
auto Input::checkAxisInput(Action input, std::shared_ptr<Gamepad> gamepad, bool repeat) -> bool {
|
|
// Umbral para considerar el eje como activo
|
|
bool axis_active_now = false;
|
|
|
|
switch (input) {
|
|
case Action::LEFT:
|
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
|
|
break;
|
|
case Action::RIGHT:
|
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
|
|
break;
|
|
case Action::UP:
|
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTY) < -AXIS_THRESHOLD;
|
|
break;
|
|
case Action::DOWN:
|
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTY) > AXIS_THRESHOLD;
|
|
break;
|
|
default:
|
|
return false;
|
|
}
|
|
|
|
// Referencia al binding correspondiente
|
|
auto &binding = gamepad->bindings[input];
|
|
|
|
if (repeat) {
|
|
// Si se permite repetir, simplemente devolvemos el estado actual
|
|
return axis_active_now;
|
|
} // 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;
|
|
}
|
|
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::addGamepadMappingsFromFile() {
|
|
if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) {
|
|
std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << std::endl;
|
|
}
|
|
}
|
|
|
|
void Input::discoverGamepads() {
|
|
SDL_Event event;
|
|
while (SDL_PollEvent(&event)) {
|
|
handleEvent(event); // Comprueba mandos conectados
|
|
}
|
|
}
|
|
|
|
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 {
|
|
addGamepadMappingsFromFile();
|
|
loadGamepadConfigs();
|
|
discoverGamepads();
|
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "** Input System initialized successfully\n");
|
|
}
|
|
}
|
|
}
|
|
|
|
void Input::resetInputStates() {
|
|
// Resetear todos los KeyBindings.active a false
|
|
for (auto &key : keyboard_.bindings) {
|
|
key.second.is_held = false;
|
|
key.second.just_pressed = false;
|
|
}
|
|
// Resetear todos los ControllerBindings.active a false
|
|
for (auto &gamepad : gamepads_) {
|
|
for (auto &binding : gamepad->bindings) {
|
|
binding.second.is_held = false;
|
|
binding.second.just_pressed = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
void Input::update() {
|
|
// --- TECLADO ---
|
|
const bool *key_states = SDL_GetKeyboardState(nullptr);
|
|
|
|
for (auto &binding : keyboard_.bindings) {
|
|
bool key_is_down_now = key_states[binding.second.scancode];
|
|
|
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
|
binding.second.just_pressed = key_is_down_now && !binding.second.is_held;
|
|
binding.second.is_held = key_is_down_now;
|
|
}
|
|
|
|
// --- MANDOS ---
|
|
for (auto gamepad : gamepads_) {
|
|
for (auto &binding : gamepad->bindings) {
|
|
bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(gamepad->pad, binding.second.button)) != 0;
|
|
|
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
|
binding.second.just_pressed = button_is_down_now && !binding.second.is_held;
|
|
binding.second.is_held = button_is_down_now;
|
|
}
|
|
}
|
|
}
|
|
|
|
void Input::handleEvent(const SDL_Event &event) {
|
|
switch (event.type) {
|
|
case SDL_EVENT_GAMEPAD_ADDED:
|
|
add_gamepad(event.gdevice.which);
|
|
break;
|
|
case SDL_EVENT_GAMEPAD_REMOVED:
|
|
remove_gamepad(event.gdevice.which);
|
|
break;
|
|
}
|
|
}
|
|
|
|
void Input::add_gamepad(int device_index) {
|
|
SDL_Gamepad *pad = SDL_OpenGamepad(device_index);
|
|
if (!pad) {
|
|
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << std::endl;
|
|
return;
|
|
}
|
|
|
|
auto gamepad = std::make_shared<Gamepad>(pad);
|
|
std::cout << "Gamepad connected (" << gamepad->name << ")" << std::endl;
|
|
applyGamepadConfig(gamepad);
|
|
saveGamepadConfigFromGamepad(gamepad);
|
|
gamepads_.push_back(std::move(gamepad));
|
|
}
|
|
|
|
void Input::remove_gamepad(SDL_JoystickID id) {
|
|
auto it = std::remove_if(gamepads_.begin(), gamepads_.end(), [id](const std::shared_ptr<Gamepad> &gamepad) {
|
|
return gamepad->instance_id == id;
|
|
});
|
|
|
|
if (it != gamepads_.end()) {
|
|
std::cout << "Gamepad disconnected (" << (*it)->name << ")" << std::endl;
|
|
gamepads_.erase(it, gamepads_.end());
|
|
} else {
|
|
std::cerr << "No se encontró el gamepad con ID " << id << std::endl;
|
|
}
|
|
}
|
|
|
|
void Input::printConnectedGamepads() const {
|
|
if (gamepads_.empty()) {
|
|
std::cout << "No hay gamepads conectados." << std::endl;
|
|
return;
|
|
}
|
|
|
|
std::cout << "Gamepads conectados:\n";
|
|
for (const auto &gamepad : gamepads_) {
|
|
std::string name = gamepad->name == "" ? "Desconocido" : gamepad->name;
|
|
std::cout << " - ID: " << gamepad->instance_id
|
|
<< ", Nombre: " << name << ")" << std::endl;
|
|
}
|
|
}
|
|
|
|
void Input::loadGamepadConfigs() {
|
|
if (GamepadConfigManager::fileExists(gamepad_configs_file_)) {
|
|
GamepadConfigManager::readFromJson(gamepad_configs_, gamepad_configs_file_);
|
|
}
|
|
}
|
|
|
|
void Input::saveGamepadConfigs() {
|
|
GamepadConfigManager::writeToJson(gamepad_configs_, gamepad_configs_file_);
|
|
}
|
|
|
|
void Input::applyGamepadConfig(std::shared_ptr<Gamepad> gamepad) {
|
|
if (!gamepad) {
|
|
return;
|
|
}
|
|
|
|
// Buscar configuración por nombre del gamepad
|
|
auto configIt = std::find_if(gamepad_configs_.begin(), gamepad_configs_.end(), [&gamepad](const GamepadConfig &config) {
|
|
return config.name == gamepad->name;
|
|
});
|
|
|
|
if (configIt != gamepad_configs_.end()) {
|
|
// Aplicar la configuración encontrada al gamepad
|
|
for (const auto &[action, button] : configIt->bindings) {
|
|
if (gamepad->bindings.find(action) != gamepad->bindings.end()) {
|
|
gamepad->bindings[action].button = button;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void Input::saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad) {
|
|
if (!gamepad) {
|
|
return;
|
|
}
|
|
|
|
// Buscar si ya existe una configuración con este nombre
|
|
auto configIt = std::find_if(gamepad_configs_.begin(), gamepad_configs_.end(), [&gamepad](const GamepadConfig &config) {
|
|
return config.name == gamepad->name;
|
|
});
|
|
|
|
// Crear nueva configuración desde el gamepad
|
|
GamepadConfig newConfig(gamepad->name);
|
|
newConfig.bindings.clear(); // Limpiar bindings por defecto
|
|
|
|
// Copiar todos los bindings del gamepad
|
|
for (const auto &[action, buttonState] : gamepad->bindings) {
|
|
newConfig.bindings[action] = buttonState.button;
|
|
}
|
|
|
|
if (configIt != gamepad_configs_.end()) {
|
|
// Sobreescribir configuración existente
|
|
*configIt = newConfig;
|
|
} else {
|
|
// Añadir nueva configuración
|
|
gamepad_configs_.push_back(newConfig);
|
|
}
|
|
|
|
// Guardar cambios inmediatamente
|
|
saveGamepadConfigs();
|
|
}
|
|
|
|
// Método para establecer el archivo de configuración (opcional)
|
|
void Input::setGamepadConfigsFile(const std::string &filename) {
|
|
gamepad_configs_file_ = filename;
|
|
loadGamepadConfigs(); // Recargar con el nuevo archivo
|
|
}
|
|
|
|
// Método para obtener configuración de un gamepad específico (opcional)
|
|
GamepadConfig *Input::getGamepadConfig(const std::string &gamepadName) {
|
|
auto configIt = std::find_if(gamepad_configs_.begin(), gamepad_configs_.end(), [&gamepadName](const GamepadConfig &config) {
|
|
return config.name == gamepadName;
|
|
});
|
|
|
|
return (configIt != gamepad_configs_.end()) ? &(*configIt) : nullptr;
|
|
}
|
|
|
|
// Método para eliminar configuración de gamepad (opcional)
|
|
bool Input::removeGamepadConfig(const std::string &gamepadName) {
|
|
auto configIt = std::find_if(gamepad_configs_.begin(), gamepad_configs_.end(), [&gamepadName](const GamepadConfig &config) {
|
|
return config.name == gamepadName;
|
|
});
|
|
|
|
if (configIt != gamepad_configs_.end()) {
|
|
gamepad_configs_.erase(configIt);
|
|
saveGamepadConfigs();
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
std::shared_ptr<Input::Gamepad> Input::findAvailableGamepadByName(const std::string &gamepad_name)
|
|
{
|
|
// Si no hay gamepads disponibles, devolver gamepad por defecto
|
|
if (gamepads_.empty()) {
|
|
return nullptr;
|
|
}
|
|
|
|
// Buscar por nombre
|
|
for (const auto& gamepad : gamepads_) {
|
|
if (gamepad && gamepad->name == gamepad_name) {
|
|
return gamepad;
|
|
}
|
|
}
|
|
|
|
// Si no se encuentra por nombre, devolver el primer gamepad válido
|
|
for (const auto& gamepad : gamepads_) {
|
|
if (gamepad) {
|
|
return gamepad;
|
|
}
|
|
}
|
|
|
|
// Si llegamos aquí, no hay gamepads válidos
|
|
return nullptr;
|
|
} |