migrat Input a la ultima versió

cohesionats tots els metodes update de les escenes
This commit is contained in:
2025-11-01 22:28:51 +01:00
parent 1dd750ba0c
commit 824e7417ad
58 changed files with 26926 additions and 978 deletions

View File

@@ -0,0 +1,134 @@
#pragma once
#include <fstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "core/input/input_types.hpp" // Solo incluimos los tipos compartidos
#include "external/json.hpp"
// --- Estructuras ---
struct GamepadConfig {
std::string name; // Nombre del dispositivo
std::string path; // Ruta física del dispositivo
std::unordered_map<InputAction, SDL_GamepadButton> bindings; // Asociación acción-botón
GamepadConfig(std::string name, std::string path)
: name(std::move(name)),
path(std::move(path)),
bindings{
{InputAction::LEFT, SDL_GAMEPAD_BUTTON_DPAD_LEFT},
{InputAction::RIGHT, SDL_GAMEPAD_BUTTON_DPAD_RIGHT},
{InputAction::JUMP, SDL_GAMEPAD_BUTTON_WEST}} {}
// Reasigna un botón a una acción
void rebindAction(InputAction action, SDL_GamepadButton new_button) {
bindings[action] = new_button;
}
};
// --- Tipos ---
using GamepadConfigs = std::vector<GamepadConfig>; // Vector de configuraciones de gamepad
// --- Clase GamepadConfigManager: gestor de configuraciones de gamepad ---
class GamepadConfigManager {
public:
// --- Métodos estáticos ---
static auto writeToJson(const GamepadConfigs& configs, const std::string& filename) -> bool { // Escribir configuraciones a JSON
try {
nlohmann::json j;
j["gamepads"] = nlohmann::json::array();
for (const auto& config : configs) {
nlohmann::json gamepad_json;
gamepad_json["name"] = config.name;
gamepad_json["path"] = config.path;
gamepad_json["bindings"] = nlohmann::json::object();
// Convertir bindings a JSON
for (const auto& [action, button] : config.bindings) {
auto action_it = ACTION_TO_STRING.find(action);
auto button_it = BUTTON_TO_STRING.find(button);
if (action_it != ACTION_TO_STRING.end() && button_it != BUTTON_TO_STRING.end()) {
gamepad_json["bindings"][action_it->second] = button_it->second;
}
}
j["gamepads"].push_back(gamepad_json);
}
// Escribir al archivo
std::ofstream file(filename);
if (!file.is_open()) {
return false;
}
file << j.dump(4); // Formato con indentación de 4 espacios
file.close();
return true;
} catch (const std::exception& e) {
// Log del error si tienes sistema de logging
return false;
}
}
// Leer vector de GamepadConfig desde archivo JSON
static auto readFromJson(GamepadConfigs& configs, const std::string& filename) -> bool {
try {
std::ifstream file(filename);
if (!file.is_open()) {
return false;
}
nlohmann::json j;
file >> j;
file.close();
configs.clear();
if (!j.contains("gamepads") || !j["gamepads"].is_array()) {
return false;
}
for (const auto& gamepad_json : j["gamepads"]) {
if (!gamepad_json.contains("name") || !gamepad_json.contains("bindings")) {
continue; // Saltar configuraciones malformadas
}
// Leer el campo path si existe, si no dejarlo vacío
std::string path = gamepad_json.contains("path") ? gamepad_json["path"].get<std::string>() : "";
GamepadConfig config(gamepad_json["name"], path);
// Limpiar bindings por defecto para cargar los del archivo
config.bindings.clear();
// Cargar bindings desde JSON
for (const auto& [actionStr, buttonStr] : gamepad_json["bindings"].items()) {
auto action_it = STRING_TO_ACTION.find(actionStr);
auto button_it = STRING_TO_BUTTON.find(buttonStr);
if (action_it != STRING_TO_ACTION.end() && button_it != STRING_TO_BUTTON.end()) {
config.bindings[action_it->second] = button_it->second;
}
}
configs.push_back(config);
}
return true;
} catch (const std::exception& e) {
// Log del error si tienes sistema de logging
return false;
}
}
// Método auxiliar para verificar si un archivo existe
static auto fileExists(const std::string& filename) -> bool {
std::ifstream file(filename);
return file.good();
}
};

View File

