migrat Input a la ultima versió
cohesionats tots els metodes update de les escenes
This commit is contained in:
@@ -42,6 +42,7 @@ set(APP_SOURCES
|
|||||||
# Core - Input
|
# Core - Input
|
||||||
source/core/input/global_inputs.cpp
|
source/core/input/global_inputs.cpp
|
||||||
source/core/input/input.cpp
|
source/core/input/input.cpp
|
||||||
|
source/core/input/input_types.cpp
|
||||||
source/core/input/mouse.cpp
|
source/core/input/mouse.cpp
|
||||||
|
|
||||||
# Core - Rendering
|
# Core - Rendering
|
||||||
|
|||||||
1
Makefile
1
Makefile
@@ -64,6 +64,7 @@ APP_SOURCES := \
|
|||||||
source/main.cpp \
|
source/main.cpp \
|
||||||
source/core/audio/audio.cpp \
|
source/core/audio/audio.cpp \
|
||||||
source/core/input/input.cpp \
|
source/core/input/input.cpp \
|
||||||
|
source/core/input/input_types.cpp \
|
||||||
source/core/input/mouse.cpp \
|
source/core/input/mouse.cpp \
|
||||||
source/core/input/global_inputs.cpp \
|
source/core/input/global_inputs.cpp \
|
||||||
source/core/rendering/screen.cpp \
|
source/core/rendering/screen.cpp \
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ void Audio::playMusic(const std::string& name, const int loop) {
|
|||||||
|
|
||||||
// Si hay algo reproduciéndose, detenerlo primero (si el backend lo requiere)
|
// Si hay algo reproduciéndose, detenerlo primero (si el backend lo requiere)
|
||||||
if (music_.state == MusicState::PLAYING) {
|
if (music_.state == MusicState::PLAYING) {
|
||||||
JA_StopMusic(); // sustituir por la función de stop real del API si tiene otro nombre
|
JA_StopMusic(); // sustituir por la función de stop real del API si tiene otro nombre
|
||||||
}
|
}
|
||||||
|
|
||||||
// Llamada al motor para reproducir la nueva pista
|
// Llamada al motor para reproducir la nueva pista
|
||||||
@@ -64,7 +64,6 @@ void Audio::playMusic(const std::string& name, const int loop) {
|
|||||||
music_.state = MusicState::PLAYING;
|
music_.state = MusicState::PLAYING;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Pausa la música
|
// Pausa la música
|
||||||
void Audio::pauseMusic() {
|
void Audio::pauseMusic() {
|
||||||
if (music_enabled_ && music_.state == MusicState::PLAYING) {
|
if (music_enabled_ && music_.state == MusicState::PLAYING) {
|
||||||
|
|||||||
134
source/core/input/gamepad_config_manager.hpp
Normal file
134
source/core/input/gamepad_config_manager.hpp
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <fstream>
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "core/input/input_types.hpp" // Solo incluimos los tipos compartidos
|
||||||
|
#include "external/json.hpp"
|
||||||
|
|
||||||
|
// --- Estructuras ---
|
||||||
|
struct GamepadConfig {
|
||||||
|
std::string name; // Nombre del dispositivo
|
||||||
|
std::string path; // Ruta física del dispositivo
|
||||||
|
std::unordered_map<InputAction, SDL_GamepadButton> bindings; // Asociación acción-botón
|
||||||
|
|
||||||
|
GamepadConfig(std::string name, std::string path)
|
||||||
|
: name(std::move(name)),
|
||||||
|
path(std::move(path)),
|
||||||
|
bindings{
|
||||||
|
{InputAction::LEFT, SDL_GAMEPAD_BUTTON_DPAD_LEFT},
|
||||||
|
{InputAction::RIGHT, SDL_GAMEPAD_BUTTON_DPAD_RIGHT},
|
||||||
|
{InputAction::JUMP, SDL_GAMEPAD_BUTTON_WEST}} {}
|
||||||
|
|
||||||
|
// Reasigna un botón a una acción
|
||||||
|
void rebindAction(InputAction action, SDL_GamepadButton new_button) {
|
||||||
|
bindings[action] = new_button;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Tipos ---
|
||||||
|
using GamepadConfigs = std::vector<GamepadConfig>; // Vector de configuraciones de gamepad
|
||||||
|
|
||||||
|
// --- Clase GamepadConfigManager: gestor de configuraciones de gamepad ---
|
||||||
|
class GamepadConfigManager {
|
||||||
|
public:
|
||||||
|
// --- Métodos estáticos ---
|
||||||
|
static auto writeToJson(const GamepadConfigs& configs, const std::string& filename) -> bool { // Escribir configuraciones a JSON
|
||||||
|
try {
|
||||||
|
nlohmann::json j;
|
||||||
|
j["gamepads"] = nlohmann::json::array();
|
||||||
|
|
||||||
|
for (const auto& config : configs) {
|
||||||
|
nlohmann::json gamepad_json;
|
||||||
|
gamepad_json["name"] = config.name;
|
||||||
|
gamepad_json["path"] = config.path;
|
||||||
|
gamepad_json["bindings"] = nlohmann::json::object();
|
||||||
|
|
||||||
|
// Convertir bindings a JSON
|
||||||
|
for (const auto& [action, button] : config.bindings) {
|
||||||
|
auto action_it = ACTION_TO_STRING.find(action);
|
||||||
|
auto button_it = BUTTON_TO_STRING.find(button);
|
||||||
|
|
||||||
|
if (action_it != ACTION_TO_STRING.end() && button_it != BUTTON_TO_STRING.end()) {
|
||||||
|
gamepad_json["bindings"][action_it->second] = button_it->second;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
j["gamepads"].push_back(gamepad_json);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Escribir al archivo
|
||||||
|
std::ofstream file(filename);
|
||||||
|
if (!file.is_open()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
file << j.dump(4); // Formato con indentación de 4 espacios
|
||||||
|
file.close();
|
||||||
|
return true;
|
||||||
|
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
// Log del error si tienes sistema de logging
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leer vector de GamepadConfig desde archivo JSON
|
||||||
|
static auto readFromJson(GamepadConfigs& configs, const std::string& filename) -> bool {
|
||||||
|
try {
|
||||||
|
std::ifstream file(filename);
|
||||||
|
if (!file.is_open()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
nlohmann::json j;
|
||||||
|
file >> j;
|
||||||
|
file.close();
|
||||||
|
|
||||||
|
configs.clear();
|
||||||
|
|
||||||
|
if (!j.contains("gamepads") || !j["gamepads"].is_array()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto& gamepad_json : j["gamepads"]) {
|
||||||
|
if (!gamepad_json.contains("name") || !gamepad_json.contains("bindings")) {
|
||||||
|
continue; // Saltar configuraciones malformadas
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leer el campo path si existe, si no dejarlo vacío
|
||||||
|
std::string path = gamepad_json.contains("path") ? gamepad_json["path"].get<std::string>() : "";
|
||||||
|
GamepadConfig config(gamepad_json["name"], path);
|
||||||
|
|
||||||
|
// Limpiar bindings por defecto para cargar los del archivo
|
||||||
|
config.bindings.clear();
|
||||||
|
|
||||||
|
// Cargar bindings desde JSON
|
||||||
|
for (const auto& [actionStr, buttonStr] : gamepad_json["bindings"].items()) {
|
||||||
|
auto action_it = STRING_TO_ACTION.find(actionStr);
|
||||||
|
auto button_it = STRING_TO_BUTTON.find(buttonStr);
|
||||||
|
|
||||||
|
if (action_it != STRING_TO_ACTION.end() && button_it != STRING_TO_BUTTON.end()) {
|
||||||
|
config.bindings[action_it->second] = button_it->second;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
configs.push_back(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
// Log del error si tienes sistema de logging
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Método auxiliar para verificar si un archivo existe
|
||||||
|
static auto fileExists(const std::string& filename) -> bool {
|
||||||
|
std::ifstream file(filename);
|
||||||
|
return file.good();
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
|
||||||
|
|
||||||
#include "core/input/global_inputs.hpp"
|
#include "core/input/global_inputs.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
@@ -7,9 +5,10 @@
|
|||||||
#include <string> // Para allocator, operator+, char_traits, string
|
#include <string> // Para allocator, operator+, char_traits, string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT
|
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "game/options.hpp" // Para Options, options, OptionsVideo, Section
|
#include "game/options.hpp" // Para Options, options, OptionsVideo, Section
|
||||||
|
#include "game/scene_manager.hpp" // Para SceneManager
|
||||||
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText
|
#include "game/ui/notifier.hpp" // Para Notifier, NotificationText
|
||||||
#include "utils/utils.hpp" // Para stringInVector
|
#include "utils/utils.hpp" // Para stringInVector
|
||||||
|
|
||||||
@@ -46,59 +45,59 @@ void skipSection() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
|
||||||
void check() {
|
void handle() {
|
||||||
if (Input::get()->checkInput(InputAction::EXIT, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
if (Input::get()->checkAction(InputAction::EXIT, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
quit();
|
quit();
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
skipSection();
|
skipSection();
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::TOGGLE_BORDER, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::TOGGLE_BORDER, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
Screen::get()->toggleBorder();
|
Screen::get()->toggleBorder();
|
||||||
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
Notifier::get()->show({"BORDER " + std::string(Options::video.border.enabled ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::TOGGLE_VIDEOMODE, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::TOGGLE_VIDEOMODE, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
Screen::get()->toggleVideoMode();
|
Screen::get()->toggleVideoMode();
|
||||||
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")}, NotificationText::CENTER);
|
Notifier::get()->show({"FULLSCREEN " + std::string(static_cast<int>(Options::video.fullscreen) == 0 ? "DISABLED" : "ENABLED")}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::WINDOW_DEC_ZOOM, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::WINDOW_DEC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
if (Screen::get()->decWindowZoom()) {
|
if (Screen::get()->decWindowZoom()) {
|
||||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
|
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::WINDOW_INC_ZOOM, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::WINDOW_INC_ZOOM, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
if (Screen::get()->incWindowZoom()) {
|
if (Screen::get()->incWindowZoom()) {
|
||||||
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
|
Notifier::get()->show({"WINDOW ZOOM x" + std::to_string(Options::window.zoom)}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::TOGGLE_SHADERS, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::TOGGLE_SHADERS, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
Screen::get()->toggleShaders();
|
Screen::get()->toggleShaders();
|
||||||
Notifier::get()->show({"SHADERS " + std::string(Options::video.shaders ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
Notifier::get()->show({"SHADERS " + std::string(Options::video.shaders ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::NEXT_PALETTE, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::NEXT_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
Screen::get()->nextPalette();
|
Screen::get()->nextPalette();
|
||||||
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
|
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::PREVIOUS_PALETTE, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::PREVIOUS_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
Screen::get()->previousPalette();
|
Screen::get()->previousPalette();
|
||||||
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
|
Notifier::get()->show({"PALETTE " + Options::video.palette}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::TOGGLE_INTEGER_SCALE, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::TOGGLE_INTEGER_SCALE, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
Screen::get()->toggleIntegerScale();
|
Screen::get()->toggleIntegerScale();
|
||||||
Screen::get()->setVideoMode(Options::video.fullscreen);
|
Screen::get()->setVideoMode(Options::video.fullscreen);
|
||||||
Notifier::get()->show({"INTEGER SCALE " + std::string(Options::video.integer_scale ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
Notifier::get()->show({"INTEGER SCALE " + std::string(Options::video.integer_scale ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::SHOW_DEBUG_INFO, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::SHOW_DEBUG_INFO, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
Screen::get()->toggleDebugInfo();
|
Screen::get()->toggleDebugInfo();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,5 +2,5 @@
|
|||||||
|
|
||||||
namespace GlobalInputs {
|
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
|
||||||
void check();
|
void handle();
|
||||||
} // namespace GlobalInputs
|
} // namespace GlobalInputs
|
||||||
@@ -1,114 +1,79 @@
|
|||||||
#include "core/input/input.hpp"
|
#include "core/input/input.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h> // Para SDL_GetGamepadAxis, SDL_GamepadAxis, SDL_GamepadButton, SDL_GetError, SDL_JoystickID, SDL_AddGamepadMappingsFromFile, SDL_Event, SDL_EventType, SDL_GetGamepadButton, SDL_GetKeyboardState, SDL_INIT_GAMEPAD, SDL_InitSubSystem, SDL_LogError, SDL_OpenGamepad, SDL_PollEvent, SDL_WasInit, Sint16, SDL_Gamepad, SDL_LogCategory, SDL_Scancode
|
||||||
|
|
||||||
#include <algorithm> // Para find
|
#include <iostream> // Para basic_ostream, operator<<, cout, cerr
|
||||||
#include <iostream> // Para basic_ostream, operator<<, cout, endl
|
#include <memory> // Para shared_ptr, __shared_ptr_access, allocator, operator==, make_shared
|
||||||
#include <iterator> // Para distance
|
#include <ranges> // Para __find_if_fn, find_if
|
||||||
#include <unordered_map> // Para unordered_map, operator==, _Node_cons...
|
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==, _Node_iterator_base, _Node_const_iterator
|
||||||
#include <utility> // Para pair
|
#include <utility> // Para pair, move
|
||||||
|
|
||||||
// [SINGLETON]
|
// Singleton
|
||||||
Input* Input::input = nullptr;
|
Input* Input::instance = nullptr;
|
||||||
|
|
||||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
// Inicializa la instancia única del singleton
|
||||||
void Input::init(const std::string& game_controller_db_path) {
|
void Input::init(const std::string& game_controller_db_path, const std::string& gamepad_configs_file) {
|
||||||
Input::input = new Input(game_controller_db_path);
|
Input::instance = new Input(game_controller_db_path, gamepad_configs_file);
|
||||||
}
|
}
|
||||||
|
|
||||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
// Libera la instancia
|
||||||
void Input::destroy() {
|
void Input::destroy() { delete Input::instance; }
|
||||||
delete Input::input;
|
|
||||||
}
|
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
// Obtiene la instancia
|
||||||
auto Input::get() -> Input* {
|
auto Input::get() -> Input* { return Input::instance; }
|
||||||
return Input::input;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Input::Input(const std::string& game_controller_db_path)
|
Input::Input(std::string game_controller_db_path, std::string gamepad_configs_file)
|
||||||
: game_controller_db_path_(game_controller_db_path) {
|
: gamepad_mappings_file_(std::move(game_controller_db_path)),
|
||||||
// Busca si hay mandos conectados
|
gamepad_configs_file_(std::move(gamepad_configs_file)) {
|
||||||
discoverGameControllers();
|
// Inicializa el subsistema SDL_INIT_GAMEPAD
|
||||||
|
initSDLGamePad();
|
||||||
// Inicializa los vectores
|
|
||||||
key_bindings_.resize(static_cast<int>(InputAction::SIZE), KeyBindings());
|
|
||||||
controller_bindings_.resize(num_gamepads_, std::vector<ControllerBindings>(static_cast<int>(InputAction::SIZE), ControllerBindings()));
|
|
||||||
|
|
||||||
// Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
|
|
||||||
button_inputs_ = {InputAction::JUMP};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a teclas
|
// Asigna inputs a teclas
|
||||||
void Input::bindKey(InputAction input, SDL_Scancode code) {
|
void Input::bindKey(Action action, SDL_Scancode code) {
|
||||||
key_bindings_.at(static_cast<int>(input)).scancode = code;
|
keyboard_.bindings[action].scancode = code;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a botones del mando
|
// Asigna inputs a botones del mando
|
||||||
void Input::bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button) {
|
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, 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[action].button = button;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a botones del mando
|
// Asigna inputs a botones del mando
|
||||||
void Input::bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source) {
|
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_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[action_target].button = gamepad->bindings[action_source].button;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si un input esta activo
|
// Comprueba si alguna acción está activa
|
||||||
auto Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) -> bool {
|
auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const 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);
|
|
||||||
|
|
||||||
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
|
if (check_keyboard) {
|
||||||
const auto* key_states = SDL_GetKeyboardState(nullptr);
|
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
||||||
|
success_keyboard = keyboard_.bindings[action].is_held;
|
||||||
if (repeat) {
|
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
||||||
success_keyboard = static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0;
|
success_keyboard = keyboard_.bindings[action].just_pressed;
|
||||||
} else {
|
|
||||||
if (!key_bindings_[INPUT_INDEX].active) {
|
|
||||||
if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0) {
|
|
||||||
key_bindings_[INPUT_INDEX].active = true;
|
|
||||||
success_keyboard = true;
|
|
||||||
} else {
|
|
||||||
success_keyboard = false;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) == 0) {
|
|
||||||
key_bindings_[INPUT_INDEX].active = false;
|
|
||||||
}
|
|
||||||
success_keyboard = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) {
|
if (gamepad != nullptr) {
|
||||||
if ((device == InputDeviceToUse::CONTROLLER) || (device == InputDeviceToUse::ANY)) {
|
success_controller = checkAxisInput(action, gamepad, repeat);
|
||||||
success_controller = checkAxisInput(input, controller_index, repeat);
|
|
||||||
|
|
||||||
if (!success_controller) {
|
if (!success_controller) {
|
||||||
if (repeat) {
|
success_controller = checkTriggerInput(action, gamepad, repeat);
|
||||||
success_controller = static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0;
|
}
|
||||||
} else {
|
|
||||||
if (!controller_bindings_.at(controller_index).at(INPUT_INDEX).active) {
|
if (!success_controller) {
|
||||||
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0) {
|
if (repeat) { // El usuario quiere saber si está pulsada (estado mantenido)
|
||||||
controller_bindings_.at(controller_index).at(INPUT_INDEX).active = true;
|
success_controller = gamepad->bindings[action].is_held;
|
||||||
success_controller = true;
|
} else { // El usuario quiere saber si ACABA de ser pulsada (evento de un solo fotograma)
|
||||||
} else {
|
success_controller = gamepad->bindings[action].just_pressed;
|
||||||
success_controller = false;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) == 0) {
|
|
||||||
controller_bindings_.at(controller_index).at(INPUT_INDEX).active = false;
|
|
||||||
}
|
|
||||||
success_controller = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,26 +81,50 @@ auto Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device,
|
|||||||
return (success_keyboard || success_controller);
|
return (success_keyboard || success_controller);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si hay almenos un input activo
|
// Comprueba si hay almenos una acción activa
|
||||||
auto Input::checkAnyInput(InputDeviceToUse device, int controller_index) -> bool {
|
auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
|
||||||
if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
|
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
|
||||||
const bool* key_states = SDL_GetKeyboardState(nullptr);
|
|
||||||
|
|
||||||
for (auto& key_binding : key_bindings_) {
|
// --- Comprobación del Teclado ---
|
||||||
if (static_cast<int>(key_states[key_binding.scancode]) != 0 && !key_binding.active) {
|
if (check_keyboard) {
|
||||||
key_binding.active = true;
|
for (const auto& pair : keyboard_.bindings) {
|
||||||
return true;
|
// Simplemente leemos el estado pre-calculado por Input::update().
|
||||||
|
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
|
||||||
|
if (pair.second.just_pressed) {
|
||||||
|
return true; // Se encontró una acción recién pulsada.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (gameControllerFound()) {
|
// --- Comprobación del Mando ---
|
||||||
if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY) {
|
// Comprobamos si hay mandos y si el índice solicitado es válido.
|
||||||
for (int i = 0; i < (int)controller_bindings_.size(); ++i) {
|
if (gamepad != nullptr) {
|
||||||
if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button)) != 0 && !controller_bindings_[controller_index][i].active) {
|
// Iteramos sobre todas las acciones, no sobre el número de mandos.
|
||||||
controller_bindings_[controller_index][i].active = true;
|
for (const auto& pair : gamepad->bindings) {
|
||||||
return true;
|
// Leemos el estado pre-calculado para el mando y la acción específicos.
|
||||||
}
|
if (pair.second.just_pressed) {
|
||||||
|
return true; // Se encontró una acción recién pulsada en el mando.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si llegamos hasta aquí, no se detectó ninguna nueva pulsación.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comprueba si hay algún botón pulsado
|
||||||
|
auto Input::checkAnyButton(bool repeat) -> bool {
|
||||||
|
// Solo comprueba los botones definidos previamente
|
||||||
|
for (auto bi : BUTTON_INPUTS) {
|
||||||
|
// Comprueba el teclado
|
||||||
|
if (checkAction(bi, repeat, CHECK_KEYBOARD)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comprueba los mandos
|
||||||
|
for (const auto& gamepad : gamepads_) {
|
||||||
|
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -143,131 +132,68 @@ auto Input::checkAnyInput(InputDeviceToUse device, int controller_index) -> bool
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Busca si hay mandos conectados
|
|
||||||
auto Input::discoverGameControllers() -> bool {
|
|
||||||
bool found = false;
|
|
||||||
|
|
||||||
// Asegúrate de que el subsistema de gamepads está inicializado
|
|
||||||
if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) {
|
|
||||||
SDL_InitSubSystem(SDL_INIT_GAMEPAD);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Carga el mapping de mandos desde archivo
|
|
||||||
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
|
|
||||||
std::cout << "Error, could not load " << game_controller_db_path_.c_str()
|
|
||||||
<< " file: " << SDL_GetError() << '\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
// En SDL3 ya no existe SDL_NumJoysticks()
|
|
||||||
// Ahora se obtiene un array dinámico de IDs
|
|
||||||
int num_joysticks = 0;
|
|
||||||
SDL_JoystickID* joystick_ids = SDL_GetJoysticks(&num_joysticks);
|
|
||||||
|
|
||||||
num_joysticks_ = num_joysticks;
|
|
||||||
num_gamepads_ = 0;
|
|
||||||
joysticks_.clear();
|
|
||||||
|
|
||||||
// Recorremos todos los joysticks detectados
|
|
||||||
for (int i = 0; i < num_joysticks_; ++i) {
|
|
||||||
SDL_Joystick* joy = SDL_OpenJoystick(joystick_ids[i]);
|
|
||||||
joysticks_.push_back(joy);
|
|
||||||
|
|
||||||
if (SDL_IsGamepad(joystick_ids[i])) {
|
|
||||||
num_gamepads_++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << '\n';
|
|
||||||
if (num_joysticks_ != num_gamepads_) {
|
|
||||||
std::cout << "Joysticks found: " << num_joysticks_ << '\n';
|
|
||||||
std::cout << "Gamepads found : " << num_gamepads_ << '\n';
|
|
||||||
} else {
|
|
||||||
std::cout << "Gamepads found: " << num_gamepads_ << '\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (num_gamepads_ > 0) {
|
|
||||||
found = true;
|
|
||||||
|
|
||||||
for (int i = 0; i < num_joysticks_; i++) {
|
|
||||||
if (SDL_IsGamepad(joystick_ids[i])) {
|
|
||||||
SDL_Gamepad* pad = SDL_OpenGamepad(joystick_ids[i]);
|
|
||||||
if ((pad != nullptr) && SDL_GamepadConnected(pad)) {
|
|
||||||
connected_controllers_.push_back(pad);
|
|
||||||
|
|
||||||
const char* name = SDL_GetGamepadName(pad);
|
|
||||||
std::cout << "#" << i << ": " << ((name != nullptr) ? name : "Unknown") << '\n';
|
|
||||||
controller_names_.emplace_back((name != nullptr) ? name : "Unknown");
|
|
||||||
} else {
|
|
||||||
std::cout << "SDL_GetError() = " << SDL_GetError() << '\n';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// En SDL3 ya no hace falta SDL_GameControllerEventState()
|
|
||||||
// Los eventos de gamepad están siempre habilitados
|
|
||||||
}
|
|
||||||
|
|
||||||
SDL_free(joystick_ids);
|
|
||||||
|
|
||||||
std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << '\n';
|
|
||||||
return found;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Comprueba si hay algun mando conectado
|
// 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(const std::shared_ptr<Gamepad>& gamepad) -> std::string {
|
||||||
|
return gamepad == nullptr ? std::string() : gamepad->name;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtiene la lista de nombres de mandos
|
||||||
|
auto Input::getControllerNames() const -> std::vector<std::string> {
|
||||||
|
std::vector<std::string> names;
|
||||||
|
for (const auto& gamepad : gamepads_) {
|
||||||
|
names.push_back(gamepad->name);
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
// Obten el número de mandos conectados
|
// Obten el número de mandos conectados
|
||||||
auto Input::getNumControllers() const -> int { return num_gamepads_; }
|
auto Input::getNumGamepads() const -> int { return gamepads_.size(); }
|
||||||
|
|
||||||
// Obtiene el indice del controlador a partir de un event.id
|
// Obtiene el gamepad a partir de un event.id
|
||||||
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
|
auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Input::Gamepad> {
|
||||||
for (int i = 0; i < num_joysticks_; ++i) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
if (SDL_GetJoystickID(joysticks_[i]) == id) {
|
if (gamepad->instance_id == id) {
|
||||||
return i;
|
return gamepad;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el SDL_GamepadButton asignado a un input
|
auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad> {
|
||||||
auto Input::getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton {
|
for (const auto& gamepad : gamepads_) {
|
||||||
return controller_bindings_[controller_index][static_cast<int>(input)].button;
|
if (gamepad && gamepad->name == name) {
|
||||||
|
return gamepad;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el indice a partir del nombre del mando
|
// Obtiene el SDL_GamepadButton asignado a un action
|
||||||
auto Input::getIndexByName(const std::string& name) const -> int {
|
auto Input::getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton {
|
||||||
auto it = std::ranges::find(controller_names_, name);
|
return static_cast<SDL_GamepadButton>(gamepad->bindings[action].button);
|
||||||
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
// Comprueba el eje del mando
|
||||||
auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool {
|
auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
|
||||||
// Umbral para considerar el eje como activo
|
// Umbral para considerar el eje como activo
|
||||||
const Sint16 THRESHOLD = 30000;
|
|
||||||
bool axis_active_now = false;
|
bool axis_active_now = false;
|
||||||
|
|
||||||
switch (input) {
|
switch (action) {
|
||||||
case InputAction::LEFT:
|
case Action::LEFT:
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -THRESHOLD;
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) < -AXIS_THRESHOLD;
|
||||||
break;
|
break;
|
||||||
case InputAction::RIGHT:
|
case Action::RIGHT:
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > THRESHOLD;
|
axis_active_now = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFTX) > AXIS_THRESHOLD;
|
||||||
break;
|
|
||||||
case InputAction::UP:
|
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -THRESHOLD;
|
|
||||||
break;
|
|
||||||
case InputAction::DOWN:
|
|
||||||
axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > THRESHOLD;
|
|
||||||
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[action];
|
||||||
|
|
||||||
if (repeat) {
|
if (repeat) {
|
||||||
// Si se permite repetir, simplemente devolvemos el estado actual
|
// Si se permite repetir, simplemente devolvemos el estado actual
|
||||||
@@ -284,4 +210,290 @@ auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
|
|||||||
}
|
}
|
||||||
// Mantener el estado actual
|
// Mantener el estado actual
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comprueba los triggers del mando como botones digitales
|
||||||
|
auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
|
||||||
|
// Solo manejamos botones específicos que pueden ser triggers
|
||||||
|
if (gamepad->bindings[action].button != static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)) {
|
||||||
|
// Solo procesamos L2 y R2 como triggers
|
||||||
|
int button = gamepad->bindings[action].button;
|
||||||
|
|
||||||
|
// Verificar si el botón mapeado corresponde a un trigger virtual
|
||||||
|
// (Para esto necesitamos valores especiales que representen L2/R2 como botones)
|
||||||
|
bool trigger_active_now = false;
|
||||||
|
|
||||||
|
// Usamos constantes especiales para L2 y R2 como botones
|
||||||
|
if (button == TRIGGER_L2_AS_BUTTON) { // L2 como botón
|
||||||
|
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_LEFT_TRIGGER);
|
||||||
|
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
|
||||||
|
} else if (button == TRIGGER_R2_AS_BUTTON) { // R2 como botón
|
||||||
|
Sint16 trigger_value = SDL_GetGamepadAxis(gamepad->pad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER);
|
||||||
|
trigger_active_now = trigger_value > TRIGGER_THRESHOLD;
|
||||||
|
} else {
|
||||||
|
return false; // No es un trigger
|
||||||
|
}
|
||||||
|
|
||||||
|
// Referencia al binding correspondiente
|
||||||
|
auto& binding = gamepad->bindings[action];
|
||||||
|
|
||||||
|
if (repeat) {
|
||||||
|
// Si se permite repetir, simplemente devolvemos el estado actual
|
||||||
|
return trigger_active_now;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si no se permite repetir, aplicamos la lógica de transición
|
||||||
|
if (trigger_active_now && !binding.trigger_active) {
|
||||||
|
// Transición de inactivo a activo
|
||||||
|
binding.trigger_active = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!trigger_active_now && binding.trigger_active) {
|
||||||
|
// Transición de activo a inactivo
|
||||||
|
binding.trigger_active = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mantener el estado actual
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::addGamepadMappingsFromFile() {
|
||||||
|
if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) {
|
||||||
|
std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << '\n';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::discoverGamepads() {
|
||||||
|
SDL_Event event;
|
||||||
|
while (SDL_PollEvent(&event)) {
|
||||||
|
handleEvent(event); // Comprueba mandos conectados
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::initSDLGamePad() {
|
||||||
|
if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) {
|
||||||
|
if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) {
|
||||||
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GAMEPAD could not initialize! SDL Error: %s", SDL_GetError());
|
||||||
|
} else {
|
||||||
|
addGamepadMappingsFromFile();
|
||||||
|
loadGamepadConfigs();
|
||||||
|
discoverGamepads();
|
||||||
|
std::cout << "Input System initialized successfully\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::resetInputStates() {
|
||||||
|
// Resetear todos los KeyBindings.active a false
|
||||||
|
for (auto& key : keyboard_.bindings) {
|
||||||
|
key.second.is_held = false;
|
||||||
|
key.second.just_pressed = false;
|
||||||
|
}
|
||||||
|
// Resetear todos los ControllerBindings.active a false
|
||||||
|
for (auto& gamepad : gamepads_) {
|
||||||
|
for (auto& binding : gamepad->bindings) {
|
||||||
|
binding.second.is_held = false;
|
||||||
|
binding.second.just_pressed = false;
|
||||||
|
binding.second.trigger_active = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::update() {
|
||||||
|
// --- TECLADO ---
|
||||||
|
const bool* key_states = SDL_GetKeyboardState(nullptr);
|
||||||
|
|
||||||
|
for (auto& binding : keyboard_.bindings) {
|
||||||
|
bool key_is_down_now = key_states[binding.second.scancode];
|
||||||
|
|
||||||
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
||||||
|
binding.second.just_pressed = key_is_down_now && !binding.second.is_held;
|
||||||
|
binding.second.is_held = key_is_down_now;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- MANDOS ---
|
||||||
|
for (const auto& gamepad : gamepads_) {
|
||||||
|
for (auto& binding : gamepad->bindings) {
|
||||||
|
bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(gamepad->pad, static_cast<SDL_GamepadButton>(binding.second.button))) != 0;
|
||||||
|
|
||||||
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
||||||
|
binding.second.just_pressed = button_is_down_now && !binding.second.is_held;
|
||||||
|
binding.second.is_held = button_is_down_now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
auto Input::handleEvent(const SDL_Event& event) -> std::string {
|
||||||
|
switch (event.type) {
|
||||||
|
case SDL_EVENT_GAMEPAD_ADDED:
|
||||||
|
return addGamepad(event.gdevice.which);
|
||||||
|
case SDL_EVENT_GAMEPAD_REMOVED:
|
||||||
|
return removeGamepad(event.gdevice.which);
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto Input::addGamepad(int device_index) -> std::string {
|
||||||
|
SDL_Gamepad* pad = SDL_OpenGamepad(device_index);
|
||||||
|
if (pad == nullptr) {
|
||||||
|
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n';
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
auto gamepad = std::make_shared<Gamepad>(pad);
|
||||||
|
auto name = gamepad->name;
|
||||||
|
std::cout << "Gamepad connected (" << name << ")" << '\n';
|
||||||
|
applyGamepadConfig(gamepad);
|
||||||
|
saveGamepadConfigFromGamepad(gamepad);
|
||||||
|
gamepads_.push_back(std::move(gamepad));
|
||||||
|
return name + " CONNECTED";
|
||||||
|
}
|
||||||
|
|
||||||
|
auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
|
||||||
|
auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad>& gamepad) {
|
||||||
|
return gamepad->instance_id == id;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (it != gamepads_.end()) {
|
||||||
|
std::string name = (*it)->name;
|
||||||
|
std::cout << "Gamepad disconnected (" << name << ")" << '\n';
|
||||||
|
gamepads_.erase(it);
|
||||||
|
return name + " DISCONNECTED";
|
||||||
|
}
|
||||||
|
std::cerr << "No se encontró el gamepad con ID " << id << '\n';
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::printConnectedGamepads() const {
|
||||||
|
if (gamepads_.empty()) {
|
||||||
|
std::cout << "No hay gamepads conectados." << '\n';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::cout << "Gamepads conectados:\n";
|
||||||
|
for (const auto& gamepad : gamepads_) {
|
||||||
|
std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name;
|
||||||
|
std::cout << " - ID: " << gamepad->instance_id
|
||||||
|
<< ", Nombre: " << name << ")" << '\n';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::loadGamepadConfigs() {
|
||||||
|
if (GamepadConfigManager::fileExists(gamepad_configs_file_)) {
|
||||||
|
GamepadConfigManager::readFromJson(gamepad_configs_, gamepad_configs_file_);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::saveGamepadConfigs() {
|
||||||
|
GamepadConfigManager::writeToJson(gamepad_configs_, gamepad_configs_file_);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::applyGamepadConfig(std::shared_ptr<Gamepad> gamepad) {
|
||||||
|
if (!gamepad || gamepad->path.empty()) { // No podemos aplicar config sin una ruta
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Buscar configuración por RUTA (path) ---
|
||||||
|
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) {
|
||||||
|
return config.path == gamepad->path;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (config_it != gamepad_configs_.end()) {
|
||||||
|
// Se encontró una configuración específica para este puerto/dispositivo. La aplicamos.
|
||||||
|
std::cout << "Applying custom config for gamepad at path: " << gamepad->path << '\n';
|
||||||
|
for (const auto& [action, button] : config_it->bindings) {
|
||||||
|
if (gamepad->bindings.find(action) != gamepad->bindings.end()) {
|
||||||
|
gamepad->bindings[action].button = button;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Opcional: Podrías añadir un fallback para buscar por nombre si no se encuentra por ruta.
|
||||||
|
}
|
||||||
|
|
||||||
|
void Input::saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad) {
|
||||||
|
if (!gamepad || gamepad->path.empty()) { // No podemos guardar una config sin una ruta
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- CAMBIO CLAVE: Buscar si ya existe una configuración por RUTA (path) ---
|
||||||
|
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) {
|
||||||
|
return config.path == gamepad->path;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Crear nueva configuración desde el gamepad, incluyendo nombre y ruta
|
||||||
|
GamepadConfig new_config(gamepad->name, gamepad->path); // <--- CAMBIO: Pasamos ambos
|
||||||
|
new_config.bindings.clear();
|
||||||
|
|
||||||
|
// Copiar todos los bindings actuales del gamepad
|
||||||
|
for (const auto& [action, buttonState] : gamepad->bindings) {
|
||||||
|
new_config.bindings[action] = static_cast<SDL_GamepadButton>(buttonState.button);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config_it != gamepad_configs_.end()) {
|
||||||
|
// Sobreescribir configuración existente para esta ruta
|
||||||
|
*config_it = new_config;
|
||||||
|
} else {
|
||||||
|
// Añadir nueva configuración
|
||||||
|
gamepad_configs_.push_back(new_config);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Guardar cambios inmediatamente
|
||||||
|
saveGamepadConfigs();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Método para establecer el archivo de configuración (opcional)
|
||||||
|
void Input::setGamepadConfigsFile(const std::string& filename) {
|
||||||
|
gamepad_configs_file_ = filename;
|
||||||
|
loadGamepadConfigs(); // Recargar con el nuevo archivo
|
||||||
|
}
|
||||||
|
|
||||||
|
// Método para obtener configuración de un gamepad específico (opcional)
|
||||||
|
auto Input::getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig* {
|
||||||
|
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) {
|
||||||
|
return config.name == gamepad_name;
|
||||||
|
});
|
||||||
|
|
||||||
|
return (config_it != gamepad_configs_.end()) ? &(*config_it) : nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Método para eliminar configuración de gamepad (opcional)
|
||||||
|
auto Input::removeGamepadConfig(const std::string& gamepad_name) -> bool {
|
||||||
|
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) {
|
||||||
|
return config.name == gamepad_name;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (config_it != gamepad_configs_.end()) {
|
||||||
|
gamepad_configs_.erase(config_it);
|
||||||
|
saveGamepadConfigs();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto Input::findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Input::Gamepad> {
|
||||||
|
// Si no hay gamepads disponibles, devolver gamepad por defecto
|
||||||
|
if (gamepads_.empty()) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Buscar por nombre
|
||||||
|
for (const auto& gamepad : gamepads_) {
|
||||||
|
if (gamepad && gamepad->name == gamepad_name) {
|
||||||
|
return gamepad;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si no se encuentra por nombre, devolver el primer gamepad válido
|
||||||
|
for (const auto& gamepad : gamepads_) {
|
||||||
|
if (gamepad) {
|
||||||
|
return gamepad;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si llegamos aquí, no hay gamepads válidos
|
||||||
|
return nullptr;
|
||||||
}
|
}
|
||||||
@@ -1,138 +1,194 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h> // Para SDL_Scancode, SDL_GamepadButton, SDL_JoystickID, SDL_CloseGamepad, SDL_Gamepad, SDL_GetGamepadJoystick, SDL_GetGamepadName, SDL_GetGamepadPath, SDL_GetJoystickID, Sint16, Uint8, SDL_Event
|
||||||
|
|
||||||
#include <string> // Para string, basic_string
|
#include <array> // Para array
|
||||||
#include <vector> // Para vector
|
#include <memory> // Para shared_ptr
|
||||||
|
#include <string> // Para string, basic_string
|
||||||
|
#include <unordered_map> // Para unordered_map
|
||||||
|
#include <utility> // Para pair
|
||||||
|
#include <vector> // Para vector
|
||||||
|
|
||||||
// Definiciones de repetición
|
#include "core/input/gamepad_config_manager.hpp" // for GamepadConfig (ptr only), GamepadConfigs
|
||||||
constexpr bool INPUT_ALLOW_REPEAT = true;
|
#include "core/input/input_types.hpp" // for InputAction
|
||||||
constexpr bool INPUT_DO_NOT_ALLOW_REPEAT = false;
|
|
||||||
|
|
||||||
// Tipos de entrada
|
|
||||||
enum class InputDeviceToUse : int {
|
|
||||||
KEYBOARD = 0,
|
|
||||||
CONTROLLER = 1,
|
|
||||||
ANY = 2,
|
|
||||||
};
|
|
||||||
|
|
||||||
enum class InputAction {
|
|
||||||
// Inputs obligatorios
|
|
||||||
UP,
|
|
||||||
DOWN,
|
|
||||||
LEFT,
|
|
||||||
RIGHT,
|
|
||||||
PAUSE,
|
|
||||||
EXIT,
|
|
||||||
ACCEPT,
|
|
||||||
CANCEL,
|
|
||||||
|
|
||||||
// Inputs personalizados
|
|
||||||
JUMP,
|
|
||||||
WINDOW_INC_ZOOM,
|
|
||||||
WINDOW_DEC_ZOOM,
|
|
||||||
TOGGLE_VIDEOMODE,
|
|
||||||
TOGGLE_INTEGER_SCALE,
|
|
||||||
TOGGLE_BORDER,
|
|
||||||
TOGGLE_MUSIC,
|
|
||||||
NEXT_PALETTE,
|
|
||||||
PREVIOUS_PALETTE,
|
|
||||||
TOGGLE_SHADERS,
|
|
||||||
SHOW_DEBUG_INFO,
|
|
||||||
|
|
||||||
// Input obligatorio
|
|
||||||
NONE,
|
|
||||||
SIZE
|
|
||||||
};
|
|
||||||
|
|
||||||
|
// --- Clase Input: gestiona la entrada de teclado y mandos (singleton) ---
|
||||||
class Input {
|
class Input {
|
||||||
private:
|
public:
|
||||||
// [SINGLETON] Objeto privado
|
// --- Constantes ---
|
||||||
static Input* input;
|
static constexpr bool ALLOW_REPEAT = true; // Permite repetición
|
||||||
|
static constexpr bool DO_NOT_ALLOW_REPEAT = false; // No permite repetición
|
||||||
|
static constexpr bool CHECK_KEYBOARD = true; // Comprueba teclado
|
||||||
|
static constexpr bool DO_NOT_CHECK_KEYBOARD = false; // No comprueba teclado
|
||||||
|
static constexpr int TRIGGER_L2_AS_BUTTON = 100; // L2 como botón
|
||||||
|
static constexpr int TRIGGER_R2_AS_BUTTON = 101; // R2 como botón
|
||||||
|
|
||||||
struct KeyBindings {
|
// --- Tipos ---
|
||||||
Uint8 scancode; // Scancode asociado
|
using Action = InputAction; // Alias para mantener compatibilidad
|
||||||
bool active; // Indica si está activo
|
|
||||||
|
|
||||||
// Constructor
|
// --- Estructuras ---
|
||||||
explicit KeyBindings(Uint8 sc = 0, bool act = false)
|
struct KeyState {
|
||||||
: scancode(sc),
|
Uint8 scancode; // Scancode asociado
|
||||||
active(act) {}
|
bool is_held; // Está pulsada ahora mismo
|
||||||
|
bool just_pressed; // Se acaba de pulsar en este fotograma
|
||||||
|
|
||||||
|
KeyState(Uint8 scancode = 0, bool is_held = false, bool just_pressed = false)
|
||||||
|
: scancode(scancode),
|
||||||
|
is_held(is_held),
|
||||||
|
just_pressed(just_pressed) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ControllerBindings {
|
struct ButtonState {
|
||||||
SDL_GamepadButton button; // GameControllerButton asociado
|
int button; // GameControllerButton asociado
|
||||||
bool active; // Indica si está activo
|
bool is_held; // Está pulsada ahora mismo
|
||||||
bool axis_active; // Estado del eje
|
bool just_pressed; // Se acaba de pulsar en este fotograma
|
||||||
|
bool axis_active; // Estado del eje
|
||||||
|
bool trigger_active{false}; // Estado del trigger como botón digital
|
||||||
|
|
||||||
// Constructor
|
ButtonState(int btn = static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID), bool is_held = false, bool just_pressed = false, bool axis_act = false)
|
||||||
explicit ControllerBindings(SDL_GamepadButton btn = SDL_GAMEPAD_BUTTON_INVALID, bool act = false, bool axis_act = false)
|
|
||||||
: button(btn),
|
: button(btn),
|
||||||
active(act),
|
is_held(is_held),
|
||||||
|
just_pressed(just_pressed),
|
||||||
axis_active(axis_act) {}
|
axis_active(axis_act) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Variables
|
struct Keyboard {
|
||||||
std::vector<SDL_Gamepad*> connected_controllers_; // Vector con todos los mandos conectados
|
std::unordered_map<Action, KeyState> bindings;
|
||||||
std::vector<SDL_Joystick*> joysticks_; // Vector con todos los joysticks conectados
|
|
||||||
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
|
|
||||||
std::vector<std::vector<ControllerBindings>> controller_bindings_; // Vector con los botones asociadas a los inputs predefinidos para cada mando
|
|
||||||
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
|
|
||||||
std::vector<InputAction> button_inputs_; // Inputs asignados al jugador y a botones, excluyendo direcciones
|
|
||||||
int num_joysticks_ = 0; // Número de joysticks conectados
|
|
||||||
int num_gamepads_ = 0; // Número de mandos conectados
|
|
||||||
std::string game_controller_db_path_; // Ruta al archivo gamecontrollerdb.txt
|
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
Keyboard()
|
||||||
auto checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool;
|
: bindings{
|
||||||
|
// Movimiento del jugador
|
||||||
|
{Action::LEFT, KeyState(SDL_SCANCODE_LEFT)},
|
||||||
|
{Action::RIGHT, KeyState(SDL_SCANCODE_RIGHT)},
|
||||||
|
{Action::JUMP, KeyState(SDL_SCANCODE_UP)},
|
||||||
|
|
||||||
// Constructor
|
// Inputs de control
|
||||||
explicit Input(const std::string& game_controller_db_path);
|
{Action::ACCEPT, KeyState(SDL_SCANCODE_RETURN)},
|
||||||
|
{Action::CANCEL, KeyState(SDL_SCANCODE_ESCAPE)},
|
||||||
|
{Action::PAUSE, KeyState(SDL_SCANCODE_H)},
|
||||||
|
{Action::EXIT, KeyState(SDL_SCANCODE_ESCAPE)},
|
||||||
|
|
||||||
// Destructor
|
// Inputs de sistema
|
||||||
~Input() = default;
|
{Action::WINDOW_DEC_ZOOM, KeyState(SDL_SCANCODE_F1)},
|
||||||
|
{Action::WINDOW_INC_ZOOM, KeyState(SDL_SCANCODE_F2)},
|
||||||
|
{Action::TOGGLE_VIDEOMODE, KeyState(SDL_SCANCODE_F3)},
|
||||||
|
{Action::TOGGLE_SHADERS, KeyState(SDL_SCANCODE_F4)},
|
||||||
|
{Action::NEXT_PALETTE, KeyState(SDL_SCANCODE_F5)},
|
||||||
|
{Action::PREVIOUS_PALETTE, KeyState(SDL_SCANCODE_F6)},
|
||||||
|
{Action::TOGGLE_INTEGER_SCALE, KeyState(SDL_SCANCODE_F7)},
|
||||||
|
{Action::SHOW_DEBUG_INFO, KeyState(SDL_SCANCODE_F12)},
|
||||||
|
{Action::TOGGLE_MUSIC, KeyState(SDL_SCANCODE_M)},
|
||||||
|
{Action::TOGGLE_BORDER, KeyState(SDL_SCANCODE_B)}} {}
|
||||||
|
};
|
||||||
|
|
||||||
public:
|
struct Gamepad {
|
||||||
// [SINGLETON] Crearemos el objeto con esta función estática
|
SDL_Gamepad* pad;
|
||||||
static void init(const std::string& game_controller_db_path);
|
SDL_JoystickID instance_id;
|
||||||
|
std::string name;
|
||||||
|
std::string path;
|
||||||
|
std::unordered_map<Action, ButtonState> bindings;
|
||||||
|
|
||||||
// [SINGLETON] Destruiremos el objeto con esta función estática
|
Gamepad(SDL_Gamepad* gamepad)
|
||||||
|
: pad(gamepad),
|
||||||
|
instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))),
|
||||||
|
name(std::string(SDL_GetGamepadName(gamepad))),
|
||||||
|
path(std::string(SDL_GetGamepadPath(pad))),
|
||||||
|
bindings{
|
||||||
|
// Movimiento del jugador
|
||||||
|
{Action::LEFT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_LEFT))},
|
||||||
|
{Action::RIGHT, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_DPAD_RIGHT))},
|
||||||
|
{Action::JUMP, ButtonState(static_cast<int>(SDL_GAMEPAD_BUTTON_WEST))}} {}
|
||||||
|
|
||||||
|
~Gamepad() {
|
||||||
|
if (pad != nullptr) {
|
||||||
|
SDL_CloseGamepad(pad);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reasigna un botón a una acción
|
||||||
|
void rebindAction(Action action, SDL_GamepadButton new_button) {
|
||||||
|
bindings[action] = static_cast<int>(new_button);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Tipos ---
|
||||||
|
using Gamepads = std::vector<std::shared_ptr<Gamepad>>; // Vector de gamepads
|
||||||
|
|
||||||
|
// --- Métodos de singleton ---
|
||||||
|
static void init(const std::string& game_controller_db_path, const std::string& gamepad_configs_file);
|
||||||
static void destroy();
|
static void destroy();
|
||||||
|
|
||||||
// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
|
|
||||||
static auto get() -> Input*;
|
static auto get() -> Input*;
|
||||||
|
|
||||||
// Asigna inputs a teclas
|
// --- Métodos de configuración de controles ---
|
||||||
void bindKey(InputAction input, SDL_Scancode code);
|
void bindKey(Action action, SDL_Scancode code);
|
||||||
|
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button);
|
||||||
|
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source);
|
||||||
|
|
||||||
// Asigna inputs a botones del mando
|
// --- Métodos de consulta de entrada ---
|
||||||
void bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button);
|
void update();
|
||||||
void bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source);
|
auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
|
||||||
|
auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
|
||||||
|
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool;
|
||||||
|
|
||||||
// Comprueba si un input esta activo
|
// --- Métodos de gestión de mandos ---
|
||||||
auto checkInput(InputAction input, bool repeat = true, InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0) -> bool;
|
|
||||||
|
|
||||||
// Comprueba si hay almenos un input activo
|
|
||||||
auto checkAnyInput(InputDeviceToUse device = InputDeviceToUse::ANY, int controller_index = 0) -> bool;
|
|
||||||
|
|
||||||
// Busca si hay mandos conectados
|
|
||||||
auto discoverGameControllers() -> bool;
|
|
||||||
|
|
||||||
// Comprueba si hay algun mando conectado
|
|
||||||
[[nodiscard]] auto gameControllerFound() const -> bool;
|
[[nodiscard]] auto gameControllerFound() const -> bool;
|
||||||
|
static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string;
|
||||||
|
auto getControllerNames() const -> std::vector<std::string>;
|
||||||
|
[[nodiscard]] auto getNumGamepads() const -> int;
|
||||||
|
auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
|
||||||
|
auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>;
|
||||||
|
auto getGamepads() const -> const Gamepads& { return gamepads_; }
|
||||||
|
|
||||||
// Obten el número de mandos conectados
|
// --- Métodos de consulta y utilidades ---
|
||||||
[[nodiscard]] auto getNumControllers() const -> int;
|
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;
|
||||||
|
|
||||||
// Obten el nombre de un mando de juego
|
// --- Métodos de reseteo de estado de entrada ---
|
||||||
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string;
|
void resetInputStates();
|
||||||
|
|
||||||
// Obtiene el indice del controlador a partir de un event.id
|
// --- Eventos ---
|
||||||
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int;
|
auto handleEvent(const SDL_Event& event) -> std::string;
|
||||||
|
|
||||||
// Obtiene el SDL_GamepadButton asignado a un input
|
void printConnectedGamepads() const;
|
||||||
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton;
|
|
||||||
|
|
||||||
// Obtiene el indice a partir del nombre del mando
|
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
|
||||||
[[nodiscard]] auto getIndexByName(const std::string& name) const -> int;
|
void saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad);
|
||||||
|
|
||||||
|
private:
|
||||||
|
// --- Constantes ---
|
||||||
|
static constexpr Sint16 AXIS_THRESHOLD = 30000;
|
||||||
|
static constexpr Sint16 TRIGGER_THRESHOLD = 16384; // Umbral para triggers (aproximadamente 50% del rango)
|
||||||
|
static constexpr std::array<Action, 1> BUTTON_INPUTS = {Action::JUMP}; // Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
|
||||||
|
|
||||||
|
// --- Variables internas ---
|
||||||
|
Gamepads gamepads_;
|
||||||
|
Keyboard keyboard_;
|
||||||
|
std::string gamepad_mappings_file_;
|
||||||
|
std::string gamepad_configs_file_;
|
||||||
|
GamepadConfigs gamepad_configs_;
|
||||||
|
|
||||||
|
// --- Métodos internos ---
|
||||||
|
void initSDLGamePad();
|
||||||
|
static auto checkAxisInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
|
||||||
|
static auto checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
|
||||||
|
auto addGamepad(int device_index) -> std::string;
|
||||||
|
auto removeGamepad(SDL_JoystickID id) -> std::string;
|
||||||
|
void addGamepadMappingsFromFile();
|
||||||
|
void discoverGamepads();
|
||||||
|
|
||||||
|
// --- Métodos para integración con GamepadConfigManager ---
|
||||||
|
void loadGamepadConfigs();
|
||||||
|
void saveGamepadConfigs();
|
||||||
|
void applyGamepadConfig(std::shared_ptr<Gamepad> gamepad);
|
||||||
|
|
||||||
|
// Métodos auxiliares opcionales
|
||||||
|
void setGamepadConfigsFile(const std::string& filename);
|
||||||
|
auto getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig*;
|
||||||
|
auto removeGamepadConfig(const std::string& gamepad_name) -> bool;
|
||||||
|
|
||||||
|
// --- Constructor y destructor ---
|
||||||
|
explicit Input(std::string game_controller_db_path, std::string gamepad_configs_file);
|
||||||
|
~Input() = default;
|
||||||
|
|
||||||
|
// --- Singleton ---
|
||||||
|
static Input* instance;
|
||||||
};
|
};
|
||||||
76
source/core/input/input_types.cpp
Normal file
76
source/core/input/input_types.cpp
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
#include "input_types.hpp"
|
||||||
|
|
||||||
|
#include <utility> // Para pair
|
||||||
|
|
||||||
|
// Definición de los mapas
|
||||||
|
const std::unordered_map<InputAction, std::string> ACTION_TO_STRING = {
|
||||||
|
{InputAction::LEFT, "LEFT"},
|
||||||
|
{InputAction::RIGHT, "RIGHT"},
|
||||||
|
{InputAction::JUMP, "JUMP"},
|
||||||
|
{InputAction::PAUSE, "PAUSE"},
|
||||||
|
{InputAction::EXIT, "EXIT"},
|
||||||
|
{InputAction::ACCEPT, "ACCEPT"},
|
||||||
|
{InputAction::CANCEL, "CANCEL"},
|
||||||
|
{InputAction::WINDOW_INC_ZOOM, "WINDOW_INC_ZOOM"},
|
||||||
|
{InputAction::WINDOW_DEC_ZOOM, "WINDOW_DEC_ZOOM"},
|
||||||
|
{InputAction::TOGGLE_VIDEOMODE, "TOGGLE_VIDEOMODE"},
|
||||||
|
{InputAction::TOGGLE_INTEGER_SCALE, "TOGGLE_INTEGER_SCALE"},
|
||||||
|
{InputAction::TOGGLE_BORDER, "TOGGLE_BORDER"},
|
||||||
|
{InputAction::TOGGLE_MUSIC, "TOGGLE_MUSIC"},
|
||||||
|
{InputAction::NEXT_PALETTE, "NEXT_PALETTE"},
|
||||||
|
{InputAction::PREVIOUS_PALETTE, "PREVIOUS_PALETTE"},
|
||||||
|
{InputAction::TOGGLE_SHADERS, "TOGGLE_SHADERS"},
|
||||||
|
{InputAction::SHOW_DEBUG_INFO, "SHOW_DEBUG_INFO"},
|
||||||
|
{InputAction::NONE, "NONE"}};
|
||||||
|
|
||||||
|
const std::unordered_map<std::string, InputAction> STRING_TO_ACTION = {
|
||||||
|
{"LEFT", InputAction::LEFT},
|
||||||
|
{"RIGHT", InputAction::RIGHT},
|
||||||
|
{"JUMP", InputAction::JUMP},
|
||||||
|
{"PAUSE", InputAction::PAUSE},
|
||||||
|
{"EXIT", InputAction::EXIT},
|
||||||
|
{"ACCEPT", InputAction::ACCEPT},
|
||||||
|
{"CANCEL", InputAction::CANCEL},
|
||||||
|
{"WINDOW_INC_ZOOM", InputAction::WINDOW_INC_ZOOM},
|
||||||
|
{"WINDOW_DEC_ZOOM", InputAction::WINDOW_DEC_ZOOM},
|
||||||
|
{"TOGGLE_VIDEOMODE", InputAction::TOGGLE_VIDEOMODE},
|
||||||
|
{"TOGGLE_INTEGER_SCALE", InputAction::TOGGLE_INTEGER_SCALE},
|
||||||
|
{"TOGGLE_BORDER", InputAction::TOGGLE_BORDER},
|
||||||
|
{"TOGGLE_MUSIC", InputAction::TOGGLE_MUSIC},
|
||||||
|
{"NEXT_PALETTE", InputAction::NEXT_PALETTE},
|
||||||
|
{"PREVIOUS_PALETTE", InputAction::PREVIOUS_PALETTE},
|
||||||
|
{"TOGGLE_SHADERS", InputAction::TOGGLE_SHADERS},
|
||||||
|
{"SHOW_DEBUG_INFO", InputAction::SHOW_DEBUG_INFO},
|
||||||
|
{"NONE", InputAction::NONE}};
|
||||||
|
|
||||||
|
const std::unordered_map<SDL_GamepadButton, std::string> BUTTON_TO_STRING = {
|
||||||
|
{SDL_GAMEPAD_BUTTON_WEST, "WEST"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_NORTH, "NORTH"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_EAST, "EAST"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_SOUTH, "SOUTH"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_START, "START"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_BACK, "BACK"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, "LEFT_SHOULDER"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, "RIGHT_SHOULDER"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_DPAD_UP, "DPAD_UP"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_DPAD_DOWN, "DPAD_DOWN"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_DPAD_LEFT, "DPAD_LEFT"},
|
||||||
|
{SDL_GAMEPAD_BUTTON_DPAD_RIGHT, "DPAD_RIGHT"},
|
||||||
|
{static_cast<SDL_GamepadButton>(100), "L2_AS_BUTTON"},
|
||||||
|
{static_cast<SDL_GamepadButton>(101), "R2_AS_BUTTON"}};
|
||||||
|
|
||||||
|
const std::unordered_map<std::string, SDL_GamepadButton> STRING_TO_BUTTON = {
|
||||||
|
{"WEST", SDL_GAMEPAD_BUTTON_WEST},
|
||||||
|
{"NORTH", SDL_GAMEPAD_BUTTON_NORTH},
|
||||||
|
{"EAST", SDL_GAMEPAD_BUTTON_EAST},
|
||||||
|
{"SOUTH", SDL_GAMEPAD_BUTTON_SOUTH},
|
||||||
|
{"START", SDL_GAMEPAD_BUTTON_START},
|
||||||
|
{"BACK", SDL_GAMEPAD_BUTTON_BACK},
|
||||||
|
{"LEFT_SHOULDER", SDL_GAMEPAD_BUTTON_LEFT_SHOULDER},
|
||||||
|
{"RIGHT_SHOULDER", SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER},
|
||||||
|
{"DPAD_UP", SDL_GAMEPAD_BUTTON_DPAD_UP},
|
||||||
|
{"DPAD_DOWN", SDL_GAMEPAD_BUTTON_DPAD_DOWN},
|
||||||
|
{"DPAD_LEFT", SDL_GAMEPAD_BUTTON_DPAD_LEFT},
|
||||||
|
{"DPAD_RIGHT", SDL_GAMEPAD_BUTTON_DPAD_RIGHT},
|
||||||
|
{"L2_AS_BUTTON", static_cast<SDL_GamepadButton>(100)},
|
||||||
|
{"R2_AS_BUTTON", static_cast<SDL_GamepadButton>(101)}};
|
||||||
42
source/core/input/input_types.hpp
Normal file
42
source/core/input/input_types.hpp
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
|
// --- Enums ---
|
||||||
|
enum class InputAction : int { // Acciones de entrada posibles en el juego
|
||||||
|
// Inputs de movimiento
|
||||||
|
LEFT,
|
||||||
|
RIGHT,
|
||||||
|
JUMP,
|
||||||
|
|
||||||
|
// Inputs de control
|
||||||
|
PAUSE,
|
||||||
|
EXIT,
|
||||||
|
ACCEPT,
|
||||||
|
CANCEL,
|
||||||
|
|
||||||
|
// Inputs de sistema
|
||||||
|
WINDOW_INC_ZOOM,
|
||||||
|
WINDOW_DEC_ZOOM,
|
||||||
|
TOGGLE_VIDEOMODE,
|
||||||
|
TOGGLE_INTEGER_SCALE,
|
||||||
|
TOGGLE_BORDER,
|
||||||
|
TOGGLE_MUSIC,
|
||||||
|
NEXT_PALETTE,
|
||||||
|
PREVIOUS_PALETTE,
|
||||||
|
TOGGLE_SHADERS,
|
||||||
|
SHOW_DEBUG_INFO,
|
||||||
|
|
||||||
|
// Input obligatorio
|
||||||
|
NONE,
|
||||||
|
SIZE,
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Variables ---
|
||||||
|
extern const std::unordered_map<InputAction, std::string> ACTION_TO_STRING; // Mapeo de acción a string
|
||||||
|
extern const std::unordered_map<std::string, InputAction> STRING_TO_ACTION; // Mapeo de string a acción
|
||||||
|
extern const std::unordered_map<SDL_GamepadButton, std::string> BUTTON_TO_STRING; // Mapeo de botón a string
|
||||||
|
extern const std::unordered_map<std::string, SDL_GamepadButton> STRING_TO_BUTTON; // Mapeo de string a botón
|
||||||
@@ -55,8 +55,7 @@ inline auto findFirstByte(const std::vector<DictionaryEntry>& dictionary, int co
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Agrega una nueva entrada al diccionario
|
// Agrega una nueva entrada al diccionario
|
||||||
inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& dictionary_ind,
|
inline void addDictionaryEntry(std::vector<DictionaryEntry>& dictionary, int& dictionary_ind, int& code_length, int prev, int code) {
|
||||||
int& code_length, int prev, int code) {
|
|
||||||
uint8_t first_byte;
|
uint8_t first_byte;
|
||||||
if (code == dictionary_ind) {
|
if (code == dictionary_ind) {
|
||||||
first_byte = findFirstByte(dictionary, prev);
|
first_byte = findFirstByte(dictionary, prev);
|
||||||
|
|||||||
@@ -209,13 +209,6 @@ void Screen::toggleShaders() {
|
|||||||
initShaders();
|
initShaders();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la lógica de la clase (versión antigua para escenas no migradas)
|
|
||||||
void Screen::update() {
|
|
||||||
fps_.calculate(SDL_GetTicks());
|
|
||||||
Notifier::get()->update(0.016f); // Asume ~60 FPS (16ms por frame)
|
|
||||||
Mouse::updateCursorVisibility();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Actualiza la lógica de la clase (versión nueva con delta_time para escenas migradas)
|
// Actualiza la lógica de la clase (versión nueva con delta_time para escenas migradas)
|
||||||
void Screen::update(float delta_time) {
|
void Screen::update(float delta_time) {
|
||||||
fps_.calculate(SDL_GetTicks());
|
fps_.calculate(SDL_GetTicks());
|
||||||
|
|||||||
@@ -153,7 +153,6 @@ class Screen {
|
|||||||
void render();
|
void render();
|
||||||
|
|
||||||
// Actualiza la lógica de la clase
|
// Actualiza la lógica de la clase
|
||||||
void update(); // Para escenas no migradas (sin delta_time)
|
|
||||||
void update(float delta_time); // Para escenas migradas (con delta_time)
|
void update(float delta_time); // Para escenas migradas (con delta_time)
|
||||||
|
|
||||||
// Establece el modo de video
|
// Establece el modo de video
|
||||||
@@ -196,7 +195,7 @@ class Screen {
|
|||||||
void hide();
|
void hide();
|
||||||
|
|
||||||
// Establece el renderizador para las surfaces
|
// Establece el renderizador para las surfaces
|
||||||
void setRendererSurface(const std::shared_ptr<Surface> &surface = nullptr);
|
void setRendererSurface(const std::shared_ptr<Surface>& surface = nullptr);
|
||||||
|
|
||||||
// Cambia la paleta
|
// Cambia la paleta
|
||||||
void nextPalette();
|
void nextPalette();
|
||||||
|
|||||||
@@ -14,8 +14,8 @@
|
|||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "core/rendering/gif.hpp" // Para Gif
|
#include "core/rendering/gif.hpp" // Para Gif
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||||
|
|
||||||
// Carga una paleta desde un archivo .gif
|
// Carga una paleta desde un archivo .gif
|
||||||
|
|||||||
@@ -7,10 +7,10 @@
|
|||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||||
#include "utils/utils.hpp" // Para printWithDots
|
#include "utils/utils.hpp" // Para printWithDots
|
||||||
|
|
||||||
// Carga las animaciones en un vector(Animations) desde un fichero
|
// Carga las animaciones en un vector(Animations) desde un fichero
|
||||||
auto loadAnimationsFromFile(const std::string& file_path) -> Animations {
|
auto loadAnimationsFromFile(const std::string& file_path) -> Animations {
|
||||||
@@ -30,14 +30,14 @@ auto loadAnimationsFromFile(const std::string& file_path) -> Animations {
|
|||||||
std::vector<std::string> buffer;
|
std::vector<std::string> buffer;
|
||||||
std::string line;
|
std::string line;
|
||||||
while (std::getline(stream, line)) {
|
while (std::getline(stream, line)) {
|
||||||
// Eliminar \r de Windows line endings
|
// Eliminar \r de Windows line endings
|
||||||
if (!line.empty() && line.back() == '\r') {
|
if (!line.empty() && line.back() == '\r') {
|
||||||
line.pop_back();
|
line.pop_back();
|
||||||
}
|
}
|
||||||
if (!line.empty()) {
|
if (!line.empty()) {
|
||||||
buffer.push_back(line);
|
buffer.push_back(line);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return buffer;
|
return buffer;
|
||||||
}
|
}
|
||||||
@@ -60,7 +60,6 @@ SurfaceAnimatedSprite::SurfaceAnimatedSprite(const Animations& animations)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path)
|
SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr<Surface> surface, const std::string& file_path)
|
||||||
: SurfaceMovingSprite(std::move(surface)) {
|
: SurfaceMovingSprite(std::move(surface)) {
|
||||||
@@ -105,8 +104,7 @@ void SurfaceAnimatedSprite::animate(float delta_time) {
|
|||||||
// Calcula el frame actual a partir del tiempo acumulado
|
// Calcula el frame actual a partir del tiempo acumulado
|
||||||
const int TARGET_FRAME = static_cast<int>(
|
const int TARGET_FRAME = static_cast<int>(
|
||||||
animations_[current_animation_].accumulated_time /
|
animations_[current_animation_].accumulated_time /
|
||||||
animations_[current_animation_].speed
|
animations_[current_animation_].speed);
|
||||||
);
|
|
||||||
|
|
||||||
// Si alcanza el final de la animación, maneja el loop
|
// Si alcanza el final de la animación, maneja el loop
|
||||||
if (TARGET_FRAME >= static_cast<int>(animations_[current_animation_].frames.size())) {
|
if (TARGET_FRAME >= static_cast<int>(animations_[current_animation_].frames.size())) {
|
||||||
@@ -137,7 +135,7 @@ void SurfaceAnimatedSprite::animate(float delta_time) {
|
|||||||
// Establece el clip del frame actual
|
// Establece el clip del frame actual
|
||||||
if (animations_[current_animation_].current_frame >= 0 &&
|
if (animations_[current_animation_].current_frame >= 0 &&
|
||||||
animations_[current_animation_].current_frame <
|
animations_[current_animation_].current_frame <
|
||||||
static_cast<int>(animations_[current_animation_].frames.size())) {
|
static_cast<int>(animations_[current_animation_].frames.size())) {
|
||||||
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
|
setClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -215,9 +213,7 @@ auto parseGlobalParameter(const std::string& line, std::shared_ptr<Surface>& sur
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Helper: Parsea los frames de una animación desde una cadena separada por comas
|
// Helper: Parsea los frames de una animación desde una cadena separada por comas
|
||||||
void parseAnimationFrames(const std::string& value, AnimationData& animation,
|
void parseAnimationFrames(const std::string& value, AnimationData& animation, float frame_width, float frame_height, int frames_per_row, int max_tiles) {
|
||||||
float frame_width, float frame_height,
|
|
||||||
int frames_per_row, int max_tiles) {
|
|
||||||
std::stringstream ss(value);
|
std::stringstream ss(value);
|
||||||
std::string tmp;
|
std::string tmp;
|
||||||
SDL_FRect rect = {0.0F, 0.0F, frame_width, frame_height};
|
SDL_FRect rect = {0.0F, 0.0F, frame_width, frame_height};
|
||||||
@@ -269,8 +265,7 @@ auto parseAnimation(const Animations& animations, size_t& index, float frame_wid
|
|||||||
if (pos != std::string::npos) {
|
if (pos != std::string::npos) {
|
||||||
std::string key = line.substr(0, pos);
|
std::string key = line.substr(0, pos);
|
||||||
std::string value = line.substr(pos + 1);
|
std::string value = line.substr(pos + 1);
|
||||||
parseAnimationParameter(key, value, animation, frame_width, frame_height,
|
parseAnimationParameter(key, value, animation, frame_width, frame_height, frames_per_row, max_tiles);
|
||||||
frames_per_row, max_tiles);
|
|
||||||
}
|
}
|
||||||
} while (line != "[/animation]");
|
} while (line != "[/animation]");
|
||||||
|
|
||||||
@@ -302,8 +297,7 @@ void SurfaceAnimatedSprite::setAnimations(const Animations& animations) {
|
|||||||
|
|
||||||
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
|
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
|
||||||
if (line == "[animation]") {
|
if (line == "[animation]") {
|
||||||
AnimationData animation = parseAnimation(animations, index, frame_width, frame_height,
|
AnimationData animation = parseAnimation(animations, index, frame_width, frame_height, frames_per_row, max_tiles);
|
||||||
frames_per_row, max_tiles);
|
|
||||||
animations_.emplace_back(animation);
|
animations_.emplace_back(animation);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -54,5 +54,5 @@ void SurfaceSprite::clear() {
|
|||||||
// Actualiza el estado del sprite (time-based)
|
// Actualiza el estado del sprite (time-based)
|
||||||
void SurfaceSprite::update(float delta_time) {
|
void SurfaceSprite::update(float delta_time) {
|
||||||
// Base implementation does nothing (static sprites)
|
// Base implementation does nothing (static sprites)
|
||||||
(void)delta_time; // Evita warning de parámetro no usado
|
(void)delta_time; // Evita warning de parámetro no usado
|
||||||
}
|
}
|
||||||
@@ -8,11 +8,11 @@
|
|||||||
#include <sstream> // Para istringstream
|
#include <sstream> // Para istringstream
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
|
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||||
#include "utils/utils.hpp" // Para getFileName, stringToColor, printWithDots
|
#include "utils/utils.hpp" // Para getFileName, stringToColor, printWithDots
|
||||||
|
|
||||||
// Llena una estructuta TextFile desde un fichero
|
// Llena una estructuta TextFile desde un fichero
|
||||||
auto loadTextFile(const std::string& file_path) -> std::shared_ptr<TextFile> {
|
auto loadTextFile(const std::string& file_path) -> std::shared_ptr<TextFile> {
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ struct ResourceTileMap {
|
|||||||
|
|
||||||
// Estructura para almacenar habitaciones y su nombre
|
// Estructura para almacenar habitaciones y su nombre
|
||||||
struct ResourceRoom {
|
struct ResourceRoom {
|
||||||
std::string name; // Nombre de la habitación
|
std::string name; // Nombre de la habitación
|
||||||
std::shared_ptr<Room::Data> room; // Habitación
|
std::shared_ptr<Room::Data> room; // Habitación
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
@@ -152,7 +152,7 @@ class Resource {
|
|||||||
std::vector<ResourceTileMap> tile_maps_; // Vector con los mapas de tiles
|
std::vector<ResourceTileMap> tile_maps_; // Vector con los mapas de tiles
|
||||||
std::vector<ResourceRoom> rooms_; // Vector con las habitaciones
|
std::vector<ResourceRoom> rooms_; // Vector con las habitaciones
|
||||||
|
|
||||||
ResourceCount count_; // Contador de recursos
|
ResourceCount count_; // Contador de recursos
|
||||||
std::shared_ptr<Text> loading_text_; // Texto para la pantalla de carga
|
std::shared_ptr<Text> loading_text_; // Texto para la pantalla de carga
|
||||||
|
|
||||||
// Carga los sonidos
|
// Carga los sonidos
|
||||||
|
|||||||
@@ -3,13 +3,13 @@
|
|||||||
|
|
||||||
#include "resource_helper.hpp"
|
#include "resource_helper.hpp"
|
||||||
|
|
||||||
#include "resource_loader.hpp"
|
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
|
#include "resource_loader.hpp"
|
||||||
|
|
||||||
namespace jdd {
|
namespace jdd {
|
||||||
namespace ResourceHelper {
|
namespace ResourceHelper {
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,9 @@
|
|||||||
#ifndef RESOURCE_HELPER_HPP
|
#ifndef RESOURCE_HELPER_HPP
|
||||||
#define RESOURCE_HELPER_HPP
|
#define RESOURCE_HELPER_HPP
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <cstdint>
|
|
||||||
|
|
||||||
namespace jdd {
|
namespace jdd {
|
||||||
namespace ResourceHelper {
|
namespace ResourceHelper {
|
||||||
@@ -15,7 +15,7 @@ namespace ResourceHelper {
|
|||||||
// pack_file: Path to resources.pack
|
// pack_file: Path to resources.pack
|
||||||
// enable_fallback: Allow loading from filesystem if pack not available
|
// enable_fallback: Allow loading from filesystem if pack not available
|
||||||
auto initializeResourceSystem(const std::string& pack_file = "resources.pack",
|
auto initializeResourceSystem(const std::string& pack_file = "resources.pack",
|
||||||
bool enable_fallback = true) -> bool;
|
bool enable_fallback = true) -> bool;
|
||||||
|
|
||||||
// Shutdown the resource system
|
// Shutdown the resource system
|
||||||
void shutdownResourceSystem();
|
void shutdownResourceSystem();
|
||||||
|
|||||||
@@ -4,64 +4,64 @@
|
|||||||
#ifndef RESOURCE_LOADER_HPP
|
#ifndef RESOURCE_LOADER_HPP
|
||||||
#define RESOURCE_LOADER_HPP
|
#define RESOURCE_LOADER_HPP
|
||||||
|
|
||||||
#include "resource_pack.hpp"
|
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
#include "resource_pack.hpp"
|
||||||
|
|
||||||
namespace jdd {
|
namespace jdd {
|
||||||
|
|
||||||
// Singleton class for loading resources from pack or filesystem
|
// Singleton class for loading resources from pack or filesystem
|
||||||
class ResourceLoader {
|
class ResourceLoader {
|
||||||
public:
|
public:
|
||||||
// Get singleton instance
|
// Get singleton instance
|
||||||
static auto get() -> ResourceLoader&;
|
static auto get() -> ResourceLoader&;
|
||||||
|
|
||||||
// Initialize with a pack file (optional)
|
// Initialize with a pack file (optional)
|
||||||
auto initialize(const std::string& pack_file, bool enable_fallback = true) -> bool;
|
auto initialize(const std::string& pack_file, bool enable_fallback = true) -> bool;
|
||||||
|
|
||||||
// Load a resource (tries pack first, then filesystem if fallback enabled)
|
// Load a resource (tries pack first, then filesystem if fallback enabled)
|
||||||
auto loadResource(const std::string& filename) -> std::vector<uint8_t>;
|
auto loadResource(const std::string& filename) -> std::vector<uint8_t>;
|
||||||
|
|
||||||
// Check if a resource exists
|
// Check if a resource exists
|
||||||
auto resourceExists(const std::string& filename) -> bool;
|
auto resourceExists(const std::string& filename) -> bool;
|
||||||
|
|
||||||
// Check if pack is loaded
|
// Check if pack is loaded
|
||||||
auto isPackLoaded() const -> bool;
|
auto isPackLoaded() const -> bool;
|
||||||
|
|
||||||
// Get pack statistics
|
// Get pack statistics
|
||||||
auto getPackResourceCount() const -> size_t;
|
auto getPackResourceCount() const -> size_t;
|
||||||
|
|
||||||
// Validate pack integrity (checksum)
|
// Validate pack integrity (checksum)
|
||||||
auto validatePack() const -> bool;
|
auto validatePack() const -> bool;
|
||||||
|
|
||||||
// Load assets.txt from pack (for release builds)
|
// Load assets.txt from pack (for release builds)
|
||||||
auto loadAssetsConfig() const -> std::string;
|
auto loadAssetsConfig() const -> std::string;
|
||||||
|
|
||||||
// Cleanup
|
// Cleanup
|
||||||
void shutdown();
|
void shutdown();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
ResourceLoader() = default;
|
ResourceLoader() = default;
|
||||||
~ResourceLoader() = default;
|
~ResourceLoader() = default;
|
||||||
|
|
||||||
// Disable copy/move
|
// Disable copy/move
|
||||||
ResourceLoader(const ResourceLoader&) = delete;
|
ResourceLoader(const ResourceLoader&) = delete;
|
||||||
ResourceLoader& operator=(const ResourceLoader&) = delete;
|
ResourceLoader& operator=(const ResourceLoader&) = delete;
|
||||||
ResourceLoader(ResourceLoader&&) = delete;
|
ResourceLoader(ResourceLoader&&) = delete;
|
||||||
ResourceLoader& operator=(ResourceLoader&&) = delete;
|
ResourceLoader& operator=(ResourceLoader&&) = delete;
|
||||||
|
|
||||||
// Load from filesystem
|
// Load from filesystem
|
||||||
static auto loadFromFilesystem(const std::string& filepath) -> std::vector<uint8_t>;
|
static auto loadFromFilesystem(const std::string& filepath) -> std::vector<uint8_t>;
|
||||||
|
|
||||||
// Check if file exists on filesystem
|
// Check if file exists on filesystem
|
||||||
static auto fileExistsOnFilesystem(const std::string& filepath) -> bool;
|
static auto fileExistsOnFilesystem(const std::string& filepath) -> bool;
|
||||||
|
|
||||||
// Member data
|
// Member data
|
||||||
std::unique_ptr<ResourcePack> resource_pack_;
|
std::unique_ptr<ResourcePack> resource_pack_;
|
||||||
bool fallback_to_files_{true};
|
bool fallback_to_files_{true};
|
||||||
bool initialized_{false};
|
bool initialized_{false};
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace jdd
|
} // namespace jdd
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ auto ResourcePack::addFile(const std::string& filepath, const std::string& pack_
|
|||||||
|
|
||||||
// Add all files from a directory recursively
|
// Add all files from a directory recursively
|
||||||
auto ResourcePack::addDirectory(const std::string& dir_path,
|
auto ResourcePack::addDirectory(const std::string& dir_path,
|
||||||
const std::string& base_path) -> bool {
|
const std::string& base_path) -> bool {
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) {
|
if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) {
|
||||||
@@ -244,7 +244,7 @@ auto ResourcePack::getResource(const std::string& filename) -> std::vector<uint8
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> result(data_.begin() + entry.offset,
|
std::vector<uint8_t> result(data_.begin() + entry.offset,
|
||||||
data_.begin() + entry.offset + entry.size);
|
data_.begin() + entry.offset + entry.size);
|
||||||
|
|
||||||
// Verify checksum
|
// Verify checksum
|
||||||
uint32_t checksum = calculateChecksum(result);
|
uint32_t checksum = calculateChecksum(result);
|
||||||
|
|||||||
@@ -15,10 +15,10 @@ namespace jdd {
|
|||||||
|
|
||||||
// Entry metadata for each resource in the pack
|
// Entry metadata for each resource in the pack
|
||||||
struct ResourceEntry {
|
struct ResourceEntry {
|
||||||
std::string filename; // Relative path within pack
|
std::string filename; // Relative path within pack
|
||||||
uint64_t offset; // Byte offset in data block
|
uint64_t offset; // Byte offset in data block
|
||||||
uint64_t size; // Size in bytes
|
uint64_t size; // Size in bytes
|
||||||
uint32_t checksum; // CRC32 checksum for verification
|
uint32_t checksum; // CRC32 checksum for verification
|
||||||
};
|
};
|
||||||
|
|
||||||
// Resource pack file format
|
// Resource pack file format
|
||||||
@@ -26,67 +26,67 @@ struct ResourceEntry {
|
|||||||
// Metadata: Count + array of ResourceEntry
|
// Metadata: Count + array of ResourceEntry
|
||||||
// Data: Encrypted data block
|
// Data: Encrypted data block
|
||||||
class ResourcePack {
|
class ResourcePack {
|
||||||
public:
|
public:
|
||||||
ResourcePack() = default;
|
ResourcePack() = default;
|
||||||
~ResourcePack() = default;
|
~ResourcePack() = default;
|
||||||
|
|
||||||
// Disable copy/move
|
// Disable copy/move
|
||||||
ResourcePack(const ResourcePack&) = delete;
|
ResourcePack(const ResourcePack&) = delete;
|
||||||
ResourcePack& operator=(const ResourcePack&) = delete;
|
ResourcePack& operator=(const ResourcePack&) = delete;
|
||||||
ResourcePack(ResourcePack&&) = delete;
|
ResourcePack(ResourcePack&&) = delete;
|
||||||
ResourcePack& operator=(ResourcePack&&) = delete;
|
ResourcePack& operator=(ResourcePack&&) = delete;
|
||||||
|
|
||||||
// Add a single file to the pack
|
// Add a single file to the pack
|
||||||
auto addFile(const std::string& filepath, const std::string& pack_name) -> bool;
|
auto addFile(const std::string& filepath, const std::string& pack_name) -> bool;
|
||||||
|
|
||||||
// Add all files from a directory recursively
|
// Add all files from a directory recursively
|
||||||
auto addDirectory(const std::string& dir_path, const std::string& base_path = "")
|
auto addDirectory(const std::string& dir_path, const std::string& base_path = "")
|
||||||
-> bool;
|
-> bool;
|
||||||
|
|
||||||
// Save the pack to a file
|
// Save the pack to a file
|
||||||
auto savePack(const std::string& pack_file) -> bool;
|
auto savePack(const std::string& pack_file) -> bool;
|
||||||
|
|
||||||
// Load a pack from a file
|
// Load a pack from a file
|
||||||
auto loadPack(const std::string& pack_file) -> bool;
|
auto loadPack(const std::string& pack_file) -> bool;
|
||||||
|
|
||||||
// Get a resource by name
|
// Get a resource by name
|
||||||
auto getResource(const std::string& filename) -> std::vector<uint8_t>;
|
auto getResource(const std::string& filename) -> std::vector<uint8_t>;
|
||||||
|
|
||||||
// Check if a resource exists
|
// Check if a resource exists
|
||||||
auto hasResource(const std::string& filename) const -> bool;
|
auto hasResource(const std::string& filename) const -> bool;
|
||||||
|
|
||||||
// Get list of all resources
|
// Get list of all resources
|
||||||
auto getResourceList() const -> std::vector<std::string>;
|
auto getResourceList() const -> std::vector<std::string>;
|
||||||
|
|
||||||
// Check if pack is loaded
|
// Check if pack is loaded
|
||||||
auto isLoaded() const -> bool { return loaded_; }
|
auto isLoaded() const -> bool { return loaded_; }
|
||||||
|
|
||||||
// Get pack statistics
|
// Get pack statistics
|
||||||
auto getResourceCount() const -> size_t { return resources_.size(); }
|
auto getResourceCount() const -> size_t { return resources_.size(); }
|
||||||
auto getDataSize() const -> size_t { return data_.size(); }
|
auto getDataSize() const -> size_t { return data_.size(); }
|
||||||
|
|
||||||
// Calculate overall pack checksum (for validation)
|
// Calculate overall pack checksum (for validation)
|
||||||
auto calculatePackChecksum() const -> uint32_t;
|
auto calculatePackChecksum() const -> uint32_t;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static constexpr std::array<char, 4> MAGIC_HEADER = {'J', 'D', 'D', 'I'};
|
static constexpr std::array<char, 4> MAGIC_HEADER = {'J', 'D', 'D', 'I'};
|
||||||
static constexpr uint32_t VERSION = 1;
|
static constexpr uint32_t VERSION = 1;
|
||||||
static constexpr const char* DEFAULT_ENCRYPT_KEY = "JDDI_RESOURCES_2024";
|
static constexpr const char* DEFAULT_ENCRYPT_KEY = "JDDI_RESOURCES_2024";
|
||||||
|
|
||||||
// Calculate CRC32 checksum
|
// Calculate CRC32 checksum
|
||||||
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t;
|
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t;
|
||||||
|
|
||||||
// XOR encryption/decryption
|
// XOR encryption/decryption
|
||||||
static void encryptData(std::vector<uint8_t>& data, const std::string& key);
|
static void encryptData(std::vector<uint8_t>& data, const std::string& key);
|
||||||
static void decryptData(std::vector<uint8_t>& data, const std::string& key);
|
static void decryptData(std::vector<uint8_t>& data, const std::string& key);
|
||||||
|
|
||||||
// Read file from disk
|
// Read file from disk
|
||||||
static auto readFile(const std::string& filepath) -> std::vector<uint8_t>;
|
static auto readFile(const std::string& filepath) -> std::vector<uint8_t>;
|
||||||
|
|
||||||
// Member data
|
// Member data
|
||||||
std::unordered_map<std::string, ResourceEntry> resources_;
|
std::unordered_map<std::string, ResourceEntry> resources_;
|
||||||
std::vector<uint8_t> data_; // Encrypted data block
|
std::vector<uint8_t> data_; // Encrypted data block
|
||||||
bool loaded_{false};
|
bool loaded_{false};
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace jdd
|
} // namespace jdd
|
||||||
|
|||||||
@@ -11,27 +11,27 @@
|
|||||||
#include <memory> // Para make_unique, unique_ptr
|
#include <memory> // Para make_unique, unique_ptr
|
||||||
#include <string> // Para operator+, allocator, char_traits
|
#include <string> // Para operator+, allocator, char_traits
|
||||||
|
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/input.hpp" // Para Input, InputAction
|
#include "core/input/input.hpp" // Para Input, InputAction
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/resources/asset.hpp" // Para Asset, AssetType
|
#include "core/resources/asset.hpp" // Para Asset, AssetType
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||||
#include "core/resources/resource_loader.hpp" // Para ResourceLoader
|
#include "core/resources/resource_loader.hpp" // Para ResourceLoader
|
||||||
#include "core/system/debug.hpp" // Para Debug
|
#include "core/system/debug.hpp" // Para Debug
|
||||||
#include "game/gameplay/cheevos.hpp" // Para Cheevos
|
#include "game/gameplay/cheevos.hpp" // Para Cheevos
|
||||||
#include "game/options.hpp" // Para Options, options, OptionsVideo
|
#include "game/options.hpp" // Para Options, options, OptionsVideo
|
||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
#include "game/scene_manager.hpp" // Para SceneManager
|
||||||
#include "game/scenes/credits.hpp" // Para Credits
|
#include "game/scenes/credits.hpp" // Para Credits
|
||||||
#include "game/scenes/ending.hpp" // Para Ending
|
#include "game/scenes/ending.hpp" // Para Ending
|
||||||
#include "game/scenes/ending2.hpp" // Para Ending2
|
#include "game/scenes/ending2.hpp" // Para Ending2
|
||||||
#include "game/scenes/game.hpp" // Para Game, GameMode
|
#include "game/scenes/game.hpp" // Para Game, GameMode
|
||||||
#include "game/scenes/game_over.hpp" // Para GameOver
|
#include "game/scenes/game_over.hpp" // Para GameOver
|
||||||
#include "game/scenes/loading_screen.hpp" // Para LoadingScreen
|
#include "game/scenes/loading_screen.hpp" // Para LoadingScreen
|
||||||
#include "game/scenes/logo.hpp" // Para Logo
|
#include "game/scenes/logo.hpp" // Para Logo
|
||||||
#include "game/scenes/title.hpp" // Para Title
|
#include "game/scenes/title.hpp" // Para Title
|
||||||
#include "game/ui/notifier.hpp" // Para Notifier
|
#include "game/ui/notifier.hpp" // Para Notifier
|
||||||
#include "utils/defines.hpp" // Para WINDOW_CAPTION
|
#include "utils/defines.hpp" // Para WINDOW_CAPTION
|
||||||
|
|
||||||
#ifndef _WIN32
|
#ifndef _WIN32
|
||||||
#include <pwd.h>
|
#include <pwd.h>
|
||||||
@@ -92,7 +92,7 @@ Director::Director(std::vector<std::string> const& args) {
|
|||||||
// 4. Initialize Asset system with config from pack
|
// 4. Initialize Asset system with config from pack
|
||||||
// NOTE: In release, don't use executable_path or PREFIX - paths in pack are relative
|
// NOTE: In release, don't use executable_path or PREFIX - paths in pack are relative
|
||||||
// Pass empty string to avoid issues when running from different directories
|
// Pass empty string to avoid issues when running from different directories
|
||||||
Asset::init(""); // Empty executable_path in release
|
Asset::init(""); // Empty executable_path in release
|
||||||
Asset::get()->loadFromString(assets_config, "", system_folder_); // Empty PREFIX for pack
|
Asset::get()->loadFromString(assets_config, "", system_folder_); // Empty PREFIX for pack
|
||||||
std::cout << "Asset system initialized from pack\n";
|
std::cout << "Asset system initialized from pack\n";
|
||||||
|
|
||||||
@@ -134,13 +134,12 @@ Director::Director(std::vector<std::string> const& args) {
|
|||||||
#ifdef RELEASE_BUILD
|
#ifdef RELEASE_BUILD
|
||||||
// In release, construct the path manually (not from Asset which has empty executable_path)
|
// In release, construct the path manually (not from Asset which has empty executable_path)
|
||||||
std::string gamecontroller_db = executable_path_ + PREFIX + "/gamecontrollerdb.txt";
|
std::string gamecontroller_db = executable_path_ + PREFIX + "/gamecontrollerdb.txt";
|
||||||
Input::init(gamecontroller_db);
|
Input::init(gamecontroller_db, Asset::get()->get("controllers.json"));
|
||||||
#else
|
#else
|
||||||
// In development, use Asset as normal
|
// In development, use Asset as normal
|
||||||
Input::init(Asset::get()->get("gamecontrollerdb.txt"));
|
Input::init(Asset::get()->get("gamecontrollerdb.txt"), Asset::get()->get("controllers.json")); // Carga configuración de controles
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
initInput();
|
|
||||||
Debug::init();
|
Debug::init();
|
||||||
|
|
||||||
// Special handling for cheevos.bin - also needs filesystem path
|
// Special handling for cheevos.bin - also needs filesystem path
|
||||||
@@ -249,72 +248,6 @@ void Director::createSystemFolder(const std::string& folder) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inicia las variables necesarias para arrancar el programa
|
|
||||||
void Director::initInput() {
|
|
||||||
// Busca si hay un mando conectado
|
|
||||||
Input::get()->discoverGameControllers();
|
|
||||||
|
|
||||||
// Teclado - Movimiento
|
|
||||||
if (Options::keys == Options::ControlScheme::CURSOR) {
|
|
||||||
Input::get()->bindKey(InputAction::JUMP, SDL_SCANCODE_UP);
|
|
||||||
Input::get()->bindKey(InputAction::LEFT, SDL_SCANCODE_LEFT);
|
|
||||||
Input::get()->bindKey(InputAction::RIGHT, SDL_SCANCODE_RIGHT);
|
|
||||||
Input::get()->bindKey(InputAction::UP, SDL_SCANCODE_UP);
|
|
||||||
Input::get()->bindKey(InputAction::DOWN, SDL_SCANCODE_DOWN);
|
|
||||||
} else if (Options::keys == Options::ControlScheme::OPQA) {
|
|
||||||
Input::get()->bindKey(InputAction::JUMP, SDL_SCANCODE_Q);
|
|
||||||
Input::get()->bindKey(InputAction::LEFT, SDL_SCANCODE_O);
|
|
||||||
Input::get()->bindKey(InputAction::RIGHT, SDL_SCANCODE_P);
|
|
||||||
Input::get()->bindKey(InputAction::UP, SDL_SCANCODE_Q);
|
|
||||||
Input::get()->bindKey(InputAction::DOWN, SDL_SCANCODE_A);
|
|
||||||
} else if (Options::keys == Options::ControlScheme::WASD) {
|
|
||||||
Input::get()->bindKey(InputAction::JUMP, SDL_SCANCODE_W);
|
|
||||||
Input::get()->bindKey(InputAction::LEFT, SDL_SCANCODE_A);
|
|
||||||
Input::get()->bindKey(InputAction::RIGHT, SDL_SCANCODE_D);
|
|
||||||
Input::get()->bindKey(InputAction::UP, SDL_SCANCODE_W);
|
|
||||||
Input::get()->bindKey(InputAction::DOWN, SDL_SCANCODE_S);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Teclado - Otros
|
|
||||||
Input::get()->bindKey(InputAction::ACCEPT, SDL_SCANCODE_RETURN);
|
|
||||||
Input::get()->bindKey(InputAction::CANCEL, SDL_SCANCODE_ESCAPE);
|
|
||||||
Input::get()->bindKey(InputAction::PAUSE, SDL_SCANCODE_H);
|
|
||||||
Input::get()->bindKey(InputAction::EXIT, SDL_SCANCODE_ESCAPE);
|
|
||||||
Input::get()->bindKey(InputAction::WINDOW_DEC_ZOOM, SDL_SCANCODE_F1);
|
|
||||||
Input::get()->bindKey(InputAction::WINDOW_INC_ZOOM, SDL_SCANCODE_F2);
|
|
||||||
Input::get()->bindKey(InputAction::TOGGLE_VIDEOMODE, SDL_SCANCODE_F3);
|
|
||||||
Input::get()->bindKey(InputAction::TOGGLE_SHADERS, SDL_SCANCODE_F4);
|
|
||||||
Input::get()->bindKey(InputAction::NEXT_PALETTE, SDL_SCANCODE_F5);
|
|
||||||
Input::get()->bindKey(InputAction::PREVIOUS_PALETTE, SDL_SCANCODE_F6);
|
|
||||||
Input::get()->bindKey(InputAction::TOGGLE_INTEGER_SCALE, SDL_SCANCODE_F7);
|
|
||||||
Input::get()->bindKey(InputAction::SHOW_DEBUG_INFO, SDL_SCANCODE_F12);
|
|
||||||
Input::get()->bindKey(InputAction::TOGGLE_MUSIC, SDL_SCANCODE_M);
|
|
||||||
Input::get()->bindKey(InputAction::TOGGLE_BORDER, SDL_SCANCODE_B);
|
|
||||||
|
|
||||||
// MANDO
|
|
||||||
const int NUM_GAMEPADS = Input::get()->getNumControllers();
|
|
||||||
for (int i = 0; i < NUM_GAMEPADS; ++i) {
|
|
||||||
// Movimiento
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::JUMP, SDL_GAMEPAD_BUTTON_SOUTH);
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::LEFT, SDL_GAMEPAD_BUTTON_DPAD_LEFT);
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::RIGHT, SDL_GAMEPAD_BUTTON_DPAD_RIGHT);
|
|
||||||
|
|
||||||
// Otros
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::ACCEPT, SDL_GAMEPAD_BUTTON_SOUTH);
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::CANCEL, SDL_GAMEPAD_BUTTON_EAST);
|
|
||||||
#ifdef GAME_CONSOLE
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::input_pause, SDL_GAMEPAD_BUTTON_BACK);
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::input_exit, SDL_GAMEPAD_BUTTON_START);
|
|
||||||
#else
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::PAUSE, SDL_GAMEPAD_BUTTON_START);
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::EXIT, SDL_GAMEPAD_BUTTON_BACK);
|
|
||||||
#endif
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::NEXT_PALETTE, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER);
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::TOGGLE_MUSIC, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);
|
|
||||||
Input::get()->bindGameControllerButton(i, InputAction::TOGGLE_BORDER, SDL_GAMEPAD_BUTTON_NORTH);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Crea el indice de ficheros
|
// Crea el indice de ficheros
|
||||||
auto Director::setFileList() -> bool {
|
auto Director::setFileList() -> bool {
|
||||||
// Determinar el prefijo de ruta según la plataforma
|
// Determinar el prefijo de ruta según la plataforma
|
||||||
|
|||||||
@@ -8,18 +8,17 @@
|
|||||||
class Director {
|
class Director {
|
||||||
public:
|
public:
|
||||||
Director(std::vector<std::string> const& args); // Constructor
|
Director(std::vector<std::string> const& args); // Constructor
|
||||||
~Director(); // Destructor
|
~Director(); // Destructor
|
||||||
static auto run() -> int; // Bucle principal
|
static auto run() -> int; // Bucle principal
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Variables ---
|
// --- Variables ---
|
||||||
std::string executable_path_; // Path del ejecutable
|
std::string executable_path_; // Path del ejecutable
|
||||||
std::string system_folder_; // Carpeta del sistema donde guardar datos
|
std::string system_folder_; // Carpeta del sistema donde guardar datos
|
||||||
static auto checkProgramArguments(std::vector<std::string> const& args) -> std::string; // Comprueba los parametros del programa
|
static auto checkProgramArguments(std::vector<std::string> const& args) -> std::string; // Comprueba los parametros del programa
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema donde guardar datos
|
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema donde guardar datos
|
||||||
static void initInput(); // Inicializa el objeto Input
|
|
||||||
auto setFileList() -> bool; // Crea el indice de ficheros
|
auto setFileList() -> bool; // Crea el indice de ficheros
|
||||||
static void runLogo(); // Ejecuta la seccion de juego con el logo
|
static void runLogo(); // Ejecuta la seccion de juego con el logo
|
||||||
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga
|
static void runLoadingScreen(); // Ejecuta la seccion de juego de la pantalla de carga
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
|
||||||
|
|
||||||
#include "core/system/global_events.hpp"
|
#include "core/system/global_events.hpp"
|
||||||
|
|
||||||
#include "core/input/mouse.hpp"
|
#include "core/input/mouse.hpp"
|
||||||
#include "game/options.hpp" // Para Options, options, OptionsGame, OptionsAudio
|
#include "game/options.hpp" // Para Options, options, OptionsGame, OptionsAudio
|
||||||
|
#include "game/scene_manager.hpp" // Para SceneManager
|
||||||
|
|
||||||
namespace GlobalEvents {
|
namespace GlobalEvents {
|
||||||
// Comprueba los eventos que se pueden producir en cualquier sección del juego
|
// Comprueba los eventos que se pueden producir en cualquier sección del juego
|
||||||
void check(const SDL_Event& event) {
|
void handle(const SDL_Event& event) {
|
||||||
// Evento de salida de la aplicación
|
// Evento de salida de la aplicación
|
||||||
if (event.type == SDL_EVENT_QUIT) {
|
if (event.type == SDL_EVENT_QUIT) {
|
||||||
SceneManager::current = SceneManager::Scene::QUIT;
|
SceneManager::current = SceneManager::Scene::QUIT;
|
||||||
|
|||||||
@@ -4,5 +4,5 @@
|
|||||||
|
|
||||||
namespace GlobalEvents {
|
namespace GlobalEvents {
|
||||||
// Comprueba los eventos que se pueden producir en cualquier sección del juego
|
// Comprueba los eventos que se pueden producir en cualquier sección del juego
|
||||||
void check(const SDL_Event& event);
|
void handle(const SDL_Event& event);
|
||||||
} // namespace GlobalEvents
|
} // namespace GlobalEvents
|
||||||
25526
source/external/json.hpp
vendored
Normal file
25526
source/external/json.hpp
vendored
Normal file
File diff suppressed because it is too large
Load Diff
@@ -11,7 +11,7 @@
|
|||||||
// Constructor
|
// Constructor
|
||||||
Enemy::Enemy(const Data& enemy)
|
Enemy::Enemy(const Data& enemy)
|
||||||
// [DOC:29/10/2025] la surface ara se pillarà del .ANI
|
// [DOC:29/10/2025] la surface ara se pillarà del .ANI
|
||||||
: sprite_(std::make_shared<SurfaceAnimatedSprite>(/*Resource::get()->getSurface(enemy.surface_path), */Resource::get()->getAnimations(enemy.animation_path))),
|
: sprite_(std::make_shared<SurfaceAnimatedSprite>(/*Resource::get()->getSurface(enemy.surface_path), */ Resource::get()->getAnimations(enemy.animation_path))),
|
||||||
color_string_(enemy.color),
|
color_string_(enemy.color),
|
||||||
x1_(enemy.x1),
|
x1_(enemy.x1),
|
||||||
x2_(enemy.x2),
|
x2_(enemy.x2),
|
||||||
|
|||||||
@@ -18,18 +18,18 @@ class Enemy {
|
|||||||
int w = 0; // Anchura del enemigo
|
int w = 0; // Anchura del enemigo
|
||||||
int h = 0; // Altura del enemigo
|
int h = 0; // Altura del enemigo
|
||||||
[/DOC] */
|
[/DOC] */
|
||||||
float x = 0.0F; // Posición inicial en el eje X
|
float x = 0.0F; // Posición inicial en el eje X
|
||||||
float y = 0.0F; // Posición inicial en el eje Y
|
float y = 0.0F; // Posición inicial en el eje Y
|
||||||
float vx = 0.0F; // Velocidad en el eje X
|
float vx = 0.0F; // Velocidad en el eje X
|
||||||
float vy = 0.0F; // Velocidad en el eje Y
|
float vy = 0.0F; // Velocidad en el eje Y
|
||||||
int x1 = 0; // Límite izquierdo de la ruta en el eje X
|
int x1 = 0; // Límite izquierdo de la ruta en el eje X
|
||||||
int x2 = 0; // Límite derecho de la ruta en el eje X
|
int x2 = 0; // Límite derecho de la ruta en el eje X
|
||||||
int y1 = 0; // Límite superior de la ruta en el eje Y
|
int y1 = 0; // Límite superior de la ruta en el eje Y
|
||||||
int y2 = 0; // Límite inferior de la ruta en el eje Y
|
int y2 = 0; // Límite inferior de la ruta en el eje Y
|
||||||
bool flip = false; // Indica si el enemigo hace flip al terminar su ruta
|
bool flip = false; // Indica si el enemigo hace flip al terminar su ruta
|
||||||
bool mirror = false; // Indica si el enemigo está volteado verticalmente
|
bool mirror = false; // Indica si el enemigo está volteado verticalmente
|
||||||
int frame = 0; // Frame inicial para la animación del enemigo
|
int frame = 0; // Frame inicial para la animación del enemigo
|
||||||
std::string color; // Color del enemigo
|
std::string color; // Color del enemigo
|
||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
Data() = default;
|
Data() = default;
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ class Item {
|
|||||||
// Constructor
|
// Constructor
|
||||||
Data() = default;
|
Data() = default;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Constructor y Destructor
|
// Constructor y Destructor
|
||||||
explicit Item(const Data& item);
|
explicit Item(const Data& item);
|
||||||
~Item() = default;
|
~Item() = default;
|
||||||
|
|||||||
@@ -56,12 +56,12 @@ void Player::checkInput(float delta_time) {
|
|||||||
|
|
||||||
if (!auto_movement_) {
|
if (!auto_movement_) {
|
||||||
// Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica
|
// Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica
|
||||||
if (Input::get()->checkInput(InputAction::LEFT)) {
|
if (Input::get()->checkAction(InputAction::LEFT)) {
|
||||||
vx_ = -HORIZONTAL_VELOCITY;
|
vx_ = -HORIZONTAL_VELOCITY;
|
||||||
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
|
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::RIGHT)) {
|
else if (Input::get()->checkAction(InputAction::RIGHT)) {
|
||||||
vx_ = HORIZONTAL_VELOCITY;
|
vx_ = HORIZONTAL_VELOCITY;
|
||||||
sprite_->setFlip(SDL_FLIP_NONE);
|
sprite_->setFlip(SDL_FLIP_NONE);
|
||||||
}
|
}
|
||||||
@@ -84,7 +84,7 @@ void Player::checkInput(float delta_time) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Input::get()->checkInput(InputAction::JUMP)) {
|
if (Input::get()->checkAction(InputAction::JUMP)) {
|
||||||
// Solo puede saltar si ademas de estar (state == STANDING)
|
// Solo puede saltar si ademas de estar (state == STANDING)
|
||||||
// Esta sobre el suelo, rampa o suelo que se mueve
|
// Esta sobre el suelo, rampa o suelo que se mueve
|
||||||
// Esto es para evitar el salto desde el vacio al cambiar de pantalla verticalmente
|
// Esto es para evitar el salto desde el vacio al cambiar de pantalla verticalmente
|
||||||
@@ -132,16 +132,14 @@ void Player::checkState(float delta_time) {
|
|||||||
// Reproduce sonidos según el estado
|
// Reproduce sonidos según el estado
|
||||||
if (state_ == State::FALLING) {
|
if (state_ == State::FALLING) {
|
||||||
playFallSound();
|
playFallSound();
|
||||||
}
|
} else if (state_ == State::STANDING) {
|
||||||
else if (state_ == State::STANDING) {
|
|
||||||
// Si no tiene suelo debajo y no está en rampa descendente -> FALLING
|
// Si no tiene suelo debajo y no está en rampa descendente -> FALLING
|
||||||
if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) {
|
if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) {
|
||||||
last_grounded_position_ = static_cast<int>(y_); // Guarda Y actual al SALIR de STANDING
|
last_grounded_position_ = static_cast<int>(y_); // Guarda Y actual al SALIR de STANDING
|
||||||
setState(State::FALLING); // setState() establece vx_=0, vy_=MAX_VY
|
setState(State::FALLING); // setState() establece vx_=0, vy_=MAX_VY
|
||||||
playFallSound();
|
playFallSound();
|
||||||
}
|
}
|
||||||
}
|
} else if (state_ == State::JUMPING) {
|
||||||
else if (state_ == State::JUMPING) {
|
|
||||||
playJumpSound();
|
playJumpSound();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,8 +206,7 @@ void Player::handleSlopeMovement(int direction) {
|
|||||||
const LineVertical SIDE = {
|
const LineVertical SIDE = {
|
||||||
.x = SIDE_X,
|
.x = SIDE_X,
|
||||||
.y1 = static_cast<int>(y_) + HEIGHT - 2,
|
.y1 = static_cast<int>(y_) + HEIGHT - 2,
|
||||||
.y2 = static_cast<int>(y_) + HEIGHT - 1
|
.y2 = static_cast<int>(y_) + HEIGHT - 1};
|
||||||
};
|
|
||||||
|
|
||||||
// Comprueba la rampa correspondiente según la dirección
|
// Comprueba la rampa correspondiente según la dirección
|
||||||
const int SLOPE_Y = direction < 0 ? room_->checkLeftSlopes(&SIDE) : room_->checkRightSlopes(&SIDE);
|
const int SLOPE_Y = direction < 0 ? room_->checkLeftSlopes(&SIDE) : room_->checkRightSlopes(&SIDE);
|
||||||
@@ -233,16 +230,14 @@ void Player::moveHorizontal(float delta_time, int direction) {
|
|||||||
.x = x_ + DISPLACEMENT,
|
.x = x_ + DISPLACEMENT,
|
||||||
.y = y_,
|
.y = y_,
|
||||||
.w = std::ceil(std::fabs(DISPLACEMENT)),
|
.w = std::ceil(std::fabs(DISPLACEMENT)),
|
||||||
.h = HEIGHT
|
.h = HEIGHT};
|
||||||
};
|
|
||||||
} else {
|
} else {
|
||||||
// Movimiento a la derecha
|
// Movimiento a la derecha
|
||||||
proj = {
|
proj = {
|
||||||
.x = x_ + WIDTH,
|
.x = x_ + WIDTH,
|
||||||
.y = y_,
|
.y = y_,
|
||||||
.w = std::ceil(DISPLACEMENT),
|
.w = std::ceil(DISPLACEMENT),
|
||||||
.h = HEIGHT
|
.h = HEIGHT};
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba la colisión con las superficies
|
// Comprueba la colisión con las superficies
|
||||||
@@ -351,14 +346,14 @@ void Player::moveVerticalDown(float delta_time) {
|
|||||||
|
|
||||||
// Orquesta el movimiento del jugador
|
// Orquesta el movimiento del jugador
|
||||||
void Player::move(float delta_time) {
|
void Player::move(float delta_time) {
|
||||||
applyGravity(delta_time); // Aplica gravedad al jugador
|
applyGravity(delta_time); // Aplica gravedad al jugador
|
||||||
checkState(delta_time); // Comprueba el estado del jugador
|
checkState(delta_time); // Comprueba el estado del jugador
|
||||||
|
|
||||||
// Movimiento horizontal
|
// Movimiento horizontal
|
||||||
if (vx_ < 0.0F) {
|
if (vx_ < 0.0F) {
|
||||||
moveHorizontal(delta_time, -1); // Izquierda
|
moveHorizontal(delta_time, -1); // Izquierda
|
||||||
} else if (vx_ > 0.0F) {
|
} else if (vx_ > 0.0F) {
|
||||||
moveHorizontal(delta_time, 1); // Derecha
|
moveHorizontal(delta_time, 1); // Derecha
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si ha salido del suelo, el jugador cae
|
// Si ha salido del suelo, el jugador cae
|
||||||
@@ -623,7 +618,7 @@ void Player::initSprite(const std::string& animations_path) {
|
|||||||
|
|
||||||
// Actualiza collider_box y collision points
|
// Actualiza collider_box y collision points
|
||||||
void Player::updateColliderGeometry() {
|
void Player::updateColliderGeometry() {
|
||||||
placeSprite(); // Coloca el sprite en la posición del jugador
|
placeSprite(); // Coloca el sprite en la posición del jugador
|
||||||
collider_box_ = getRect(); // Actualiza el rectangulo de colisión
|
collider_box_ = getRect(); // Actualiza el rectangulo de colisión
|
||||||
updateColliderPoints(); // Actualiza los puntos de colisión
|
updateColliderPoints(); // Actualiza los puntos de colisión
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,18 +66,18 @@ class Player {
|
|||||||
~Player() = default;
|
~Player() = default;
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void render(); // Pinta el enemigo en pantalla
|
void render(); // Pinta el enemigo en pantalla
|
||||||
void update(float delta_time); // Actualiza las variables del objeto
|
void update(float delta_time); // Actualiza las variables del objeto
|
||||||
[[nodiscard]] auto getOnBorder() const -> bool { return is_on_border_; } // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
|
[[nodiscard]] auto getOnBorder() const -> bool { return is_on_border_; } // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
|
||||||
[[nodiscard]] auto getBorder() const -> Room::Border { return border_; } // Indica en cual de los cuatro bordes se encuentra
|
[[nodiscard]] auto getBorder() const -> Room::Border { return border_; } // Indica en cual de los cuatro bordes se encuentra
|
||||||
void switchBorders(); // Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
|
void switchBorders(); // Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla
|
||||||
auto getRect() -> SDL_FRect { return {x_, y_, WIDTH, HEIGHT}; } // Obtiene el rectangulo que delimita al jugador
|
auto getRect() -> SDL_FRect { return {x_, y_, WIDTH, HEIGHT}; } // Obtiene el rectangulo que delimita al jugador
|
||||||
auto getCollider() -> SDL_FRect& { return collider_box_; } // Obtiene el rectangulo de colision del jugador
|
auto getCollider() -> SDL_FRect& { return collider_box_; } // Obtiene el rectangulo de colision del jugador
|
||||||
auto getSpawnParams() -> SpawnData { return {x_, y_, vx_, vy_, last_grounded_position_, state_, sprite_->getFlip()}; } // Obtiene el estado de reaparición del jugador
|
auto getSpawnParams() -> SpawnData { return {x_, y_, vx_, vy_, last_grounded_position_, state_, sprite_->getFlip()}; } // Obtiene el estado de reaparición del jugador
|
||||||
void setColor(); // Establece el color del jugador
|
void setColor(); // Establece el color del jugador
|
||||||
void setRoom(std::shared_ptr<Room> room) { room_ = std::move(room); } // Establece la habitación en la que se encuentra el jugador
|
void setRoom(std::shared_ptr<Room> room) { room_ = std::move(room); } // Establece la habitación en la que se encuentra el jugador
|
||||||
[[nodiscard]] auto isAlive() const -> bool { return is_alive_; } // Comprueba si el jugador esta vivo
|
[[nodiscard]] auto isAlive() const -> bool { return is_alive_; } // Comprueba si el jugador esta vivo
|
||||||
void setPaused(bool value) { is_paused_ = value; } // Pone el jugador en modo pausa
|
void setPaused(bool value) { is_paused_ = value; } // Pone el jugador en modo pausa
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
@@ -99,15 +99,15 @@ class Player {
|
|||||||
std::unique_ptr<SurfaceAnimatedSprite> sprite_; // Sprite del jugador
|
std::unique_ptr<SurfaceAnimatedSprite> sprite_; // Sprite del jugador
|
||||||
|
|
||||||
// --- Variables de posición y física ---
|
// --- Variables de posición y física ---
|
||||||
float x_ = 0.0F; // Posición del jugador en el eje X
|
float x_ = 0.0F; // Posición del jugador en el eje X
|
||||||
float y_ = 0.0F; // Posición del jugador en el eje Y
|
float y_ = 0.0F; // Posición del jugador en el eje Y
|
||||||
float y_prev_ = 0.0F; // Posición Y del frame anterior (para detectar hitos de distancia en sonidos)
|
float y_prev_ = 0.0F; // Posición Y del frame anterior (para detectar hitos de distancia en sonidos)
|
||||||
float vx_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje X
|
float vx_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje X
|
||||||
float vy_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje Y
|
float vy_ = 0.0F; // Velocidad/desplazamiento del jugador en el eje Y
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
State state_ = State::STANDING; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
|
State state_ = State::STANDING; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
|
||||||
State previous_state_ = State::STANDING; // Estado previo en el que se encontraba el jugador
|
State previous_state_ = State::STANDING; // Estado previo en el que se encontraba el jugador
|
||||||
|
|
||||||
// --- Variables de colisión ---
|
// --- Variables de colisión ---
|
||||||
SDL_FRect collider_box_; // Caja de colisión con los enemigos u objetos
|
SDL_FRect collider_box_; // Caja de colisión con los enemigos u objetos
|
||||||
@@ -116,17 +116,17 @@ class Player {
|
|||||||
std::array<SDL_FPoint, 2> feet_{}; // Contiene los puntos que hay en el pie del jugador
|
std::array<SDL_FPoint, 2> feet_{}; // Contiene los puntos que hay en el pie del jugador
|
||||||
|
|
||||||
// --- Variables de juego ---
|
// --- Variables de juego ---
|
||||||
bool is_on_border_ = false; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
|
bool is_on_border_ = false; // Indica si el jugador esta en uno de los cuatro bordes de la pantalla
|
||||||
bool is_alive_ = true; // Indica si el jugador esta vivo o no
|
bool is_alive_ = true; // Indica si el jugador esta vivo o no
|
||||||
bool is_paused_ = false; // Indica si el jugador esta en modo pausa
|
bool is_paused_ = false; // Indica si el jugador esta en modo pausa
|
||||||
bool auto_movement_ = false; // Indica si esta siendo arrastrado por una superficie automatica
|
bool auto_movement_ = false; // Indica si esta siendo arrastrado por una superficie automatica
|
||||||
Room::Border border_ = Room::Border::TOP; // Indica en cual de los cuatro bordes se encuentra
|
Room::Border border_ = Room::Border::TOP; // Indica en cual de los cuatro bordes se encuentra
|
||||||
int last_grounded_position_ = 0; // Ultima posición en Y en la que se estaba en contacto con el suelo (hace doble función: tracking de caída + altura inicial del salto)
|
int last_grounded_position_ = 0; // Ultima posición en Y en la que se estaba en contacto con el suelo (hace doble función: tracking de caída + altura inicial del salto)
|
||||||
|
|
||||||
// --- Variables de renderizado y sonido ---
|
// --- Variables de renderizado y sonido ---
|
||||||
Uint8 color_ = 0; // Color del jugador
|
Uint8 color_ = 0; // Color del jugador
|
||||||
std::vector<JA_Sound_t*> jumping_sound_; // Vecor con todos los sonidos del salto
|
std::vector<JA_Sound_t*> jumping_sound_; // Vecor con todos los sonidos del salto
|
||||||
std::vector<JA_Sound_t*> falling_sound_; // Vecor con todos los sonidos de la caída
|
std::vector<JA_Sound_t*> falling_sound_; // Vecor con todos los sonidos de la caída
|
||||||
|
|
||||||
// --- Funciones de inicialización ---
|
// --- Funciones de inicialización ---
|
||||||
void initSprite(const std::string& animations_path); // Inicializa el sprite del jugador
|
void initSprite(const std::string& animations_path); // Inicializa el sprite del jugador
|
||||||
@@ -134,38 +134,38 @@ class Player {
|
|||||||
void applySpawnValues(const SpawnData& spawn); // Aplica los valores de spawn al jugador
|
void applySpawnValues(const SpawnData& spawn); // Aplica los valores de spawn al jugador
|
||||||
|
|
||||||
// --- Funciones de procesamiento de entrada ---
|
// --- Funciones de procesamiento de entrada ---
|
||||||
void checkInput(float delta_time); // Comprueba las entradas y modifica variables
|
void checkInput(float delta_time); // Comprueba las entradas y modifica variables
|
||||||
|
|
||||||
// --- Funciones de gestión de estado ---
|
// --- Funciones de gestión de estado ---
|
||||||
void checkState(float delta_time); // Comprueba el estado del jugador y actualiza variables
|
void checkState(float delta_time); // Comprueba el estado del jugador y actualiza variables
|
||||||
void setState(State value); // Cambia el estado del jugador
|
void setState(State value); // Cambia el estado del jugador
|
||||||
|
|
||||||
// --- Funciones de física ---
|
// --- Funciones de física ---
|
||||||
void applyGravity(float delta_time); // Aplica gravedad al jugador
|
void applyGravity(float delta_time); // Aplica gravedad al jugador
|
||||||
|
|
||||||
// --- Funciones de movimiento y colisión ---
|
// --- Funciones de movimiento y colisión ---
|
||||||
void move(float delta_time); // Orquesta el movimiento del jugador
|
void move(float delta_time); // Orquesta el movimiento del jugador
|
||||||
void moveHorizontal(float delta_time, int direction); // Maneja el movimiento horizontal (-1: izq, 1: der)
|
void moveHorizontal(float delta_time, int direction); // Maneja el movimiento horizontal (-1: izq, 1: der)
|
||||||
void moveVerticalUp(float delta_time); // Maneja el movimiento vertical hacia arriba
|
void moveVerticalUp(float delta_time); // Maneja el movimiento vertical hacia arriba
|
||||||
void moveVerticalDown(float delta_time); // Maneja el movimiento vertical hacia abajo
|
void moveVerticalDown(float delta_time); // Maneja el movimiento vertical hacia abajo
|
||||||
void handleSlopeMovement(int direction); // Maneja el movimiento sobre rampas
|
void handleSlopeMovement(int direction); // Maneja el movimiento sobre rampas
|
||||||
|
|
||||||
// --- Funciones de detección de superficies ---
|
// --- Funciones de detección de superficies ---
|
||||||
auto isOnFloor() -> bool; // Comprueba si el jugador tiene suelo debajo de los pies
|
auto isOnFloor() -> bool; // Comprueba si el jugador tiene suelo debajo de los pies
|
||||||
auto isOnAutoSurface() -> bool; // Comprueba si el jugador esta sobre una superficie automática
|
auto isOnAutoSurface() -> bool; // Comprueba si el jugador esta sobre una superficie automática
|
||||||
auto isOnDownSlope() -> bool; // Comprueba si el jugador está sobre una rampa hacia abajo
|
auto isOnDownSlope() -> bool; // Comprueba si el jugador está sobre una rampa hacia abajo
|
||||||
|
|
||||||
// --- Funciones de actualización de geometría ---
|
// --- Funciones de actualización de geometría ---
|
||||||
void updateColliderGeometry(); // Actualiza collider_box y collision points
|
void updateColliderGeometry(); // Actualiza collider_box y collision points
|
||||||
void updateColliderPoints(); // Actualiza los puntos de colisión
|
void updateColliderPoints(); // Actualiza los puntos de colisión
|
||||||
void updateFeet(); // Actualiza los puntos de los pies
|
void updateFeet(); // Actualiza los puntos de los pies
|
||||||
void placeSprite(); // Coloca el sprite en la posición del jugador
|
void placeSprite(); // Coloca el sprite en la posición del jugador
|
||||||
|
|
||||||
// --- Funciones de finalización ---
|
// --- Funciones de finalización ---
|
||||||
void animate(float delta_time); // Establece la animación del jugador
|
void animate(float delta_time); // Establece la animación del jugador
|
||||||
void checkBorders(); // Comprueba si se halla en alguno de los cuatro bordes
|
void checkBorders(); // Comprueba si se halla en alguno de los cuatro bordes
|
||||||
void checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio
|
void checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio
|
||||||
auto checkKillingTiles() -> bool; // Comprueba que el jugador no toque ningun tile de los que matan
|
auto checkKillingTiles() -> bool; // Comprueba que el jugador no toque ningun tile de los que matan
|
||||||
void playJumpSound(); // Calcula y reproduce el sonido de salto
|
void playJumpSound(); // Calcula y reproduce el sonido de salto
|
||||||
void playFallSound(); // Calcula y reproduce el sonido de caer
|
void playFallSound(); // Calcula y reproduce el sonido de caer
|
||||||
};
|
};
|
||||||
@@ -7,18 +7,18 @@
|
|||||||
#include <sstream> // Para basic_stringstream
|
#include <sstream> // Para basic_stringstream
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
|
||||||
#include "core/system/debug.hpp" // Para Debug
|
#include "core/system/debug.hpp" // Para Debug
|
||||||
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
|
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
|
||||||
#include "game/gameplay/scoreboard.hpp" // Para ScoreboardData
|
#include "game/gameplay/scoreboard.hpp" // Para ScoreboardData
|
||||||
#include "game/options.hpp" // Para Options, OptionsStats, options
|
#include "game/options.hpp" // Para Options, OptionsStats, options
|
||||||
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH
|
#include "utils/defines.hpp" // Para BLOCK, PLAY_AREA_HEIGHT, PLAY_AREA_WIDTH
|
||||||
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
|
#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Room::Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data)
|
Room::Room(const std::string& room_path, std::shared_ptr<ScoreboardData> data)
|
||||||
@@ -869,14 +869,15 @@ auto Room::setEnemy(Enemy::Data* enemy, const std::string& key, const std::strin
|
|||||||
try {
|
try {
|
||||||
/*if (key == "tileSetFile") {
|
/*if (key == "tileSetFile") {
|
||||||
enemy->surface_path = value;
|
enemy->surface_path = value;
|
||||||
} else */if (key == "animation") {
|
} else */
|
||||||
|
if (key == "animation") {
|
||||||
enemy->animation_path = value;
|
enemy->animation_path = value;
|
||||||
/* [DOC:29/10/2025] w i h ja no fan falta, se pilla del .ANI
|
/* [DOC:29/10/2025] w i h ja no fan falta, se pilla del .ANI
|
||||||
} else if (key == "width") {
|
} else if (key == "width") {
|
||||||
enemy->w = std::stoi(value);
|
enemy->w = std::stoi(value);
|
||||||
} else if (key == "height") {
|
} else if (key == "height") {
|
||||||
enemy->h = std::stoi(value);
|
enemy->h = std::stoi(value);
|
||||||
[/DOC] */
|
[/DOC] */
|
||||||
} else if (key == "x") {
|
} else if (key == "x") {
|
||||||
enemy->x = std::stof(value) * TILE_SIZE;
|
enemy->x = std::stof(value) * TILE_SIZE;
|
||||||
} else if (key == "y") {
|
} else if (key == "y") {
|
||||||
@@ -991,8 +992,7 @@ auto Room::loadRoomTileFile(const std::string& file_path, bool verbose) -> std::
|
|||||||
if (verbose) {
|
if (verbose) {
|
||||||
std::cout << "TileMap loaded: " << FILENAME.c_str() << '\n';
|
std::cout << "TileMap loaded: " << FILENAME.c_str() << '\n';
|
||||||
}
|
}
|
||||||
}
|
} else { // El fichero no se puede abrir
|
||||||
else { // El fichero no se puede abrir
|
|
||||||
if (verbose) {
|
if (verbose) {
|
||||||
std::cout << "Warning: Unable to open " << FILENAME.c_str() << " file" << '\n';
|
std::cout << "Warning: Unable to open " << FILENAME.c_str() << " file" << '\n';
|
||||||
}
|
}
|
||||||
@@ -1046,8 +1046,7 @@ auto Room::loadRoomFile(const std::string& file_path, bool verbose) -> Data {
|
|||||||
if (verbose) {
|
if (verbose) {
|
||||||
std::cout << "Room loaded: " << FILE_NAME.c_str() << '\n';
|
std::cout << "Room loaded: " << FILE_NAME.c_str() << '\n';
|
||||||
}
|
}
|
||||||
}
|
} else { // El fichero no se puede abrir
|
||||||
else { // El fichero no se puede abrir
|
|
||||||
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << '\n';
|
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,27 +34,27 @@ class Room {
|
|||||||
};
|
};
|
||||||
|
|
||||||
struct AnimatedTile {
|
struct AnimatedTile {
|
||||||
std::shared_ptr<SurfaceSprite> sprite; // SurfaceSprite para dibujar el tile
|
std::shared_ptr<SurfaceSprite> sprite; // SurfaceSprite para dibujar el tile
|
||||||
int x_orig = 0; // Posición X donde se encuentra el primer tile de la animación en la tilesheet
|
int x_orig = 0; // Posición X donde se encuentra el primer tile de la animación en la tilesheet
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Data {
|
struct Data {
|
||||||
std::string number; // Numero de la habitación
|
std::string number; // Numero de la habitación
|
||||||
std::string name; // Nombre de la habitación
|
std::string name; // Nombre de la habitación
|
||||||
std::string bg_color; // Color de fondo de la habitación
|
std::string bg_color; // Color de fondo de la habitación
|
||||||
std::string border_color; // Color del borde de la pantalla
|
std::string border_color; // Color del borde de la pantalla
|
||||||
std::string item_color1; // Color 1 para los items de la habitación
|
std::string item_color1; // Color 1 para los items de la habitación
|
||||||
std::string item_color2; // Color 2 para los items de la habitación
|
std::string item_color2; // Color 2 para los items de la habitación
|
||||||
std::string upper_room; // Identificador de la habitación que se encuentra arriba
|
std::string upper_room; // Identificador de la habitación que se encuentra arriba
|
||||||
std::string lower_room; // Identificador de la habitación que se encuentra abajo
|
std::string lower_room; // Identificador de la habitación que se encuentra abajo
|
||||||
std::string left_room; // Identificador de la habitación que se encuentra a la izquierda
|
std::string left_room; // Identificador de la habitación que se encuentra a la izquierda
|
||||||
std::string right_room; // Identificador de la habitación que se encuentra a la derecha
|
std::string right_room; // Identificador de la habitación que se encuentra a la derecha
|
||||||
std::string tile_set_file; // Imagen con los gráficos para la habitación
|
std::string tile_set_file; // Imagen con los gráficos para la habitación
|
||||||
std::string tile_map_file; // Fichero con el mapa de índices de tile
|
std::string tile_map_file; // Fichero con el mapa de índices de tile
|
||||||
int conveyor_belt_direction = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
|
int conveyor_belt_direction = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||||
std::vector<int> tile_map; // Índice de los tiles a dibujar en la habitación
|
std::vector<int> tile_map; // Índice de los tiles a dibujar en la habitación
|
||||||
std::vector<Enemy::Data> enemies; // Listado con los enemigos de la habitación
|
std::vector<Enemy::Data> enemies; // Listado con los enemigos de la habitación
|
||||||
std::vector<Item::Data> items; // Listado con los items que hay en la habitación
|
std::vector<Item::Data> items; // Listado con los items que hay en la habitación
|
||||||
|
|
||||||
// Constructor por defecto
|
// Constructor por defecto
|
||||||
Data() = default;
|
Data() = default;
|
||||||
@@ -108,34 +108,34 @@ class Room {
|
|||||||
std::shared_ptr<ScoreboardData> data_; // Puntero a los datos del marcador
|
std::shared_ptr<ScoreboardData> data_; // Puntero a los datos del marcador
|
||||||
|
|
||||||
// --- Variables ---
|
// --- Variables ---
|
||||||
std::string number_; // Numero de la habitación
|
std::string number_; // Numero de la habitación
|
||||||
std::string name_; // Nombre de la habitación
|
std::string name_; // Nombre de la habitación
|
||||||
std::string bg_color_; // Color de fondo de la habitación
|
std::string bg_color_; // Color de fondo de la habitación
|
||||||
std::string border_color_; // Color del borde de la pantalla
|
std::string border_color_; // Color del borde de la pantalla
|
||||||
std::string item_color1_; // Color 1 para los items de la habitación
|
std::string item_color1_; // Color 1 para los items de la habitación
|
||||||
std::string item_color2_; // Color 2 para los items de la habitación
|
std::string item_color2_; // Color 2 para los items de la habitación
|
||||||
std::string upper_room_; // Identificador de la habitación que se encuentra arriba
|
std::string upper_room_; // Identificador de la habitación que se encuentra arriba
|
||||||
std::string lower_room_; // Identificador de la habitación que se encuentra abajp
|
std::string lower_room_; // Identificador de la habitación que se encuentra abajp
|
||||||
std::string left_room_; // Identificador de la habitación que se encuentra a la izquierda
|
std::string left_room_; // Identificador de la habitación que se encuentra a la izquierda
|
||||||
std::string right_room_; // Identificador de la habitación que se encuentra a la derecha
|
std::string right_room_; // Identificador de la habitación que se encuentra a la derecha
|
||||||
std::string tile_set_file_; // Imagen con los graficos para la habitación
|
std::string tile_set_file_; // Imagen con los graficos para la habitación
|
||||||
std::string tile_map_file_; // Fichero con el mapa de indices de tile
|
std::string tile_map_file_; // Fichero con el mapa de indices de tile
|
||||||
std::vector<int> tile_map_; // Indice de los tiles a dibujar en la habitación
|
std::vector<int> tile_map_; // Indice de los tiles a dibujar en la habitación
|
||||||
int conveyor_belt_direction_ = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
|
int conveyor_belt_direction_ = 0; // Sentido en el que arrastran las superficies automáticas de la habitación
|
||||||
std::vector<LineHorizontal> bottom_floors_; // Lista con las superficies inferiores de la habitación
|
std::vector<LineHorizontal> bottom_floors_; // Lista con las superficies inferiores de la habitación
|
||||||
std::vector<LineHorizontal> top_floors_; // Lista con las superficies superiores de la habitación
|
std::vector<LineHorizontal> top_floors_; // Lista con las superficies superiores de la habitación
|
||||||
std::vector<LineVertical> left_walls_; // Lista con las superficies laterales de la parte izquierda de la habitación
|
std::vector<LineVertical> left_walls_; // Lista con las superficies laterales de la parte izquierda de la habitación
|
||||||
std::vector<LineVertical> right_walls_; // Lista con las superficies laterales de la parte derecha de la habitación
|
std::vector<LineVertical> right_walls_; // Lista con las superficies laterales de la parte derecha de la habitación
|
||||||
std::vector<LineDiagonal> left_slopes_; // Lista con todas las rampas que suben hacia la izquierda
|
std::vector<LineDiagonal> left_slopes_; // Lista con todas las rampas que suben hacia la izquierda
|
||||||
std::vector<LineDiagonal> right_slopes_; // Lista con todas las rampas que suben hacia la derecha
|
std::vector<LineDiagonal> right_slopes_; // Lista con todas las rampas que suben hacia la derecha
|
||||||
float time_accumulator_ = 0.0F; // Acumulador de tiempo para animaciones (time-based)
|
float time_accumulator_ = 0.0F; // Acumulador de tiempo para animaciones (time-based)
|
||||||
bool is_paused_ = false; // Indica si el mapa esta en modo pausa
|
bool is_paused_ = false; // Indica si el mapa esta en modo pausa
|
||||||
|
|
||||||
// Constantes de tiempo
|
// Constantes de tiempo
|
||||||
static constexpr float CONVEYOR_FRAME_DURATION = 0.05F; // Duración de cada frame de conveyor belt (3 frames @ 60fps)
|
static constexpr float CONVEYOR_FRAME_DURATION = 0.05F; // Duración de cada frame de conveyor belt (3 frames @ 60fps)
|
||||||
std::vector<AnimatedTile> animated_tiles_; // Vector con los indices de tiles animados
|
std::vector<AnimatedTile> animated_tiles_; // Vector con los indices de tiles animados
|
||||||
std::vector<LineHorizontal> conveyor_belt_floors_; // Lista con las superficies automaticas de la habitación
|
std::vector<LineHorizontal> conveyor_belt_floors_; // Lista con las superficies automaticas de la habitación
|
||||||
int tile_set_width_ = 0; // Ancho del tileset en tiles
|
int tile_set_width_ = 0; // Ancho del tileset en tiles
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void initializeRoom(const Data& room); // Inicializa los valores
|
void initializeRoom(const Data& room); // Inicializa los valores
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ Scoreboard::Scoreboard(std::shared_ptr<ScoreboardData> data)
|
|||||||
constexpr float SURFACE_HEIGHT = 6.0F * TILE_SIZE;
|
constexpr float SURFACE_HEIGHT = 6.0F * TILE_SIZE;
|
||||||
|
|
||||||
// Reserva memoria para los objetos
|
// Reserva memoria para los objetos
|
||||||
//auto player_texture = Resource::get()->getSurface(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif");
|
// auto player_texture = Resource::get()->getSurface(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.gif" : "player.gif");
|
||||||
auto player_animations = Resource::get()->getAnimations(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani");
|
auto player_animations = Resource::get()->getAnimations(Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.ani" : "player.ani");
|
||||||
player_sprite_ = std::make_shared<SurfaceAnimatedSprite>(player_animations);
|
player_sprite_ = std::make_shared<SurfaceAnimatedSprite>(player_animations);
|
||||||
player_sprite_->setCurrentAnimation("walk_menu");
|
player_sprite_->setCurrentAnimation("walk_menu");
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
class SurfaceAnimatedSprite; // lines 10-10
|
class SurfaceAnimatedSprite; // lines 10-10
|
||||||
@@ -74,13 +74,13 @@ class Scoreboard {
|
|||||||
static constexpr int SPRITE_WALK_FRAMES = 4; // Número de frames de animación
|
static constexpr int SPRITE_WALK_FRAMES = 4; // Número de frames de animación
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
std::vector<Uint8> color_; // Vector con los colores del objeto
|
std::vector<Uint8> color_; // Vector con los colores del objeto
|
||||||
bool is_paused_; // Indica si el marcador esta en modo pausa
|
bool is_paused_; // Indica si el marcador esta en modo pausa
|
||||||
Uint32 paused_time_; // Milisegundos que ha estado el marcador en pausa
|
Uint32 paused_time_; // Milisegundos que ha estado el marcador en pausa
|
||||||
Uint32 paused_time_elapsed_; // Tiempo acumulado en pausa
|
Uint32 paused_time_elapsed_; // Tiempo acumulado en pausa
|
||||||
ClockData clock_; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida
|
ClockData clock_; // Contiene las horas, minutos y segundos transcurridos desde el inicio de la partida
|
||||||
Uint8 items_color_; // Color de la cantidad de items recogidos
|
Uint8 items_color_; // Color de la cantidad de items recogidos
|
||||||
SDL_FRect surface_dest_; // Rectangulo donde dibujar la surface del marcador
|
SDL_FRect surface_dest_; // Rectangulo donde dibujar la surface del marcador
|
||||||
float time_accumulator_ = 0.0F; // Acumulador de tiempo para animaciones
|
float time_accumulator_ = 0.0F; // Acumulador de tiempo para animaciones
|
||||||
float items_color_timer_ = 0.0F; // Timer para parpadeo de color de items
|
float items_color_timer_ = 0.0F; // Timer para parpadeo de color de items
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ class Stats {
|
|||||||
public:
|
public:
|
||||||
// Constructostd::string nst stdstd::string nst std::string& buffer);
|
// Constructostd::string nst stdstd::string nst std::string& buffer);
|
||||||
Stats(std::string file, std::string buffer);
|
Stats(std::string file, std::string buffer);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Stats();
|
~Stats();
|
||||||
|
|
||||||
|
|||||||
@@ -2,19 +2,19 @@
|
|||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
#include <algorithm> // Para find_if
|
#include <algorithm> // Para find_if
|
||||||
#include <cctype> // Para isspace
|
#include <cctype> // Para isspace
|
||||||
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
|
#include <fstream> // Para basic_ostream, operator<<, basic_ofstream
|
||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
#include <iostream> // Para cout, cerr
|
#include <iostream> // Para cout, cerr
|
||||||
#include <ranges>
|
#include <ranges>
|
||||||
#include <sstream> // Para basic_istringstream
|
#include <sstream> // Para basic_istringstream
|
||||||
#include <string> // Para char_traits, string, operator<<, hash
|
#include <string> // Para char_traits, string, operator<<, hash
|
||||||
#include <unordered_map> // Para unordered_map, operator==, _Node_const_i...
|
#include <unordered_map> // Para unordered_map, operator==, _Node_const_i...
|
||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
|
|
||||||
#include "utils/utils.hpp" // Para stringToBool, boolToString, safeStoi
|
|
||||||
#include "game/defaults.hpp" // Para GameDefaults::VERSION
|
#include "game/defaults.hpp" // Para GameDefaults::VERSION
|
||||||
|
#include "utils/utils.hpp" // Para stringToBool, boolToString, safeStoi
|
||||||
|
|
||||||
namespace Options {
|
namespace Options {
|
||||||
// Declaración de funciones internas
|
// Declaración de funciones internas
|
||||||
@@ -145,7 +145,6 @@ auto saveToFile(const std::string& file_path) -> bool {
|
|||||||
file << "# Versión de la configuración\n";
|
file << "# Versión de la configuración\n";
|
||||||
file << "version " << version << "\n";
|
file << "version " << version << "\n";
|
||||||
|
|
||||||
|
|
||||||
file << "\n## WINDOW\n";
|
file << "\n## WINDOW\n";
|
||||||
file << "# Zoom de la ventana: 1 = Normal, 2 = Doble, 3 = Triple, ...\n";
|
file << "# Zoom de la ventana: 1 = Normal, 2 = Doble, 3 = Triple, ...\n";
|
||||||
file << "window.zoom " << window.zoom << "\n";
|
file << "window.zoom " << window.zoom << "\n";
|
||||||
@@ -234,4 +233,4 @@ auto setOptions(const std::string& var, const std::string& value) -> bool {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
} // namespace Options
|
||||||
@@ -4,7 +4,9 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para min
|
#include <algorithm> // Para min
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
|
#include "core/input/input.hpp" // Para Input
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||||
@@ -40,16 +42,17 @@ Credits::Credits()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Credits::checkEvents() {
|
void Credits::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Credits::checkInput() {
|
void Credits::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inicializa los textos
|
// Inicializa los textos
|
||||||
@@ -153,24 +156,21 @@ void Credits::fillTexture() {
|
|||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void Credits::update() {
|
void Credits::update() {
|
||||||
// Obtiene el delta time
|
// Obtiene el delta time
|
||||||
current_delta_ = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
|
total_time_ += DELTA_TIME; // Actualiza el tiempo total
|
||||||
|
|
||||||
// Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza el tiempo total
|
updateState(DELTA_TIME); // Actualiza la máquina de estados
|
||||||
total_time_ += current_delta_;
|
|
||||||
|
|
||||||
// Actualiza la máquina de estados
|
|
||||||
updateState(current_delta_);
|
|
||||||
|
|
||||||
// Actualiza la pantalla
|
|
||||||
Screen::get()->update(current_delta_);
|
|
||||||
|
|
||||||
// Actualiza el sprite con el brillo si está después del tiempo de inicio
|
// Actualiza el sprite con el brillo si está después del tiempo de inicio
|
||||||
if (reveal_time_ > SHINE_START_TIME) {
|
if (reveal_time_ > SHINE_START_TIME) {
|
||||||
shining_sprite_->update(current_delta_);
|
shining_sprite_->update(DELTA_TIME);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transición entre estados
|
// Transición entre estados
|
||||||
@@ -276,7 +276,6 @@ void Credits::render() {
|
|||||||
void Credits::run() {
|
void Credits::run() {
|
||||||
while (SceneManager::current == SceneManager::Scene::CREDITS) {
|
while (SceneManager::current == SceneManager::Scene::CREDITS) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -33,16 +33,16 @@ class Credits {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// --- Constantes de tiempo (basado en 60 FPS) ---
|
// --- Constantes de tiempo (basado en 60 FPS) ---
|
||||||
static constexpr float REVEAL_PHASE_1_DURATION = 3.733F; // 224 frames @ 60fps
|
static constexpr float REVEAL_PHASE_1_DURATION = 3.733F; // 224 frames @ 60fps
|
||||||
static constexpr float PAUSE_DURATION = 1.667F; // 100 frames @ 60fps
|
static constexpr float PAUSE_DURATION = 1.667F; // 100 frames @ 60fps
|
||||||
static constexpr float REVEAL_PHASE_2_DURATION = 5.333F; // 320 frames (544-224) @ 60fps
|
static constexpr float REVEAL_PHASE_2_DURATION = 5.333F; // 320 frames (544-224) @ 60fps
|
||||||
static constexpr float REVEAL_PHASE_3_DURATION = 2.133F; // 128 frames (672-544) @ 60fps
|
static constexpr float REVEAL_PHASE_3_DURATION = 2.133F; // 128 frames (672-544) @ 60fps
|
||||||
static constexpr float DISPLAY_WITH_SHINE_DURATION = 7.967F; // 478 frames (1150-672) @ 60fps
|
static constexpr float DISPLAY_WITH_SHINE_DURATION = 7.967F; // 478 frames (1150-672) @ 60fps
|
||||||
static constexpr float FADE_OUT_DURATION = 0.833F; // 50 frames (1200-1150) @ 60fps
|
static constexpr float FADE_OUT_DURATION = 0.833F; // 50 frames (1200-1150) @ 60fps
|
||||||
static constexpr float TOTAL_DURATION = 20.0F; // 1200 frames @ 60fps
|
static constexpr float TOTAL_DURATION = 20.0F; // 1200 frames @ 60fps
|
||||||
static constexpr float SHINE_START_TIME = 12.833F; // 770 frames @ 60fps
|
static constexpr float SHINE_START_TIME = 12.833F; // 770 frames @ 60fps
|
||||||
static constexpr float FADE_OUT_START = 19.167F; // 1150 frames @ 60fps
|
static constexpr float FADE_OUT_START = 19.167F; // 1150 frames @ 60fps
|
||||||
static constexpr float REVEAL_SPEED = 60.0F; // counter equivalente por segundo @ 60fps
|
static constexpr float REVEAL_SPEED = 60.0F; // counter equivalente por segundo @ 60fps
|
||||||
struct Captions {
|
struct Captions {
|
||||||
std::string label; // Texto a escribir
|
std::string label; // Texto a escribir
|
||||||
Uint8 color; // Color del texto
|
Uint8 color; // Color del texto
|
||||||
@@ -59,16 +59,15 @@ class Credits {
|
|||||||
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
||||||
float total_time_ = 0.0F; // Tiempo total acumulado
|
float total_time_ = 0.0F; // Tiempo total acumulado
|
||||||
float reveal_time_ = 0.0F; // Tiempo acumulado solo durante revelación (se congela en pausas)
|
float reveal_time_ = 0.0F; // Tiempo acumulado solo durante revelación (se congela en pausas)
|
||||||
float current_delta_ = 0.0F; // Delta time del frame actual
|
|
||||||
std::vector<Captions> texts_; // Vector con los textos
|
std::vector<Captions> texts_; // Vector con los textos
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza las variables
|
void update(); // Actualiza las variables
|
||||||
void render(); // Dibuja en pantalla
|
void render(); // Dibuja en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateState(float delta_time); // Actualiza la máquina de estados
|
void updateState(float delta_time); // Actualiza la máquina de estados
|
||||||
void transitionToState(State new_state); // Transición entre estados
|
void transitionToState(State new_state); // Transición entre estados
|
||||||
void iniTexts(); // Inicializa los textos
|
void iniTexts(); // Inicializa los textos
|
||||||
void fillTexture(); // Escribe el texto en la textura
|
void fillTexture(); // Escribe el texto en la textura
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,14 +4,15 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para min
|
#include <algorithm> // Para min
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
|
#include "core/input/input.hpp" // Para Input
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
#include "core/rendering/text.hpp" // Para Text, TEXT_STROKE
|
#include "core/rendering/text.hpp" // Para Text, TEXT_STROKE
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
#include "core/system/global_events.hpp" // Para check
|
#include "core/system/global_events.hpp" // Para check
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
|
||||||
#include "game/options.hpp" // Para Options, options, OptionsGame, SectionS...
|
#include "game/options.hpp" // Para Options, options, OptionsGame, SectionS...
|
||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
#include "game/scene_manager.hpp" // Para SceneManager
|
||||||
#include "utils/defines.hpp" // Para GAME_SPEED
|
#include "utils/defines.hpp" // Para GAME_SPEED
|
||||||
@@ -46,22 +47,17 @@ Ending::Ending()
|
|||||||
// Actualiza el objeto
|
// Actualiza el objeto
|
||||||
void Ending::update() {
|
void Ending::update() {
|
||||||
// Obtiene el delta time
|
// Obtiene el delta time
|
||||||
current_delta_ = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
|
total_time_ += DELTA_TIME; // Actualiza el tiempo total
|
||||||
|
|
||||||
// Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza el tiempo total
|
updateState(DELTA_TIME); // Actualiza la máquina de estados
|
||||||
total_time_ += current_delta_;
|
updateSpriteCovers(); // Actualiza las cortinillas de los elementos
|
||||||
|
|
||||||
// Actualiza la máquina de estados
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
updateState(current_delta_);
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
|
|
||||||
// Actualiza las cortinillas de los elementos
|
|
||||||
updateSpriteCovers();
|
|
||||||
|
|
||||||
// Actualiza el objeto Screen
|
|
||||||
Screen::get()->update(current_delta_);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja el final en pantalla
|
// Dibuja el final en pantalla
|
||||||
@@ -98,16 +94,17 @@ void Ending::render() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Ending::checkEvents() {
|
void Ending::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Ending::checkInput() {
|
void Ending::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transición entre estados
|
// Transición entre estados
|
||||||
@@ -424,7 +421,6 @@ void Ending::run() {
|
|||||||
|
|
||||||
while (SceneManager::current == SceneManager::Scene::ENDING) {
|
while (SceneManager::current == SceneManager::Scene::ENDING) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -472,8 +468,7 @@ void Ending::updateSpriteCovers() {
|
|||||||
0,
|
0,
|
||||||
sprite_texts_.at(ti.index).cover_clip_desp,
|
sprite_texts_.at(ti.index).cover_clip_desp,
|
||||||
sprite_texts_.at(ti.index).cover_sprite->getWidth(),
|
sprite_texts_.at(ti.index).cover_sprite->getWidth(),
|
||||||
sprite_texts_.at(ti.index).cover_clip_height
|
sprite_texts_.at(ti.index).cover_clip_height);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -496,12 +491,7 @@ void Ending::updateSpriteCovers() {
|
|||||||
sprite_pics_.at(current_scene_).cover_sprite->setY(Y_INITIAL + static_cast<int>(CONTENT_PIXELS));
|
sprite_pics_.at(current_scene_).cover_sprite->setY(Y_INITIAL + static_cast<int>(CONTENT_PIXELS));
|
||||||
}
|
}
|
||||||
|
|
||||||
sprite_pics_.at(current_scene_).cover_sprite->setClip(
|
sprite_pics_.at(current_scene_).cover_sprite->setClip(0, sprite_pics_.at(current_scene_).cover_clip_desp, sprite_pics_.at(current_scene_).cover_sprite->getWidth(), sprite_pics_.at(current_scene_).cover_clip_height);
|
||||||
0,
|
|
||||||
sprite_pics_.at(current_scene_).cover_clip_desp,
|
|
||||||
sprite_pics_.at(current_scene_).cover_sprite->getWidth(),
|
|
||||||
sprite_pics_.at(current_scene_).cover_clip_height
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si se ha de cambiar de escena
|
// Comprueba si se ha de cambiar de escena
|
||||||
|
|||||||
@@ -31,17 +31,17 @@ class Ending {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// --- Constantes de tiempo (basado en 60 FPS) ---
|
// --- Constantes de tiempo (basado en 60 FPS) ---
|
||||||
static constexpr float WARMUP_DURATION = 3.333F; // 200 frames @ 60fps
|
static constexpr float WARMUP_DURATION = 3.333F; // 200 frames @ 60fps
|
||||||
static constexpr float FADEOUT_DURATION = 1.667F; // 100 frames @ 60fps
|
static constexpr float FADEOUT_DURATION = 1.667F; // 100 frames @ 60fps
|
||||||
static constexpr float SCENE_0_DURATION = 16.667F; // 1000 frames @ 60fps
|
static constexpr float SCENE_0_DURATION = 16.667F; // 1000 frames @ 60fps
|
||||||
static constexpr float SCENE_1_DURATION = 23.333F; // 1400 frames @ 60fps
|
static constexpr float SCENE_1_DURATION = 23.333F; // 1400 frames @ 60fps
|
||||||
static constexpr float SCENE_2_DURATION = 16.667F; // 1000 frames @ 60fps
|
static constexpr float SCENE_2_DURATION = 16.667F; // 1000 frames @ 60fps
|
||||||
static constexpr float SCENE_3_DURATION = 13.333F; // 800 frames @ 60fps
|
static constexpr float SCENE_3_DURATION = 13.333F; // 800 frames @ 60fps
|
||||||
static constexpr float SCENE_4_DURATION = 16.667F; // 1000 frames @ 60fps
|
static constexpr float SCENE_4_DURATION = 16.667F; // 1000 frames @ 60fps
|
||||||
static constexpr float TEXT_REVEAL_SPEED = 30.0F; // 2px cada 4 frames @ 60fps
|
static constexpr float TEXT_REVEAL_SPEED = 30.0F; // 2px cada 4 frames @ 60fps
|
||||||
static constexpr float IMAGE_REVEAL_SPEED = 60.0F; // 2px cada 2 frames @ 60fps
|
static constexpr float IMAGE_REVEAL_SPEED = 60.0F; // 2px cada 2 frames @ 60fps
|
||||||
static constexpr float TEXT_LAPSE = 1.333F; // 80 frames @ 60fps
|
static constexpr float TEXT_LAPSE = 1.333F; // 80 frames @ 60fps
|
||||||
static constexpr float FADEOUT_START_OFFSET = 1.667F; // Inicio fade-out 100 frames antes del fin
|
static constexpr float FADEOUT_START_OFFSET = 1.667F; // Inicio fade-out 100 frames antes del fin
|
||||||
|
|
||||||
// --- Estructuras ---
|
// --- Estructuras ---
|
||||||
struct EndingSurface // Estructura con dos texturas y sprites, uno para mostrar y el otro hace de cortinilla
|
struct EndingSurface // Estructura con dos texturas y sprites, uno para mostrar y el otro hace de cortinilla
|
||||||
@@ -81,25 +81,24 @@ class Ending {
|
|||||||
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
||||||
float total_time_ = 0.0F; // Tiempo total acumulado desde el inicio
|
float total_time_ = 0.0F; // Tiempo total acumulado desde el inicio
|
||||||
float fadeout_time_ = 0.0F; // Tiempo acumulado para el fade-out
|
float fadeout_time_ = 0.0F; // Tiempo acumulado para el fade-out
|
||||||
float current_delta_ = 0.0F; // Delta time del frame actual
|
|
||||||
std::vector<EndingSurface> sprite_texts_; // Vector con los sprites de texto con su cortinilla
|
std::vector<EndingSurface> sprite_texts_; // Vector con los sprites de texto con su cortinilla
|
||||||
std::vector<EndingSurface> sprite_pics_; // Vector con los sprites de texto con su cortinilla
|
std::vector<EndingSurface> sprite_pics_; // Vector con los sprites de texto con su cortinilla
|
||||||
int current_scene_ = 0; // Escena actual (0-4)
|
int current_scene_ = 0; // Escena actual (0-4)
|
||||||
std::vector<SceneData> scenes_; // Vector con los textos e imagenes de cada escena
|
std::vector<SceneData> scenes_; // Vector con los textos e imagenes de cada escena
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza el objeto
|
void update(); // Actualiza el objeto
|
||||||
void render(); // Dibuja el final en pantalla
|
void render(); // Dibuja el final en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void iniTexts(); // Inicializa los textos
|
void iniTexts(); // Inicializa los textos
|
||||||
void iniPics(); // Inicializa las imagenes
|
void iniPics(); // Inicializa las imagenes
|
||||||
void iniScenes(); // Inicializa las escenas
|
void iniScenes(); // Inicializa las escenas
|
||||||
void updateState(float delta_time); // Actualiza la máquina de estados
|
void updateState(float delta_time); // Actualiza la máquina de estados
|
||||||
void transitionToState(State new_state); // Transición entre estados
|
void transitionToState(State new_state); // Transición entre estados
|
||||||
void updateSpriteCovers(); // Actualiza las cortinillas de los elementos
|
void updateSpriteCovers(); // Actualiza las cortinillas de los elementos
|
||||||
void checkChangeScene(); // Comprueba si se ha de cambiar de escena
|
void checkChangeScene(); // Comprueba si se ha de cambiar de escena
|
||||||
void fillCoverTexture(); // Rellena la textura para la cortinilla
|
void fillCoverTexture(); // Rellena la textura para la cortinilla
|
||||||
void renderCoverTexture(); // Dibuja la cortinilla de cambio de escena
|
void renderCoverTexture(); // Dibuja la cortinilla de cambio de escena
|
||||||
void updateMusicVolume() const; // Actualiza el volumen de la musica
|
void updateMusicVolume() const; // Actualiza el volumen de la musica
|
||||||
};
|
};
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
|
#include "core/input/input.hpp" // Para Input
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||||
@@ -54,20 +55,19 @@ Ending2::Ending2()
|
|||||||
// Actualiza el objeto
|
// Actualiza el objeto
|
||||||
void Ending2::update() {
|
void Ending2::update() {
|
||||||
// Obtiene el delta time
|
// Obtiene el delta time
|
||||||
current_delta_ = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
|
|
||||||
// Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza el estado
|
updateState(DELTA_TIME); // Actualiza el estado
|
||||||
updateState(current_delta_);
|
|
||||||
|
|
||||||
switch (state_.state) {
|
switch (state_.state) {
|
||||||
case EndingState::CREDITS:
|
case EndingState::CREDITS:
|
||||||
// Actualiza los sprites, los textos y los textos del final
|
// Actualiza los sprites, los textos y los textos del final
|
||||||
updateSprites(current_delta_);
|
updateSprites(DELTA_TIME);
|
||||||
updateTextSprites(current_delta_);
|
updateTextSprites(DELTA_TIME);
|
||||||
updateTexts(current_delta_);
|
updateTexts(DELTA_TIME);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case EndingState::FADING:
|
case EndingState::FADING:
|
||||||
@@ -80,8 +80,8 @@ void Ending2::update() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el objeto
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
Screen::get()->update(current_delta_);
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja el final en pantalla
|
// Dibuja el final en pantalla
|
||||||
@@ -127,16 +127,17 @@ void Ending2::render() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Ending2::checkEvents() {
|
void Ending2::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Ending2::checkInput() {
|
void Ending2::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
@@ -145,7 +146,6 @@ void Ending2::run() {
|
|||||||
|
|
||||||
while (SceneManager::current == SceneManager::Scene::ENDING2) {
|
while (SceneManager::current == SceneManager::Scene::ENDING2) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -50,11 +50,11 @@ class Ending2 {
|
|||||||
static constexpr int TEXT_SPACING_MULTIPLIER = 2; // Multiplicador para espaciado entre líneas de texto
|
static constexpr int TEXT_SPACING_MULTIPLIER = 2; // Multiplicador para espaciado entre líneas de texto
|
||||||
|
|
||||||
// Constantes de tiempo (basadas en tiempo real, no en frames)
|
// Constantes de tiempo (basadas en tiempo real, no en frames)
|
||||||
static constexpr float SPRITE_DESP_SPEED = -12.0F; // Velocidad de desplazamiento en pixels/segundo (era -0.2 px/frame @ 60fps)
|
static constexpr float SPRITE_DESP_SPEED = -12.0F; // Velocidad de desplazamiento en pixels/segundo (era -0.2 px/frame @ 60fps)
|
||||||
static constexpr float STATE_PRE_CREDITS_DURATION = 3.0F; // Duración del estado previo a créditos en segundos
|
static constexpr float STATE_PRE_CREDITS_DURATION = 3.0F; // Duración del estado previo a créditos en segundos
|
||||||
static constexpr float STATE_POST_CREDITS_DURATION = 5.0F; // Duración del estado posterior a créditos en segundos
|
static constexpr float STATE_POST_CREDITS_DURATION = 5.0F; // Duración del estado posterior a créditos en segundos
|
||||||
static constexpr float STATE_FADE_DURATION = 5.0F; // Duración del fade final en segundos
|
static constexpr float STATE_FADE_DURATION = 5.0F; // Duración del fade final en segundos
|
||||||
static constexpr int MUSIC_FADE_DURATION = 3000; // Duración del fade de música en milisegundos (para Audio API)
|
static constexpr int MUSIC_FADE_DURATION = 3000; // Duración del fade de música en milisegundos (para Audio API)
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
std::vector<std::shared_ptr<SurfaceAnimatedSprite>> sprites_; // Vector con todos los sprites a dibujar
|
std::vector<std::shared_ptr<SurfaceAnimatedSprite>> sprites_; // Vector con todos los sprites a dibujar
|
||||||
@@ -68,26 +68,25 @@ class Ending2 {
|
|||||||
float sprite_max_width_ = 0; // El valor de ancho del sprite mas ancho
|
float sprite_max_width_ = 0; // El valor de ancho del sprite mas ancho
|
||||||
float sprite_max_height_ = 0; // El valor de alto del sprite mas alto
|
float sprite_max_height_ = 0; // El valor de alto del sprite mas alto
|
||||||
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
float state_time_ = 0.0F; // Tiempo acumulado en el estado actual
|
||||||
float current_delta_ = 0.0F; // Delta time del frame actual
|
|
||||||
State state_; // Controla el estado de la clase
|
State state_; // Controla el estado de la clase
|
||||||
|
|
||||||
// --- Fucniones ---
|
// --- Fucniones ---
|
||||||
void update(); // Actualiza el objeto
|
void update(); // Actualiza el objeto
|
||||||
void render(); // Dibuja el final en pantalla
|
void render(); // Dibuja el final en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateState(float delta_time); // Actualiza el estado
|
void updateState(float delta_time); // Actualiza el estado
|
||||||
void transitionToState(EndingState new_state); // Transición entre estados
|
void transitionToState(EndingState new_state); // Transición entre estados
|
||||||
void iniSpriteList(); // Inicializa la lista de sprites
|
void iniSpriteList(); // Inicializa la lista de sprites
|
||||||
void loadSprites(); // Carga todos los sprites desde una lista
|
void loadSprites(); // Carga todos los sprites desde una lista
|
||||||
void updateSprites(float delta); // Actualiza los sprites
|
void updateSprites(float delta); // Actualiza los sprites
|
||||||
void updateTextSprites(float delta); // Actualiza los sprites de texto
|
void updateTextSprites(float delta); // Actualiza los sprites de texto
|
||||||
void updateTexts(float delta); // Actualiza los sprites de texto del final
|
void updateTexts(float delta); // Actualiza los sprites de texto del final
|
||||||
void renderSprites(); // Dibuja los sprites
|
void renderSprites(); // Dibuja los sprites
|
||||||
void renderSpriteTexts(); // Dibuja los sprites con el texto
|
void renderSpriteTexts(); // Dibuja los sprites con el texto
|
||||||
void renderTexts(); // Dibuja los sprites con el texto del final
|
void renderTexts(); // Dibuja los sprites con el texto del final
|
||||||
void placeSprites(); // Coloca los sprites en su sito
|
void placeSprites(); // Coloca los sprites en su sito
|
||||||
void createSpriteTexts(); // Crea los sprites con las texturas con los textos
|
void createSpriteTexts(); // Crea los sprites con las texturas con los textos
|
||||||
void createTexts(); // Crea los sprites con las texturas con los textos del final
|
void createTexts(); // Crea los sprites con las texturas con los textos del final
|
||||||
void updateFinalFade(); // Actualiza el fade final
|
void updateFinalFade(); // Actualiza el fade final
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,8 +5,9 @@
|
|||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT
|
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
|
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
|
||||||
@@ -14,7 +15,6 @@
|
|||||||
#include "core/resources/resource.hpp" // Para ResourceRoom, Resource
|
#include "core/resources/resource.hpp" // Para ResourceRoom, Resource
|
||||||
#include "core/system/debug.hpp" // Para Debug
|
#include "core/system/debug.hpp" // Para Debug
|
||||||
#include "core/system/global_events.hpp" // Para check
|
#include "core/system/global_events.hpp" // Para check
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
|
||||||
#include "game/gameplay/cheevos.hpp" // Para Cheevos
|
#include "game/gameplay/cheevos.hpp" // Para Cheevos
|
||||||
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
|
#include "game/gameplay/item_tracker.hpp" // Para ItemTracker
|
||||||
#include "game/gameplay/room.hpp" // Para Room, RoomData
|
#include "game/gameplay/room.hpp" // Para Room, RoomData
|
||||||
@@ -69,30 +69,32 @@ Game::~Game() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los eventos de la cola
|
// Comprueba los eventos de la cola
|
||||||
void Game::checkEvents() {
|
void Game::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
checkDebugEvents(event);
|
handleDebugEvents(event);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el teclado
|
// Comprueba el teclado
|
||||||
void Game::checkInput() {
|
void Game::handleInput() {
|
||||||
if (Input::get()->checkInput(InputAction::TOGGLE_MUSIC, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
Input::get()->update();
|
||||||
|
|
||||||
|
if (Input::get()->checkAction(InputAction::TOGGLE_MUSIC, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
board_->music = !board_->music;
|
board_->music = !board_->music;
|
||||||
board_->music ? Audio::get()->resumeMusic() : Audio::get()->pauseMusic();
|
board_->music ? Audio::get()->resumeMusic() : Audio::get()->pauseMusic();
|
||||||
Notifier::get()->show({"MUSIC " + std::string(board_->music ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
Notifier::get()->show({"MUSIC " + std::string(board_->music ? "ENABLED" : "DISABLED")}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (Input::get()->checkInput(InputAction::PAUSE, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
else if (Input::get()->checkAction(InputAction::PAUSE, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
togglePause();
|
togglePause();
|
||||||
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER);
|
Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}, NotificationText::CENTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
GlobalInputs::check();
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle para el juego
|
// Bucle para el juego
|
||||||
@@ -104,7 +106,6 @@ void Game::run() {
|
|||||||
|
|
||||||
while (SceneManager::current == SceneManager::Scene::GAME || SceneManager::current == SceneManager::Scene::DEMO) {
|
while (SceneManager::current == SceneManager::Scene::GAME || SceneManager::current == SceneManager::Scene::DEMO) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,8 +119,8 @@ void Game::update() {
|
|||||||
// Calcula el delta time
|
// Calcula el delta time
|
||||||
const float DELTA_TIME = delta_timer_.tick();
|
const float DELTA_TIME = delta_timer_.tick();
|
||||||
|
|
||||||
// Comprueba el teclado
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
Debug::get()->clear();
|
Debug::get()->clear();
|
||||||
@@ -143,7 +144,8 @@ void Game::update() {
|
|||||||
keepMusicPlaying();
|
keepMusicPlaying();
|
||||||
updateBlackScreen(DELTA_TIME);
|
updateBlackScreen(DELTA_TIME);
|
||||||
|
|
||||||
Screen::get()->update(DELTA_TIME);
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
|
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
updateDebugInfo();
|
updateDebugInfo();
|
||||||
@@ -213,7 +215,7 @@ void Game::renderDebugInfo() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los eventos
|
// Comprueba los eventos
|
||||||
void Game::checkDebugEvents(const SDL_Event& event) {
|
void Game::handleDebugEvents(const SDL_Event& event) {
|
||||||
if (event.type == SDL_EVENT_KEY_DOWN && static_cast<int>(event.key.repeat) == 0) {
|
if (event.type == SDL_EVENT_KEY_DOWN && static_cast<int>(event.key.repeat) == 0) {
|
||||||
switch (event.key.key) {
|
switch (event.key.key) {
|
||||||
case SDL_SCANCODE_G:
|
case SDL_SCANCODE_G:
|
||||||
@@ -588,8 +590,8 @@ void Game::keepMusicPlaying() {
|
|||||||
|
|
||||||
// Si la música no está sonando
|
// Si la música no está sonando
|
||||||
if (Audio::get()->getMusicState() == Audio::MusicState::STOPPED) {
|
if (Audio::get()->getMusicState() == Audio::MusicState::STOPPED) {
|
||||||
Audio::get()->playMusic(MUSIC_PATH);
|
Audio::get()->playMusic(MUSIC_PATH);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// DEMO MODE: Inicializa las variables para el modo demo
|
// DEMO MODE: Inicializa las variables para el modo demo
|
||||||
|
|||||||
@@ -82,10 +82,10 @@ class Game {
|
|||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza el juego, las variables, comprueba la entrada, etc.
|
void update(); // Actualiza el juego, las variables, comprueba la entrada, etc.
|
||||||
void render(); // Pinta los objetos en pantalla
|
void render(); // Pinta los objetos en pantalla
|
||||||
void checkEvents(); // Comprueba los eventos de la cola
|
void handleEvents(); // Comprueba los eventos de la cola
|
||||||
void renderRoomName(); // Escribe el nombre de la pantalla
|
void renderRoomName(); // Escribe el nombre de la pantalla
|
||||||
auto changeRoom(const std::string& room_path) -> bool; // Cambia de habitación
|
auto changeRoom(const std::string& room_path) -> bool; // Cambia de habitación
|
||||||
void checkInput(); // Comprueba el teclado
|
void handleInput(); // Comprueba el teclado
|
||||||
void checkPlayerIsOnBorder(); // Comprueba si el jugador esta en el borde de la pantalla y actua
|
void checkPlayerIsOnBorder(); // Comprueba si el jugador esta en el borde de la pantalla y actua
|
||||||
auto checkPlayerAndEnemies() -> bool; // Comprueba las colisiones del jugador con los enemigos
|
auto checkPlayerAndEnemies() -> bool; // Comprueba las colisiones del jugador con los enemigos
|
||||||
void checkPlayerAndItems(); // Comprueba las colisiones del jugador con los objetos
|
void checkPlayerAndItems(); // Comprueba las colisiones del jugador con los objetos
|
||||||
@@ -110,8 +110,8 @@ class Game {
|
|||||||
void demoInit(); // DEMO MODE: Inicializa las variables para el modo demo
|
void demoInit(); // DEMO MODE: Inicializa las variables para el modo demo
|
||||||
void demoCheckRoomChange(float delta_time); // DEMO MODE: Comprueba si se ha de cambiar de habitación
|
void demoCheckRoomChange(float delta_time); // DEMO MODE: Comprueba si se ha de cambiar de habitación
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
void updateDebugInfo(); // Pone la información de debug en pantalla
|
void updateDebugInfo(); // Pone la información de debug en pantalla
|
||||||
static void renderDebugInfo(); // Pone la información de debug en pantalla
|
static void renderDebugInfo(); // Pone la información de debug en pantalla
|
||||||
void checkDebugEvents(const SDL_Event& event); // Comprueba los eventos
|
void handleDebugEvents(const SDL_Event& event); // Comprueba los eventos
|
||||||
#endif
|
#endif
|
||||||
};
|
};
|
||||||
@@ -5,13 +5,14 @@
|
|||||||
#include <algorithm> // Para min, max
|
#include <algorithm> // Para min, max
|
||||||
#include <string> // Para basic_string, operator+, to_string
|
#include <string> // Para basic_string, operator+, to_string
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
|
#include "core/input/input.hpp" // Para Input
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
#include "core/rendering/surface_animated_sprite.hpp" // Para SAnimatedSprite
|
||||||
#include "core/rendering/text.hpp" // Para TEXT_CENTER, TEXT_COLOR, Text
|
#include "core/rendering/text.hpp" // Para TEXT_CENTER, TEXT_COLOR, Text
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
#include "core/system/global_events.hpp" // Para check
|
#include "core/system/global_events.hpp" // Para check
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
|
||||||
#include "game/options.hpp" // Para Options, options, OptionsStats, Secti...
|
#include "game/options.hpp" // Para Options, options, OptionsStats, Secti...
|
||||||
#include "game/scene_manager.hpp" // Para SceneManager
|
#include "game/scene_manager.hpp" // Para SceneManager
|
||||||
#include "utils/defines.hpp" // Para GAMECANVAS_CENTER_X
|
#include "utils/defines.hpp" // Para GAMECANVAS_CENTER_X
|
||||||
@@ -45,24 +46,19 @@ GameOver::GameOver()
|
|||||||
// Actualiza el objeto
|
// Actualiza el objeto
|
||||||
void GameOver::update() {
|
void GameOver::update() {
|
||||||
// Obtiene el delta time desde el último frame
|
// Obtiene el delta time desde el último frame
|
||||||
const float delta = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
elapsed_time_ += delta;
|
elapsed_time_ += DELTA_TIME;
|
||||||
|
|
||||||
// Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza el estado de la escena
|
updateState(); // Actualiza el estado de la escena
|
||||||
updateState();
|
updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
|
||||||
|
player_sprite_->update(DELTA_TIME); // Actualiza el sprite
|
||||||
|
tv_sprite_->update(DELTA_TIME); // Actualiza el sprite
|
||||||
|
|
||||||
// Actualiza el color usado para renderizar los textos e imagenes
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
updateColor();
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
|
|
||||||
// Actualiza los dos sprites con delta time
|
|
||||||
player_sprite_->update(delta);
|
|
||||||
tv_sprite_->update(delta);
|
|
||||||
|
|
||||||
// Actualiza el objeto Screen
|
|
||||||
Screen::get()->update(delta);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja el final en pantalla
|
// Dibuja el final en pantalla
|
||||||
@@ -95,23 +91,23 @@ void GameOver::render() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void GameOver::checkEvents() {
|
void GameOver::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void GameOver::checkInput() {
|
void GameOver::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle principal
|
// Bucle principal
|
||||||
void GameOver::run() {
|
void GameOver::run() {
|
||||||
while (SceneManager::current == SceneManager::Scene::GAME_OVER) {
|
while (SceneManager::current == SceneManager::Scene::GAME_OVER) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,35 +19,35 @@ class GameOver {
|
|||||||
private:
|
private:
|
||||||
// --- Estados ---
|
// --- Estados ---
|
||||||
enum class State {
|
enum class State {
|
||||||
WAITING, // Espera inicial antes de empezar
|
WAITING, // Espera inicial antes de empezar
|
||||||
FADE_IN, // Fade in de colores desde black
|
FADE_IN, // Fade in de colores desde black
|
||||||
DISPLAY, // Mostrando contenido con color brillante
|
DISPLAY, // Mostrando contenido con color brillante
|
||||||
FADE_OUT, // Fade out hacia black
|
FADE_OUT, // Fade out hacia black
|
||||||
ENDING, // Pantalla en negro antes de salir
|
ENDING, // Pantalla en negro antes de salir
|
||||||
TRANSITION // Cambio a logo
|
TRANSITION // Cambio a logo
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Constantes de Duración (segundos) ---
|
// --- Constantes de Duración (segundos) ---
|
||||||
static constexpr float WAITING_DURATION = 0.8f; // Espera inicial
|
static constexpr float WAITING_DURATION = 0.8f; // Espera inicial
|
||||||
static constexpr float FADE_IN_DURATION = 0.32f; // Duración del fade in
|
static constexpr float FADE_IN_DURATION = 0.32f; // Duración del fade in
|
||||||
static constexpr float DISPLAY_DURATION = 4.64f; // Duración mostrando contenido
|
static constexpr float DISPLAY_DURATION = 4.64f; // Duración mostrando contenido
|
||||||
static constexpr float FADE_OUT_DURATION = 0.32f; // Duración del fade out
|
static constexpr float FADE_OUT_DURATION = 0.32f; // Duración del fade out
|
||||||
static constexpr float ENDING_DURATION = 1.12f; // Espera en negro antes de salir
|
static constexpr float ENDING_DURATION = 1.12f; // Espera en negro antes de salir
|
||||||
|
|
||||||
// --- Constantes de Posición ---
|
// --- Constantes de Posición ---
|
||||||
static constexpr int TEXT_Y = 32; // Posición Y del texto principal
|
static constexpr int TEXT_Y = 32; // Posición Y del texto principal
|
||||||
static constexpr int SPRITE_Y_OFFSET = 30; // Offset Y para sprites desde TEXT_Y
|
static constexpr int SPRITE_Y_OFFSET = 30; // Offset Y para sprites desde TEXT_Y
|
||||||
static constexpr int PLAYER_X_OFFSET = 10; // Offset X del jugador desde el centro
|
static constexpr int PLAYER_X_OFFSET = 10; // Offset X del jugador desde el centro
|
||||||
static constexpr int TV_X_OFFSET = 10; // Offset X del TV desde el centro
|
static constexpr int TV_X_OFFSET = 10; // Offset X del TV desde el centro
|
||||||
static constexpr int ITEMS_Y_OFFSET = 80; // Offset Y del texto de items desde TEXT_Y
|
static constexpr int ITEMS_Y_OFFSET = 80; // Offset Y del texto de items desde TEXT_Y
|
||||||
static constexpr int ROOMS_Y_OFFSET = 90; // Offset Y del texto de rooms desde TEXT_Y
|
static constexpr int ROOMS_Y_OFFSET = 90; // Offset Y del texto de rooms desde TEXT_Y
|
||||||
static constexpr int NIGHTMARE_TITLE_Y_OFFSET = 110; // Offset Y del título nightmare desde TEXT_Y
|
static constexpr int NIGHTMARE_TITLE_Y_OFFSET = 110; // Offset Y del título nightmare desde TEXT_Y
|
||||||
static constexpr int NIGHTMARE_TEXT_Y_OFFSET = 120; // Offset Y del texto nightmare desde TEXT_Y
|
static constexpr int NIGHTMARE_TEXT_Y_OFFSET = 120; // Offset Y del texto nightmare desde TEXT_Y
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
std::shared_ptr<SurfaceAnimatedSprite> player_sprite_; // Sprite con el jugador
|
std::shared_ptr<SurfaceAnimatedSprite> player_sprite_; // Sprite con el jugador
|
||||||
std::shared_ptr<SurfaceAnimatedSprite> tv_sprite_; // Sprite con el televisor
|
std::shared_ptr<SurfaceAnimatedSprite> tv_sprite_; // Sprite con el televisor
|
||||||
std::shared_ptr<DeltaTimer> delta_timer_; // Timer para time-based logic
|
std::shared_ptr<DeltaTimer> delta_timer_; // Timer para time-based logic
|
||||||
|
|
||||||
// --- Variables ---
|
// --- Variables ---
|
||||||
State state_ = State::WAITING; // Estado actual de la escena
|
State state_ = State::WAITING; // Estado actual de la escena
|
||||||
@@ -56,11 +56,11 @@ class GameOver {
|
|||||||
Uint8 color_; // Color usado para el texto y los sprites
|
Uint8 color_; // Color usado para el texto y los sprites
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza el objeto
|
void update(); // Actualiza el objeto
|
||||||
void render(); // Dibuja el final en pantalla
|
void render(); // Dibuja el final en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateState(); // Actualiza el estado y transiciones
|
void updateState(); // Actualiza el estado y transiciones
|
||||||
void updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
|
void updateColor(); // Actualiza el color usado para renderizar los textos e imagenes
|
||||||
void renderSprites(); // Dibuja los sprites
|
void renderSprites(); // Dibuja los sprites
|
||||||
};
|
};
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
|
#include "core/input/input.hpp" // Para Input
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
@@ -49,16 +50,17 @@ LoadingScreen::~LoadingScreen() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void LoadingScreen::checkEvents() {
|
void LoadingScreen::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void LoadingScreen::checkInput() {
|
void LoadingScreen::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inicializa el array de índices de líneas (imita el direccionamiento de memoria del Spectrum)
|
// Inicializa el array de índices de líneas (imita el direccionamiento de memoria del Spectrum)
|
||||||
@@ -323,7 +325,9 @@ void LoadingScreen::update() {
|
|||||||
// Obtener delta time desde el último frame
|
// Obtener delta time desde el último frame
|
||||||
const float DELTA_TIME = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
|
|
||||||
checkInput(); // Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
|
handleInput(); // Comprueba las entradas
|
||||||
|
|
||||||
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
|
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
|
||||||
|
|
||||||
// Actualizar la carga según el estado actual
|
// Actualizar la carga según el estado actual
|
||||||
@@ -352,8 +356,8 @@ void LoadingScreen::update() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Singletones
|
// Singletones
|
||||||
Audio::update(); // Actualiza el objeto Audio
|
Audio::update(); // Actualiza el objeto Audio
|
||||||
Screen::get()->update(); // Actualiza el objeto Screen
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dibuja en pantalla
|
// Dibuja en pantalla
|
||||||
@@ -384,7 +388,6 @@ void LoadingScreen::run() {
|
|||||||
|
|
||||||
while (SceneManager::current == SceneManager::Scene::LOADING_SCREEN) {
|
while (SceneManager::current == SceneManager::Scene::LOADING_SCREEN) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -77,8 +77,8 @@ class LoadingScreen {
|
|||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza las variables
|
void update(); // Actualiza las variables
|
||||||
void render(); // Dibuja en pantalla
|
void render(); // Dibuja en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateState(float delta_time); // Actualiza el estado actual
|
void updateState(float delta_time); // Actualiza el estado actual
|
||||||
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
||||||
void updateMonoLoad(float delta_time); // Gestiona la carga monocromática (time-based)
|
void updateMonoLoad(float delta_time); // Gestiona la carga monocromática (time-based)
|
||||||
|
|||||||
@@ -4,7 +4,9 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para std::clamp
|
#include <algorithm> // Para std::clamp
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
|
#include "core/input/input.hpp" // Para Input
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
@@ -39,16 +41,17 @@ Logo::Logo()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Logo::checkEvents() {
|
void Logo::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Logo::checkInput() {
|
void Logo::handleInput() {
|
||||||
GlobalInputs::check();
|
Input::get()->update();
|
||||||
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Gestiona el logo de JAILGAME (time-based)
|
// Gestiona el logo de JAILGAME (time-based)
|
||||||
@@ -180,10 +183,14 @@ void Logo::update() {
|
|||||||
// Obtener delta time desde el último frame
|
// Obtener delta time desde el último frame
|
||||||
const float DELTA_TIME = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
|
|
||||||
checkInput(); // Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
|
handleInput(); // Comprueba las entradas
|
||||||
updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
|
|
||||||
updateTextureColors(); // Gestiona el color de las texturas
|
updateState(DELTA_TIME); // Actualiza el estado y gestiona transiciones
|
||||||
|
updateJAILGAMES(DELTA_TIME); // Gestiona el logo de JAILGAME
|
||||||
|
updateTextureColors(); // Gestiona el color de las texturas
|
||||||
|
|
||||||
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,7 +214,6 @@ void Logo::render() {
|
|||||||
void Logo::run() {
|
void Logo::run() {
|
||||||
while (SceneManager::current == SceneManager::Scene::LOGO) {
|
while (SceneManager::current == SceneManager::Scene::LOGO) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,8 +57,8 @@ class Logo {
|
|||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza las variables
|
void update(); // Actualiza las variables
|
||||||
void render(); // Dibuja en pantalla
|
void render(); // Dibuja en pantalla
|
||||||
static void checkEvents(); // Comprueba el manejador de eventos
|
static void handleEvents(); // Comprueba el manejador de eventos
|
||||||
static void checkInput(); // Comprueba las entradas
|
static void handleInput(); // Comprueba las entradas
|
||||||
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based)
|
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based)
|
||||||
void updateTextureColors(); // Gestiona el color de las texturas
|
void updateTextureColors(); // Gestiona el color de las texturas
|
||||||
void updateState(float delta_time); // Actualiza el estado actual
|
void updateState(float delta_time); // Actualiza el estado actual
|
||||||
|
|||||||
@@ -4,8 +4,9 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para clamp
|
#include <algorithm> // Para clamp
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/input/global_inputs.hpp" // Para check
|
#include "core/input/global_inputs.hpp" // Para check
|
||||||
#include "core/input/input.hpp" // Para Input, InputAction, INPUT_DO_NOT_ALLOW_REPEAT, REP...
|
#include "core/input/input.hpp" // Para Input, InputAction, Input::DO_NOT_ALLOW_REPEAT, REP...
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
@@ -30,8 +31,7 @@ Title::Title()
|
|||||||
first_active_letter_(0),
|
first_active_letter_(0),
|
||||||
last_active_letter_(0),
|
last_active_letter_(0),
|
||||||
state_time_(0.0F),
|
state_time_(0.0F),
|
||||||
fade_accumulator_(0.0F),
|
fade_accumulator_(0.0F) {
|
||||||
current_delta_(0.0F) {
|
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
state_ = SceneManager::options == SceneManager::Options::TITLE_WITH_LOADING_SCREEN ? State::SHOW_LOADING_SCREEN : State::SHOW_MENU;
|
state_ = SceneManager::options == SceneManager::Options::TITLE_WITH_LOADING_SCREEN ? State::SHOW_LOADING_SCREEN : State::SHOW_MENU;
|
||||||
SceneManager::current = SceneManager::Scene::TITLE;
|
SceneManager::current = SceneManager::Scene::TITLE;
|
||||||
@@ -72,10 +72,10 @@ void Title::initMarquee() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el manejador de eventos
|
// Comprueba el manejador de eventos
|
||||||
void Title::checkEvents() {
|
void Title::handleEvents() {
|
||||||
SDL_Event event;
|
SDL_Event event;
|
||||||
while (SDL_PollEvent(&event)) {
|
while (SDL_PollEvent(&event)) {
|
||||||
GlobalEvents::check(event);
|
GlobalEvents::handle(event);
|
||||||
|
|
||||||
// Solo se comprueban estas teclas si no está activo el menu de logros
|
// Solo se comprueban estas teclas si no está activo el menu de logros
|
||||||
if (event.type == SDL_EVENT_KEY_DOWN) {
|
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||||
@@ -99,24 +99,26 @@ void Title::checkEvents() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba las entradas
|
// Comprueba las entradas
|
||||||
void Title::checkInput() {
|
void Title::handleInput(float delta_time) {
|
||||||
|
Input::get()->update();
|
||||||
|
|
||||||
if (show_cheevos_) {
|
if (show_cheevos_) {
|
||||||
if (Input::get()->checkInput(InputAction::DOWN, INPUT_ALLOW_REPEAT)) {
|
if (Input::get()->checkAction(InputAction::RIGHT, Input::ALLOW_REPEAT)) {
|
||||||
moveCheevosList(1, current_delta_);
|
moveCheevosList(1, delta_time);
|
||||||
} else if (Input::get()->checkInput(InputAction::UP, INPUT_ALLOW_REPEAT)) {
|
} else if (Input::get()->checkAction(InputAction::LEFT, Input::ALLOW_REPEAT)) {
|
||||||
moveCheevosList(0, current_delta_);
|
moveCheevosList(0, delta_time);
|
||||||
} else if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
} else if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
hideCheevosList();
|
hideCheevosList();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Input::get()->checkInput(InputAction::ACCEPT, INPUT_DO_NOT_ALLOW_REPEAT)) {
|
if (Input::get()->checkAction(InputAction::ACCEPT, Input::DO_NOT_ALLOW_REPEAT)) {
|
||||||
if (state_ == State::SHOW_LOADING_SCREEN) {
|
if (state_ == State::SHOW_LOADING_SCREEN) {
|
||||||
transitionToState(State::FADE_LOADING_SCREEN);
|
transitionToState(State::FADE_LOADING_SCREEN);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GlobalInputs::check();
|
GlobalInputs::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la marquesina
|
// Actualiza la marquesina
|
||||||
@@ -169,16 +171,15 @@ void Title::renderMarquee() {
|
|||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void Title::update() {
|
void Title::update() {
|
||||||
// Obtener delta time
|
// Obtener delta time
|
||||||
current_delta_ = delta_timer_->tick();
|
const float DELTA_TIME = delta_timer_->tick();
|
||||||
|
|
||||||
// Comprueba las entradas
|
handleEvents(); // Comprueba los eventos
|
||||||
checkInput();
|
handleInput(DELTA_TIME); // Comprueba las entradas
|
||||||
|
|
||||||
// Actualiza la pantalla
|
updateState(DELTA_TIME); // Actualiza el estado actual
|
||||||
Screen::get()->update(current_delta_);
|
|
||||||
|
|
||||||
// Actualiza el estado actual
|
Audio::get()->update(); // Actualiza el objeto Audio
|
||||||
updateState(current_delta_);
|
Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado actual
|
// Actualiza el estado actual
|
||||||
@@ -263,7 +264,6 @@ void Title::render() {
|
|||||||
void Title::run() {
|
void Title::run() {
|
||||||
while (SceneManager::current == SceneManager::Scene::TITLE) {
|
while (SceneManager::current == SceneManager::Scene::TITLE) {
|
||||||
update();
|
update();
|
||||||
checkEvents();
|
|
||||||
render();
|
render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,13 +69,12 @@ class Title {
|
|||||||
State state_; // Estado en el que se encuentra el bucle principal
|
State state_; // Estado en el que se encuentra el bucle principal
|
||||||
float state_time_; // Tiempo acumulado en el estado actual
|
float state_time_; // Tiempo acumulado en el estado actual
|
||||||
float fade_accumulator_; // Acumulador para controlar el fade por tiempo
|
float fade_accumulator_; // Acumulador para controlar el fade por tiempo
|
||||||
float current_delta_; // Delta time del frame actual
|
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void update(); // Actualiza las variables
|
void update(); // Actualiza las variables
|
||||||
void render(); // Dibuja en pantalla
|
void render(); // Dibuja en pantalla
|
||||||
void checkEvents(); // Comprueba el manejador de eventos
|
void handleEvents(); // Comprueba el manejador de eventos
|
||||||
void checkInput(); // Comprueba las entradas
|
void handleInput(float delta_time); // Comprueba las entradas
|
||||||
void updateState(float delta_time); // Actualiza el estado actual
|
void updateState(float delta_time); // Actualiza el estado actual
|
||||||
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
void transitionToState(State new_state); // Transiciona a un nuevo estado
|
||||||
void initMarquee(); // Inicializa la marquesina
|
void initMarquee(); // Inicializa la marquesina
|
||||||
|
|||||||
@@ -8,12 +8,12 @@
|
|||||||
#include <string> // Para string, basic_string
|
#include <string> // Para string, basic_string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
|
#include "core/audio/audio.hpp" // Para Audio
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/surface.hpp" // Para Surface
|
#include "core/rendering/surface.hpp" // Para Surface
|
||||||
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
#include "core/rendering/surface_sprite.hpp" // Para SSprite
|
||||||
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
|
#include "core/rendering/text.hpp" // Para Text, TEXT_CENTER, TEXT_COLOR
|
||||||
#include "core/resources/resource.hpp" // Para Resource
|
#include "core/resources/resource.hpp" // Para Resource
|
||||||
#include "core/audio/audio.hpp" // Para Audio
|
|
||||||
#include "game/options.hpp" // Para Options, options, NotificationPosition
|
#include "game/options.hpp" // Para Options, options, NotificationPosition
|
||||||
#include "utils/delta_timer.hpp" // Para DeltaTimer
|
#include "utils/delta_timer.hpp" // Para DeltaTimer
|
||||||
#include "utils/utils.hpp" // Para PaletteColor
|
#include "utils/utils.hpp" // Para PaletteColor
|
||||||
|
|||||||
@@ -62,8 +62,8 @@ class Notifier {
|
|||||||
explicit Notification() = default;
|
explicit Notification() = default;
|
||||||
};
|
};
|
||||||
|
|
||||||
std::shared_ptr<Surface> icon_surface_; // Textura para los iconos de las notificaciones
|
std::shared_ptr<Surface> icon_surface_; // Textura para los iconos de las notificaciones
|
||||||
std::shared_ptr<Text> text_; // Objeto para dibujar texto
|
std::shared_ptr<Text> text_; // Objeto para dibujar texto
|
||||||
std::unique_ptr<DeltaTimer> delta_timer_; // Timer for frame-independent animations
|
std::unique_ptr<DeltaTimer> delta_timer_; // Timer for frame-independent animations
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
|
|||||||
@@ -1,27 +1,28 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
|
||||||
class DeltaTimer {
|
class DeltaTimer {
|
||||||
public:
|
public:
|
||||||
DeltaTimer() noexcept;
|
DeltaTimer() noexcept;
|
||||||
|
|
||||||
// Calcula delta en segundos y actualiza el contador interno
|
// Calcula delta en segundos y actualiza el contador interno
|
||||||
auto tick() noexcept -> float;
|
auto tick() noexcept -> float;
|
||||||
|
|
||||||
// Devuelve el delta estimado desde el último tick sin actualizar el contador
|
// Devuelve el delta estimado desde el último tick sin actualizar el contador
|
||||||
[[nodiscard]] auto peek() const noexcept -> float;
|
[[nodiscard]] auto peek() const noexcept -> float;
|
||||||
|
|
||||||
// Reinicia el contador al valor actual o al valor pasado (en performance counter ticks)
|
// Reinicia el contador al valor actual o al valor pasado (en performance counter ticks)
|
||||||
void reset(Uint64 counter = 0) noexcept;
|
void reset(Uint64 counter = 0) noexcept;
|
||||||
|
|
||||||
// Escala el tiempo retornado por tick/peek, por defecto 1.0f
|
// Escala el tiempo retornado por tick/peek, por defecto 1.0f
|
||||||
void setTimeScale(float scale) noexcept;
|
void setTimeScale(float scale) noexcept;
|
||||||
[[nodiscard]] auto getTimeScale() const noexcept -> float;
|
[[nodiscard]] auto getTimeScale() const noexcept -> float;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
Uint64 last_counter_;
|
Uint64 last_counter_;
|
||||||
double perf_freq_;
|
double perf_freq_;
|
||||||
float time_scale_;
|
float time_scale_;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user