Files
coffee-crisis-ae/source/input.h
T

173 lines
8.2 KiB
C++

#pragma once
#include <SDL3/SDL.h> // Para SDL_GamepadButton, Uint8, SDL_Gamepad, SDL_Joystick, SDL_JoystickID, SDL_Scancode, Sint16
#include <iostream>
#include <memory> // Para std::unique_ptr
#include <string> // Para basic_string, string
#include <vector> // Para vector
/*
connectedControllers es un vector donde están todos los mandos encontrados [0 .. n]
checkInput requiere de un índice para comprobar las pulsaciones de un controlador en concreto [0 .. n]
device contiene el tipo de dispositivo a comprobar:
InputDeviceToUse::KEYBOARD solo mirará el teclado
InputDeviceToUse::CONTROLLER solo mirará el controlador especificado (Si no se especifica, el primero)
InputDeviceToUse::ANY mirará tanto el teclado como el PRIMER controlador
*/
// Clase Input: gestiona la entrada de teclado y mandos (singleton)
class Input {
public:
// --- Constantes ---
static constexpr bool ALLOW_REPEAT = true;
static constexpr bool DO_NOT_ALLOW_REPEAT = false;
// Acciones de entrada posibles en el juego
enum class Action : int {
// Inputs de movimiento
UP,
DOWN,
LEFT,
RIGHT,
// Inputs personalizados
FIRE_LEFT,
FIRE_CENTER,
FIRE_RIGHT,
START,
// Service Menu
SM_SELECT,
SM_BACK,
// Inputs de control
BACK,
EXIT,
PAUSE,
SERVICE,
WINDOW_FULLSCREEN,
WINDOW_INC_SIZE,
WINDOW_DEC_SIZE,
TOGGLE_VIDEO_SHADERS,
TOGGLE_VIDEO_INTEGER_SCALE,
TOGGLE_VIDEO_VSYNC,
RESET,
TOGGLE_AUDIO,
CHANGE_LANG,
SHOW_INFO,
CONFIG,
SWAP_CONTROLLERS,
TOGGLE_AUTO_FIRE,
// Input obligatorio
NONE,
SIZE,
};
// Tipos de dispositivos de entrada
enum class Device : int {
KEYBOARD = 0,
CONTROLLER = 1,
ANY = 2,
};
// --- 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 ButtonState {
SDL_GamepadButton 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
ButtonState(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool is_held = false, bool just_pressed = false, bool axis_act = false)
: button(btn), is_held(is_held), just_pressed(just_pressed), axis_active(axis_act) {}
};
struct Gamepad {
SDL_Gamepad *pad;
SDL_JoystickID instance_id;
std::string name;
std::vector<ButtonState> button_states;
Gamepad(SDL_Gamepad *gamepad)
: pad(gamepad),
instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))),
name(std::string(SDL_GetGamepadName(gamepad)) + " #" + std::to_string(instance_id)) {}
~Gamepad() {
if (pad) {
SDL_CloseGamepad(pad);
// std::cout << "Gamepad cerrado (ID " << instance_id << ")\n";
}
}
};
// --- Métodos de singleton ---
static void init(const std::string &game_controller_db_path); // Inicializa el singleton
static void destroy(); // Libera el singleton
static auto get() -> Input *; // Obtiene la instancia
// --- Métodos de configuración de controles ---
void bindKey(Action input, SDL_Scancode code); // Asigna inputs a teclas
void bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action input, SDL_GamepadButton button); // Asigna inputs a botones del mando
void bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action input_target, Action input_source); // Asigna inputs a otros inputs del mando
// --- Métodos de consulta de entrada ---
void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
auto checkAction(Action input, bool repeat = true, Device device = Device::ANY, std::shared_ptr<Gamepad> gamepad = nullptr) -> bool; // Comprueba si un input está activo
auto checkAnyInput(Device device = Device::ANY, std::shared_ptr<Gamepad> gamepad = nullptr) -> bool; // Comprueba si hay al menos un input activo
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool; // Comprueba si hay algún botón pulsado
// --- Métodos de gestión de mandos ---
[[nodiscard]] auto gameControllerFound() const -> bool; // Comprueba si hay algún mando conectado
auto getControllerName(std::shared_ptr<Gamepad> gamepad) const -> std::string; // Obten el nombre de un mando de juego
[[nodiscard]] auto getNumControllers() const -> int; // Obtiene el número de mandos conectados
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int; // Obtiene el índice del controlador a partir de un event.id
// --- Métodos de consulta y utilidades ---
[[nodiscard]] auto getControllerBinding(std::shared_ptr<Gamepad> gamepad, Action input) const -> SDL_GamepadButton; // Obtiene el SDL_GamepadButton asignado a un input
[[nodiscard]] static auto inputToString(Action input) -> std::string; // Convierte un InputAction a std::string
[[nodiscard]] static auto stringToInput(const std::string &name) -> Action; // Convierte un std::string a InputAction
// --- Métodos de reseteo de estado de entrada ---
void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false
// --- Eventos ---
void handleEvent(const SDL_Event &event); // Comprueba si se conecta algun mando
void printConnectedGamepads() const;
[[nodiscard]] auto getGamepads() const -> const std::vector<std::shared_ptr<Gamepad>> & { return gamepads_; }
private:
// --- Constantes ---
static constexpr Sint16 AXIS_THRESHOLD = 30000;
// --- Variables internas ---
std::vector<std::shared_ptr<Gamepad>> gamepads_; // Mandos conectados
std::vector<KeyState> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<Action> button_inputs_; // Inputs asignados al jugador y a botones, excluyendo direcciones
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
// --- Métodos internos ---
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
auto checkAxisInput(Action input, std::shared_ptr<Gamepad> gamepad, bool repeat) -> bool; // Comprueba el eje del mando
void add_gamepad(int device_index);
void remove_gamepad(SDL_JoystickID id);
// --- Constructor y destructor ---
explicit Input(std::string game_controller_db_path); // Constructor privado
~Input() = default; // Destructor privado
// --- Singleton ---
static Input *instance;
};