@@ -1,5 +1,3 @@
#include "game/scene_manager.hpp" // Para SceneManager
#include "core/input/global_inputs.hpp"
#include <SDL3/SDL.h>
@@ -7,9 +5,10 @@
#include <string> // Para allocator, operator+, char_traits, string
#include <vector> // Para vector
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT
#include "core/rendering/screen.hpp" // Para Screen
#include "game/options.hpp" // Para Options, options, OptionsVideo, Section
#include "game/options.hpp" // Para Options, options, OptionsVideo, Section
#include "game/scene_manager.hpp" // Para SceneManager
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText
#include "utils/utils.hpp" // Para stringInVector
@@ -46,59 +45,59 @@ void skipSection() {
}
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
void check() {
if (Input::get()->checkInput(InputAction::EXIT, INPUT_DO_NOT_ALLOW_REPEAT)) {
void handle() {
if (Input::get()->checkAction(InputAction::EXIT, Input::DO_NOT_ALLOW_REPEAT)) {
quit();
}
else if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
skipSection();
}
else if (Input::get()->checkInput(InputAction::TOGGLE_BORDER, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::TOGGLE_BORDER, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleBorder();
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::TOGGLE_VIDEOMODE, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::TOGGLE_VIDEOMODE, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleVideoMode();
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::WINDOW_DEC_ZOOM, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::WINDOW_DEC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
if (Screen::get()->decWindowZoom()) {
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
}
}
else if (Input::get()->checkInput(InputAction::WINDOW_INC_ZOOM, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::WINDOW_INC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
if (Screen::get()->incWindowZoom()) {
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
}
}
else if (Input::get()->checkInput(InputAction::TOGGLE_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::TOGGLE_SHADERS, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleShaders();
Notifier::get()->show({"SHADERS " + std::string(Options::video.shaders ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::NEXT_PALETTE, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::NEXT_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->nextPalette();
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::PREVIOUS_PALETTE, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::PREVIOUS_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->previousPalette();
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::TOGGLE_INTEGER_SCALE, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::TOGGLE_INTEGER_SCALE, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleIntegerScale();
Screen::get()->setVideoMode(Options::video.fullscreen);
Notifier::get()->show({"INTEGER SCALE " + std::string(Options::video.integer_scale ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
}
else if (Input::get()->checkInput(InputAction::SHOW_DEBUG_INFO, INPUT_DO_NOT_ALLOW_REPEAT)) {
else if (Input::get()->checkAction(InputAction::SHOW_DEBUG_INFO, Input::DO_NOT_ALLOW_REPEAT)) {
Screen::get()->toggleDebugInfo();
}
}

View File

@@ -2,5 +2,5 @@
namespace GlobalInputs {
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
void check();
void handle();
} // namespace GlobalInputs

View File

@@ -1,114 +1,79 @@
#include "core/input/input.hpp"
#include <SDL3/SDL.h>
#include <SDL3/SDL.h> // Para SDL_GetGamepadAxis, SDL_GamepadAxis, SDL_GamepadButton, SDL_GetError, SDL_JoystickID, SDL_AddGamepadMappingsFromFile, SDL_Event, SDL_EventType, SDL_GetGamepadButton, SDL_GetKeyboardState, SDL_INIT_GAMEPAD, SDL_InitSubSystem, SDL_LogError, SDL_OpenGamepad, SDL_PollEvent, SDL_WasInit, Sint16, SDL_Gamepad, SDL_LogCategory, SDL_Scancode
#include <algorithm> // Para find
#include <iostream> // Para basic_ostream, operator<<, cout, endl
#include <iterator> // Para distance
#include <unordered_map> // Para unordered_map, operator==, _Node_cons...
#include <utility> // Para pair
#include <iostream> // Para basic_ostream, operator<<, cout, cerr
#include <memory> // Para shared_ptr, __shared_ptr_access, allocator, operator==, make_shared
#include <ranges> // Para __find_if_fn, find_if
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==, _Node_iterator_base, _Node_const_iterator
#include <utility> // Para pair, move
// [SINGLETON]
Input* Input::input = nullptr;
// Singleton
Input* Input::instance = nullptr;
// [SINGLETON] Crearemos el objeto con esta función estática
void Input::init(const std::string& game_controller_db_path) {
Input::input = new Input(game_controller_db_path);
// 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);
}
// [SINGLETON] Destruiremos el objeto con esta función estática
void Input::destroy() {
delete Input::input;
}
// Libera la instancia
void Input::destroy() { delete Input::instance; }
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
auto Input::get() -> Input* {
return Input::input;
}
// Obtiene la instancia
auto Input::get() -> Input* { return Input::instance; }
// Constructor
Input::Input(const std::string& game_controller_db_path)
: game_controller_db_path_(game_controller_db_path) {
// Busca si hay mandos conectados
discoverGameControllers();
// 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::JUMP};
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();
}
// Asigna inputs a teclas
void Input::bindKey(InputAction input, SDL_Scancode code) {
key_bindings_.at(static_cast<int>(input)).scancode = code;
void Input::bindKey(Action action, SDL_Scancode code) {
keyboard_.bindings[action].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;
void Input::bindGameControllerButton(const 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(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;
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source) {
if (gamepad != nullptr) {
gamepad->bindings[action_target].button = gamepad->bindings[action_source].button;
}
}
// Comprueba si un input esta activo
auto Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) -> bool {
// Comprueba si alguna acción está activa
auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
bool success_keyboard = false;
bool success_controller = false;
const int INPUT_INDEX = static_cast<int>(input);
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
const auto* key_states = SDL_GetKeyboardState(nullptr);
if (repeat) {
success_keyboard = static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0;
} else {
if (!key_bindings_[INPUT_INDEX].active) {
if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0) {
key_bindings_[INPUT_INDEX].active = true;
success_keyboard = true;
} else {
success_keyboard = false;
}
} else {
if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) == 0) {
key_bindings_[INPUT_INDEX].active = false;
}
success_keyboard = 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 (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) {
if ((device == InputDeviceToUse::CONTROLLER) || (device == InputDeviceToUse::ANY)) {
success_controller = checkAxisInput(input, controller_index, repeat);
if (gamepad != nullptr) {
success_controller = checkAxisInput(action, gamepad, repeat);
if (!success_controller) {
if (repeat) {
success_controller = static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0;
} else {
if (!controller_bindings_.at(controller_index).at(INPUT_INDEX).active) {
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0) {
controller_bindings_.at(controller_index).at(INPUT_INDEX).active = true;
success_controller = true;
} else {
success_controller = false;
}
} else {
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) == 0) {
controller_bindings_.at(controller_index).at(INPUT_INDEX).active = false;
}
success_controller = false;
}
}
if (!success_controller) {
success_controller = checkTriggerInput(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;
}
}
}
@@ -116,26 +81,50 @@ auto Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
return (success_keyboard || success_controller);
}
// Comprueba si hay almenos un input activo
auto Input::checkAnyInput(InputDeviceToUse device, int controller_index) -> bool {
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
const bool* key_states = SDL_GetKeyboardState(nullptr);
// Comprueba si hay almenos una acción activa
auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
for (auto& key_binding : key_bindings_) {
if (static_cast<int>(key_states[key_binding.scancode]) != 0 && !key_binding.active) {
key_binding.active = true;
return true;
// --- 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.
}
}
}
if (gameControllerFound()) {
if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY) {
for (int i = 0; i < (int)controller_bindings_.size(); ++i) {
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button)) != 0 && !controller_bindings_[controller_index][i].active) {
controller_bindings_[controller_index][i].active = true;
return true;
}
// --- 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 (const auto& gamepad : gamepads_) {
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
return true;
}
}
}
@@ -143,131 +132,68 @@ auto Input::checkAnyInput(InputDeviceToUse device, int controller_index) -> bool
return false;
}
// Busca si hay mandos conectados
auto Input::discoverGameControllers() -> bool {
bool found = false;
// Asegúrate de que el subsistema de gamepads está inicializado
if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) {
SDL_InitSubSystem(SDL_INIT_GAMEPAD);
}
// Carga el mapping de mandos desde archivo
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
std::cout << "Error, could not load " << game_controller_db_path_.c_str()
<< " file: " << SDL_GetError() << '\n';
}
// En SDL3 ya no existe SDL_NumJoysticks()
// Ahora se obtiene un array dinámico de IDs
int num_joysticks = 0;
SDL_JoystickID* joystick_ids = SDL_GetJoysticks(&num_joysticks);
num_joysticks_ = num_joysticks;
num_gamepads_ = 0;
joysticks_.clear();
// Recorremos todos los joysticks detectados
for (int i = 0; i < num_joysticks_; ++i) {
SDL_Joystick* joy = SDL_OpenJoystick(joystick_ids[i]);
joysticks_.push_back(joy);
if (SDL_IsGamepad(joystick_ids[i])) {
num_gamepads_++;
}
}
std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << '\n';
if (num_joysticks_ != num_gamepads_) {
std::cout << "Joysticks found: " << num_joysticks_ << '\n';
std::cout << "Gamepads found : " << num_gamepads_ << '\n';
} else {
std::cout << "Gamepads found: " << num_gamepads_ << '\n';
}
if (num_gamepads_ > 0) {
found = true;
for (int i = 0; i < num_joysticks_; i++) {
if (SDL_IsGamepad(joystick_ids[i])) {
SDL_Gamepad* pad = SDL_OpenGamepad(joystick_ids[i]);
if ((pad != nullptr) && SDL_GamepadConnected(pad)) {
connected_controllers_.push_back(pad);
const char* name = SDL_GetGamepadName(pad);
std::cout << "#" << i << ": " << ((name != nullptr) ? name : "Unknown") << '\n';
controller_names_.emplace_back((name != nullptr) ? name : "Unknown");
} else {
std::cout << "SDL_GetError() = " << SDL_GetError() << '\n';
}
}
}
// En SDL3 ya no hace falta SDL_GameControllerEventState()
// Los eventos de gamepad están siempre habilitados
}
SDL_free(joystick_ids);
std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << '\n';
return found;
}
// Comprueba si hay algun mando conectado
auto Input::gameControllerFound() const -> bool { return num_gamepads_ > 0; }
auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); }
// Obten el nombre de un mando de juego
auto Input::getControllerName(int controller_index) const -> std::string { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
auto Input::getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string {
return gamepad == nullptr ? std::string() : gamepad->name;
}
// Obtiene la lista de nombres de mandos
auto Input::getControllerNames() const -> std::vector<std::string> {
std::vector<std::string> names;
for (const auto& gamepad : gamepads_) {
names.push_back(gamepad->name);
}
return names;
}
// Obten el número de mandos conectados
auto Input::getNumControllers() const -> int { return num_gamepads_; }
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;
// Obtiene el gamepad a partir de un event.id
auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Input::Gamepad> {
for (const auto& gamepad : gamepads_) {
if (gamepad->instance_id == id) {
return gamepad;
}
}
return -1;
return nullptr;
}
// Obtiene el SDL_GamepadButton asignado a un input
auto Input::getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton {
return controller_bindings_[controller_index][static_cast<int>(input)].button;
auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad> {
for (const auto& gamepad : gamepads_) {
if (gamepad && gamepad->name == name) {
return gamepad;
}
}
return nullptr;
}
// Obtiene el indice a partir del nombre del mando
auto Input::getIndexByName(const std::string& name) const -> int {
auto it = std::ranges::find(controller_names_, name);
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
// Obtiene el SDL_GamepadButton asignado a un action
auto Input::getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton {
return static_cast<SDL_GamepadButton>(gamepad->bindings[action].button);
}
// Comprueba el eje del mando
auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool {
auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
// Umbral para considerar el eje como activo
const Sint16 THRESHOLD = 30000;
bool axis_active_now = false;
switch (input) {
case InputAction::LEFT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -THRESHOLD;
switch (action) {
case Action::LEFT:
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
break;
case InputAction::RIGHT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > THRESHOLD;
break;
case InputAction::UP:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -THRESHOLD;
break;
case InputAction::DOWN:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > THRESHOLD;
case Action::RIGHT:
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
break;
default:
return false;
}
// Referencia al binding correspondiente
auto& binding = controller_bindings_.at(controller_index).at(static_cast<int>(input));
auto& binding = gamepad->bindings[action];
if (repeat) {
// Si se permite repetir, simplemente devolvemos el estado actual
@@ -284,4 +210,290 @@ auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
}
// Mantener el estado actual
return false;
}
// Comprueba los triggers del mando como botones digitales
auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
// Solo manejamos botones específicos que pueden ser triggers
if (gamepad->bindings[action].button != static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)) {
// Solo procesamos L2 y R2 como triggers
int button = gamepad->bindings[action].button;
// Verificar si el botón mapeado corresponde a un trigger virtual
// (Para esto necesitamos valores especiales que representen L2/R2 como botones)
bool trigger_active_now = false;
// Usamos constantes especiales para L2 y R2 como botones
if (button == TRIGGER_L2_AS_BUTTON) { // L2 como botón
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER);
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
} else if (button == TRIGGER_R2_AS_BUTTON) { // R2 como botón
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER);
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
} else {
return false; // No es un trigger
}
// Referencia al binding correspondiente
auto& binding = gamepad->bindings[action];
if (repeat) {
// Si se permite repetir, simplemente devolvemos el estado actual
return trigger_active_now;
}
// Si no se permite repetir, aplicamos la lógica de transición
if (trigger_active_now && !binding.trigger_active) {
// Transición de inactivo a activo
binding.trigger_active = true;
return true;
}
if (!trigger_active_now && binding.trigger_active) {
// Transición de activo a inactivo
binding.trigger_active = false;
}
// Mantener el estado actual
return false;
}
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() << '\n';
}
}
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();
std::cout << "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;
binding.second.trigger_active = 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 (const auto& gamepad : gamepads_) {
for (auto& binding : gamepad->bindings) {
bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(gamepad->pad, static_cast<SDL_GamepadButton>(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;
}
}
}
auto Input::handleEvent(const SDL_Event& event) -> std::string {
switch (event.type) {
case SDL_EVENT_GAMEPAD_ADDED:
return addGamepad(event.gdevice.which);
case SDL_EVENT_GAMEPAD_REMOVED:
return removeGamepad(event.gdevice.which);
}
return {};
}
auto Input::addGamepad(int device_index) -> std::string {
SDL_Gamepad* pad = SDL_OpenGamepad(device_index);
if (pad == nullptr) {
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n';
return {};
}
auto gamepad = std::make_shared<Gamepad>(pad);
auto name = gamepad->name;
std::cout << "Gamepad connected (" << name << ")" << '\n';
applyGamepadConfig(gamepad);
saveGamepadConfigFromGamepad(gamepad);
gamepads_.push_back(std::move(gamepad));
return name + " CONNECTED";
}
auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad>& gamepad) {
return gamepad->instance_id == id;
});
if (it != gamepads_.end()) {
std::string name = (*it)->name;
std::cout << "Gamepad disconnected (" << name << ")" << '\n';
gamepads_.erase(it);
return name + " DISCONNECTED";
}
std::cerr << "No se encontró el gamepad con ID " << id << '\n';
return {};
}
void Input::printConnectedGamepads() const {
if (gamepads_.empty()) {
std::cout << "No hay gamepads conectados." << '\n';
return;
}
std::cout << "Gamepads conectados:\n";
for (const auto& gamepad : gamepads_) {
std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name;
std::cout << " - ID: " << gamepad->instance_id
<< ", Nombre: " << name << ")" << '\n';
}
}
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 || gamepad->path.empty()) { // No podemos aplicar config sin una ruta
return;
}
// --- Buscar configuración por RUTA (path) ---
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) {
return config.path == gamepad->path;
});
if (config_it != gamepad_configs_.end()) {
// Se encontró una configuración específica para este puerto/dispositivo. La aplicamos.
std::cout << "Applying custom config for gamepad at path: " << gamepad->path << '\n';
for (const auto& [action, button] : config_it->bindings) {
if (gamepad->bindings.find(action) != gamepad->bindings.end()) {
gamepad->bindings[action].button = button;
}
}
}
// Opcional: Podrías añadir un fallback para buscar por nombre si no se encuentra por ruta.
}
void Input::saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad) {
if (!gamepad || gamepad->path.empty()) { // No podemos guardar una config sin una ruta
return;
}
// --- CAMBIO CLAVE: Buscar si ya existe una configuración por RUTA (path) ---
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) {
return config.path == gamepad->path;
});
// Crear nueva configuración desde el gamepad, incluyendo nombre y ruta
GamepadConfig new_config(gamepad->name, gamepad->path); // <--- CAMBIO: Pasamos ambos
new_config.bindings.clear();
// Copiar todos los bindings actuales del gamepad
for (const auto& [action, buttonState] : gamepad->bindings) {
new_config.bindings[action] = static_cast<SDL_GamepadButton>(buttonState.button);
}
if (config_it != gamepad_configs_.end()) {
// Sobreescribir configuración existente para esta ruta
*config_it = new_config;
} else {
// Añadir nueva configuración
gamepad_configs_.push_back(new_config);
}
// 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)
auto Input::getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig* {
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) {
return config.name == gamepad_name;
});
return (config_it != gamepad_configs_.end()) ? &(*config_it) : nullptr;
}
// Método para eliminar configuración de gamepad (opcional)
auto Input::removeGamepadConfig(const std::string& gamepad_name) -> bool {
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) {
return config.name == gamepad_name;
});
if (config_it != gamepad_configs_.end()) {
gamepad_configs_.erase(config_it);
saveGamepadConfigs();
return true;
}
return false;
}
auto Input::findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Input::Gamepad> {
// 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;
}

