341 lines
12 KiB
C++
341 lines
12 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) { Input::instance = new Input(game_controller_db_path); }
|
|
|
|
// 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)
|
|
: game_controller_db_path_(std::move(game_controller_db_path)) {
|
|
// Inicializa el subsistema SDL_INIT_GAMEPAD
|
|
initSDLGamePad();
|
|
|
|
// Inicializa los vectores
|
|
// key_bindings_.resize(static_cast<int>(Action::SIZE), KeyBindings());
|
|
// controller_bindings_.resize(gamepads.size(), std::vector<ControllerBindings>(static_cast<int>(Action::SIZE), ControllerBindings()));
|
|
|
|
// 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 input, SDL_Scancode code) {
|
|
key_bindings_.at(static_cast<int>(input)).scancode = code;
|
|
}
|
|
|
|
// Asigna inputs a botones del mando
|
|
void Input::bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action input, SDL_GamepadButton button) {
|
|
if (gamepad != nullptr) {
|
|
gamepad->button_states.at(static_cast<int>(input)).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->button_states.at(static_cast<int>(input_target)).button = gamepad->button_states.at(static_cast<int>(input_source)).button;
|
|
}
|
|
}
|
|
|
|
// Comprueba si un input esta activo
|
|
auto Input::checkAction(Action input, bool repeat, Device device, std::shared_ptr<Gamepad> gamepad) -> bool {
|
|
bool success_keyboard = false;
|
|
bool success_controller = false;
|
|
const int INPUT_INDEX = static_cast<int>(input);
|
|
|
|
if (device == Device::KEYBOARD || device == Device::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 (gamepad != nullptr) {
|
|
if ((device == Device::CONTROLLER) || (device == Device::ANY)) {
|
|
success_controller = checkAxisInput(input, gamepad, repeat);
|
|
|
|
if (!success_controller) {
|
|
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
|
success_controller = gamepad->button_states.at(INPUT_INDEX).is_held;
|
|
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
|
success_controller = gamepad->button_states.at(INPUT_INDEX).just_pressed;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return (success_keyboard || success_controller);
|
|
}
|
|
|
|
// Comprueba si hay almenos un input activo
|
|
auto Input::checkAnyInput(Device device, std::shared_ptr<Gamepad> gamepad) -> bool {
|
|
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
|
|
const int NUM_ACTIONS = static_cast<int>(Action::SIZE);
|
|
|
|
// --- Comprobación del Teclado ---
|
|
if (device == Device::KEYBOARD || device == Device::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 (gamepad != nullptr) {
|
|
if (device == Device::CONTROLLER || device == Device::ANY) {
|
|
// 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 (gamepad->button_states.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
|
|
auto Input::checkAnyButton(bool repeat) -> bool {
|
|
// Solo comprueba los botones definidos previamente
|
|
for (auto bi : button_inputs_) {
|
|
// Comprueba el teclado
|
|
if (checkAction(bi, repeat, Device::KEYBOARD)) {
|
|
return true;
|
|
}
|
|
|
|
// Comprueba los mandos
|
|
for (auto gamepad : gamepads_) {
|
|
if (checkAction(bi, repeat, Device::CONTROLLER, 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::getNumControllers() 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->button_states.at(static_cast<int>(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->button_states.at(static_cast<int>(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::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_Event event;
|
|
while (SDL_PollEvent(&event)) {
|
|
handleEvent(event); // Comprueba mandos conectados
|
|
}
|
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "** Input System initialized successfully\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 &gamepad : gamepads_) {
|
|
for (auto &binding : gamepad->button_states) {
|
|
binding.is_held = false;
|
|
binding.just_pressed = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
void Input::update() {
|
|
// --- TECLADO ---
|
|
const bool *key_states = SDL_GetKeyboardState(nullptr);
|
|
|
|
for (auto &key_binding : key_bindings_) {
|
|
bool key_is_down_now = key_states[key_binding.scancode];
|
|
|
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
|
key_binding.just_pressed = key_is_down_now && !key_binding.is_held;
|
|
key_binding.is_held = key_is_down_now;
|
|
}
|
|
|
|
// --- MANDOS ---
|
|
for (auto gamepad : gamepads_) {
|
|
for (auto &binding : gamepad->button_states) {
|
|
bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(gamepad->pad, binding.button)) != 0;
|
|
|
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
|
binding.just_pressed = button_is_down_now && !binding.is_held;
|
|
binding.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;
|
|
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;
|
|
}
|
|
}
|