canvi de pc
This commit is contained in:
@@ -12,8 +12,7 @@
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
DefineButtons::DefineButtons()
|
DefineButtons::DefineButtons()
|
||||||
: input_(Input::get()),
|
: input_(Input::get()) {
|
||||||
text_(Resource::get()->getText("8bithud")) {
|
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
x_ = param.game.width / 2;
|
x_ = param.game.width / 2;
|
||||||
y_ = param.title.press_start_position;
|
y_ = param.title.press_start_position;
|
||||||
@@ -27,10 +26,11 @@ DefineButtons::DefineButtons()
|
|||||||
|
|
||||||
// Dibuja el objeto en pantalla
|
// Dibuja el objeto en pantalla
|
||||||
void DefineButtons::render() {
|
void DefineButtons::render() {
|
||||||
|
static auto text = Resource::get()->getText("8bithud");
|
||||||
if (enabled_) {
|
if (enabled_) {
|
||||||
text_->writeCentered(x_, y_ - 10, Lang::getText("[DEFINE_BUTTONS] PLAYER") + std::to_string(Options::controllers.at(index_controller_).player_id));
|
text->writeCentered(x_, y_ - 10, Lang::getText("[DEFINE_BUTTONS] PLAYER") + std::to_string(Options::controllers.at(index_controller_).player_id));
|
||||||
text_->writeCentered(x_, y_, controller_names_.at(index_controller_));
|
text->writeCentered(x_, y_, controller_names_.at(index_controller_));
|
||||||
text_->writeCentered(x_, y_ + 10, buttons_.at(index_button_).label);
|
text->writeCentered(x_, y_ + 10, buttons_.at(index_button_).label);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,14 +49,14 @@ void DefineButtons::doControllerButtonDown(const SDL_GamepadButtonEvent &event)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Asigna los botones definidos al input_
|
// Asigna los botones definidos al input_
|
||||||
void DefineButtons::bindButtons() {
|
void DefineButtons::bindButtons(std::shared_ptr<Input::Gamepad> gamepad) {
|
||||||
for (const auto &button : buttons_) {
|
for (const auto &button : buttons_) {
|
||||||
input_->bindGameControllerButton(index_controller_, button.action, button.button);
|
input_->bindGameControllerButton(gamepad, button.action, button.button);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remapea los inputs a inputs
|
// Remapea los inputs a inputs
|
||||||
input_->bindGameControllerButton(index_controller_, Input::Action::SM_SELECT, Input::Action::FIRE_LEFT);
|
input_->bindGameControllerButton(gamepad, Input::Action::SM_SELECT, Input::Action::FIRE_LEFT);
|
||||||
input_->bindGameControllerButton(index_controller_, Input::Action::SM_BACK, Input::Action::FIRE_CENTER);
|
input_->bindGameControllerButton(gamepad, Input::Action::SM_BACK, Input::Action::FIRE_CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los eventos
|
// Comprueba los eventos
|
||||||
@@ -80,7 +80,6 @@ auto DefineButtons::enable(int index) -> bool {
|
|||||||
if (index < input_->getNumControllers()) {
|
if (index < input_->getNumControllers()) {
|
||||||
enabled_ = true;
|
enabled_ = true;
|
||||||
finished_ = false;
|
finished_ = false;
|
||||||
index_controller_ = index;
|
|
||||||
index_button_ = 0;
|
index_button_ = 0;
|
||||||
clearButtons();
|
clearButtons();
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -9,7 +9,6 @@
|
|||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "input.h"
|
#include "input.h"
|
||||||
#include "text.h"
|
|
||||||
|
|
||||||
// Clase DefineButtons
|
// Clase DefineButtons
|
||||||
class DefineButtons {
|
class DefineButtons {
|
||||||
@@ -35,13 +34,11 @@ class DefineButtons {
|
|||||||
private:
|
private:
|
||||||
// Objetos
|
// Objetos
|
||||||
Input *input_ = nullptr; // Gestión de entrada
|
Input *input_ = nullptr; // Gestión de entrada
|
||||||
std::shared_ptr<Text> text_; // Renderizado de texto
|
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
bool enabled_ = false; // Indica si está activo
|
bool enabled_ = false; // Indica si está activo
|
||||||
int x_ = 0, y_ = 0; // Coordenadas de texto
|
int x_ = 0, y_ = 0; // Coordenadas de texto
|
||||||
std::vector<Button> buttons_; // Definiciones de botones
|
std::vector<Button> buttons_; // Definiciones de botones
|
||||||
size_t index_controller_ = 0; // Índice del controlador asignado
|
|
||||||
size_t index_button_ = 0; // Índice del botón en proceso
|
size_t index_button_ = 0; // Índice del botón en proceso
|
||||||
std::vector<std::string> controller_names_; // Nombres de los mandos
|
std::vector<std::string> controller_names_; // Nombres de los mandos
|
||||||
bool finished_ = false;
|
bool finished_ = false;
|
||||||
@@ -49,7 +46,7 @@ class DefineButtons {
|
|||||||
// Métodos internos
|
// Métodos internos
|
||||||
void incIndexButton(); // Incrementa el índice de botones
|
void incIndexButton(); // Incrementa el índice de botones
|
||||||
void doControllerButtonDown(const SDL_GamepadButtonEvent &event); // Procesa pulsaciones
|
void doControllerButtonDown(const SDL_GamepadButtonEvent &event); // Procesa pulsaciones
|
||||||
void bindButtons(); // Asigna botones al sistema de entrada
|
void bindButtons(std::shared_ptr<Input::Gamepad> gamepad); // Asigna botones al sistema de entrada
|
||||||
void saveBindingsToOptions(); // Guarda configuraciones
|
void saveBindingsToOptions(); // Guarda configuraciones
|
||||||
auto checkButtonNotInUse(SDL_GamepadButton button) -> bool; // Verifica uso de botones
|
auto checkButtonNotInUse(SDL_GamepadButton button) -> bool; // Verifica uso de botones
|
||||||
void clearButtons(); // Limpia asignaciones actuales
|
void clearButtons(); // Limpia asignaciones actuales
|
||||||
|
|||||||
@@ -149,91 +149,93 @@ void Director::loadScoreFile() {
|
|||||||
|
|
||||||
// Asigna los botones y teclas al objeto Input
|
// Asigna los botones y teclas al objeto Input
|
||||||
void Director::bindInputs() {
|
void Director::bindInputs() {
|
||||||
|
static auto input = Input::get();
|
||||||
|
|
||||||
// Teclado - Movimiento del jugador
|
// Teclado - Movimiento del jugador
|
||||||
Input::get()->bindKey(Input::Action::UP, SDL_SCANCODE_UP);
|
input->bindKey(Input::Action::UP, SDL_SCANCODE_UP);
|
||||||
Input::get()->bindKey(Input::Action::DOWN, SDL_SCANCODE_DOWN);
|
input->bindKey(Input::Action::DOWN, SDL_SCANCODE_DOWN);
|
||||||
Input::get()->bindKey(Input::Action::LEFT, SDL_SCANCODE_LEFT);
|
input->bindKey(Input::Action::LEFT, SDL_SCANCODE_LEFT);
|
||||||
Input::get()->bindKey(Input::Action::RIGHT, SDL_SCANCODE_RIGHT);
|
input->bindKey(Input::Action::RIGHT, SDL_SCANCODE_RIGHT);
|
||||||
|
|
||||||
// Teclado - Disparo del jugador
|
// Teclado - Disparo del jugador
|
||||||
Input::get()->bindKey(Input::Action::FIRE_LEFT, SDL_SCANCODE_Q);
|
input->bindKey(Input::Action::FIRE_LEFT, SDL_SCANCODE_Q);
|
||||||
Input::get()->bindKey(Input::Action::FIRE_CENTER, SDL_SCANCODE_W);
|
input->bindKey(Input::Action::FIRE_CENTER, SDL_SCANCODE_W);
|
||||||
Input::get()->bindKey(Input::Action::FIRE_RIGHT, SDL_SCANCODE_E);
|
input->bindKey(Input::Action::FIRE_RIGHT, SDL_SCANCODE_E);
|
||||||
|
|
||||||
// Teclado - Interfaz
|
// Teclado - Interfaz
|
||||||
Input::get()->bindKey(Input::Action::START, SDL_SCANCODE_RETURN);
|
input->bindKey(Input::Action::START, SDL_SCANCODE_RETURN);
|
||||||
|
|
||||||
// Teclado - Menu de servicio
|
// Teclado - Menu de servicio
|
||||||
Input::get()->bindKey(Input::Action::SERVICE, SDL_SCANCODE_0);
|
input->bindKey(Input::Action::SERVICE, SDL_SCANCODE_0);
|
||||||
Input::get()->bindKey(Input::Action::SM_SELECT, SDL_SCANCODE_RETURN);
|
input->bindKey(Input::Action::SM_SELECT, SDL_SCANCODE_RETURN);
|
||||||
Input::get()->bindKey(Input::Action::SM_BACK, SDL_SCANCODE_BACKSPACE);
|
input->bindKey(Input::Action::SM_BACK, SDL_SCANCODE_BACKSPACE);
|
||||||
|
|
||||||
// Teclado - Control del programa
|
// Teclado - Control del programa
|
||||||
Input::get()->bindKey(Input::Action::EXIT, SDL_SCANCODE_ESCAPE);
|
input->bindKey(Input::Action::EXIT, SDL_SCANCODE_ESCAPE);
|
||||||
Input::get()->bindKey(Input::Action::PAUSE, SDL_SCANCODE_P);
|
input->bindKey(Input::Action::PAUSE, SDL_SCANCODE_P);
|
||||||
Input::get()->bindKey(Input::Action::BACK, SDL_SCANCODE_BACKSPACE);
|
input->bindKey(Input::Action::BACK, SDL_SCANCODE_BACKSPACE);
|
||||||
|
|
||||||
Input::get()->bindKey(Input::Action::WINDOW_DEC_SIZE, SDL_SCANCODE_F1);
|
input->bindKey(Input::Action::WINDOW_DEC_SIZE, SDL_SCANCODE_F1);
|
||||||
Input::get()->bindKey(Input::Action::WINDOW_INC_SIZE, SDL_SCANCODE_F2);
|
input->bindKey(Input::Action::WINDOW_INC_SIZE, SDL_SCANCODE_F2);
|
||||||
Input::get()->bindKey(Input::Action::WINDOW_FULLSCREEN, SDL_SCANCODE_F3);
|
input->bindKey(Input::Action::WINDOW_FULLSCREEN, SDL_SCANCODE_F3);
|
||||||
Input::get()->bindKey(Input::Action::TOGGLE_VIDEO_SHADERS, SDL_SCANCODE_F4);
|
input->bindKey(Input::Action::TOGGLE_VIDEO_SHADERS, SDL_SCANCODE_F4);
|
||||||
Input::get()->bindKey(Input::Action::TOGGLE_VIDEO_INTEGER_SCALE, SDL_SCANCODE_F5);
|
input->bindKey(Input::Action::TOGGLE_VIDEO_INTEGER_SCALE, SDL_SCANCODE_F5);
|
||||||
Input::get()->bindKey(Input::Action::TOGGLE_VIDEO_VSYNC, SDL_SCANCODE_F6);
|
input->bindKey(Input::Action::TOGGLE_VIDEO_VSYNC, SDL_SCANCODE_F6);
|
||||||
|
|
||||||
Input::get()->bindKey(Input::Action::TOGGLE_AUDIO, SDL_SCANCODE_F7);
|
input->bindKey(Input::Action::TOGGLE_AUDIO, SDL_SCANCODE_F7);
|
||||||
Input::get()->bindKey(Input::Action::TOGGLE_AUTO_FIRE, SDL_SCANCODE_F8);
|
input->bindKey(Input::Action::TOGGLE_AUTO_FIRE, SDL_SCANCODE_F8);
|
||||||
Input::get()->bindKey(Input::Action::CHANGE_LANG, SDL_SCANCODE_F9);
|
input->bindKey(Input::Action::CHANGE_LANG, SDL_SCANCODE_F9);
|
||||||
|
|
||||||
Input::get()->bindKey(Input::Action::RESET, SDL_SCANCODE_F10);
|
input->bindKey(Input::Action::RESET, SDL_SCANCODE_F10);
|
||||||
Input::get()->bindKey(Input::Action::SHOW_INFO, SDL_SCANCODE_F12);
|
input->bindKey(Input::Action::SHOW_INFO, SDL_SCANCODE_F12);
|
||||||
|
|
||||||
// Asigna botones a inputs
|
// Asigna botones a inputs
|
||||||
const int NUM_GAMEPADS = Input::get()->getNumControllers();
|
auto gamepads = input->getGamepads();
|
||||||
for (int i = 0; i < NUM_GAMEPADS; ++i) {
|
for (auto &gamepad : gamepads) {
|
||||||
// Mando - Movimiento del jugador
|
// Mando - Movimiento del jugador
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::UP, SDL_GAMEPAD_BUTTON_DPAD_UP);
|
input->bindGameControllerButton(gamepad, Input::Action::UP, SDL_GAMEPAD_BUTTON_DPAD_UP);
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::DOWN, SDL_GAMEPAD_BUTTON_DPAD_DOWN);
|
input->bindGameControllerButton(gamepad, Input::Action::DOWN, SDL_GAMEPAD_BUTTON_DPAD_DOWN);
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::LEFT, SDL_GAMEPAD_BUTTON_DPAD_LEFT);
|
input->bindGameControllerButton(gamepad, Input::Action::LEFT, SDL_GAMEPAD_BUTTON_DPAD_LEFT);
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::RIGHT, SDL_GAMEPAD_BUTTON_DPAD_RIGHT);
|
input->bindGameControllerButton(gamepad, Input::Action::RIGHT, SDL_GAMEPAD_BUTTON_DPAD_RIGHT);
|
||||||
|
|
||||||
// Mando - Disparo del jugador
|
// Mando - Disparo del jugador
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::FIRE_LEFT, SDL_GAMEPAD_BUTTON_WEST);
|
input->bindGameControllerButton(gamepad, Input::Action::FIRE_LEFT, SDL_GAMEPAD_BUTTON_WEST);
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::FIRE_CENTER, SDL_GAMEPAD_BUTTON_NORTH);
|
input->bindGameControllerButton(gamepad, Input::Action::FIRE_CENTER, SDL_GAMEPAD_BUTTON_NORTH);
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::FIRE_RIGHT, SDL_GAMEPAD_BUTTON_EAST);
|
input->bindGameControllerButton(gamepad, Input::Action::FIRE_RIGHT, SDL_GAMEPAD_BUTTON_EAST);
|
||||||
|
|
||||||
// Mando - Interfaz
|
// Mando - Interfaz
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::START, SDL_GAMEPAD_BUTTON_START);
|
input->bindGameControllerButton(gamepad, Input::Action::START, SDL_GAMEPAD_BUTTON_START);
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::SERVICE, SDL_GAMEPAD_BUTTON_BACK);
|
input->bindGameControllerButton(gamepad, Input::Action::SERVICE, SDL_GAMEPAD_BUTTON_BACK);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mapea las asignaciones a los botones desde el archivo de configuración, si se da el caso
|
// Mapea las asignaciones a los botones desde el archivo de configuración, si se da el caso
|
||||||
const size_t MAX_CONTROLLERS = std::min(2, NUM_GAMEPADS);
|
const size_t MAX_CONTROLLERS = std::min(2, NUM_GAMEPADS);
|
||||||
for (size_t i = 0; i < MAX_CONTROLLERS; ++i) {
|
for (size_t i = 0; i < MAX_CONTROLLERS; ++i) {
|
||||||
for (auto &controller : Options::controllers) {
|
for (auto &controller : Options::controllers) {
|
||||||
if (Input::get()->getControllerName(i) == controller.name) {
|
if (input->getControllerName(i) == controller.name) {
|
||||||
for (size_t j = 0; j < controller.inputs.size(); ++j) {
|
for (size_t j = 0; j < controller.inputs.size(); ++j) {
|
||||||
Input::get()->bindGameControllerButton(i, controller.inputs.at(j), controller.buttons.at(j));
|
input->bindGameControllerButton(i, controller.inputs.at(j), controller.buttons.at(j));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna botones a inputs desde otros inputs
|
// Asigna botones a inputs desde otros inputs
|
||||||
for (int i = 0; i < NUM_GAMEPADS; ++i) {
|
for (auto &gamepad : gamepads) {
|
||||||
// Mando - Menu de servicio
|
// Mando - Menu de servicio
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::SM_SELECT, Input::Action::FIRE_LEFT);
|
input->bindGameControllerButton(gamepad, Input::Action::SM_SELECT, Input::Action::FIRE_LEFT);
|
||||||
Input::get()->bindGameControllerButton(i, Input::Action::SM_BACK, Input::Action::FIRE_CENTER);
|
input->bindGameControllerButton(gamepad, Input::Action::SM_BACK, Input::Action::FIRE_CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Guarda las asignaciones de botones en las opciones de los dos primeros mandos
|
// Guarda las asignaciones de botones en las opciones de los dos primeros mandos
|
||||||
for (size_t i = 0; i < MAX_CONTROLLERS; ++i) {
|
for (size_t i = 0; i < MAX_CONTROLLERS; ++i) {
|
||||||
// Variables asociadas al mando
|
// Variables asociadas al mando
|
||||||
Options::controllers.at(i).index = i;
|
Options::controllers.at(i).index = i;
|
||||||
Options::controllers.at(i).name = Input::get()->getControllerName(i);
|
Options::controllers.at(i).name = input->getControllerName(i);
|
||||||
Options::controllers.at(i).plugged = true;
|
Options::controllers.at(i).plugged = true;
|
||||||
// Asignaciones de botones
|
// Asignaciones de botones
|
||||||
for (size_t j = 0; j < Options::controllers.at(i).inputs.size(); ++j) {
|
for (size_t j = 0; j < Options::controllers.at(i).inputs.size(); ++j) {
|
||||||
Options::controllers.at(i).buttons.at(j) = Input::get()->getControllerBinding(i, Options::controllers.at(i).inputs.at(j));
|
Options::controllers.at(i).buttons.at(j) = input->getControllerBinding(i, Options::controllers.at(i).inputs.at(j));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -303,7 +303,7 @@ auto checkInputs() -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Saltar sección
|
// Saltar sección
|
||||||
if ((Input::get()->checkAnyButton() != 0) && !ServiceMenu::get()->isEnabled()) {
|
if ((Input::get()->checkAnyButton()) && !ServiceMenu::get()->isEnabled()) {
|
||||||
skipSection();
|
skipSection();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
215
source/input.cpp
215
source/input.cpp
@@ -28,8 +28,8 @@ Input::Input(std::string game_controller_db_path)
|
|||||||
initSDLGamePad();
|
initSDLGamePad();
|
||||||
|
|
||||||
// Inicializa los vectores
|
// Inicializa los vectores
|
||||||
key_bindings_.resize(static_cast<int>(Action::SIZE), KeyBindings());
|
// key_bindings_.resize(static_cast<int>(Action::SIZE), KeyBindings());
|
||||||
controller_bindings_.resize(num_gamepads_, std::vector<ControllerBindings>(static_cast<int>(Action::SIZE), ControllerBindings()));
|
// 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
|
// 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};
|
button_inputs_ = {Action::FIRE_LEFT, Action::FIRE_CENTER, Action::FIRE_RIGHT, Action::START};
|
||||||
@@ -41,21 +41,21 @@ void Input::bindKey(Action input, SDL_Scancode code) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a botones del mando
|
// Asigna inputs a botones del mando
|
||||||
void Input::bindGameControllerButton(int controller_index, Action input, SDL_GamepadButton button) {
|
void Input::bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action input, SDL_GamepadButton button) {
|
||||||
if (controller_index < num_gamepads_) {
|
if (gamepad != nullptr) {
|
||||||
controller_bindings_.at(controller_index).at(static_cast<int>(input)).button = button;
|
gamepad->bindings.at(static_cast<int>(input)).button = button;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a botones del mando
|
// Asigna inputs a botones del mando
|
||||||
void Input::bindGameControllerButton(int controller_index, Action input_target, Action input_source) {
|
void Input::bindGameControllerButton(std::shared_ptr<Gamepad> gamepad, Action input_target, Action input_source) {
|
||||||
if (controller_index < num_gamepads_) {
|
if (gamepad != nullptr) {
|
||||||
controller_bindings_.at(controller_index).at(static_cast<int>(input_target)).button = controller_bindings_.at(controller_index).at(static_cast<int>(input_source)).button;
|
gamepad->bindings.at(static_cast<int>(input_target)).button = gamepad->bindings.at(static_cast<int>(input_source)).button;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si un input esta activo
|
// Comprueba si un input esta activo
|
||||||
auto Input::checkAction(Action input, bool repeat, Device device, int controller_index) -> bool {
|
auto Input::checkAction(Action input, bool repeat, Device device, std::shared_ptr<Gamepad> gamepad) -> bool {
|
||||||
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);
|
||||||
@@ -68,15 +68,15 @@ auto Input::checkAction(Action input, bool repeat, Device device, int controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) {
|
if (gamepad != nullptr) {
|
||||||
if ((device == Device::CONTROLLER) || (device == Device::ANY)) {
|
if ((device == Device::CONTROLLER) || (device == Device::ANY)) {
|
||||||
success_controller = checkAxisInput(input, controller_index, repeat);
|
success_controller = checkAxisInput(input, gamepad, repeat);
|
||||||
|
|
||||||
if (!success_controller) {
|
if (!success_controller) {
|
||||||
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
||||||
success_controller = controller_bindings_.at(controller_index).at(INPUT_INDEX).is_held;
|
success_controller = gamepad->bindings.at(INPUT_INDEX).is_held;
|
||||||
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
||||||
success_controller = controller_bindings_.at(controller_index).at(INPUT_INDEX).just_pressed;
|
success_controller = gamepad->bindings.at(INPUT_INDEX).just_pressed;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -86,7 +86,7 @@ auto Input::checkAction(Action input, bool repeat, Device device, int controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si hay almenos un input activo
|
// Comprueba si hay almenos un input activo
|
||||||
auto Input::checkAnyInput(Device device, int controller_index) -> bool {
|
auto Input::checkAnyInput(Device device, std::shared_ptr<Gamepad> gamepad) -> bool {
|
||||||
// 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>(Action::SIZE);
|
const int NUM_ACTIONS = static_cast<int>(Action::SIZE);
|
||||||
|
|
||||||
@@ -103,12 +103,12 @@ auto Input::checkAnyInput(Device device, int controller_index) -> bool {
|
|||||||
|
|
||||||
// --- 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 (gamepad != nullptr) {
|
||||||
if (device == Device::CONTROLLER || device == Device::ANY) {
|
if (device == Device::CONTROLLER || device == Device::ANY) {
|
||||||
// Bucle CORREGIDO: Iteramos sobre todas las acciones, no sobre el número de mandos.
|
// 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 (gamepad->bindings.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.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -119,102 +119,34 @@ auto Input::checkAnyInput(Device device, int controller_index) -> bool {
|
|||||||
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
|
||||||
auto Input::checkAnyButton(bool repeat) -> int {
|
auto Input::checkAnyButton(bool repeat) -> bool {
|
||||||
// Solo comprueba los botones definidos previamente
|
// Solo comprueba los botones definidos previamente
|
||||||
for (auto bi : button_inputs_) {
|
for (auto bi : button_inputs_) {
|
||||||
// Comprueba el teclado
|
// Comprueba el teclado
|
||||||
if (checkAction(bi, repeat, Device::KEYBOARD)) {
|
if (checkAction(bi, repeat, Device::KEYBOARD)) {
|
||||||
return 1;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los mandos
|
// Comprueba los mandos
|
||||||
for (int i = 0; i < num_gamepads_; ++i) {
|
for (auto gamepad : gamepads_) {
|
||||||
if (checkAction(bi, repeat, Device::CONTROLLER, i)) {
|
if (checkAction(bi, repeat, Device::CONTROLLER, gamepad)) {
|
||||||
return i + 1;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Busca si hay mandos conectados
|
|
||||||
/*auto Input::discoverGameControllers() -> bool {
|
|
||||||
bool found = false;
|
|
||||||
|
|
||||||
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: could not load %s file: %s", game_controller_db_path_.c_str(), SDL_GetError());
|
|
||||||
}
|
|
||||||
|
|
||||||
// En SDL3, SDL_GetJoysticks devuelve un array de IDs, no un contador
|
|
||||||
SDL_JoystickID *joystick_ids = SDL_GetJoysticks(&num_joysticks_);
|
|
||||||
num_gamepads_ = 0;
|
|
||||||
|
|
||||||
// Cuenta el número de mandos
|
|
||||||
joysticks_.clear();
|
|
||||||
for (int i = 0; i < num_joysticks_; ++i) {
|
|
||||||
// Usar el ID del joystick, no el índice
|
|
||||||
auto *joy = SDL_OpenJoystick(joystick_ids[i]);
|
|
||||||
joysticks_.push_back(joy);
|
|
||||||
|
|
||||||
// En SDL3, SDL_IsGamepad toma un SDL_JoystickID, no un índice
|
|
||||||
if (SDL_IsGamepad(joystick_ids[i])) {
|
|
||||||
num_gamepads_++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> LOOKING FOR GAME CONTROLLERS");
|
|
||||||
if (num_joysticks_ != num_gamepads_) {
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Joysticks found: %d", num_joysticks_);
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Gamepads found : %d", num_gamepads_);
|
|
||||||
} else {
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Gamepads found: %d", num_gamepads_);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (num_gamepads_ > 0) {
|
|
||||||
found = true;
|
|
||||||
|
|
||||||
// Recorrer los joysticks y abrir solo los que son gamepads
|
|
||||||
for (int i = 0; i < num_joysticks_; i++) {
|
|
||||||
if (SDL_IsGamepad(joystick_ids[i])) {
|
|
||||||
// Abre el mando usando el ID del joystick
|
|
||||||
auto *pad = SDL_OpenGamepad(joystick_ids[i]);
|
|
||||||
if (pad != nullptr) {
|
|
||||||
connected_controllers_.push_back(pad);
|
|
||||||
|
|
||||||
// Obtener el nombre usando el ID del joystick
|
|
||||||
const char *name_cstr = SDL_GetGamepadNameForID(joystick_ids[i]);
|
|
||||||
std::string name = (name_cstr != nullptr) ? name_cstr : "Unknown Gamepad";
|
|
||||||
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "#%d: %s", i, name.c_str());
|
|
||||||
controller_names_.push_back(name);
|
|
||||||
} else {
|
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to open gamepad %d: %s", joystick_ids[i], SDL_GetError());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SDL_SetGamepadEventsEnabled(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Liberar el array de IDs
|
|
||||||
if (joystick_ids != nullptr) {
|
|
||||||
SDL_free(joystick_ids);
|
|
||||||
}
|
|
||||||
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> FINISHED LOOKING FOR GAME CONTROLLERS");
|
|
||||||
return found;
|
|
||||||
}*/
|
|
||||||
|
|
||||||
// Comprueba si hay algun mando conectado
|
// 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
|
// 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(std::shared_ptr<Gamepad> gamepad) const -> std::string { return gamepad == nullptr ? std::string() : gamepad->name; }
|
||||||
|
|
||||||
// Obten el número de mandos conectados
|
// Obten el número de mandos conectados
|
||||||
auto Input::getNumControllers() const -> int { return num_gamepads_; }
|
auto Input::getNumControllers() const -> int { return gamepads_.size(); }
|
||||||
|
|
||||||
// Obtiene el indice del controlador a partir de un event.id
|
// Obtiene el indice del controlador a partir de un event.id
|
||||||
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
|
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
|
||||||
@@ -226,36 +158,9 @@ auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Muestra por consola los controles asignados
|
|
||||||
void Input::printBindings(Device device, int controller_index) const {
|
|
||||||
if (device == Device::ANY || device == Device::KEYBOARD) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (device == Device::CONTROLLER) {
|
|
||||||
if (controller_index >= num_gamepads_) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Muestra el nombre del mando
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n%s", controller_names_.at(controller_index).c_str());
|
|
||||||
|
|
||||||
// Muestra los botones asignados
|
|
||||||
for (auto bi : button_inputs_) {
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s : %d", inputToString(bi).c_str(), controller_bindings_.at(controller_index).at(static_cast<int>(bi)).button);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Obtiene el SDL_GamepadButton asignado a un input
|
// Obtiene el SDL_GamepadButton asignado a un input
|
||||||
auto Input::getControllerBinding(int controller_index, Action input) const -> SDL_GamepadButton {
|
auto Input::getControllerBinding(std::shared_ptr<Gamepad> gamepad, Action input) const -> SDL_GamepadButton {
|
||||||
return controller_bindings_[controller_index][static_cast<int>(input)].button;
|
return gamepad->bindings.at(static_cast<int>(input)).button;
|
||||||
}
|
|
||||||
|
|
||||||
// Obtiene el indice a partir del nombre del mando
|
|
||||||
auto Input::getIndexByName(const std::string &name) const -> int {
|
|
||||||
auto it = std::find(controller_names_.begin(), controller_names_.end(), name);
|
|
||||||
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convierte un InputAction a std::string
|
// Convierte un InputAction a std::string
|
||||||
@@ -290,29 +195,29 @@ auto Input::stringToInput(const std::string &name) -> Action {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
// Comprueba el eje del mando
|
||||||
auto Input::checkAxisInput(Action input, int controller_index, bool repeat) -> bool {
|
auto Input::checkAxisInput(Action input, std::shared_ptr<Gamepad> gamepad, bool repeat) -> bool {
|
||||||
// Umbral para considerar el eje como activo
|
// Umbral para considerar el eje como activo
|
||||||
bool axis_active_now = false;
|
bool axis_active_now = false;
|
||||||
|
|
||||||
switch (input) {
|
switch (input) {
|
||||||
case Action::LEFT:
|
case Action::LEFT:
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
|
||||||
break;
|
break;
|
||||||
case Action::RIGHT:
|
case Action::RIGHT:
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
|
||||||
break;
|
break;
|
||||||
case Action::UP:
|
case Action::UP:
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -AXIS_THRESHOLD;
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTY) < -AXIS_THRESHOLD;
|
||||||
break;
|
break;
|
||||||
case Action::DOWN:
|
case Action::DOWN:
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > AXIS_THRESHOLD;
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTY) > AXIS_THRESHOLD;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Referencia al binding correspondiente
|
// Referencia al binding correspondiente
|
||||||
auto &binding = controller_bindings_.at(controller_index).at(static_cast<int>(input));
|
auto &binding = gamepad->bindings.at(static_cast<int>(input));
|
||||||
|
|
||||||
if (repeat) {
|
if (repeat) {
|
||||||
// Si se permite repetir, simplemente devolvemos el estado actual
|
// Si se permite repetir, simplemente devolvemos el estado actual
|
||||||
@@ -336,9 +241,10 @@ void Input::initSDLGamePad() {
|
|||||||
if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) {
|
if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GAMEPAD could not initialize! SDL Error: %s", SDL_GetError());
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GAMEPAD could not initialize! SDL Error: %s", SDL_GetError());
|
||||||
} else {
|
} else {
|
||||||
//SDL_LogInfo(SDL_LOG_CATEGORY_TEST, "\n** SDL_GAMEPAD: INITIALIZING");
|
SDL_Event event;
|
||||||
//discoverGameControllers();
|
while (SDL_PollEvent(&event)) {
|
||||||
//printConnectedGamepads();
|
handleEvent(event); // Comprueba mandos conectados
|
||||||
|
}
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "** Input System initialized successfully\n");
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "** Input System initialized successfully\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -351,8 +257,8 @@ void Input::resetInputStates() {
|
|||||||
key.just_pressed = false;
|
key.just_pressed = false;
|
||||||
}
|
}
|
||||||
// Resetear todos los ControllerBindings.active a false
|
// Resetear todos los ControllerBindings.active a false
|
||||||
for (auto &controller_vec : controller_bindings_) {
|
for (auto &gamepad : gamepads_) {
|
||||||
for (auto &binding : controller_vec) {
|
for (auto &binding : gamepad->bindings) {
|
||||||
binding.is_held = false;
|
binding.is_held = false;
|
||||||
binding.just_pressed = false;
|
binding.just_pressed = false;
|
||||||
}
|
}
|
||||||
@@ -372,13 +278,13 @@ void Input::update() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- MANDOS ---
|
// --- MANDOS ---
|
||||||
for (int c = 0; c < num_gamepads_; ++c) {
|
for (auto gamepad : gamepads_) {
|
||||||
for (size_t i = 0; i < controller_bindings_[c].size(); ++i) {
|
for (auto &binding : gamepad->bindings) {
|
||||||
bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(c), controller_bindings_.at(c).at(i).button)) != 0;
|
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
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
||||||
controller_bindings_[c][i].just_pressed = button_is_down_now && !controller_bindings_[c][i].is_held;
|
binding.just_pressed = button_is_down_now && !binding.is_held;
|
||||||
controller_bindings_[c][i].is_held = button_is_down_now;
|
binding.is_held = button_is_down_now;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -397,39 +303,38 @@ void Input::handleEvent(const SDL_Event &event) {
|
|||||||
void Input::add_gamepad(int device_index) {
|
void Input::add_gamepad(int device_index) {
|
||||||
SDL_Gamepad *pad = SDL_OpenGamepad(device_index);
|
SDL_Gamepad *pad = SDL_OpenGamepad(device_index);
|
||||||
if (!pad) {
|
if (!pad) {
|
||||||
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << "\n";
|
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << std::endl;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto gamepad = std::make_unique<Gamepad>(pad);
|
auto gamepad = std::make_shared<Gamepad>(pad);
|
||||||
//std::cout << "Gamepad conectado (ID " << gamepad->instance_id << ")\n";
|
std::cout << "Gamepad connected (" << gamepad->name << ")" << std::endl;
|
||||||
std::cout << "Gamepad connected (" << gamepad->name << ")\n";
|
gamepads_.push_back(std::move(gamepad));
|
||||||
gamepads.push_back(std::move(gamepad));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Input::remove_gamepad(SDL_JoystickID id) {
|
void Input::remove_gamepad(SDL_JoystickID id) {
|
||||||
auto it = std::remove_if(gamepads.begin(), gamepads.end(), [id](const std::unique_ptr<Gamepad> &gamepad) {
|
auto it = std::remove_if(gamepads_.begin(), gamepads_.end(), [id](const std::shared_ptr<Gamepad> &gamepad) {
|
||||||
return gamepad->instance_id == id;
|
return gamepad->instance_id == id;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (it != gamepads.end()) {
|
if (it != gamepads_.end()) {
|
||||||
std::cout << "Gamepad disconnected (" << (*it)->name << ")\n";
|
std::cout << "Gamepad disconnected (" << (*it)->name << ")" << std::endl;
|
||||||
gamepads.erase(it, gamepads.end());
|
gamepads_.erase(it, gamepads_.end());
|
||||||
} else {
|
} else {
|
||||||
std::cerr << "No se encontró el gamepad con ID " << id << "\n";
|
std::cerr << "No se encontró el gamepad con ID " << id << std::endl;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Input::printConnectedGamepads() const {
|
void Input::printConnectedGamepads() const {
|
||||||
if (gamepads.empty()) {
|
if (gamepads_.empty()) {
|
||||||
std::cout << "No hay gamepads conectados.\n";
|
std::cout << "No hay gamepads conectados." << std::endl;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "Gamepads conectados:\n";
|
std::cout << "Gamepads conectados:\n";
|
||||||
for (const auto& gamepad : gamepads) {
|
for (const auto &gamepad : gamepads_) {
|
||||||
const char* name = SDL_GetGamepadName(gamepad->pad);
|
std::string name = gamepad->name == "" ? "Desconocido" : gamepad->name;
|
||||||
std::cout << " - ID: " << gamepad->instance_id
|
std::cout << " - ID: " << gamepad->instance_id
|
||||||
<< ", Nombre: " << (name ? name : "Desconocido") << "\n";
|
<< ", Nombre: " << name << ")" << std::endl;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
101
source/input.h
101
source/input.h
@@ -72,47 +72,7 @@ class Input {
|
|||||||
ANY = 2,
|
ANY = 2,
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Métodos de singleton ---
|
// --- Estructuras ---
|
||||||
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(int controller_index, Action input, SDL_GamepadButton button); // Asigna inputs a botones del mando
|
|
||||||
void bindGameControllerButton(int controller_index, 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, int controller_index = 0) -> bool; // Comprueba si un input está activo
|
|
||||||
auto checkAnyInput(Device device = Device::ANY, int controller_index = 0) -> bool; // Comprueba si hay al menos un input activo
|
|
||||||
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> int; // Comprueba si hay algún botón pulsado
|
|
||||||
|
|
||||||
// --- Métodos de gestión de mandos ---
|
|
||||||
// auto discoverGameControllers() -> bool; // Busca si hay mandos conectados
|
|
||||||
// void discoverGameControllers();
|
|
||||||
[[nodiscard]] auto gameControllerFound() const -> bool; // Comprueba si hay algún mando conectado
|
|
||||||
[[nodiscard]] auto getNumControllers() const -> int; // Obtiene el número de mandos conectados
|
|
||||||
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string; // Obtiene el nombre de un mando de juego
|
|
||||||
[[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 ---
|
|
||||||
void printBindings(Device device = Device::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
|
|
||||||
[[nodiscard]] auto getControllerBinding(int controller_index, 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
|
|
||||||
[[nodiscard]] auto getIndexByName(const std::string &name) const -> int; // Obtiene el índice a partir del nombre del mando
|
|
||||||
|
|
||||||
// --- 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;
|
|
||||||
|
|
||||||
private:
|
|
||||||
// --- Estructuras internas ---
|
|
||||||
struct KeyBindings {
|
struct KeyBindings {
|
||||||
Uint8 scancode; // Scancode asociado
|
Uint8 scancode; // Scancode asociado
|
||||||
bool is_held; // Está pulsada ahora mismo
|
bool is_held; // Está pulsada ahora mismo
|
||||||
@@ -136,6 +96,7 @@ class Input {
|
|||||||
SDL_Gamepad *pad;
|
SDL_Gamepad *pad;
|
||||||
SDL_JoystickID instance_id;
|
SDL_JoystickID instance_id;
|
||||||
std::string name;
|
std::string name;
|
||||||
|
std::vector<ControllerBindings> bindings;
|
||||||
|
|
||||||
Gamepad(SDL_Gamepad *gamepad)
|
Gamepad(SDL_Gamepad *gamepad)
|
||||||
: pad(gamepad),
|
: pad(gamepad),
|
||||||
@@ -145,29 +106,61 @@ class Input {
|
|||||||
~Gamepad() {
|
~Gamepad() {
|
||||||
if (pad) {
|
if (pad) {
|
||||||
SDL_CloseGamepad(pad);
|
SDL_CloseGamepad(pad);
|
||||||
//std::cout << "Gamepad cerrado (ID " << instance_id << ")\n";
|
// 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 ---
|
// --- Constantes ---
|
||||||
static constexpr Sint16 AXIS_THRESHOLD = 30000;
|
static constexpr Sint16 AXIS_THRESHOLD = 30000;
|
||||||
|
|
||||||
// --- Variables internas ---
|
// --- Variables internas ---
|
||||||
std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados
|
std::vector<std::shared_ptr<Gamepad>> gamepads_; // 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<KeyBindings> 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::vector<std::vector<ControllerBindings>> controller_bindings_; // Vector con los botones asociados a los inputs predefinidos para cada mando
|
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
|
||||||
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
|
|
||||||
std::vector<Action> 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
|
|
||||||
std::vector<std::unique_ptr<Gamepad>> gamepads;
|
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
|
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
|
||||||
auto checkAxisInput(Action input, int controller_index, bool repeat) -> bool; // Comprueba el eje del mando
|
auto checkAxisInput(Action input, std::shared_ptr<Gamepad> gamepad, bool repeat) -> bool; // Comprueba el eje del mando
|
||||||
void add_gamepad(int device_index);
|
void add_gamepad(int device_index);
|
||||||
void remove_gamepad(SDL_JoystickID id);
|
void remove_gamepad(SDL_JoystickID id);
|
||||||
|
|
||||||
|
|||||||
@@ -39,9 +39,8 @@ void init() {
|
|||||||
|
|
||||||
// Opciones de control
|
// Opciones de control
|
||||||
controllers.clear();
|
controllers.clear();
|
||||||
controllers.resize(2);
|
controllers.emplace_back(GamepadOptions(1));
|
||||||
controllers.at(0).player_id = 1;
|
controllers.emplace_back(GamepadOptions(2));
|
||||||
controllers.at(1).player_id = 2;
|
|
||||||
setKeyboardToPlayer(1);
|
setKeyboardToPlayer(1);
|
||||||
|
|
||||||
// Opciones pendientes
|
// Opciones pendientes
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_ScaleMode
|
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_ScaleMode
|
||||||
|
|
||||||
#include <algorithm> // Para copy
|
#include <algorithm> // Para copy
|
||||||
|
#include <array> // Para array
|
||||||
#include <string> // Para allocator, string
|
#include <string> // Para allocator, string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
@@ -83,14 +84,14 @@ struct SettingsOptions {
|
|||||||
|
|
||||||
// Reinicia las últimas entradas de puntuación
|
// Reinicia las últimas entradas de puntuación
|
||||||
void clearLastHiScoreEntries() {
|
void clearLastHiScoreEntries() {
|
||||||
last_hi_score_entry[0] = INVALID_INDEX;
|
last_hi_score_entry.at(0) = INVALID_INDEX;
|
||||||
last_hi_score_entry[1] = INVALID_INDEX;
|
last_hi_score_entry.at(1) = INVALID_INDEX;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Opciones de mando ---
|
// --- Opciones de mando ---
|
||||||
struct GamepadOptions {
|
struct GamepadOptions {
|
||||||
int index; // Índice en el vector de mandos
|
Input::Gamepad gamepad; // Mando
|
||||||
int player_id; // Jugador asociado al mando
|
int player_id; // Jugador asociado al mando
|
||||||
Input::Device type{Input::Device::CONTROLLER}; // Indica si se usará teclado, mando o ambos
|
Input::Device type{Input::Device::CONTROLLER}; // Indica si se usará teclado, mando o ambos
|
||||||
std::string name; // Nombre del dispositivo
|
std::string name; // Nombre del dispositivo
|
||||||
@@ -100,7 +101,7 @@ struct GamepadOptions {
|
|||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
GamepadOptions()
|
GamepadOptions()
|
||||||
: index(INVALID_INDEX),
|
: gamepad(nullptr),
|
||||||
player_id(INVALID_INDEX),
|
player_id(INVALID_INDEX),
|
||||||
inputs{
|
inputs{
|
||||||
Input::Action::FIRE_LEFT,
|
Input::Action::FIRE_LEFT,
|
||||||
@@ -114,6 +115,23 @@ struct GamepadOptions {
|
|||||||
SDL_GAMEPAD_BUTTON_EAST,
|
SDL_GAMEPAD_BUTTON_EAST,
|
||||||
SDL_GAMEPAD_BUTTON_START,
|
SDL_GAMEPAD_BUTTON_START,
|
||||||
SDL_GAMEPAD_BUTTON_BACK} {}
|
SDL_GAMEPAD_BUTTON_BACK} {}
|
||||||
|
|
||||||
|
// Constructor con player_id
|
||||||
|
GamepadOptions(int custom_player_id)
|
||||||
|
: gamepad(nullptr),
|
||||||
|
player_id(custom_player_id),
|
||||||
|
inputs{
|
||||||
|
Input::Action::FIRE_LEFT,
|
||||||
|
Input::Action::FIRE_CENTER,
|
||||||
|
Input::Action::FIRE_RIGHT,
|
||||||
|
Input::Action::START,
|
||||||
|
Input::Action::SERVICE},
|
||||||
|
buttons{
|
||||||
|
SDL_GAMEPAD_BUTTON_WEST,
|
||||||
|
SDL_GAMEPAD_BUTTON_NORTH,
|
||||||
|
SDL_GAMEPAD_BUTTON_EAST,
|
||||||
|
SDL_GAMEPAD_BUTTON_START,
|
||||||
|
SDL_GAMEPAD_BUTTON_BACK} {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Opciones pendientes de aplicar ---
|
// --- Opciones pendientes de aplicar ---
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ void Credits::checkInput() {
|
|||||||
|
|
||||||
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)
|
||||||
if (Input::get()->checkAnyButton(Input::ALLOW_REPEAT) != 0) {
|
if (Input::get()->checkAnyButton(Input::ALLOW_REPEAT)) {
|
||||||
want_to_pass_ = true;
|
want_to_pass_ = true;
|
||||||
fading_ = mini_logo_on_position_;
|
fading_ = mini_logo_on_position_;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1259,7 +1259,7 @@ void Game::checkPauseInput() {
|
|||||||
|
|
||||||
// Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
|
// Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
|
||||||
void Game::demoHandlePassInput() {
|
void Game::demoHandlePassInput() {
|
||||||
if (input_->checkAnyButton() != 0) {
|
if (input_->checkAnyButton()) {
|
||||||
Section::name = Section::Name::TITLE; // Salir del modo demo y regresar al menú principal.
|
Section::name = Section::Name::TITLE; // Salir del modo demo y regresar al menú principal.
|
||||||
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; // El juego volverá a mostrar la demo
|
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; // El juego volverá a mostrar la demo
|
||||||
return;
|
return;
|
||||||
|
|||||||
Reference in New Issue
Block a user