View File

@@ -1,138 +1,194 @@
#pragma once
#include <SDL3/SDL.h>
#include <SDL3/SDL.h> // Para SDL_Scancode, SDL_GamepadButton, SDL_JoystickID, SDL_CloseGamepad, SDL_Gamepad, SDL_GetGamepadJoystick, SDL_GetGamepadName, SDL_GetGamepadPath, SDL_GetJoystickID, Sint16, Uint8, SDL_Event
#include <string> // Para string, basic_string
#include <vector> // Para vector
#include <array> // Para array
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string
#include <unordered_map> // Para unordered_map
#include <utility> // Para pair
#include <vector> // Para vector
// Definiciones de repetición
constexpr bool INPUT_ALLOW_REPEAT = true;
constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false;
// Tipos de entrada
enum class InputDeviceToUse : int {
KEYBOARD = 0,
CONTROLLER = 1,
ANY = 2,
};
enum class InputAction {
// Inputs obligatorios
UP,
DOWN,
LEFT,
RIGHT,
PAUSE,
EXIT,
ACCEPT,
CANCEL,
// Inputs personalizados
JUMP,
WINDOW_INC_ZOOM,
WINDOW_DEC_ZOOM,
TOGGLE_VIDEOMODE,
TOGGLE_INTEGER_SCALE,
TOGGLE_BORDER,
TOGGLE_MUSIC,
NEXT_PALETTE,
PREVIOUS_PALETTE,
TOGGLE_SHADERS,
SHOW_DEBUG_INFO,
// Input obligatorio
NONE,
SIZE
};
#include "core/input/gamepad_config_manager.hpp" // for GamepadConfig (ptr only), GamepadConfigs
#include "core/input/input_types.hpp" // for InputAction
// --- Clase Input: gestiona la entrada de teclado y mandos (singleton) ---
class Input {
private:
// [SINGLETON] Objeto privado
static Input* input;
public:
// --- Constantes ---
static constexpr bool ALLOW_REPEAT = true; // Permite repetición
static constexpr bool DO_NOT_ALLOW_REPEAT = false; // No permite repetición
static constexpr bool CHECK_KEYBOARD = true; // Comprueba teclado
static constexpr bool DO_NOT_CHECK_KEYBOARD = false; // No comprueba teclado
static constexpr int TRIGGER_L2_AS_BUTTON = 100; // L2 como botón
static constexpr int TRIGGER_R2_AS_BUTTON = 101; // R2 como botón
struct KeyBindings {
Uint8 scancode; // Scancode asociado
bool active; // Indica si está activo
// --- Tipos ---
using Action = InputAction; // Alias para mantener compatibilidad
// Constructor
explicit KeyBindings(Uint8 sc = 0, bool act = false)
: scancode(sc),
active(act) {}
// --- Estructuras ---
struct KeyState {
Uint8 scancode; // Scancode asociado
bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
KeyState(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
: scancode(scancode),
is_held(is_held),
just_pressed(just_pressed) {}
};
struct ControllerBindings {
SDL_GamepadButton button; // GameControllerButton asociado
bool active; // Indica si está activo
bool axis_active; // Estado del eje
struct ButtonState {
int button; // GameControllerButton asociado
bool is_held; // Está pulsada ahora mismo
bool just_pressed; // Se acaba de pulsar en este fotograma
bool axis_active; // Estado del eje
bool trigger_active{false}; // Estado del trigger como botón digital
// Constructor
explicit ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool act = false, bool axis_act = false)
ButtonState(int btn = static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID), bool is_held = false, bool just_pressed = false, bool axis_act = false)
: button(btn),
active(act),
is_held(is_held),
just_pressed(just_pressed),
axis_active(axis_act) {}
};
// Variables
std::vector<SDL_Gamepad*> connected_controllers_; // Vector con todos los mandos conectados
std::vector<SDL_Joystick*> joysticks_; // Vector con todos los joysticks conectados
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<std::vector<ControllerBindings>> controller_bindings_; // Vector con los botones asociadas a los inputs predefinidos para cada mando
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
std::vector<InputAction> button_inputs_; // Inputs asignados al jugador y a botones, excluyendo direcciones
int num_joysticks_ = 0; // Número de joysticks conectados
int num_gamepads_ = 0; // Número de mandos conectados
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
struct Keyboard {
std::unordered_map<Action, KeyState> bindings;
// Comprueba el eje del mando
auto checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool;
Keyboard()
: bindings{
// Movimiento del jugador
{Action::LEFT, KeyState(SDL_SCANCODE_LEFT)},
{Action::RIGHT, KeyState(SDL_SCANCODE_RIGHT)},
{Action::JUMP, KeyState(SDL_SCANCODE_UP)},
// Constructor
explicit Input(const std::string& game_controller_db_path);
// Inputs de control
{Action::ACCEPT, KeyState(SDL_SCANCODE_RETURN)},
{Action::CANCEL, KeyState(SDL_SCANCODE_ESCAPE)},
{Action::PAUSE, KeyState(SDL_SCANCODE_H)},
{Action::EXIT, KeyState(SDL_SCANCODE_ESCAPE)},
// Destructor
~Input() = default;
// Inputs de sistema
{Action::WINDOW_DEC_ZOOM, KeyState(SDL_SCANCODE_F1)},
{Action::WINDOW_INC_ZOOM, KeyState(SDL_SCANCODE_F2)},
{Action::TOGGLE_VIDEOMODE, KeyState(SDL_SCANCODE_F3)},
{Action::TOGGLE_SHADERS, KeyState(SDL_SCANCODE_F4)},
{Action::NEXT_PALETTE, KeyState(SDL_SCANCODE_F5)},
{Action::PREVIOUS_PALETTE, KeyState(SDL_SCANCODE_F6)},
{Action::TOGGLE_INTEGER_SCALE, KeyState(SDL_SCANCODE_F7)},
{Action::SHOW_DEBUG_INFO, KeyState(SDL_SCANCODE_F12)},
{Action::TOGGLE_MUSIC, KeyState(SDL_SCANCODE_M)},
{Action::TOGGLE_BORDER, KeyState(SDL_SCANCODE_B)}} {}
};
public:
// [SINGLETON] Crearemos el objeto con esta función estática
static void init(const std::string& game_controller_db_path);
struct Gamepad {
SDL_Gamepad* pad;
SDL_JoystickID instance_id;
std::string name;
std::string path;
std::unordered_map<Action, ButtonState> bindings;
// [SINGLETON] Destruiremos el objeto con esta función estática
Gamepad(SDL_Gamepad* gamepad)
: pad(gamepad),
instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))),
name(std::string(SDL_GetGamepadName(gamepad))),
path(std::string(SDL_GetGamepadPath(pad))),
bindings{
// Movimiento del jugador
{Action::LEFT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_LEFT))},
{Action::RIGHT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_RIGHT))},
{Action::JUMP, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_WEST))}} {}
~Gamepad() {
if (pad != nullptr) {
SDL_CloseGamepad(pad);
}
}
// Reasigna un botón a una acción
void rebindAction(Action action, SDL_GamepadButton new_button) {
bindings[action] = static_cast<int>(new_button);
}
};
// --- Tipos ---
using Gamepads = std::vector<std::shared_ptr<Gamepad>>; // Vector de gamepads
// --- Métodos de singleton ---
static void init(const std::string& game_controller_db_path, const std::string& gamepad_configs_file);
static void destroy();
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
static auto get() -> Input*;
// Asigna inputs a teclas
void bindKey(InputAction input, SDL_Scancode code);
// --- Métodos de configuración de controles ---
void bindKey(Action action, SDL_Scancode code);
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button);
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source);
// Asigna inputs a botones del mando
void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button);
void bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source);
// --- Métodos de consulta de entrada ---
void update();
auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool;
// Comprueba si un input esta activo
auto checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0) -> bool;
// Comprueba si hay almenos un input activo
auto checkAnyInput(InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0) -> bool;
// Busca si hay mandos conectados
auto discoverGameControllers() -> bool;
// Comprueba si hay algun mando conectado
// --- Métodos de gestión de mandos ---
[[nodiscard]] auto gameControllerFound() const -> bool;
static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string;
auto getControllerNames() const -> std::vector<std::string>;
[[nodiscard]] auto getNumGamepads() const -> int;
auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>;
auto getGamepads() const -> const Gamepads& { return gamepads_; }
// Obten el número de mandos conectados
[[nodiscard]] auto getNumControllers() const -> int;
// --- Métodos de consulta y utilidades ---
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;
// Obten el nombre de un mando de juego
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string;
// --- Métodos de reseteo de estado de entrada ---
void resetInputStates();
// Obtiene el indice del controlador a partir de un event.id
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int;
// --- Eventos ---
auto handleEvent(const SDL_Event& event) -> std::string;
// Obtiene el SDL_GamepadButton asignado a un input
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton;
void printConnectedGamepads() const;
// Obtiene el indice a partir del nombre del mando
[[nodiscard]] auto getIndexByName(const std::string& name) const -> int;
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
void saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad);
private:
// --- Constantes ---
static constexpr Sint16 AXIS_THRESHOLD = 30000;
static constexpr Sint16 TRIGGER_THRESHOLD = 16384; // Umbral para triggers (aproximadamente 50% del rango)
static constexpr std::array<Action, 1> BUTTON_INPUTS = {Action::JUMP}; // Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
// --- Variables internas ---
Gamepads gamepads_;
Keyboard keyboard_;
std::string gamepad_mappings_file_;
std::string gamepad_configs_file_;
GamepadConfigs gamepad_configs_;
// --- Métodos internos ---
void initSDLGamePad();
static auto checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
static auto checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
auto addGamepad(int device_index) -> std::string;
auto removeGamepad(SDL_JoystickID id) -> std::string;
void addGamepadMappingsFromFile();
void discoverGamepads();
// --- Métodos para integración con GamepadConfigManager ---
void loadGamepadConfigs();
void saveGamepadConfigs();
void applyGamepadConfig(std::shared_ptr<Gamepad> gamepad);
// Métodos auxiliares opcionales
void setGamepadConfigsFile(const std::string& filename);
auto getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig*;
auto removeGamepadConfig(const std::string& gamepad_name) -> bool;
// --- Constructor y destructor ---
explicit Input(std::string game_controller_db_path, std::string gamepad_configs_file);
~Input() = default;
// --- Singleton ---
static Input* instance;
};

