Input: model upate/poll finalitzat

This commit is contained in:
2025-06-29 11:37:01 +02:00
parent ce1ae74e88
commit 5006289a5d
21 changed files with 183 additions and 155 deletions

View File

@@ -11,7 +11,6 @@ set(CMAKE_CXX_STANDARD_REQUIRED True)
set(APP_SOURCES set(APP_SOURCES
# --- Archivos Principales del Sistema --- # --- Archivos Principales del Sistema ---
source/main.cpp source/main.cpp
source/game.cpp
source/director.cpp source/director.cpp
source/section.cpp source/section.cpp
source/screen.cpp source/screen.cpp
@@ -30,28 +29,29 @@ set(APP_SOURCES
source/ui/service_menu.cpp source/ui/service_menu.cpp
source/ui/menu_renderer.cpp source/ui/menu_renderer.cpp
source/ui/ui_message.cpp source/ui/ui_message.cpp
# --- Lógica y Escenas del Juego --- # --- Lógica del Juego ---
source/player.cpp
source/balloon.cpp
source/balloon_formations.cpp source/balloon_formations.cpp
source/balloon_manager.cpp source/balloon_manager.cpp
source/balloon.cpp
source/bullet.cpp source/bullet.cpp
source/item.cpp
source/explosions.cpp
# --- Escenas y Flujo ---
source/title.cpp
source/logo.cpp
source/game_logo.cpp
source/intro.cpp
source/credits.cpp
source/instructions.cpp
source/hiscore_table.cpp
source/enter_name.cpp source/enter_name.cpp
source/explosions.cpp
source/game_logo.cpp
source/item.cpp
source/manage_hiscore_table.cpp source/manage_hiscore_table.cpp
source/player.cpp
source/scoreboard.cpp source/scoreboard.cpp
# --- Escenas ---
source/sections/credits.cpp
source/sections/game.cpp
source/sections/hiscore_table.cpp
source/sections/instructions.cpp
source/sections/intro.cpp
source/sections/logo.cpp
source/sections/title.cpp
# --- Sprites y Gráficos --- # --- Sprites y Gráficos ---
source/sprite.cpp source/sprite.cpp
source/animated_sprite.cpp source/animated_sprite.cpp

View File

@@ -1,42 +1,42 @@
// IWYU pragma: no_include <bits/chrono.h> // IWYU pragma: no_include <bits/chrono.h>
#include "director.h" #include "director.h"
#include <SDL3/SDL_audio.h> // Para SDL_AudioFormat #include <SDL3/SDL_audio.h> // Para SDL_AudioFormat
#include <SDL3/SDL_error.h> // Para SDL_GetError #include <SDL3/SDL_error.h> // Para SDL_GetError
#include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton #include <SDL3/SDL_gamepad.h> // Para SDL_GamepadButton
#include <SDL3/SDL_init.h> // Para SDL_Init, SDL_Quit, SDL_INIT_AUDIO #include <SDL3/SDL_init.h> // Para SDL_Init, SDL_Quit, SDL_INIT_AUDIO
#include <SDL3/SDL.h> // Para SDL_Log, SDL_LogCategory, SDL_LogE... #include <SDL3/SDL.h> // Para SDL_Log, SDL_LogCategory, SDL_LogE...
#include <SDL3/SDL_scancode.h> // Para SDL_Scancode #include <SDL3/SDL_scancode.h> // Para SDL_Scancode
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOOLONG #include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOOLONG
#include <stdio.h> // Para printf, perror #include <stdio.h> // Para printf, perror
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU #include <sys/stat.h> // Para mkdir, stat, S_IRWXU
#include <unistd.h> // Para getuid #include <unistd.h> // Para getuid
#include <algorithm> // Para min #include <algorithm> // Para min
#include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand #include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand
#include <ctime> // Para time #include <ctime> // Para time
#include <memory> // Para make_unique, unique_ptr #include <memory> // Para make_unique, unique_ptr
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include <string> // Para operator+, allocator, char_traits #include <string> // Para operator+, allocator, char_traits
#include <vector> // Para vector #include <vector> // Para vector
#include "asset.h" // Para Asset, AssetType #include "asset.h" // Para Asset, AssetType
#include "audio.h" // Para Audio #include "audio.h" // Para Audio
#include "credits.h" // Para Credits #include "input.h" // Para Input, InputAction
#include "game.h" // Para Game, GAME_MODE_DEMO_OFF, GAME_MOD... #include "lang.h" // Para Code, loadFromFile
#include "hiscore_table.h" // Para HiScoreTable #include "manage_hiscore_table.h" // Para ManageHiScoreTable
#include "input.h" // Para Input, InputAction #include "notifier.h" // Para Notifier
#include "instructions.h" // Para Instructions #include "options.h" // Para GamepadOptions, Options, options
#include "intro.h" // Para Intro #include "param.h" // Para loadParamsFromFile
#include "lang.h" // Para Code, loadFromFile #include "resource.h" // Para Resource
#include "logo.h" // Para Logo #include "screen.h" // Para Screen
#include "manage_hiscore_table.h" // Para ManageHiScoreTable #include "section.h" // Para Name, Options, name, options
#include "notifier.h" // Para Notifier #include "sections/credits.h" // Para Credits
#include "options.h" // Para GamepadOptions, Options, options #include "sections/game.h" // Para Game, GAME_MODE_DEMO_OFF, GAME_MOD...
#include "param.h" // Para loadParamsFromFile #include "sections/hiscore_table.h" // Para HiScoreTable
#include "resource.h" // Para Resource #include "sections/instructions.h" // Para Instructions
#include "screen.h" // Para Screen #include "sections/intro.h" // Para Intro
#include "section.h" // Para Name, Options, name, options #include "sections/logo.h" // Para Logo
#include "ui/service_menu.h" // Para ServiceMenu #include "sections/title.h" // Para Title
#include "title.h" // Para Title #include "ui/service_menu.h" // Para ServiceMenu
#include "utils.h" // Para Overrides, overrides #include "utils.h" // Para Overrides, overrides
#ifndef _WIN32 #ifndef _WIN32
#include <pwd.h> // Para getpwuid, passwd #include <pwd.h> // Para getpwuid, passwd

View File

@@ -195,7 +195,7 @@ namespace GlobalInputs
bool checkServiceButton() bool checkServiceButton()
{ {
// Teclado // Teclado
if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleServiceMenu(); toggleServiceMenu();
return true; return true;
@@ -205,7 +205,7 @@ namespace GlobalInputs
{ {
for (int i = 0; i < Input::get()->getNumControllers(); ++i) for (int i = 0; i < Input::get()->getNumControllers(); ++i)
{ {
if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
toggleServiceMenu(); toggleServiceMenu();
return true; return true;
@@ -224,42 +224,42 @@ namespace GlobalInputs
// Teclado // Teclado
{ {
// Arriba // Arriba
if (Input::get()->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->setSelectorUp(); ServiceMenu::get()->setSelectorUp();
return true; return true;
} }
// Abajo // Abajo
if (Input::get()->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->setSelectorDown(); ServiceMenu::get()->setSelectorDown();
return true; return true;
} }
// Derecha // Derecha
if (Input::get()->checkInput(InputAction::RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->adjustOption(true); ServiceMenu::get()->adjustOption(true);
return true; return true;
} }
// Izquierda // Izquierda
if (Input::get()->checkInput(InputAction::LEFT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::LEFT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->adjustOption(false); ServiceMenu::get()->adjustOption(false);
return true; return true;
} }
// Aceptar // Aceptar
if (Input::get()->checkInput(InputAction::SM_SELECT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::SM_SELECT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->selectOption(); ServiceMenu::get()->selectOption();
return true; return true;
} }
// Atras // Atras
if (Input::get()->checkInput(InputAction::SM_BACK, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::SM_BACK, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
ServiceMenu::get()->moveBack(); ServiceMenu::get()->moveBack();
return true; return true;
@@ -271,42 +271,42 @@ namespace GlobalInputs
for (int i = 0; i < Input::get()->getNumControllers(); ++i) for (int i = 0; i < Input::get()->getNumControllers(); ++i)
{ {
// Arriba // Arriba
if (Input::get()->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::UP, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->setSelectorUp(); ServiceMenu::get()->setSelectorUp();
return true; return true;
} }
// Abajo // Abajo
if (Input::get()->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::DOWN, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->setSelectorDown(); ServiceMenu::get()->setSelectorDown();
return true; return true;
} }
// Derecha // Derecha
if (Input::get()->checkInput(InputAction::RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::RIGHT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->adjustOption(true); ServiceMenu::get()->adjustOption(true);
return true; return true;
} }
// Izquierda // Izquierda
if (Input::get()->checkInput(InputAction::LEFT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::LEFT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->adjustOption(false); ServiceMenu::get()->adjustOption(false);
return true; return true;
} }
// Aceptar // Aceptar
if (Input::get()->checkInput(InputAction::SM_SELECT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::SM_SELECT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->selectOption(); ServiceMenu::get()->selectOption();
return true; return true;
} }
// Atras // Atras
if (Input::get()->checkInput(InputAction::SM_BACK, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (Input::get()->checkInput(InputAction::SM_BACK, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
ServiceMenu::get()->moveBack(); ServiceMenu::get()->moveBack();
return true; return true;
@@ -322,7 +322,7 @@ namespace GlobalInputs
// Teclado // Teclado
{ {
// Comprueba el teclado para cambiar entre pantalla completa y ventana // Comprueba el teclado para cambiar entre pantalla completa y ventana
if (Input::get()->checkInput(InputAction::WINDOW_FULLSCREEN, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::WINDOW_FULLSCREEN, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
Screen::get()->toggleFullscreen(); Screen::get()->toggleFullscreen();
const std::string MODE = Options::video.fullscreen ? Lang::getText("[NOTIFICATIONS] 11") : Lang::getText("[NOTIFICATIONS] 10"); const std::string MODE = Options::video.fullscreen ? Lang::getText("[NOTIFICATIONS] 11") : Lang::getText("[NOTIFICATIONS] 10");
@@ -331,7 +331,7 @@ namespace GlobalInputs
} }
// Comprueba el teclado para decrementar el tamaño de la ventana // Comprueba el teclado para decrementar el tamaño de la ventana
if (Input::get()->checkInput(InputAction::WINDOW_DEC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::WINDOW_DEC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
if (Screen::get()->decWindowSize()) if (Screen::get()->decWindowSize())
{ {
@@ -341,7 +341,7 @@ namespace GlobalInputs
} }
// Comprueba el teclado para incrementar el tamaño de la ventana // Comprueba el teclado para incrementar el tamaño de la ventana
if (Input::get()->checkInput(InputAction::WINDOW_INC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::WINDOW_INC_SIZE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
if (Screen::get()->incWindowSize()) if (Screen::get()->incWindowSize())
{ {
@@ -351,7 +351,7 @@ namespace GlobalInputs
} }
// Salir // Salir
if (Input::get()->checkInput(InputAction::EXIT, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::EXIT, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
quit(); quit();
return true; return true;
@@ -365,49 +365,49 @@ namespace GlobalInputs
} }
// Reset // Reset
if (Input::get()->checkInput(InputAction::RESET, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::RESET, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
reset(); reset();
return true; return true;
} }
// Audio // Audio
if (Input::get()->checkInput(InputAction::TOGGLE_AUDIO, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_AUDIO, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleAudio(); toggleAudio();
return true; return true;
} }
// Autofire // Autofire
if (Input::get()->checkInput(InputAction::TOGGLE_AUTO_FIRE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_AUTO_FIRE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleFireMode(); toggleFireMode();
return true; return true;
} }
// Idioma // Idioma
if (Input::get()->checkInput(InputAction::CHANGE_LANG, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::CHANGE_LANG, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
changeLang(); changeLang();
return true; return true;
} }
// Shaders // Shaders
if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleShaders(); toggleShaders();
return true; return true;
} }
// Integer Scale // Integer Scale
if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_INTEGER_SCALE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_INTEGER_SCALE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleIntegerScale(); toggleIntegerScale();
return true; return true;
} }
// VSync // VSync
if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_VSYNC, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::TOGGLE_VIDEO_VSYNC, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
toggleVSync(); toggleVSync();
return true; return true;
@@ -415,7 +415,7 @@ namespace GlobalInputs
#ifdef DEBUG #ifdef DEBUG
// Debug info // Debug info
if (Input::get()->checkInput(InputAction::SHOW_INFO, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (Input::get()->checkInput(InputAction::SHOW_INFO, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
Screen::get()->toggleDebugInfo(); Screen::get()->toggleDebugInfo();
return true; return true;
@@ -428,7 +428,6 @@ namespace GlobalInputs
// Comprueba los inputs que se pueden introducir en cualquier sección del juego // Comprueba los inputs que se pueden introducir en cualquier sección del juego
bool check() bool check()
{ {
Input::get()->update();
if (checkServiceButton()) if (checkServiceButton())
return true; return true;
if (checkServiceInputs()) if (checkServiceInputs())

View File

@@ -60,27 +60,27 @@ void Input::bindGameControllerButton(int controller_index, InputAction input_tar
} }
// Comprueba si un input esta activo // Comprueba si un input esta activo
bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index)
{ {
bool success_keyboard = false; bool success_keyboard = false;
bool success_controller = false; bool success_controller = false;
const int input_index = static_cast<int>(input); const int input_index = static_cast<int>(input);
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) if (device == InputDevice::KEYBOARD || device == InputDevice::ANY)
{ {
if (repeat) if (repeat)
{ // El usuario quiere saber si está pulsada (estado mantenido) { // El usuario quiere saber si está pulsada (estado mantenido)
return key_bindings_[input_index].is_held; success_keyboard = key_bindings_[input_index].is_held;
} }
else else
{ // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma) { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
return key_bindings_[input_index].just_pressed; success_keyboard = key_bindings_[input_index].just_pressed;
} }
} }
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_)
{ {
if ((device == InputDeviceToUse::CONTROLLER) || (device == InputDeviceToUse::ANY)) if ((device == InputDevice::CONTROLLER) || (device == InputDevice::ANY))
{ {
success_controller = checkAxisInput(input, controller_index, repeat); success_controller = checkAxisInput(input, controller_index, repeat);
@@ -88,11 +88,11 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
{ {
if (repeat) if (repeat)
{ // El usuario quiere saber si está pulsada (estado mantenido) { // El usuario quiere saber si está pulsada (estado mantenido)
return controller_bindings_.at(controller_index).at(input_index).is_held; success_controller = controller_bindings_.at(controller_index).at(input_index).is_held;
} }
else else
{ // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma) { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
return controller_bindings_.at(controller_index).at(input_index).just_pressed; success_controller = controller_bindings_.at(controller_index).at(input_index).just_pressed;
} }
} }
} }
@@ -102,45 +102,45 @@ bool Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
} }
// Comprueba si hay almenos un input activo // Comprueba si hay almenos un input activo
bool Input::checkAnyInput(InputDeviceToUse device, int controller_index) bool Input::checkAnyInput(InputDevice device, int controller_index)
{ {
// Obtenemos el número total de acciones posibles para iterar sobre ellas. // Obtenemos el número total de acciones posibles para iterar sobre ellas.
const int num_actions = static_cast<int>(InputAction::SIZE); const int num_actions = static_cast<int>(InputAction::SIZE);
// --- Comprobación del Teclado --- // --- Comprobación del Teclado ---
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) if (device == InputDevice::KEYBOARD || device == InputDevice::ANY)
{ {
for (int i = 0; i < num_actions; ++i) for (int i = 0; i < num_actions; ++i)
{ {
// Simplemente leemos el estado pre-calculado por Input::update(). // Simplemente leemos el estado pre-calculado por Input::update().
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'. // Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
if (key_bindings_.at(i).just_pressed) if (key_bindings_.at(i).just_pressed)
{ {
return true; // Se encontró una acción recién pulsada. return true; // Se encontró una acción recién pulsada.
} }
} }
} }
// --- Comprobación del Mando --- // --- Comprobación del Mando ---
// Comprobamos si hay mandos y si el índice solicitado es válido. // Comprobamos si hay mandos y si el índice solicitado es válido.
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_)
{ {
if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY) if (device == InputDevice::CONTROLLER || device == InputDevice::ANY)
{ {
// Bucle CORREGIDO: Iteramos sobre todas las acciones, no sobre el número de mandos. // Bucle CORREGIDO: Iteramos sobre todas las acciones, no sobre el número de mandos.
for (int i = 0; i < num_actions; ++i) for (int i = 0; i < num_actions; ++i)
{ {
// Leemos el estado pre-calculado para el mando y la acción específicos. // Leemos el estado pre-calculado para el mando y la acción específicos.
if (controller_bindings_.at(controller_index).at(i).just_pressed) if (controller_bindings_.at(controller_index).at(i).just_pressed)
{ {
return true; // Se encontró una acción recién pulsada en el mando. return true; // Se encontró una acción recién pulsada en el mando.
} }
} }
} }
} }
// Si llegamos hasta aquí, no se detectó ninguna nueva pulsación. // Si llegamos hasta aquí, no se detectó ninguna nueva pulsación.
return false; 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" // 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"
@@ -150,7 +150,7 @@ int Input::checkAnyButton(bool repeat)
for (auto bi : button_inputs_) for (auto bi : button_inputs_)
{ {
// Comprueba el teclado // Comprueba el teclado
if (checkInput(bi, repeat, InputDeviceToUse::KEYBOARD)) if (checkInput(bi, repeat, InputDevice::KEYBOARD))
{ {
return 1; return 1;
} }
@@ -158,7 +158,7 @@ int Input::checkAnyButton(bool repeat)
// Comprueba los mandos // Comprueba los mandos
for (int i = 0; i < num_gamepads_; ++i) for (int i = 0; i < num_gamepads_; ++i)
{ {
if (checkInput(bi, repeat, InputDeviceToUse::CONTROLLER, i)) if (checkInput(bi, repeat, InputDevice::CONTROLLER, i))
{ {
return i + 1; return i + 1;
} }
@@ -273,14 +273,14 @@ int Input::getJoyIndex(SDL_JoystickID id) const
} }
// Muestra por consola los controles asignados // Muestra por consola los controles asignados
void Input::printBindings(InputDeviceToUse device, int controller_index) const void Input::printBindings(InputDevice device, int controller_index) const
{ {
if (device == InputDeviceToUse::ANY || device == InputDeviceToUse::KEYBOARD) if (device == InputDevice::ANY || device == InputDevice::KEYBOARD)
{ {
return; return;
} }
if (device == InputDeviceToUse::CONTROLLER) if (device == InputDevice::CONTROLLER)
{ {
if (controller_index >= num_gamepads_) if (controller_index >= num_gamepads_)
{ {
@@ -349,22 +349,21 @@ InputAction Input::to_inputs_e(const std::string &name) const
bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat) bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
{ {
// Umbral para considerar el eje como activo // Umbral para considerar el eje como activo
const Sint16 threshold = 30000;
bool axis_active_now = false; bool axis_active_now = false;
switch (input) switch (input)
{ {
case InputAction::LEFT: case InputAction::LEFT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD_;
break; break;
case InputAction::RIGHT: case InputAction::RIGHT:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD_;
break; break;
case InputAction::UP: case InputAction::UP:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -AXIS_THRESHOLD_;
break; break;
case InputAction::DOWN: case InputAction::DOWN:
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > threshold; axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > AXIS_THRESHOLD_;
break; break;
default: default:
return false; return false;

View File

@@ -63,7 +63,7 @@ constexpr bool INPUT_ALLOW_REPEAT = true;
constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false; constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false;
// Tipos de dispositivos de entrada // Tipos de dispositivos de entrada
enum class InputDeviceToUse : int enum class InputDevice : int
{ {
KEYBOARD = 0, KEYBOARD = 0,
CONTROLLER = 1, CONTROLLER = 1,
@@ -85,10 +85,10 @@ public:
void bindGameControllerButton(int controller_index, InputAction inputTarget, InputAction inputSource); // Asigna inputs a otros inputs del mando void bindGameControllerButton(int controller_index, InputAction inputTarget, InputAction inputSource); // Asigna inputs a otros inputs del mando
// --- Métodos de consulta de entrada --- // --- Métodos de consulta de entrada ---
void update(); // Comprueba fisicamente los botones y teclas que se han pulsado void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
bool checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0); // Comprueba si un input está activo bool checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si un input está activo
bool checkAnyInput(InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0); // Comprueba si hay al menos un input activo bool checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si hay al menos un input activo
int checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT); // Comprueba si hay algún botón pulsado int checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT); // Comprueba si hay algún botón pulsado
// --- Métodos de gestión de mandos --- // --- Métodos de gestión de mandos ---
bool discoverGameControllers(); // Busca si hay mandos conectados bool discoverGameControllers(); // Busca si hay mandos conectados
@@ -98,11 +98,11 @@ public:
int getJoyIndex(SDL_JoystickID id) const; // Obtiene el índice del controlador a partir de un event.id int getJoyIndex(SDL_JoystickID id) const; // Obtiene el índice del controlador a partir de un event.id
// --- Métodos de consulta y utilidades --- // --- Métodos de consulta y utilidades ---
void printBindings(InputDeviceToUse device = InputDeviceToUse::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
SDL_GamepadButton getControllerBinding(int controller_index, InputAction input) const; // Obtiene el SDL_GamepadButton asignado a un input SDL_GamepadButton getControllerBinding(int controller_index, InputAction input) const; // Obtiene el SDL_GamepadButton asignado a un input
std::string to_string(InputAction input) const; // Convierte un InputAction a std::string std::string to_string(InputAction input) const; // Convierte un InputAction a std::string
InputAction to_inputs_e(const std::string &name) const; // Convierte un std::string a InputAction InputAction to_inputs_e(const std::string &name) const; // Convierte un std::string a InputAction
int getIndexByName(const std::string &name) const; // Obtiene el índice a partir del nombre del mando int getIndexByName(const std::string &name) const; // Obtiene el índice a partir del nombre del mando
// --- Métodos de reseteo de estado de entrada --- // --- Métodos de reseteo de estado de entrada ---
void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false
@@ -133,6 +133,9 @@ private:
: button(btn), is_held(is_held), just_pressed(just_pressed), axis_active(axis_act) {} : button(btn), is_held(is_held), just_pressed(just_pressed), axis_active(axis_act) {}
}; };
// --- Constantes ---
static constexpr Sint16 AXIS_THRESHOLD_ = 30000;
// --- Variables internas --- // --- Variables internas ---
std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados 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<SDL_Joystick *> joysticks_; // Vector con todos los joysticks conectados

View File

@@ -264,7 +264,7 @@ namespace Options
} }
else if (var == "controller.0.type") else if (var == "controller.0.type")
{ {
controllers.at(0).type = static_cast<InputDeviceToUse>(std::stoi(value)); controllers.at(0).type = static_cast<InputDevice>(std::stoi(value));
} }
else if (var == "controller.0.button.fire_left") else if (var == "controller.0.button.fire_left")
{ {
@@ -296,7 +296,7 @@ namespace Options
} }
else if (var == "controller.1.type") else if (var == "controller.1.type")
{ {
controllers.at(1).type = static_cast<InputDeviceToUse>(std::stoi(value)); controllers.at(1).type = static_cast<InputDevice>(std::stoi(value));
} }
else if (var == "controller.1.button.fire_left") else if (var == "controller.1.button.fire_left")
{ {
@@ -338,11 +338,11 @@ namespace Options
{ {
if (controller.player_id == player_id) if (controller.player_id == player_id)
{ {
controller.type = InputDeviceToUse::ANY; controller.type = InputDevice::ANY;
} }
else else
{ {
controller.type = InputDeviceToUse::CONTROLLER; controller.type = InputDevice::CONTROLLER;
} }
} }
} }
@@ -365,7 +365,7 @@ namespace Options
{ {
for (const auto &controller : controllers) for (const auto &controller : controllers)
{ {
if (controller.type == InputDeviceToUse::ANY) if (controller.type == InputDevice::ANY)
{ {
return controller.player_id; return controller.player_id;
} }

View File

@@ -143,7 +143,7 @@ namespace Options
{ {
int index; // Índice en el vector de mandos int index; // Índice en el vector de mandos
int player_id; // Jugador asociado al mando int player_id; // Jugador asociado al mando
InputDeviceToUse type; // Indica si se usará teclado, mando o ambos InputDevice type; // Indica si se usará teclado, mando o ambos
std::string name; // Nombre del dispositivo std::string name; // Nombre del dispositivo
bool plugged; // Indica si el mando está conectado bool plugged; // Indica si el mando está conectado
std::vector<InputAction> inputs; // Listado de acciones asignadas std::vector<InputAction> inputs; // Listado de acciones asignadas
@@ -153,7 +153,7 @@ namespace Options
GamepadOptions() GamepadOptions()
: index(INVALID_INDEX), : index(INVALID_INDEX),
player_id(INVALID_INDEX), player_id(INVALID_INDEX),
type(InputDeviceToUse::CONTROLLER), type(InputDevice::CONTROLLER),
name(), name(),
plugged(false), plugged(false),
inputs{ inputs{

View File

@@ -27,6 +27,7 @@
#include "tiled_bg.h" // Para TiledBG, TiledBGMode #include "tiled_bg.h" // Para TiledBG, TiledBGMode
#include "utils.h" // Para Color, Zone, shdw_txt_color, no_color #include "utils.h" // Para Color, Zone, shdw_txt_color, no_color
#include "ui/service_menu.h" #include "ui/service_menu.h"
#include "input.h"
// Textos // Textos
constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner"; constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner";
@@ -141,6 +142,8 @@ void Credits::checkEvents()
// Comprueba las entradas // Comprueba las entradas
void Credits::checkInput() void Credits::checkInput()
{ {
Input::get()->update();
if (!ServiceMenu::get()->isEnabled()) if (!ServiceMenu::get()->isEnabled())
{ {
// Comprueba si se ha pulsado cualquier botón (de los usados para jugar) // Comprueba si se ha pulsado cualquier botón (de los usados para jugar)

View File

@@ -1330,6 +1330,8 @@ int Game::getController(int player_id)
// Gestiona la entrada durante el juego // Gestiona la entrada durante el juego
void Game::checkInput() void Game::checkInput()
{ {
Input::get()->update();
// Comprueba las entradas si no está el menú de servicio activo // Comprueba las entradas si no está el menú de servicio activo
if (!ServiceMenu::get()->isEnabled()) if (!ServiceMenu::get()->isEnabled())
{ {
@@ -1353,7 +1355,7 @@ void Game::checkPauseInput()
// Comprueba los mandos // Comprueba los mandos
for (int i = 0; i < input_->getNumControllers(); ++i) for (int i = 0; i < input_->getNumControllers(); ++i)
{ {
if (input_->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::CONTROLLER, i)) if (input_->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::CONTROLLER, i))
{ {
pause(!paused_); pause(!paused_);
return; return;
@@ -1361,7 +1363,7 @@ void Game::checkPauseInput()
} }
// Comprueba el teclado // Comprueba el teclado
if (input_->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDeviceToUse::KEYBOARD)) if (input_->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD))
{ {
pause(!paused_); pause(!paused_);
return; return;

View File

@@ -25,6 +25,7 @@
#include "text.h" // Para Text, TEXT_SHADOW, TEXT_COLOR #include "text.h" // Para Text, TEXT_SHADOW, TEXT_COLOR
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para Color, easeOutQuint, fade_color, Zone #include "utils.h" // Para Color, easeOutQuint, fade_color, Zone
#include "input.h"
// Constructor // Constructor
HiScoreTable::HiScoreTable() HiScoreTable::HiScoreTable()
@@ -142,7 +143,11 @@ void HiScoreTable::checkEvents()
} }
// Comprueba las entradas // Comprueba las entradas
void HiScoreTable::checkInput() { GlobalInputs::check(); } void HiScoreTable::checkInput()
{
Input::get()->update();
GlobalInputs::check();
}
// Bucle para la pantalla de instrucciones // Bucle para la pantalla de instrucciones
void HiScoreTable::run() void HiScoreTable::run()

View File

@@ -20,6 +20,7 @@
#include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR, TEXT_... #include "text.h" // Para Text, TEXT_CENTER, TEXT_COLOR, TEXT_...
#include "tiled_bg.h" // Para TiledBG, TiledBGMode #include "tiled_bg.h" // Para TiledBG, TiledBGMode
#include "utils.h" // Para Color, shdw_txt_color, Zone, no_color #include "utils.h" // Para Color, shdw_txt_color, Zone, no_color
#include "input.h"
// Constructor // Constructor
Instructions::Instructions() Instructions::Instructions()
@@ -273,7 +274,11 @@ void Instructions::checkEvents()
} }
// Comprueba las entradas // Comprueba las entradas
void Instructions::checkInput() { GlobalInputs::check(); } void Instructions::checkInput()
{
Input::get()->update();
GlobalInputs::check();
}
// Bucle para la pantalla de instrucciones // Bucle para la pantalla de instrucciones
void Instructions::run() void Instructions::run()

View File

@@ -22,6 +22,7 @@
#include "tiled_bg.h" // Para TiledBG, TiledBGMode #include "tiled_bg.h" // Para TiledBG, TiledBGMode
#include "utils.h" // Para Color, Zone, easeOutQuint, BLOCK #include "utils.h" // Para Color, Zone, easeOutQuint, BLOCK
#include "writer.h" // Para Writer #include "writer.h" // Para Writer
#include "input.h"
// Constructor // Constructor
Intro::Intro() Intro::Intro()
@@ -53,7 +54,11 @@ void Intro::checkEvents()
} }
// Comprueba las entradas // Comprueba las entradas
void Intro::checkInput() { GlobalInputs::check(); } void Intro::checkInput()
{
Input::get()->update();
GlobalInputs::check();
}
// Actualiza las escenas de la intro // Actualiza las escenas de la intro
void Intro::updateScenes() void Intro::updateScenes()

View File

@@ -12,6 +12,7 @@
#include "sprite.h" // Para Sprite #include "sprite.h" // Para Sprite
#include "texture.h" // Para Texture #include "texture.h" // Para Texture
#include "utils.h" // Para Color, Zone #include "utils.h" // Para Color, Zone
#include "input.h"
// Constructor // Constructor
Logo::Logo() Logo::Logo()
@@ -74,7 +75,11 @@ void Logo::checkEvents()
} }
// Comprueba las entradas // Comprueba las entradas
void Logo::checkInput() { GlobalInputs::check(); } void Logo::checkInput()
{
Input::get()->update();
GlobalInputs::check();
}
// Gestiona el logo de JAILGAMES // Gestiona el logo de JAILGAMES
void Logo::updateJAILGAMES() void Logo::updateJAILGAMES()

View File

@@ -180,6 +180,8 @@ void Title::checkEvents()
// Comprueba las entradas // Comprueba las entradas
void Title::checkInput() void Title::checkInput()
{ {
Input::get()->update();
if (!ServiceMenu::get()->isEnabled()) if (!ServiceMenu::get()->isEnabled())
{ {
// Comprueba las entradas solo si no se estan definiendo los botones // Comprueba las entradas solo si no se estan definiendo los botones