View File

@@ -0,0 +1,76 @@
#include "input_types.hpp"
#include <utility> // Para pair
// Definición de los mapas
const std::unordered_map<InputAction, std::string> ACTION_TO_STRING = {
{InputAction::LEFT, "LEFT"},
{InputAction::RIGHT, "RIGHT"},
{InputAction::JUMP, "JUMP"},
{InputAction::PAUSE, "PAUSE"},
{InputAction::EXIT, "EXIT"},
{InputAction::ACCEPT, "ACCEPT"},
{InputAction::CANCEL, "CANCEL"},
{InputAction::WINDOW_INC_ZOOM, "WINDOW_INC_ZOOM"},
{InputAction::WINDOW_DEC_ZOOM, "WINDOW_DEC_ZOOM"},
{InputAction::TOGGLE_VIDEOMODE, "TOGGLE_VIDEOMODE"},
{InputAction::TOGGLE_INTEGER_SCALE, "TOGGLE_INTEGER_SCALE"},
{InputAction::TOGGLE_BORDER, "TOGGLE_BORDER"},
{InputAction::TOGGLE_MUSIC, "TOGGLE_MUSIC"},
{InputAction::NEXT_PALETTE, "NEXT_PALETTE"},
{InputAction::PREVIOUS_PALETTE, "PREVIOUS_PALETTE"},
{InputAction::TOGGLE_SHADERS, "TOGGLE_SHADERS"},
{InputAction::SHOW_DEBUG_INFO, "SHOW_DEBUG_INFO"},
{InputAction::NONE, "NONE"}};
const std::unordered_map<std::string, InputAction> STRING_TO_ACTION = {
{"LEFT", InputAction::LEFT},
{"RIGHT", InputAction::RIGHT},
{"JUMP", InputAction::JUMP},
{"PAUSE", InputAction::PAUSE},
{"EXIT", InputAction::EXIT},
{"ACCEPT", InputAction::ACCEPT},
{"CANCEL", InputAction::CANCEL},
{"WINDOW_INC_ZOOM", InputAction::WINDOW_INC_ZOOM},
{"WINDOW_DEC_ZOOM", InputAction::WINDOW_DEC_ZOOM},
{"TOGGLE_VIDEOMODE", InputAction::TOGGLE_VIDEOMODE},
{"TOGGLE_INTEGER_SCALE", InputAction::TOGGLE_INTEGER_SCALE},
{"TOGGLE_BORDER", InputAction::TOGGLE_BORDER},
{"TOGGLE_MUSIC", InputAction::TOGGLE_MUSIC},
{"NEXT_PALETTE", InputAction::NEXT_PALETTE},
{"PREVIOUS_PALETTE", InputAction::PREVIOUS_PALETTE},
{"TOGGLE_SHADERS", InputAction::TOGGLE_SHADERS},
{"SHOW_DEBUG_INFO", InputAction::SHOW_DEBUG_INFO},
{"NONE", InputAction::NONE}};
const std::unordered_map<SDL_GamepadButton, std::string> BUTTON_TO_STRING = {
{SDL_GAMEPAD_BUTTON_WEST, "WEST"},
{SDL_GAMEPAD_BUTTON_NORTH, "NORTH"},
{SDL_GAMEPAD_BUTTON_EAST, "EAST"},
{SDL_GAMEPAD_BUTTON_SOUTH, "SOUTH"},
{SDL_GAMEPAD_BUTTON_START, "START"},
{SDL_GAMEPAD_BUTTON_BACK, "BACK"},
{SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, "LEFT_SHOULDER"},
{SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, "RIGHT_SHOULDER"},
{SDL_GAMEPAD_BUTTON_DPAD_UP, "DPAD_UP"},
{SDL_GAMEPAD_BUTTON_DPAD_DOWN, "DPAD_DOWN"},
{SDL_GAMEPAD_BUTTON_DPAD_LEFT, "DPAD_LEFT"},
{SDL_GAMEPAD_BUTTON_DPAD_RIGHT, "DPAD_RIGHT"},
{static_cast<SDL_GamepadButton>(100), "L2_AS_BUTTON"},
{static_cast<SDL_GamepadButton>(101), "R2_AS_BUTTON"}};
const std::unordered_map<std::string, SDL_GamepadButton> STRING_TO_BUTTON = {
{"WEST", SDL_GAMEPAD_BUTTON_WEST},
{"NORTH", SDL_GAMEPAD_BUTTON_NORTH},
{"EAST", SDL_GAMEPAD_BUTTON_EAST},
{"SOUTH", SDL_GAMEPAD_BUTTON_SOUTH},
{"START", SDL_GAMEPAD_BUTTON_START},
{"BACK", SDL_GAMEPAD_BUTTON_BACK},
{"LEFT_SHOULDER", SDL_GAMEPAD_BUTTON_LEFT_SHOULDER},
{"RIGHT_SHOULDER", SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER},
{"DPAD_UP", SDL_GAMEPAD_BUTTON_DPAD_UP},
{"DPAD_DOWN", SDL_GAMEPAD_BUTTON_DPAD_DOWN},
{"DPAD_LEFT", SDL_GAMEPAD_BUTTON_DPAD_LEFT},
{"DPAD_RIGHT", SDL_GAMEPAD_BUTTON_DPAD_RIGHT},
{"L2_AS_BUTTON", static_cast<SDL_GamepadButton>(100)},
{"R2_AS_BUTTON", static_cast<SDL_GamepadButton>(101)}};

View File

@@ -0,0 +1,42 @@
#pragma once
#include <SDL3/SDL.h>
#include <string>
#include <unordered_map>
// --- Enums ---
enum class InputAction : int { // Acciones de entrada posibles en el juego
// Inputs de movimiento
LEFT,
RIGHT,
JUMP,
// Inputs de control
PAUSE,
EXIT,
ACCEPT,
CANCEL,
// Inputs de sistema
WINDOW_INC_ZOOM,
WINDOW_DEC_ZOOM,
TOGGLE_VIDEOMODE,
TOGGLE_INTEGER_SCALE,
TOGGLE_BORDER,
TOGGLE_MUSIC,
NEXT_PALETTE,
PREVIOUS_PALETTE,
TOGGLE_SHADERS,
SHOW_DEBUG_INFO,
// Input obligatorio
NONE,
SIZE,
};
// --- Variables ---
extern const std::unordered_map<InputAction, std::string> ACTION_TO_STRING; // Mapeo de acción a string
extern const std::unordered_map<std::string, InputAction> STRING_TO_ACTION; // Mapeo de string a acción
extern const std::unordered_map<SDL_GamepadButton, std::string> BUTTON_TO_STRING; // Mapeo de botón a string
extern const std::unordered_map<std::string, SDL_GamepadButton> STRING_TO_BUTTON; // Mapeo de string a botón