renombrades extensions .h a .hpp
This commit is contained in:
@@ -1,43 +0,0 @@
|
|||||||
# Directrices de Desarrollo - Coffee Crisis Arcade Edition
|
|
||||||
|
|
||||||
## Directrices Principales Confirmadas
|
|
||||||
|
|
||||||
### 1. **Sistema Temporal**
|
|
||||||
- **TODO migrado de frame based a time based**
|
|
||||||
- **Delta time en segundos (float)**
|
|
||||||
- **Unidades de tiempo: SOLO segundos** (no frames, no milisegundos)
|
|
||||||
|
|
||||||
### 2. **Contadores y Timers**
|
|
||||||
- **CRECIENTES**: para sistemas con múltiples eventos temporales (timeline)
|
|
||||||
- Patrón: `elapsed_time += deltaTime; if (elapsed_time >= EVENT_TIME) { /* acción */ }`
|
|
||||||
- **DECRECIENTES**: para contadores con diferentes valores de inicialización
|
|
||||||
- Patrón: `timer -= deltaTime; if (timer <= 0.0f) { /* acción */ timer = DURATION; }`
|
|
||||||
|
|
||||||
### 3. **Números Mágicos**
|
|
||||||
- **Definidos en constantes**
|
|
||||||
- **Preferencia**: cabecera de la clase
|
|
||||||
- **Excepción**: si es algo local a un método específico
|
|
||||||
|
|
||||||
## Problemas Pendientes de Reparación (game.cpp)
|
|
||||||
|
|
||||||
### ❌ PENDIENTES
|
|
||||||
1. **param.fade.post_duration_ms verification** (líneas 89, 1671)
|
|
||||||
2. **setRotateSpeed verification** (línea 797)
|
|
||||||
3. **TOTAL_DEMO_DATA - 200 magic number** (línea 1669)
|
|
||||||
4. **Comprehensive magic number search** - Buscar 100, 150, 200, 250, 300, 400, 500, 1000
|
|
||||||
|
|
||||||
### 4. **Velocidades y Aceleraciones**
|
|
||||||
- **Velocidades**: pixels/segundo
|
|
||||||
- **Aceleraciones**: pixels/segundo²
|
|
||||||
|
|
||||||
### 5. **Documentación de Conversiones**
|
|
||||||
- **Comentarios explicativos** en cambios críticos de timing
|
|
||||||
- Documentar conversiones frame→tiempo en el código
|
|
||||||
|
|
||||||
### 6. **Patrón de Constantes**
|
|
||||||
- Crear constantes para valores repetidos (evitar duplicación)
|
|
||||||
- Nombres descriptivos para constantes de tiempo
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Estado**: Directrices completas confirmadas
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "animated_sprite.h"
|
#include "animated_sprite.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError, SDL_FRect
|
#include <SDL3/SDL.h> // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError, SDL_FRect
|
||||||
|
|
||||||
@@ -9,9 +9,9 @@
|
|||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
|
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
#include "resource_helper.hpp" // Para ResourceHelper
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "utils.h" // Para printWithDots
|
#include "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) -> AnimationsFileBuffer {
|
auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffer {
|
||||||
@@ -94,12 +94,12 @@ void AnimatedSprite::animate(float deltaTime) {
|
|||||||
|
|
||||||
// Acumular tiempo transcurrido
|
// Acumular tiempo transcurrido
|
||||||
animations_[current_animation_].time_accumulator += deltaTime;
|
animations_[current_animation_].time_accumulator += deltaTime;
|
||||||
|
|
||||||
// Verificar si es momento de cambiar frame
|
// Verificar si es momento de cambiar frame
|
||||||
if (animations_[current_animation_].time_accumulator >= animations_[current_animation_].speed) {
|
if (animations_[current_animation_].time_accumulator >= animations_[current_animation_].speed) {
|
||||||
animations_[current_animation_].time_accumulator -= animations_[current_animation_].speed;
|
animations_[current_animation_].time_accumulator -= animations_[current_animation_].speed;
|
||||||
animations_[current_animation_].current_frame++;
|
animations_[current_animation_].current_frame++;
|
||||||
|
|
||||||
// Si alcanza el final de la animación
|
// Si alcanza el final de la animación
|
||||||
if (animations_[current_animation_].current_frame >= animations_[current_animation_].frames.size()) {
|
if (animations_[current_animation_].current_frame >= animations_[current_animation_].frames.size()) {
|
||||||
if (animations_[current_animation_].loop == -1) { // Si no hay loop, deja el último frame
|
if (animations_[current_animation_].loop == -1) { // Si no hay loop, deja el último frame
|
||||||
@@ -110,7 +110,7 @@ void AnimatedSprite::animate(float deltaTime) {
|
|||||||
animations_[current_animation_].current_frame = animations_[current_animation_].loop;
|
animations_[current_animation_].current_frame = animations_[current_animation_].loop;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualizar el sprite clip
|
// Actualizar el sprite clip
|
||||||
updateSpriteClip();
|
updateSpriteClip();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "moving_sprite.h" // Para MovingSprite
|
#include "moving_sprite.hpp" // Para MovingSprite
|
||||||
|
|
||||||
// Declaración adelantada
|
// Declaración adelantada
|
||||||
class Texture;
|
class Texture;
|
||||||
@@ -55,7 +55,7 @@ class AnimatedSprite : public MovingSprite {
|
|||||||
~AnimatedSprite() override = default;
|
~AnimatedSprite() override = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(float deltaTime) override; // Actualiza la animación (time-based)
|
void update(float deltaTime) override; // Actualiza la animación (time-based)
|
||||||
|
|
||||||
// --- Control de animaciones ---
|
// --- Control de animaciones ---
|
||||||
void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre
|
void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "asset.h"
|
#include "asset.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogCategory, SDL_LogInfo, SDL_LogError, SDL_LogWarn
|
#include <SDL3/SDL.h> // Para SDL_LogCategory, SDL_LogInfo, SDL_LogError, SDL_LogWarn
|
||||||
|
|
||||||
@@ -10,14 +10,14 @@
|
|||||||
#include <sstream> // Para basic_istringstream
|
#include <sstream> // Para basic_istringstream
|
||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
|
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
#include "resource_helper.hpp" // Para ResourceHelper
|
||||||
#include "utils.h" // Para getFileName
|
#include "ui/logger.hpp" // Pâra Logger
|
||||||
#include "ui/logger.h" // Pâra Logger
|
#include "utils.hpp" // Para getFileName
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Asset *Asset::instance = nullptr;
|
Asset* Asset::instance = nullptr;
|
||||||
|
|
||||||
void Asset::init(const std::string &executable_path) {
|
void Asset::init(const std::string& executable_path) {
|
||||||
Asset::instance = new Asset(executable_path);
|
Asset::instance = new Asset(executable_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,12 +25,12 @@ void Asset::destroy() {
|
|||||||
delete Asset::instance;
|
delete Asset::instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto Asset::get() -> Asset * {
|
auto Asset::get() -> Asset* {
|
||||||
return Asset::instance;
|
return Asset::instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade un elemento al mapa (función auxiliar)
|
// Añade un elemento al mapa (función auxiliar)
|
||||||
void Asset::addToMap(const std::string &file_path, Type type, bool required, bool absolute) {
|
void Asset::addToMap(const std::string& file_path, Type type, bool required, bool absolute) {
|
||||||
std::string full_path = absolute ? file_path : executable_path_ + file_path;
|
std::string full_path = absolute ? file_path : executable_path_ + file_path;
|
||||||
std::string filename = getFileName(full_path);
|
std::string filename = getFileName(full_path);
|
||||||
|
|
||||||
@@ -45,13 +45,13 @@ void Asset::addToMap(const std::string &file_path, Type type, bool required, boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Añade un elemento a la lista
|
// Añade un elemento a la lista
|
||||||
void Asset::add(const std::string &file_path, Type type, bool required, bool absolute) {
|
void Asset::add(const std::string& file_path, Type type, bool required, bool absolute) {
|
||||||
addToMap(file_path, type, required, absolute);
|
addToMap(file_path, type, required, absolute);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga recursos desde un archivo de configuración con soporte para variables
|
// Carga recursos desde un archivo de configuración con soporte para variables
|
||||||
// Carga recursos desde un archivo de configuración con soporte para variables
|
// Carga recursos desde un archivo de configuración con soporte para variables
|
||||||
void Asset::loadFromFile(const std::string &config_file_path, const std::string &prefix, const std::string &system_folder) {
|
void Asset::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) {
|
||||||
std::ifstream file(config_file_path);
|
std::ifstream file(config_file_path);
|
||||||
if (!file.is_open()) {
|
if (!file.is_open()) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
@@ -96,7 +96,7 @@ void Asset::loadFromFile(const std::string &config_file_path, const std::string
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const std::string &type_str = parts[0];
|
const std::string& type_str = parts[0];
|
||||||
std::string path = parts[1];
|
std::string path = parts[1];
|
||||||
|
|
||||||
// Valores por defecto
|
// Valores por defecto
|
||||||
@@ -117,7 +117,7 @@ void Asset::loadFromFile(const std::string &config_file_path, const std::string
|
|||||||
// Añadir al mapa
|
// Añadir al mapa
|
||||||
addToMap(path, type, required, absolute);
|
addToMap(path, type, required, absolute);
|
||||||
|
|
||||||
} catch (const std::exception &e) {
|
} catch (const std::exception& e) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error parsing line %d in config file: %s",
|
"Error parsing line %d in config file: %s",
|
||||||
line_number,
|
line_number,
|
||||||
@@ -133,7 +133,7 @@ void Asset::loadFromFile(const std::string &config_file_path, const std::string
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve la ruta completa a un fichero (búsqueda O(1))
|
// Devuelve la ruta completa a un fichero (búsqueda O(1))
|
||||||
auto Asset::get(const std::string &filename) const -> std::string {
|
auto Asset::get(const std::string& filename) const -> std::string {
|
||||||
auto it = file_list_.find(filename);
|
auto it = file_list_.find(filename);
|
||||||
if (it != file_list_.end()) {
|
if (it != file_list_.end()) {
|
||||||
return it->second.file;
|
return it->second.file;
|
||||||
@@ -144,7 +144,7 @@ auto Asset::get(const std::string &filename) const -> std::string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Carga datos del archivo usando ResourceHelper
|
// Carga datos del archivo usando ResourceHelper
|
||||||
auto Asset::loadData(const std::string &filename) const -> std::vector<uint8_t> {
|
auto Asset::loadData(const std::string& filename) const -> std::vector<uint8_t> {
|
||||||
auto it = file_list_.find(filename);
|
auto it = file_list_.find(filename);
|
||||||
if (it != file_list_.end()) {
|
if (it != file_list_.end()) {
|
||||||
return ResourceHelper::loadFile(it->second.file);
|
return ResourceHelper::loadFile(it->second.file);
|
||||||
@@ -155,7 +155,7 @@ auto Asset::loadData(const std::string &filename) const -> std::vector<uint8_t>
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Verifica si un recurso existe
|
// Verifica si un recurso existe
|
||||||
auto Asset::exists(const std::string &filename) const -> bool {
|
auto Asset::exists(const std::string& filename) const -> bool {
|
||||||
return file_list_.find(filename) != file_list_.end();
|
return file_list_.find(filename) != file_list_.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,13 +163,13 @@ auto Asset::exists(const std::string &filename) const -> bool {
|
|||||||
auto Asset::check() const -> bool {
|
auto Asset::check() const -> bool {
|
||||||
bool success = true;
|
bool success = true;
|
||||||
|
|
||||||
//SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES");
|
// SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES");
|
||||||
Logger::section("CHECKING FILES", Logger::CYAN);
|
Logger::section("CHECKING FILES", Logger::CYAN);
|
||||||
|
|
||||||
// Agrupar por tipo para mostrar organizado
|
// Agrupar por tipo para mostrar organizado
|
||||||
std::unordered_map<Type, std::vector<const Item *>> by_type;
|
std::unordered_map<Type, std::vector<const Item*>> by_type;
|
||||||
|
|
||||||
for (const auto &[filename, item] : file_list_) {
|
for (const auto& [filename, item] : file_list_) {
|
||||||
if (item.required) {
|
if (item.required) {
|
||||||
by_type[item.type].push_back(&item);
|
by_type[item.type].push_back(&item);
|
||||||
}
|
}
|
||||||
@@ -185,7 +185,7 @@ auto Asset::check() const -> bool {
|
|||||||
getTypeName(asset_type).c_str());
|
getTypeName(asset_type).c_str());
|
||||||
|
|
||||||
bool type_success = true;
|
bool type_success = true;
|
||||||
for (const auto *item : by_type[asset_type]) {
|
for (const auto* item : by_type[asset_type]) {
|
||||||
if (!checkFile(item->file)) {
|
if (!checkFile(item->file)) {
|
||||||
success = false;
|
success = false;
|
||||||
type_success = false;
|
type_success = false;
|
||||||
@@ -209,7 +209,7 @@ auto Asset::check() const -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba que existe un fichero
|
// Comprueba que existe un fichero
|
||||||
auto Asset::checkFile(const std::string &path) const -> bool {
|
auto Asset::checkFile(const std::string& path) const -> bool {
|
||||||
// Construir ruta del pack usando executable_path_
|
// Construir ruta del pack usando executable_path_
|
||||||
std::string pack_path = executable_path_ + "resources.pack";
|
std::string pack_path = executable_path_ + "resources.pack";
|
||||||
bool pack_exists = std::filesystem::exists(pack_path);
|
bool pack_exists = std::filesystem::exists(pack_path);
|
||||||
@@ -226,7 +226,8 @@ auto Asset::checkFile(const std::string &path) const -> bool {
|
|||||||
|
|
||||||
if (!success) {
|
if (!success) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error: Could not open file: %s", path.c_str());
|
"Error: Could not open file: %s",
|
||||||
|
path.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
return success;
|
return success;
|
||||||
@@ -234,7 +235,7 @@ auto Asset::checkFile(const std::string &path) const -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Parsea string a Type
|
// Parsea string a Type
|
||||||
auto Asset::parseAssetType(const std::string &type_str) -> Type {
|
auto Asset::parseAssetType(const std::string& type_str) -> Type {
|
||||||
if (type_str == "BITMAP") {
|
if (type_str == "BITMAP") {
|
||||||
return Type::BITMAP;
|
return Type::BITMAP;
|
||||||
}
|
}
|
||||||
@@ -296,7 +297,7 @@ auto Asset::getTypeName(Type type) -> std::string {
|
|||||||
auto Asset::getListByType(Type type) const -> std::vector<std::string> {
|
auto Asset::getListByType(Type type) const -> std::vector<std::string> {
|
||||||
std::vector<std::string> list;
|
std::vector<std::string> list;
|
||||||
|
|
||||||
for (const auto &[filename, item] : file_list_) {
|
for (const auto& [filename, item] : file_list_) {
|
||||||
if (item.type == type) {
|
if (item.type == type) {
|
||||||
list.push_back(item.file);
|
list.push_back(item.file);
|
||||||
}
|
}
|
||||||
@@ -309,7 +310,7 @@ auto Asset::getListByType(Type type) const -> std::vector<std::string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Reemplaza variables en las rutas
|
// Reemplaza variables en las rutas
|
||||||
auto Asset::replaceVariables(const std::string &path, const std::string &prefix, const std::string &system_folder) -> std::string {
|
auto Asset::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string {
|
||||||
std::string result = path;
|
std::string result = path;
|
||||||
|
|
||||||
// Reemplazar ${PREFIX}
|
// Reemplazar ${PREFIX}
|
||||||
@@ -330,7 +331,7 @@ auto Asset::replaceVariables(const std::string &path, const std::string &prefix,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Parsea las opciones de una línea de configuración
|
// Parsea las opciones de una línea de configuración
|
||||||
auto Asset::parseOptions(const std::string &options, bool &required, bool &absolute) -> void {
|
auto Asset::parseOptions(const std::string& options, bool& required, bool& absolute) -> void {
|
||||||
if (options.empty()) {
|
if (options.empty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,20 +24,20 @@ class Asset {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// --- Métodos de singleton ---
|
// --- Métodos de singleton ---
|
||||||
static void init(const std::string &executable_path);
|
static void init(const std::string& executable_path);
|
||||||
static void destroy();
|
static void destroy();
|
||||||
static auto get() -> Asset *;
|
static auto get() -> Asset*;
|
||||||
Asset(const Asset &) = delete;
|
Asset(const Asset&) = delete;
|
||||||
auto operator=(const Asset &) -> Asset & = delete;
|
auto operator=(const Asset&) -> Asset& = delete;
|
||||||
|
|
||||||
// --- Métodos para la gestión de recursos ---
|
// --- Métodos para la gestión de recursos ---
|
||||||
void add(const std::string &file_path, Type type, bool required = true, bool absolute = false);
|
void add(const std::string& file_path, Type type, bool required = true, bool absolute = false);
|
||||||
void loadFromFile(const std::string &config_file_path, const std::string &prefix = "", const std::string &system_folder = ""); // Con soporte para variables
|
void loadFromFile(const std::string& config_file_path, const std::string& prefix = "", const std::string& system_folder = ""); // Con soporte para variables
|
||||||
[[nodiscard]] auto get(const std::string &filename) const -> std::string; // Mantener nombre original
|
[[nodiscard]] auto get(const std::string& filename) const -> std::string; // Mantener nombre original
|
||||||
[[nodiscard]] auto loadData(const std::string &filename) const -> std::vector<uint8_t>; // Carga datos del archivo
|
[[nodiscard]] auto loadData(const std::string& filename) const -> std::vector<uint8_t>; // Carga datos del archivo
|
||||||
[[nodiscard]] auto check() const -> bool;
|
[[nodiscard]] auto check() const -> bool;
|
||||||
[[nodiscard]] auto getListByType(Type type) const -> std::vector<std::string>;
|
[[nodiscard]] auto getListByType(Type type) const -> std::vector<std::string>;
|
||||||
[[nodiscard]] auto exists(const std::string &filename) const -> bool; // Nueva función para verificar existencia
|
[[nodiscard]] auto exists(const std::string& filename) const -> bool; // Nueva función para verificar existencia
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Estructuras privadas ---
|
// --- Estructuras privadas ---
|
||||||
@@ -57,12 +57,12 @@ class Asset {
|
|||||||
std::string executable_path_; // Ruta del ejecutable
|
std::string executable_path_; // Ruta del ejecutable
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
[[nodiscard]] auto checkFile(const std::string &path) const -> bool; // Verifica si un archivo existe
|
[[nodiscard]] auto checkFile(const std::string& path) const -> bool; // Verifica si un archivo existe
|
||||||
[[nodiscard]] static auto getTypeName(Type type) -> std::string; // Obtiene el nombre del tipo
|
[[nodiscard]] static auto getTypeName(Type type) -> std::string; // Obtiene el nombre del tipo
|
||||||
[[nodiscard]] static auto parseAssetType(const std::string &type_str) -> Type; // Convierte string a tipo
|
[[nodiscard]] static auto parseAssetType(const std::string& type_str) -> Type; // Convierte string a tipo
|
||||||
void addToMap(const std::string &file_path, Type type, bool required, bool absolute); // Añade archivo al mapa
|
void addToMap(const std::string& file_path, Type type, bool required, bool absolute); // Añade archivo al mapa
|
||||||
[[nodiscard]] static auto replaceVariables(const std::string &path, const std::string &prefix, const std::string &system_folder) -> std::string; // Reemplaza variables en la ruta
|
[[nodiscard]] static auto replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string; // Reemplaza variables en la ruta
|
||||||
static auto parseOptions(const std::string &options, bool &required, bool &absolute) -> void; // Parsea opciones
|
static auto parseOptions(const std::string& options, bool& required, bool& absolute) -> void; // Parsea opciones
|
||||||
|
|
||||||
// --- Constructores y destructor privados (singleton) ---
|
// --- Constructores y destructor privados (singleton) ---
|
||||||
explicit Asset(std::string executable_path) // Constructor privado
|
explicit Asset(std::string executable_path) // Constructor privado
|
||||||
@@ -70,5 +70,5 @@ class Asset {
|
|||||||
~Asset() = default; // Destructor privado
|
~Asset() = default; // Destructor privado
|
||||||
|
|
||||||
// --- Instancia singleton ---
|
// --- Instancia singleton ---
|
||||||
static Asset *instance; // Instancia única de Asset
|
static Asset* instance; // Instancia única de Asset
|
||||||
};
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "asset_integrated.h"
|
#include "asset_integrated.hpp"
|
||||||
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
@@ -6,13 +6,13 @@
|
|||||||
|
|
||||||
bool AssetIntegrated::resource_pack_enabled_ = false;
|
bool AssetIntegrated::resource_pack_enabled_ = false;
|
||||||
|
|
||||||
void AssetIntegrated::initWithResourcePack(const std::string &executable_path,
|
void AssetIntegrated::initWithResourcePack(const std::string& executable_path,
|
||||||
const std::string &resource_pack_path) {
|
const std::string& resource_pack_path) {
|
||||||
// Inicializar Asset normal
|
// Inicializar Asset normal
|
||||||
Asset::init(executable_path);
|
Asset::init(executable_path);
|
||||||
|
|
||||||
// Inicializar ResourceLoader
|
// Inicializar ResourceLoader
|
||||||
auto &loader = ResourceLoader::getInstance();
|
auto& loader = ResourceLoader::getInstance();
|
||||||
if (loader.initialize(resource_pack_path, true)) {
|
if (loader.initialize(resource_pack_path, true)) {
|
||||||
resource_pack_enabled_ = true;
|
resource_pack_enabled_ = true;
|
||||||
std::cout << "Asset system initialized with resource pack: " << resource_pack_path << std::endl;
|
std::cout << "Asset system initialized with resource pack: " << resource_pack_path << std::endl;
|
||||||
@@ -22,10 +22,10 @@ void AssetIntegrated::initWithResourcePack(const std::string &executable_path,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> AssetIntegrated::loadFile(const std::string &filename) {
|
std::vector<uint8_t> AssetIntegrated::loadFile(const std::string& filename) {
|
||||||
if (shouldUseResourcePack(filename) && resource_pack_enabled_) {
|
if (shouldUseResourcePack(filename) && resource_pack_enabled_) {
|
||||||
// Intentar cargar del pack de recursos
|
// Intentar cargar del pack de recursos
|
||||||
auto &loader = ResourceLoader::getInstance();
|
auto& loader = ResourceLoader::getInstance();
|
||||||
|
|
||||||
// Convertir ruta completa a ruta relativa para el pack
|
// Convertir ruta completa a ruta relativa para el pack
|
||||||
std::string relativePath = filename;
|
std::string relativePath = filename;
|
||||||
@@ -53,7 +53,7 @@ std::vector<uint8_t> AssetIntegrated::loadFile(const std::string &filename) {
|
|||||||
file.seekg(0, std::ios::beg);
|
file.seekg(0, std::ios::beg);
|
||||||
|
|
||||||
std::vector<uint8_t> data(fileSize);
|
std::vector<uint8_t> data(fileSize);
|
||||||
if (!file.read(reinterpret_cast<char *>(data.data()), fileSize)) {
|
if (!file.read(reinterpret_cast<char*>(data.data()), fileSize)) {
|
||||||
std::cerr << "Error: Could not read file: " << filename << std::endl;
|
std::cerr << "Error: Could not read file: " << filename << std::endl;
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
@@ -61,9 +61,9 @@ std::vector<uint8_t> AssetIntegrated::loadFile(const std::string &filename) {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool AssetIntegrated::fileExists(const std::string &filename) const {
|
bool AssetIntegrated::fileExists(const std::string& filename) const {
|
||||||
if (shouldUseResourcePack(filename) && resource_pack_enabled_) {
|
if (shouldUseResourcePack(filename) && resource_pack_enabled_) {
|
||||||
auto &loader = ResourceLoader::getInstance();
|
auto& loader = ResourceLoader::getInstance();
|
||||||
|
|
||||||
// Convertir ruta completa a ruta relativa para el pack
|
// Convertir ruta completa a ruta relativa para el pack
|
||||||
std::string relativePath = filename;
|
std::string relativePath = filename;
|
||||||
@@ -81,12 +81,12 @@ bool AssetIntegrated::fileExists(const std::string &filename) const {
|
|||||||
return std::filesystem::exists(filename);
|
return std::filesystem::exists(filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string AssetIntegrated::getSystemPath(const std::string &filename) const {
|
std::string AssetIntegrated::getSystemPath(const std::string& filename) const {
|
||||||
// Los archivos de sistema/config siempre van al filesystem
|
// Los archivos de sistema/config siempre van al filesystem
|
||||||
return filename;
|
return filename;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool AssetIntegrated::shouldUseResourcePack(const std::string &filepath) const {
|
bool AssetIntegrated::shouldUseResourcePack(const std::string& filepath) const {
|
||||||
// Los archivos que NO van al pack:
|
// Los archivos que NO van al pack:
|
||||||
// - Archivos de config/ (ahora están fuera de data/)
|
// - Archivos de config/ (ahora están fuera de data/)
|
||||||
// - Archivos con absolute=true en assets.txt
|
// - Archivos con absolute=true en assets.txt
|
||||||
|
|||||||
@@ -2,28 +2,28 @@
|
|||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
#include "asset.h"
|
#include "asset.hpp"
|
||||||
#include "resource_loader.h"
|
#include "resource_loader.hpp"
|
||||||
|
|
||||||
// Extensión de Asset que integra ResourceLoader
|
// Extensión de Asset que integra ResourceLoader
|
||||||
class AssetIntegrated : public Asset {
|
class AssetIntegrated : public Asset {
|
||||||
public:
|
public:
|
||||||
// Inicializa Asset con ResourceLoader
|
// Inicializa Asset con ResourceLoader
|
||||||
static void initWithResourcePack(const std::string &executable_path,
|
static void initWithResourcePack(const std::string& executable_path,
|
||||||
const std::string &resource_pack_path = "resources.pack");
|
const std::string& resource_pack_path = "resources.pack");
|
||||||
|
|
||||||
// Carga un archivo usando ResourceLoader como primera opción
|
// Carga un archivo usando ResourceLoader como primera opción
|
||||||
std::vector<uint8_t> loadFile(const std::string &filename);
|
std::vector<uint8_t> loadFile(const std::string& filename);
|
||||||
|
|
||||||
// Verifica si un archivo existe (pack o filesystem)
|
// Verifica si un archivo existe (pack o filesystem)
|
||||||
bool fileExists(const std::string &filename) const;
|
bool fileExists(const std::string& filename) const;
|
||||||
|
|
||||||
// Obtiene la ruta completa para archivos del sistema/config
|
// Obtiene la ruta completa para archivos del sistema/config
|
||||||
std::string getSystemPath(const std::string &filename) const;
|
std::string getSystemPath(const std::string& filename) const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static bool resource_pack_enabled_;
|
static bool resource_pack_enabled_;
|
||||||
|
|
||||||
// Determina si un archivo debe cargarse del pack o del filesystem
|
// Determina si un archivo debe cargarse del pack o del filesystem
|
||||||
bool shouldUseResourcePack(const std::string &filepath) const;
|
bool shouldUseResourcePack(const std::string& filepath) const;
|
||||||
};
|
};
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
#include "audio.h"
|
#include "audio.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_G...
|
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_G...
|
||||||
|
|
||||||
#include <algorithm> // Para clamp
|
#include <algorithm> // Para clamp
|
||||||
|
|
||||||
#include "external/jail_audio.h" // Para JA_FadeOutMusic, JA_Init, JA_PauseM...
|
#include "external/jail_audio.h" // Para JA_FadeOutMusic, JA_Init, JA_PauseM...
|
||||||
#include "options.h" // Para AudioOptions, audio, MusicOptions
|
#include "options.hpp" // Para AudioOptions, audio, MusicOptions
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Audio *Audio::instance = nullptr;
|
Audio* Audio::instance = nullptr;
|
||||||
|
|
||||||
// Inicializa la instancia única del singleton
|
// Inicializa la instancia única del singleton
|
||||||
void Audio::init() { Audio::instance = new Audio(); }
|
void Audio::init() { Audio::instance = new Audio(); }
|
||||||
@@ -18,7 +18,7 @@ void Audio::init() { Audio::instance = new Audio(); }
|
|||||||
void Audio::destroy() { delete Audio::instance; }
|
void Audio::destroy() { delete Audio::instance; }
|
||||||
|
|
||||||
// Obtiene la instancia
|
// Obtiene la instancia
|
||||||
auto Audio::get() -> Audio * { return Audio::instance; }
|
auto Audio::get() -> Audio* { return Audio::instance; }
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Audio::Audio() { initSDLAudio(); }
|
Audio::Audio() { initSDLAudio(); }
|
||||||
@@ -34,7 +34,7 @@ void Audio::update() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Reproduce la música
|
// Reproduce la música
|
||||||
void Audio::playMusic(const std::string &name, const int loop) {
|
void Audio::playMusic(const std::string& name, const int loop) {
|
||||||
music_.name = name;
|
music_.name = name;
|
||||||
music_.loop = (loop != 0);
|
music_.loop = (loop != 0);
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ void Audio::stopMusic() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Reproduce un sonido
|
// Reproduce un sonido
|
||||||
void Audio::playSound(const std::string &name, Group group) const {
|
void Audio::playSound(const std::string& name, Group group) const {
|
||||||
if (sound_enabled_) {
|
if (sound_enabled_) {
|
||||||
JA_PlaySound(Resource::get()->getSound(name), 0, static_cast<int>(group));
|
JA_PlaySound(Resource::get()->getSound(name), 0, static_cast<int>(group));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,24 +25,24 @@ class Audio {
|
|||||||
static constexpr int FREQUENCY = 48000; // Frecuencia de audio
|
static constexpr int FREQUENCY = 48000; // Frecuencia de audio
|
||||||
|
|
||||||
// --- Métodos de singleton ---
|
// --- Métodos de singleton ---
|
||||||
static void init(); // Inicializa el objeto Audio
|
static void init(); // Inicializa el objeto Audio
|
||||||
static void destroy(); // Libera el objeto Audio
|
static void destroy(); // Libera el objeto Audio
|
||||||
static auto get() -> Audio *; // Obtiene el puntero al objeto Audio
|
static auto get() -> Audio*; // Obtiene el puntero al objeto Audio
|
||||||
Audio(const Audio &) = delete; // Evitar copia
|
Audio(const Audio&) = delete; // Evitar copia
|
||||||
auto operator=(const Audio &) -> Audio & = delete; // Evitar asignación
|
auto operator=(const Audio&) -> Audio& = delete; // Evitar asignación
|
||||||
|
|
||||||
// --- Método principal ---
|
// --- Método principal ---
|
||||||
static void update();
|
static void update();
|
||||||
|
|
||||||
// --- Control de Música ---
|
// --- Control de Música ---
|
||||||
void playMusic(const std::string &name, int loop = -1); // Reproducir música en bucle
|
void playMusic(const std::string& name, int loop = -1); // Reproducir música en bucle
|
||||||
void pauseMusic(); // Pausar reproducción de música
|
void pauseMusic(); // Pausar reproducción de música
|
||||||
void resumeMusic(); // Continua la música pausada
|
void resumeMusic(); // Continua la música pausada
|
||||||
void stopMusic(); // Detener completamente la música
|
void stopMusic(); // Detener completamente la música
|
||||||
void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música
|
void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música
|
||||||
|
|
||||||
// --- Control de Sonidos ---
|
// --- Control de Sonidos ---
|
||||||
void playSound(const std::string &name, Group group = Group::GAME) const; // Reproducir sonido puntual
|
void playSound(const std::string& name, Group group = Group::GAME) const; // Reproducir sonido puntual
|
||||||
void stopAllSounds() const; // Detener todos los sonidos
|
void stopAllSounds() const; // Detener todos los sonidos
|
||||||
|
|
||||||
// --- Configuración General ---
|
// --- Configuración General ---
|
||||||
@@ -107,5 +107,5 @@ class Audio {
|
|||||||
~Audio(); // Destructor privado
|
~Audio(); // Destructor privado
|
||||||
|
|
||||||
// --- Instancia singleton ---
|
// --- Instancia singleton ---
|
||||||
static Audio *instance; // Instancia única de Audio
|
static Audio* instance; // Instancia única de Audio
|
||||||
};
|
};
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#define _USE_MATH_DEFINES
|
#define _USE_MATH_DEFINES
|
||||||
#include "background.h"
|
#include "background.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_SetRenderTarget, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetRenderTarget, SDL_RenderTexture, SDL_SetTextureAlphaMod, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_RenderClear, SDL_SetRenderDrawColor, SDL_TextureAccess, SDL_FPoint
|
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_SetRenderTarget, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetRenderTarget, SDL_RenderTexture, SDL_SetTextureAlphaMod, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_RenderClear, SDL_SetRenderDrawColor, SDL_TextureAccess, SDL_FPoint
|
||||||
|
|
||||||
@@ -7,14 +7,14 @@
|
|||||||
#include <cmath> // Para M_PI, cos, sin
|
#include <cmath> // Para M_PI, cos, sin
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para MovingSprite
|
#include "animated_sprite.hpp" // Para MovingSprite
|
||||||
#include "moving_sprite.h" // Para MovingSprite
|
#include "moving_sprite.hpp" // Para MovingSprite
|
||||||
#include "param.h" // Para Param, ParamBackground, param
|
#include "param.hpp" // Para Param, ParamBackground, param
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "utils.h" // Para funciones de easing
|
#include "utils.hpp" // Para funciones de easing
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Background::Background(float total_progress_to_complete)
|
Background::Background(float total_progress_to_complete)
|
||||||
@@ -116,7 +116,7 @@ void Background::initializeSpriteProperties() {
|
|||||||
grass_sprite_->setPos(0.0F, base_ - 10.0F);
|
grass_sprite_->setPos(0.0F, base_ - 10.0F);
|
||||||
grass_sprite_->setWidth(320.0F);
|
grass_sprite_->setWidth(320.0F);
|
||||||
grass_sprite_->setHeight(10.0F);
|
grass_sprite_->setHeight(10.0F);
|
||||||
//grass_sprite_->setCurrentAnimation(0);
|
// grass_sprite_->setCurrentAnimation(0);
|
||||||
|
|
||||||
buildings_sprite_->setY(base_ - buildings_sprite_->getHeight());
|
buildings_sprite_->setY(base_ - buildings_sprite_->getHeight());
|
||||||
sun_sprite_->setPosition(sun_path_.front());
|
sun_sprite_->setPosition(sun_path_.front());
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
#include <memory> // Para unique_ptr, shared_ptr
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "color.h" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
|
|
||||||
class MovingSprite;
|
class MovingSprite;
|
||||||
class Sprite;
|
class Sprite;
|
||||||
@@ -94,27 +94,27 @@ class Background {
|
|||||||
ProgressCallback progress_callback_; // Callback para notificar cambios de progreso
|
ProgressCallback progress_callback_; // Callback para notificar cambios de progreso
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
std::vector<SDL_FPoint> sun_path_; // Recorrido del sol
|
std::vector<SDL_FPoint> sun_path_; // Recorrido del sol
|
||||||
std::vector<SDL_FPoint> moon_path_; // Recorrido de la luna
|
std::vector<SDL_FPoint> moon_path_; // Recorrido de la luna
|
||||||
std::array<SDL_FRect, STAGES> gradient_rect_; // Fondos degradados
|
std::array<SDL_FRect, STAGES> gradient_rect_; // Fondos degradados
|
||||||
std::array<SDL_FRect, 4> top_clouds_rect_; // Nubes superiores
|
std::array<SDL_FRect, 4> top_clouds_rect_; // Nubes superiores
|
||||||
std::array<SDL_FRect, 4> bottom_clouds_rect_; // Nubes inferiores
|
std::array<SDL_FRect, 4> bottom_clouds_rect_; // Nubes inferiores
|
||||||
SDL_FRect rect_; // Tamaño del objeto
|
SDL_FRect rect_; // Tamaño del objeto
|
||||||
SDL_FRect src_rect_; // Parte del objeto para copiar en pantalla
|
SDL_FRect src_rect_; // Parte del objeto para copiar en pantalla
|
||||||
SDL_FRect dst_rect_; // Posición en pantalla donde se copia el objeto
|
SDL_FRect dst_rect_; // Posición en pantalla donde se copia el objeto
|
||||||
Color attenuate_color_; // Color de atenuación
|
Color attenuate_color_; // Color de atenuación
|
||||||
State state_ = State::NORMAL; // Estado actual
|
State state_ = State::NORMAL; // Estado actual
|
||||||
float progress_ = 0.0F; // Progresión interna
|
float progress_ = 0.0F; // Progresión interna
|
||||||
float clouds_speed_ = 0; // Velocidad de las nubes
|
float clouds_speed_ = 0; // Velocidad de las nubes
|
||||||
float transition_ = 0; // Porcentaje de transición
|
float transition_ = 0; // Porcentaje de transición
|
||||||
size_t gradient_number_ = 0; // Índice de fondo degradado
|
size_t gradient_number_ = 0; // Índice de fondo degradado
|
||||||
size_t alpha_color_texture_ = 0; // Transparencia de atenuación
|
size_t alpha_color_texture_ = 0; // Transparencia de atenuación
|
||||||
size_t previous_alpha_color_texture_ = 0; // Transparencia anterior
|
size_t previous_alpha_color_texture_ = 0; // Transparencia anterior
|
||||||
size_t sun_index_ = 0; // Índice del recorrido del sol
|
size_t sun_index_ = 0; // Índice del recorrido del sol
|
||||||
size_t moon_index_ = 0; // Índice del recorrido de la luna
|
size_t moon_index_ = 0; // Índice del recorrido de la luna
|
||||||
int base_ = 0; // Posición base del fondo
|
int base_ = 0; // Posición base del fondo
|
||||||
Uint8 alpha_ = 0; // Transparencia entre fases
|
Uint8 alpha_ = 0; // Transparencia entre fases
|
||||||
bool manual_mode_ = false; // Si está en modo manual
|
bool manual_mode_ = false; // Si está en modo manual
|
||||||
|
|
||||||
// --- Variables para transición suave de completado ---
|
// --- Variables para transición suave de completado ---
|
||||||
float completion_transition_timer_ = 0.0f; // Timer para la transición de completado
|
float completion_transition_timer_ = 0.0f; // Timer para la transición de completado
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
#include "balloon.h"
|
#include "balloon.hpp"
|
||||||
|
|
||||||
#include <algorithm> // Para clamp
|
#include <algorithm> // Para clamp
|
||||||
#include <array> // Para array
|
#include <array> // Para array
|
||||||
#include <cmath> // Para fabs
|
#include <cmath> // Para fabs
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "param.h" // Para Param, ParamBalloon, param
|
#include "param.hpp" // Para Param, ParamBalloon, param
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Balloon::Balloon(const Config& config)
|
Balloon::Balloon(const Config& config)
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
#include <string_view> // Para string_view
|
#include <string_view> // Para string_view
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
#include "utils.h" // Para Circle
|
#include "utils.hpp" // Para Circle
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
@@ -89,11 +89,11 @@ class Balloon {
|
|||||||
~Balloon() = default;
|
~Balloon() = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void alignTo(int x); // Centra el globo en la posición X
|
void alignTo(int x); // Centra el globo en la posición X
|
||||||
void render(); // Pinta el globo en la pantalla
|
void render(); // Pinta el globo en la pantalla
|
||||||
void move(float deltaTime); // Actualiza la posición y estados del globo (time-based)
|
void move(float deltaTime); // Actualiza la posición y estados del globo (time-based)
|
||||||
void update(float deltaTime); // Actualiza el globo (posición, animación, contadores) (time-based)
|
void update(float deltaTime); // Actualiza el globo (posición, animación, contadores) (time-based)
|
||||||
void stop(); // Detiene el globo
|
void stop(); // Detiene el globo
|
||||||
void start(); // Pone el globo en movimiento
|
void start(); // Pone el globo en movimiento
|
||||||
void pop(bool should_sound = false); // Explota el globo
|
void pop(bool should_sound = false); // Explota el globo
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@ class Balloon {
|
|||||||
// --- Setters ---
|
// --- Setters ---
|
||||||
void setVelY(float vel_y) { vy_ = vel_y; }
|
void setVelY(float vel_y) { vy_ = vel_y; }
|
||||||
void setVelX(float vel_x) { vx_ = vel_x; }
|
void setVelX(float vel_x) { vx_ = vel_x; }
|
||||||
void alterVelX(float percent) {vx_ *= percent; }
|
void alterVelX(float percent) { vx_ *= percent; }
|
||||||
void setGameTempo(float tempo) { game_tempo_ = tempo; }
|
void setGameTempo(float tempo) { game_tempo_ = tempo; }
|
||||||
void setInvulnerable(bool value) { invulnerable_ = value; }
|
void setInvulnerable(bool value) { invulnerable_ = value; }
|
||||||
void setBouncingSound(bool value) { sound_.bouncing_enabled = value; }
|
void setBouncingSound(bool value) { sound_.bouncing_enabled = value; }
|
||||||
@@ -245,34 +245,34 @@ class Balloon {
|
|||||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
|
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
|
||||||
|
|
||||||
// --- Variables de estado y físicas ---
|
// --- Variables de estado y físicas ---
|
||||||
float x_; // Posición X
|
float x_; // Posición X
|
||||||
float y_; // Posición Y
|
float y_; // Posición Y
|
||||||
float w_; // Ancho
|
float w_; // Ancho
|
||||||
float h_; // Alto
|
float h_; // Alto
|
||||||
float vx_; // Velocidad X
|
float vx_; // Velocidad X
|
||||||
float vy_; // Velocidad Y
|
float vy_; // Velocidad Y
|
||||||
float gravity_; // Aceleración en Y
|
float gravity_; // Aceleración en Y
|
||||||
float default_vy_; // Velocidad inicial al rebotar
|
float default_vy_; // Velocidad inicial al rebotar
|
||||||
float max_vy_; // Máxima velocidad en Y
|
float max_vy_; // Máxima velocidad en Y
|
||||||
bool being_created_; // Si el globo se está creando
|
bool being_created_; // Si el globo se está creando
|
||||||
bool enabled_ = true; // Si el globo está activo
|
bool enabled_ = true; // Si el globo está activo
|
||||||
bool invulnerable_; // Si el globo es invulnerable
|
bool invulnerable_; // Si el globo es invulnerable
|
||||||
bool stopped_; // Si el globo está parado
|
bool stopped_; // Si el globo está parado
|
||||||
bool use_reversed_colors_ = false; // Si se usa el color alternativo
|
bool use_reversed_colors_ = false; // Si se usa el color alternativo
|
||||||
Circle collider_; // Círculo de colisión
|
Circle collider_; // Círculo de colisión
|
||||||
float creation_counter_; // Temporizador de creación
|
float creation_counter_; // Temporizador de creación
|
||||||
float creation_counter_ini_; // Valor inicial del temporizador de creación
|
float creation_counter_ini_; // Valor inicial del temporizador de creación
|
||||||
Uint16 score_; // Puntos al destruir el globo
|
Uint16 score_; // Puntos al destruir el globo
|
||||||
Type type_; // Tipo de globo
|
Type type_; // Tipo de globo
|
||||||
Size size_; // Tamaño de globo
|
Size size_; // Tamaño de globo
|
||||||
Uint8 menace_; // Amenaza que genera el globo
|
Uint8 menace_; // Amenaza que genera el globo
|
||||||
Uint32 counter_ = 0; // Contador interno
|
Uint32 counter_ = 0; // Contador interno
|
||||||
float game_tempo_; // Multiplicador de tempo del juego
|
float game_tempo_; // Multiplicador de tempo del juego
|
||||||
float movement_accumulator_ = 0.0f; // Acumulador para movimiento durante creación (deltaTime)
|
float movement_accumulator_ = 0.0f; // Acumulador para movimiento durante creación (deltaTime)
|
||||||
Uint8 power_; // Poder que alberga el globo
|
Uint8 power_; // Poder que alberga el globo
|
||||||
SDL_FRect play_area_; // Zona de movimiento del globo
|
SDL_FRect play_area_; // Zona de movimiento del globo
|
||||||
Sound sound_; // Configuración de sonido del globo
|
Sound sound_; // Configuración de sonido del globo
|
||||||
BounceEffect bounce_effect_; // Efecto de rebote
|
BounceEffect bounce_effect_; // Efecto de rebote
|
||||||
|
|
||||||
// --- Posicionamiento y transformación ---
|
// --- Posicionamiento y transformación ---
|
||||||
void shiftColliders(); // Alinea el círculo de colisión con el sprite
|
void shiftColliders(); // Alinea el círculo de colisión con el sprite
|
||||||
@@ -284,9 +284,9 @@ class Balloon {
|
|||||||
void playPoppingSound(); // Reproduce el sonido de reventar
|
void playPoppingSound(); // Reproduce el sonido de reventar
|
||||||
|
|
||||||
// --- Movimiento y física ---
|
// --- Movimiento y física ---
|
||||||
void handleHorizontalMovement(float deltaTime); // Maneja el movimiento horizontal (time-based)
|
void handleHorizontalMovement(float deltaTime); // Maneja el movimiento horizontal (time-based)
|
||||||
void handleVerticalMovement(float deltaTime); // Maneja el movimiento vertical (time-based)
|
void handleVerticalMovement(float deltaTime); // Maneja el movimiento vertical (time-based)
|
||||||
void applyGravity(float deltaTime); // Aplica la gravedad al objeto (time-based)
|
void applyGravity(float deltaTime); // Aplica la gravedad al objeto (time-based)
|
||||||
|
|
||||||
// --- Rebote ---
|
// --- Rebote ---
|
||||||
void enableBounceEffect(); // Activa el efecto de rebote
|
void enableBounceEffect(); // Activa el efecto de rebote
|
||||||
@@ -301,5 +301,5 @@ class Balloon {
|
|||||||
void handleBottomCollision(); // Maneja la colisión inferior
|
void handleBottomCollision(); // Maneja la colisión inferior
|
||||||
|
|
||||||
// --- Lógica de estado ---
|
// --- Lógica de estado ---
|
||||||
void updateState(float deltaTime); // Actualiza los estados del globo (time-based)
|
void updateState(float deltaTime); // Actualiza los estados del globo (time-based)
|
||||||
};
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "balloon_formations.h"
|
#include "balloon_formations.hpp"
|
||||||
|
|
||||||
#include <algorithm> // Para max, min, copy
|
#include <algorithm> // Para max, min, copy
|
||||||
#include <array> // Para array
|
#include <array> // Para array
|
||||||
@@ -11,10 +11,10 @@
|
|||||||
#include <sstream> // Para basic_istringstream
|
#include <sstream> // Para basic_istringstream
|
||||||
#include <string> // Para string, char_traits, allocator, operator==, stoi, getline, operator<=>, basic_string
|
#include <string> // Para string, char_traits, allocator, operator==, stoi, getline, operator<=>, basic_string
|
||||||
|
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.hpp" // Para Asset
|
||||||
#include "balloon.h" // Para Balloon
|
#include "balloon.hpp" // Para Balloon
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "param.hpp" // Para Param, ParamGame, param
|
||||||
#include "utils.h" // Para Zone, BLOCK
|
#include "utils.hpp" // Para Zone, BLOCK
|
||||||
|
|
||||||
void BalloonFormations::initFormations() {
|
void BalloonFormations::initFormations() {
|
||||||
// Calcular posiciones base
|
// Calcular posiciones base
|
||||||
@@ -235,10 +235,10 @@ void BalloonFormations::createFloaterVariants() {
|
|||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
void BalloonFormations::addTestFormation() {
|
void BalloonFormations::addTestFormation() {
|
||||||
std::vector<SpawnParams> test_params = {
|
std::vector<SpawnParams> test_params = {
|
||||||
{10, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::SMALL, 3.334f}, // 200 frames ÷ 60fps = 3.334s
|
{10, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::SMALL, 3.334f}, // 200 frames ÷ 60fps = 3.334s
|
||||||
{50, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::MEDIUM, 3.334f}, // 200 frames ÷ 60fps = 3.334s
|
{50, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::MEDIUM, 3.334f}, // 200 frames ÷ 60fps = 3.334s
|
||||||
{90, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::LARGE, 3.334f}, // 200 frames ÷ 60fps = 3.334s
|
{90, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::LARGE, 3.334f}, // 200 frames ÷ 60fps = 3.334s
|
||||||
{140, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::EXTRALARGE, 3.334f}}; // 200 frames ÷ 60fps = 3.334s
|
{140, -BLOCK, 0, Balloon::Type::FLOATER, Balloon::Size::EXTRALARGE, 3.334f}}; // 200 frames ÷ 60fps = 3.334s
|
||||||
|
|
||||||
formations_.at(99) = Formation(test_params);
|
formations_.at(99) = Formation(test_params);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "balloon.h" // Para Balloon
|
#include "balloon.hpp" // Para Balloon
|
||||||
|
|
||||||
// --- Clase BalloonFormations ---
|
// --- Clase BalloonFormations ---
|
||||||
class BalloonFormations {
|
class BalloonFormations {
|
||||||
@@ -81,8 +81,8 @@ class BalloonFormations {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
static constexpr int BALLOON_SPAWN_HEIGHT = 208; // Altura desde el suelo en la que aparecen los globos
|
static constexpr int BALLOON_SPAWN_HEIGHT = 208; // Altura desde el suelo en la que aparecen los globos
|
||||||
static constexpr float CREATION_TIME = 5.0f; // Tiempo base de creación de los globos en segundos (300 frames ÷ 60fps = 5.0s)
|
static constexpr float CREATION_TIME = 5.0f; // Tiempo base de creación de los globos en segundos (300 frames ÷ 60fps = 5.0s)
|
||||||
static constexpr float DEFAULT_CREATION_TIME = 3.334f; // Tiempo base de creación de los globos en segundos (200 frames ÷ 60fps = 3.334s)
|
static constexpr float DEFAULT_CREATION_TIME = 3.334f; // Tiempo base de creación de los globos en segundos (200 frames ÷ 60fps = 3.334s)
|
||||||
|
|
||||||
// --- Variables ---
|
// --- Variables ---
|
||||||
@@ -1,19 +1,19 @@
|
|||||||
#include "balloon_manager.h"
|
#include "balloon_manager.hpp"
|
||||||
|
|
||||||
#include <algorithm> // Para remove_if
|
#include <algorithm> // Para remove_if
|
||||||
#include <array>
|
#include <array>
|
||||||
#include <cstdlib> // Para rand
|
#include <cstdlib> // Para rand
|
||||||
#include <numeric> // Para accumulate
|
#include <numeric> // Para accumulate
|
||||||
|
|
||||||
#include "balloon.h" // Para Balloon, Balloon::SCORE.at( )ALLOON_VELX...
|
#include "balloon.hpp" // Para Balloon, Balloon::SCORE.at( )ALLOON_VELX...
|
||||||
#include "balloon_formations.h" // Para BalloonFormationParams, BalloonForma...
|
#include "balloon_formations.hpp" // Para BalloonFormationParams, BalloonForma...
|
||||||
#include "color.h" // Para Zone, Color, flash_color
|
#include "color.hpp" // Para Zone, Color, flash_color
|
||||||
#include "explosions.h" // Para Explosions
|
#include "explosions.hpp" // Para Explosions
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "param.hpp" // Para Param, ParamGame, param
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "stage_interface.h" // Para IStageInfo
|
#include "stage_interface.hpp" // Para IStageInfo
|
||||||
#include "utils.h"
|
#include "utils.hpp"
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
BalloonManager::BalloonManager(IStageInfo* stage_info)
|
BalloonManager::BalloonManager(IStageInfo* stage_info)
|
||||||
|
|||||||
@@ -8,12 +8,12 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "balloon.h" // Para BALLOON_SPEED, Balloon, Balloon::Size (ptr only), Balloon::Type (ptr only)
|
#include "balloon.hpp" // Para BALLOON_SPEED, Balloon, Balloon::Size (ptr only), Balloon::Type (ptr only)
|
||||||
#include "balloon_formations.h" // Para BalloonFormations
|
#include "balloon_formations.hpp" // Para BalloonFormations
|
||||||
#include "explosions.h" // Para Explosions
|
#include "explosions.hpp" // Para Explosions
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "param.hpp" // Para Param, ParamGame, param
|
||||||
#include "stage_interface.h" // Para IStageInfo
|
#include "stage_interface.hpp" // Para IStageInfo
|
||||||
#include "utils.h" // Para Zone
|
#include "utils.hpp" // Para Zone
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ using Balloons = std::vector<std::shared_ptr<Balloon>>;
|
|||||||
class BalloonManager {
|
class BalloonManager {
|
||||||
public:
|
public:
|
||||||
// --- Constructor y destructor ---
|
// --- Constructor y destructor ---
|
||||||
BalloonManager(IStageInfo *stage_info);
|
BalloonManager(IStageInfo* stage_info);
|
||||||
~BalloonManager() = default;
|
~BalloonManager() = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
@@ -41,7 +41,7 @@ class BalloonManager {
|
|||||||
|
|
||||||
// --- Creación de globos ---
|
// --- Creación de globos ---
|
||||||
auto createBalloon(Balloon::Config config) -> std::shared_ptr<Balloon>; // Crea un nuevo globo
|
auto createBalloon(Balloon::Config config) -> std::shared_ptr<Balloon>; // Crea un nuevo globo
|
||||||
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
|
void createChildBalloon(const std::shared_ptr<Balloon>& balloon, const std::string& direction); // Crea un globo a partir de otro
|
||||||
void createPowerBall(); // Crea una PowerBall
|
void createPowerBall(); // Crea una PowerBall
|
||||||
void createTwoBigBalloons(); // Crea dos globos grandes
|
void createTwoBigBalloons(); // Crea dos globos grandes
|
||||||
|
|
||||||
@@ -54,8 +54,8 @@ class BalloonManager {
|
|||||||
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
|
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
|
||||||
|
|
||||||
// --- Manipulación de globos existentes ---
|
// --- Manipulación de globos existentes ---
|
||||||
auto popBalloon(const std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo, creando otros si aplica
|
auto popBalloon(const std::shared_ptr<Balloon>& balloon) -> int; // Explosiona un globo, creando otros si aplica
|
||||||
auto destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo sin crear otros
|
auto destroyBalloon(std::shared_ptr<Balloon>& balloon) -> int; // Explosiona un globo sin crear otros
|
||||||
auto destroyAllBalloons() -> int; // Destruye todos los globos
|
auto destroyAllBalloons() -> int; // Destruye todos los globos
|
||||||
void stopAllBalloons(); // Detiene el movimiento de los globos
|
void stopAllBalloons(); // Detiene el movimiento de los globos
|
||||||
void startAllBalloons(); // Reactiva el movimiento de los globos
|
void startAllBalloons(); // Reactiva el movimiento de los globos
|
||||||
@@ -77,7 +77,7 @@ class BalloonManager {
|
|||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos
|
auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos
|
||||||
[[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; }
|
[[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; }
|
||||||
auto getBalloons() -> Balloons & { return balloons_; }
|
auto getBalloons() -> Balloons& { return balloons_; }
|
||||||
[[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); }
|
[[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -94,7 +94,7 @@ class BalloonManager {
|
|||||||
std::vector<std::shared_ptr<Texture>> explosions_textures_; // Texturas de explosiones
|
std::vector<std::shared_ptr<Texture>> explosions_textures_; // Texturas de explosiones
|
||||||
std::vector<std::vector<std::string>> balloon_animations_; // Animaciones de los globos
|
std::vector<std::vector<std::string>> balloon_animations_; // Animaciones de los globos
|
||||||
std::vector<std::vector<std::string>> explosions_animations_; // Animaciones de las explosiones
|
std::vector<std::vector<std::string>> explosions_animations_; // Animaciones de las explosiones
|
||||||
IStageInfo *stage_info_; // Informacion de la pantalla actual
|
IStageInfo* stage_info_; // Informacion de la pantalla actual
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
SDL_FRect play_area_ = param.game.play_area.rect;
|
SDL_FRect play_area_ = param.game.play_area.rect;
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
#include "bullet.h"
|
#include "bullet.hpp"
|
||||||
|
|
||||||
#include <memory> // Para allocator, unique_ptr, make_unique
|
#include <memory> // Para allocator, unique_ptr, make_unique
|
||||||
#include <string> // Para char_traits, basic_string, operator+, string
|
#include <string> // Para char_traits, basic_string, operator+, string
|
||||||
|
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "param.hpp" // Para Param, ParamGame, param
|
||||||
#include "player.h" // Para Player::Id
|
#include "player.hpp" // Para Player::Id
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Bullet::Bullet(float x, float y, Type type, Color color, int owner)
|
Bullet::Bullet(float x, float y, Type type, Color color, int owner)
|
||||||
|
|||||||
@@ -5,8 +5,8 @@
|
|||||||
#include <memory> // Para unique_ptr
|
#include <memory> // Para unique_ptr
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
#include "utils.h" // Para Circle
|
#include "utils.hpp" // Para Circle
|
||||||
|
|
||||||
// --- Clase Bullet: representa una bala del jugador ---
|
// --- Clase Bullet: representa una bala del jugador ---
|
||||||
class Bullet {
|
class Bullet {
|
||||||
@@ -37,7 +37,7 @@ class Bullet {
|
|||||||
|
|
||||||
// --- Constructor y destructor ---
|
// --- Constructor y destructor ---
|
||||||
Bullet(float x, float y, Type type, Color color, int owner); // Constructor principal
|
Bullet(float x, float y, Type type, Color color, int owner); // Constructor principal
|
||||||
~Bullet() = default; // Destructor
|
~Bullet() = default; // Destructor
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void render(); // Dibuja la bala en pantalla
|
void render(); // Dibuja la bala en pantalla
|
||||||
@@ -68,9 +68,9 @@ class Bullet {
|
|||||||
float vel_x_; // Velocidad en el eje X
|
float vel_x_; // Velocidad en el eje X
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void shiftColliders(); // Ajusta el círculo de colisión
|
void shiftColliders(); // Ajusta el círculo de colisión
|
||||||
void shiftSprite(); // Ajusta el sprite
|
void shiftSprite(); // Ajusta el sprite
|
||||||
auto move(float deltaTime) -> MoveStatus; // Mueve la bala y devuelve su estado (time-based)
|
auto move(float deltaTime) -> MoveStatus; // Mueve la bala y devuelve su estado (time-based)
|
||||||
static auto calculateVelocity(Type type) -> float; // Calcula la velocidad horizontal de la bala
|
static auto calculateVelocity(Type type) -> float; // Calcula la velocidad horizontal de la bala
|
||||||
static auto buildAnimationString(Type type, Color color) -> std::string; // Construye el string de animación
|
static auto buildAnimationString(Type type, Color color) -> std::string; // Construye el string de animación
|
||||||
};
|
};
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
#include "bullet_manager.h"
|
#include "bullet_manager.hpp"
|
||||||
|
|
||||||
#include <algorithm> // Para remove_if
|
#include <algorithm> // Para remove_if
|
||||||
|
|
||||||
#include "bullet.h" // Para Bullet
|
#include "bullet.hpp" // Para Bullet
|
||||||
#include "param.h" // Para param
|
#include "param.hpp" // Para param
|
||||||
#include "player.h" // Para Player
|
#include "player.hpp" // Para Player
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
BulletManager::BulletManager()
|
BulletManager::BulletManager()
|
||||||
@@ -39,10 +39,9 @@ void BulletManager::freeBullets() {
|
|||||||
if (!bullets_.empty()) {
|
if (!bullets_.empty()) {
|
||||||
// Elimina las balas deshabilitadas del vector
|
// Elimina las balas deshabilitadas del vector
|
||||||
bullets_.erase(
|
bullets_.erase(
|
||||||
std::remove_if(bullets_.begin(), bullets_.end(),
|
std::remove_if(bullets_.begin(), bullets_.end(), [](const std::shared_ptr<Bullet>& bullet) {
|
||||||
[](const std::shared_ptr<Bullet>& bullet) {
|
return !bullet->isEnabled();
|
||||||
return !bullet->isEnabled();
|
}),
|
||||||
}),
|
|
||||||
bullets_.end());
|
bullets_.end());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -103,7 +102,7 @@ auto BulletManager::isBulletOutOfBounds(const std::shared_ptr<Bullet>& bullet) -
|
|||||||
auto collider = bullet->getCollider();
|
auto collider = bullet->getCollider();
|
||||||
|
|
||||||
return (collider.x < play_area_.x ||
|
return (collider.x < play_area_.x ||
|
||||||
collider.x > play_area_.x + play_area_.w ||
|
collider.x > play_area_.x + play_area_.w ||
|
||||||
collider.y < play_area_.y ||
|
collider.y < play_area_.y ||
|
||||||
collider.y > play_area_.y + play_area_.h);
|
collider.y > play_area_.y + play_area_.h);
|
||||||
}
|
}
|
||||||
@@ -6,8 +6,8 @@
|
|||||||
#include <memory> // Para shared_ptr, unique_ptr
|
#include <memory> // Para shared_ptr, unique_ptr
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "bullet.h" // Para Bullet
|
#include "bullet.hpp" // Para Bullet
|
||||||
#include "utils.h" // Para Circle
|
#include "utils.hpp" // Para Circle
|
||||||
|
|
||||||
// --- Types ---
|
// --- Types ---
|
||||||
using Bullets = std::vector<std::shared_ptr<Bullet>>;
|
using Bullets = std::vector<std::shared_ptr<Bullet>>;
|
||||||
@@ -49,16 +49,16 @@ class BulletManager {
|
|||||||
void clearAllBullets(); // Elimina todas las balas
|
void clearAllBullets(); // Elimina todas las balas
|
||||||
|
|
||||||
// --- Detección de colisiones ---
|
// --- Detección de colisiones ---
|
||||||
void checkCollisions(); // Verifica colisiones de todas las balas
|
void checkCollisions(); // Verifica colisiones de todas las balas
|
||||||
void setTabeCollisionCallback(CollisionCallback callback); // Establece callback para colisión con Tabe
|
void setTabeCollisionCallback(CollisionCallback callback); // Establece callback para colisión con Tabe
|
||||||
void setBalloonCollisionCallback(CollisionCallback callback); // Establece callback para colisión con globos
|
void setBalloonCollisionCallback(CollisionCallback callback); // Establece callback para colisión con globos
|
||||||
void setOutOfBoundsCallback(OutOfBoundsCallback callback); // Establece callback para balas fuera de límites
|
void setOutOfBoundsCallback(OutOfBoundsCallback callback); // Establece callback para balas fuera de límites
|
||||||
|
|
||||||
// --- Configuración ---
|
// --- Configuración ---
|
||||||
void setPlayArea(SDL_FRect play_area) { play_area_ = play_area; }; // Define el área de juego
|
void setPlayArea(SDL_FRect play_area) { play_area_ = play_area; }; // Define el área de juego
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
auto getBullets() -> Bullets& { return bullets_; } // Obtiene referencia al vector de balas
|
auto getBullets() -> Bullets& { return bullets_; } // Obtiene referencia al vector de balas
|
||||||
[[nodiscard]] auto getNumBullets() const -> int { return bullets_.size(); } // Obtiene el número de balas activas
|
[[nodiscard]] auto getNumBullets() const -> int { return bullets_.size(); } // Obtiene el número de balas activas
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -71,7 +71,7 @@ class BulletManager {
|
|||||||
// --- Callbacks para colisiones ---
|
// --- Callbacks para colisiones ---
|
||||||
CollisionCallback tabe_collision_callback_; // Callback para colisión con Tabe
|
CollisionCallback tabe_collision_callback_; // Callback para colisión con Tabe
|
||||||
CollisionCallback balloon_collision_callback_; // Callback para colisión con globos
|
CollisionCallback balloon_collision_callback_; // Callback para colisión con globos
|
||||||
OutOfBoundsCallback out_of_bounds_callback_; // Callback para balas fuera de límites
|
OutOfBoundsCallback out_of_bounds_callback_; // Callback para balas fuera de límites
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void processBulletUpdate(const std::shared_ptr<Bullet>& bullet, float deltaTime); // Procesa actualización individual
|
void processBulletUpdate(const std::shared_ptr<Bullet>& bullet, float deltaTime); // Procesa actualización individual
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#define _USE_MATH_DEFINES
|
#define _USE_MATH_DEFINES
|
||||||
#include "color.h"
|
#include "color.hpp"
|
||||||
|
|
||||||
#include <cctype> // Para isxdigit
|
#include <cctype> // Para isxdigit
|
||||||
#include <cmath> // Para sinf, fmaxf, fminf, M_PI, fmodf, roundf, fmod
|
#include <cmath> // Para sinf, fmaxf, fminf, M_PI, fmodf, roundf, fmod
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
#include <string> // Para basic_string, stoi, string
|
#include <string> // Para basic_string, stoi, string
|
||||||
|
|
||||||
// Método estático para crear Color desde string hexadecimal
|
// Método estático para crear Color desde string hexadecimal
|
||||||
auto Color::fromHex(const std::string &hex_str) -> Color {
|
auto Color::fromHex(const std::string& hex_str) -> Color {
|
||||||
std::string hex = hex_str;
|
std::string hex = hex_str;
|
||||||
|
|
||||||
// Quitar '#' si existe
|
// Quitar '#' si existe
|
||||||
@@ -117,7 +117,7 @@ constexpr auto Color::hsvToRgb(HSV hsv) -> Color {
|
|||||||
// Implementaciones del namespace Colors
|
// Implementaciones del namespace Colors
|
||||||
namespace Colors {
|
namespace Colors {
|
||||||
// Obtiene un color del vector de colores imitando al Coche Fantástico
|
// Obtiene un color del vector de colores imitando al Coche Fantástico
|
||||||
auto getColorLikeKnightRider(const std::vector<Color> &colors, int counter) -> Color {
|
auto getColorLikeKnightRider(const std::vector<Color>& colors, int counter) -> Color {
|
||||||
int cycle_length = (colors.size() * 2) - 2;
|
int cycle_length = (colors.size() * 2) - 2;
|
||||||
size_t n = counter % cycle_length;
|
size_t n = counter % cycle_length;
|
||||||
|
|
||||||
|
|||||||
@@ -69,17 +69,17 @@ struct Color {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Método estático para crear Color desde string hexadecimal
|
// Método estático para crear Color desde string hexadecimal
|
||||||
static auto fromHex(const std::string &hex_str) -> Color;
|
static auto fromHex(const std::string& hex_str) -> Color;
|
||||||
|
|
||||||
// Conversiones de formato de color
|
// Conversiones de formato de color
|
||||||
[[nodiscard]] constexpr static auto rgbToHsv(Color color) -> HSV;
|
[[nodiscard]] constexpr static auto rgbToHsv(Color color) -> HSV;
|
||||||
[[nodiscard]] constexpr static auto hsvToRgb(HSV hsv) -> Color;
|
[[nodiscard]] constexpr static auto hsvToRgb(HSV hsv) -> Color;
|
||||||
|
|
||||||
[[nodiscard]] constexpr auto IS_EQUAL_TO(const Color &other) const -> bool {
|
[[nodiscard]] constexpr auto IS_EQUAL_TO(const Color& other) const -> bool {
|
||||||
return r == other.r && g == other.g && b == other.b && a == other.a;
|
return r == other.r && g == other.g && b == other.b && a == other.a;
|
||||||
}
|
}
|
||||||
|
|
||||||
[[nodiscard]] constexpr auto APPROACH_TO(const Color &target, int step = DEFAULT_APPROACH_STEP) const -> Color {
|
[[nodiscard]] constexpr auto APPROACH_TO(const Color& target, int step = DEFAULT_APPROACH_STEP) const -> Color {
|
||||||
auto approach_component = [step](Uint8 current, Uint8 target_val) -> Uint8 {
|
auto approach_component = [step](Uint8 current, Uint8 target_val) -> Uint8 {
|
||||||
if (std::abs(current - target_val) <= step) {
|
if (std::abs(current - target_val) <= step) {
|
||||||
return target_val;
|
return target_val;
|
||||||
@@ -96,7 +96,7 @@ struct Color {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Interpolación lineal hacia otro color (t=0.0: this, t=1.0: target)
|
// Interpolación lineal hacia otro color (t=0.0: this, t=1.0: target)
|
||||||
[[nodiscard]] constexpr auto LERP(const Color &target, float t) const -> Color {
|
[[nodiscard]] constexpr auto LERP(const Color& target, float t) const -> Color {
|
||||||
// Asegurar que t esté en el rango [0.0, 1.0]
|
// Asegurar que t esté en el rango [0.0, 1.0]
|
||||||
t = std::clamp(t, 0.0f, 1.0f);
|
t = std::clamp(t, 0.0f, 1.0f);
|
||||||
|
|
||||||
@@ -109,8 +109,7 @@ struct Color {
|
|||||||
lerp_component(r, target.r),
|
lerp_component(r, target.r),
|
||||||
lerp_component(g, target.g),
|
lerp_component(g, target.g),
|
||||||
lerp_component(b, target.b),
|
lerp_component(b, target.b),
|
||||||
lerp_component(a, target.a)
|
lerp_component(a, target.a));
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sobrecarga para aceptar componentes RGBA directamente
|
// Sobrecarga para aceptar componentes RGBA directamente
|
||||||
@@ -157,6 +156,6 @@ constexpr Color PINK_SKY = Color(0XFF, 0X6B, 0X97);
|
|||||||
constexpr Color GREEN_SKY = Color(0X00, 0X79, 0X6B);
|
constexpr Color GREEN_SKY = Color(0X00, 0X79, 0X6B);
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
auto getColorLikeKnightRider(const std::vector<Color> &colors, int counter) -> Color;
|
auto getColorLikeKnightRider(const std::vector<Color>& colors, int counter) -> Color;
|
||||||
auto generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SUBTLE_PULSE) -> Cycle;
|
auto generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SUBTLE_PULSE) -> Cycle;
|
||||||
} // namespace Colors
|
} // namespace Colors
|
||||||
@@ -4,9 +4,9 @@
|
|||||||
|
|
||||||
#include <array>
|
#include <array>
|
||||||
|
|
||||||
#include "color.h"
|
#include "color.hpp"
|
||||||
#include "ui/notifier.h" // Para Notifier::Position
|
#include "ui/notifier.hpp" // Para Notifier::Position
|
||||||
#include "version.h" // Para Version::APP_NAME
|
#include "version.h" // Para Version::APP_NAME
|
||||||
|
|
||||||
// --- Namespace GameDefaults: configuración centralizada con valores por defecto del juego ---
|
// --- Namespace GameDefaults: configuración centralizada con valores por defecto del juego ---
|
||||||
namespace GameDefaults {
|
namespace GameDefaults {
|
||||||
@@ -15,8 +15,8 @@ namespace GameDefaults {
|
|||||||
namespace Game {
|
namespace Game {
|
||||||
constexpr float WIDTH = 320.0F;
|
constexpr float WIDTH = 320.0F;
|
||||||
constexpr float HEIGHT = 256.0F;
|
constexpr float HEIGHT = 256.0F;
|
||||||
constexpr int NAME_ENTRY_IDLE_TIME = 10;
|
constexpr int NAME_ENTRY_IDLE_TIME = 10;
|
||||||
constexpr int NAME_ENTRY_TOTAL_TIME = 60;
|
constexpr int NAME_ENTRY_TOTAL_TIME = 60;
|
||||||
constexpr bool HIT_STOP = false;
|
constexpr bool HIT_STOP = false;
|
||||||
constexpr int HIT_STOP_MS = 500;
|
constexpr int HIT_STOP_MS = 500;
|
||||||
constexpr const char* ITEM_TEXT_OUTLINE_COLOR = "FFFFFF00"; // 255, 255, 255, 0
|
constexpr const char* ITEM_TEXT_OUTLINE_COLOR = "FFFFFF00"; // 255, 255, 255, 0
|
||||||
@@ -1,25 +1,25 @@
|
|||||||
#include "define_buttons.h"
|
#include "define_buttons.hpp"
|
||||||
|
|
||||||
#include <algorithm> // Para __all_of_fn, all_of
|
#include <algorithm> // Para __all_of_fn, all_of
|
||||||
#include <functional> // Para identity
|
#include <functional> // Para identity
|
||||||
#include <memory> // Para allocator, unique_ptr, shared_ptr, make_unique, operator==
|
#include <memory> // Para allocator, unique_ptr, shared_ptr, make_unique, operator==
|
||||||
|
|
||||||
#include "color.h" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "input_types.h" // Para InputAction
|
#include "input_types.hpp" // Para InputAction
|
||||||
#include "lang.h" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "options.h" // Para Gamepad
|
#include "options.hpp" // Para Gamepad
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "param.hpp" // Para Param, ParamGame, param
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "ui/window_message.h" // Para WindowMessage
|
#include "ui/window_message.hpp" // Para WindowMessage
|
||||||
#include "utils.h" // Para Zone
|
#include "utils.hpp" // Para Zone
|
||||||
|
|
||||||
DefineButtons::DefineButtons()
|
DefineButtons::DefineButtons()
|
||||||
: input_(Input::get()) {
|
: input_(Input::get()) {
|
||||||
clearButtons();
|
clearButtons();
|
||||||
|
|
||||||
auto gamepads = input_->getGamepads();
|
auto gamepads = input_->getGamepads();
|
||||||
for (const auto &gamepad : gamepads) {
|
for (const auto& gamepad : gamepads) {
|
||||||
controller_names_.emplace_back(Input::getControllerName(gamepad));
|
controller_names_.emplace_back(Input::getControllerName(gamepad));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,7 +63,7 @@ void DefineButtons::update(float delta_time) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void DefineButtons::handleEvents(const SDL_Event &event) {
|
void DefineButtons::handleEvents(const SDL_Event& event) {
|
||||||
if (enabled_) {
|
if (enabled_) {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case SDL_EVENT_GAMEPAD_BUTTON_DOWN:
|
case SDL_EVENT_GAMEPAD_BUTTON_DOWN:
|
||||||
@@ -81,7 +81,7 @@ void DefineButtons::handleEvents(const SDL_Event &event) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
auto DefineButtons::enable(Options::Gamepad *options_gamepad) -> bool {
|
auto DefineButtons::enable(Options::Gamepad* options_gamepad) -> bool {
|
||||||
if (options_gamepad != nullptr) {
|
if (options_gamepad != nullptr) {
|
||||||
options_gamepad_ = options_gamepad;
|
options_gamepad_ = options_gamepad;
|
||||||
enabled_ = true;
|
enabled_ = true;
|
||||||
@@ -117,7 +117,7 @@ void DefineButtons::disable() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void DefineButtons::doControllerButtonDown(const SDL_GamepadButtonEvent &event) {
|
void DefineButtons::doControllerButtonDown(const SDL_GamepadButtonEvent& event) {
|
||||||
auto gamepad = input_->getGamepad(event.which);
|
auto gamepad = input_->getGamepad(event.which);
|
||||||
|
|
||||||
if (!gamepad || gamepad != options_gamepad_->instance) {
|
if (!gamepad || gamepad != options_gamepad_->instance) {
|
||||||
@@ -132,7 +132,7 @@ void DefineButtons::doControllerButtonDown(const SDL_GamepadButtonEvent &event)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void DefineButtons::doControllerAxisMotion(const SDL_GamepadAxisEvent &event) {
|
void DefineButtons::doControllerAxisMotion(const SDL_GamepadAxisEvent& event) {
|
||||||
auto gamepad = input_->getGamepad(event.which);
|
auto gamepad = input_->getGamepad(event.which);
|
||||||
|
|
||||||
if (!gamepad || gamepad != options_gamepad_->instance) {
|
if (!gamepad || gamepad != options_gamepad_->instance) {
|
||||||
@@ -182,8 +182,8 @@ void DefineButtons::doControllerAxisMotion(const SDL_GamepadAxisEvent &event) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void DefineButtons::bindButtons(Options::Gamepad *options_gamepad) {
|
void DefineButtons::bindButtons(Options::Gamepad* options_gamepad) {
|
||||||
for (const auto &button : buttons_) {
|
for (const auto& button : buttons_) {
|
||||||
Input::bindGameControllerButton(options_gamepad->instance, button.action, static_cast<SDL_GamepadButton>(button.button));
|
Input::bindGameControllerButton(options_gamepad->instance, button.action, static_cast<SDL_GamepadButton>(button.button));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,13 +200,13 @@ void DefineButtons::incIndexButton() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
auto DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) -> bool {
|
auto DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) -> bool {
|
||||||
return std::ranges::all_of(buttons_, [button](const auto &b) {
|
return std::ranges::all_of(buttons_, [button](const auto& b) {
|
||||||
return b.button != button;
|
return b.button != button;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
auto DefineButtons::checkTriggerNotInUse(int trigger_button) -> bool {
|
auto DefineButtons::checkTriggerNotInUse(int trigger_button) -> bool {
|
||||||
return std::ranges::all_of(buttons_, [trigger_button](const auto &b) {
|
return std::ranges::all_of(buttons_, [trigger_button](const auto& b) {
|
||||||
return b.button != trigger_button;
|
return b.button != trigger_button;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "input.h"
|
#include "input.hpp"
|
||||||
#include "ui/window_message.h"
|
#include "ui/window_message.hpp"
|
||||||
|
|
||||||
namespace Options {
|
namespace Options {
|
||||||
struct Gamepad;
|
struct Gamepad;
|
||||||
@@ -37,8 +37,8 @@ class DefineButtons {
|
|||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void render();
|
void render();
|
||||||
void update(float delta_time);
|
void update(float delta_time);
|
||||||
void handleEvents(const SDL_Event &event);
|
void handleEvents(const SDL_Event& event);
|
||||||
auto enable(Options::Gamepad *options_gamepad) -> bool;
|
auto enable(Options::Gamepad* options_gamepad) -> bool;
|
||||||
void disable();
|
void disable();
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
@@ -51,8 +51,8 @@ class DefineButtons {
|
|||||||
static constexpr float MESSAGE_DISPLAY_DURATION_S = 2.0f; // Cuánto tiempo mostrar el mensaje en segundos
|
static constexpr float MESSAGE_DISPLAY_DURATION_S = 2.0f; // Cuánto tiempo mostrar el mensaje en segundos
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
Input *input_ = nullptr; // Entrada del usuario
|
Input* input_ = nullptr; // Entrada del usuario
|
||||||
Options::Gamepad *options_gamepad_ = nullptr; // Opciones del gamepad
|
Options::Gamepad* options_gamepad_ = nullptr; // Opciones del gamepad
|
||||||
std::unique_ptr<WindowMessage> window_message_; // Mensaje de ventana
|
std::unique_ptr<WindowMessage> window_message_; // Mensaje de ventana
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
@@ -69,9 +69,9 @@ class DefineButtons {
|
|||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void incIndexButton();
|
void incIndexButton();
|
||||||
void doControllerButtonDown(const SDL_GamepadButtonEvent &event);
|
void doControllerButtonDown(const SDL_GamepadButtonEvent& event);
|
||||||
void doControllerAxisMotion(const SDL_GamepadAxisEvent &event);
|
void doControllerAxisMotion(const SDL_GamepadAxisEvent& event);
|
||||||
void bindButtons(Options::Gamepad *options_gamepad);
|
void bindButtons(Options::Gamepad* options_gamepad);
|
||||||
auto checkButtonNotInUse(SDL_GamepadButton button) -> bool;
|
auto checkButtonNotInUse(SDL_GamepadButton button) -> bool;
|
||||||
auto checkTriggerNotInUse(int trigger_button) -> bool;
|
auto checkTriggerNotInUse(int trigger_button) -> bool;
|
||||||
void clearButtons();
|
void clearButtons();
|
||||||
@@ -1,16 +1,17 @@
|
|||||||
#include "demo.h"
|
#include "demo.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_IOStream, SDL_IOFromConstMem, SDL_IOFromFile, SDL_ReadIO, SDL_WriteIO, SDL_CloseIO
|
#include <SDL3/SDL.h> // Para SDL_IOStream, SDL_IOFromConstMem, SDL_IOFromFile, SDL_ReadIO, SDL_WriteIO, SDL_CloseIO
|
||||||
#include <stdexcept> // Para runtime_error
|
|
||||||
|
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
#include <stdexcept> // Para runtime_error
|
||||||
#include "utils.h" // Para printWithDots, getFileName
|
|
||||||
|
#include "resource_helper.hpp" // Para ResourceHelper
|
||||||
|
#include "utils.hpp" // Para printWithDots, getFileName
|
||||||
|
|
||||||
// Carga el fichero de datos para la demo
|
// Carga el fichero de datos para la demo
|
||||||
auto loadDemoDataFromFile(const std::string &file_path) -> DemoData {
|
auto loadDemoDataFromFile(const std::string& file_path) -> DemoData {
|
||||||
DemoData dd;
|
DemoData dd;
|
||||||
|
|
||||||
SDL_IOStream *file = nullptr;
|
SDL_IOStream* file = nullptr;
|
||||||
|
|
||||||
// Intentar cargar desde ResourceHelper primero
|
// Intentar cargar desde ResourceHelper primero
|
||||||
auto resource_data = ResourceHelper::loadFile(file_path);
|
auto resource_data = ResourceHelper::loadFile(file_path);
|
||||||
@@ -42,13 +43,13 @@ auto loadDemoDataFromFile(const std::string &file_path) -> DemoData {
|
|||||||
|
|
||||||
#ifdef RECORDING
|
#ifdef RECORDING
|
||||||
// Guarda el fichero de datos para la demo
|
// Guarda el fichero de datos para la demo
|
||||||
bool saveDemoFile(const std::string &file_path, const DemoData &dd) {
|
bool saveDemoFile(const std::string& file_path, const DemoData& dd) {
|
||||||
auto success = true;
|
auto success = true;
|
||||||
auto file = SDL_IOFromFile(file_path.c_str(), "w+b");
|
auto file = SDL_IOFromFile(file_path.c_str(), "w+b");
|
||||||
|
|
||||||
if (file) {
|
if (file) {
|
||||||
// Guarda los datos
|
// Guarda los datos
|
||||||
for (const auto &data : dd) {
|
for (const auto& data : dd) {
|
||||||
if (SDL_WriteIO(file, &data, sizeof(DemoKeys)) != sizeof(DemoKeys)) {
|
if (SDL_WriteIO(file, &data, sizeof(DemoKeys)) != sizeof(DemoKeys)) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al escribir el fichero %s", getFileName(file_path).c_str());
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al escribir el fichero %s", getFileName(file_path).c_str());
|
||||||
success = false;
|
success = false;
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para Uint8
|
#include <SDL3/SDL.h> // Para Uint8
|
||||||
#include <string> // Para string
|
|
||||||
#include <vector> // Para vector
|
#include <string> // Para string
|
||||||
|
#include <vector> // Para vector
|
||||||
|
|
||||||
// --- Constantes ---
|
// --- Constantes ---
|
||||||
constexpr int TOTAL_DEMO_DATA = 2000;
|
constexpr int TOTAL_DEMO_DATA = 2000;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "difficulty.h"
|
#include "difficulty.hpp"
|
||||||
|
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// IWYU pragma: no_include <bits/chrono.h>
|
// IWYU pragma: no_include <bits/chrono.h>
|
||||||
#include "director.h"
|
#include "director.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_SetLogPriority, SDL_LogPriority, SDL_Quit
|
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_SetLogPriority, SDL_LogPriority, SDL_Quit
|
||||||
|
|
||||||
@@ -11,33 +11,33 @@
|
|||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <string> // Para allocator, char_traits, operator==, string, basic_string, operator+
|
#include <string> // Para allocator, char_traits, operator==, string, basic_string, operator+
|
||||||
|
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.hpp" // Para Asset
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "lang.h" // Para setLanguage
|
#include "lang.hpp" // Para setLanguage
|
||||||
#include "manage_hiscore_table.h" // Para ManageHiScoreTable
|
#include "manage_hiscore_table.hpp" // Para ManageHiScoreTable
|
||||||
#include "options.h" // Para loadFromFile, saveToFile, Settings, settings, setConfigFile, setControllersFile
|
#include "options.hpp" // Para loadFromFile, saveToFile, Settings, settings, setConfigFile, setControllersFile
|
||||||
#include "param.h" // Para loadParamsFromFile
|
#include "param.hpp" // Para loadParamsFromFile
|
||||||
#include "player.h" // Para Player
|
#include "player.hpp" // Para Player
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
#include "resource_helper.hpp" // Para ResourceHelper
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "section.hpp" // Para Name, Options, name, options, AttractMode, attract_mode
|
#include "section.hpp" // Para Name, Options, name, options, AttractMode, attract_mode
|
||||||
#include "sections/credits.h" // Para Credits
|
#include "sections/credits.hpp" // Para Credits
|
||||||
#include "sections/game.h" // Para Game
|
#include "sections/game.hpp" // Para Game
|
||||||
#include "sections/hiscore_table.h" // Para HiScoreTable
|
#include "sections/hiscore_table.hpp" // Para HiScoreTable
|
||||||
#include "sections/instructions.h" // Para Instructions
|
#include "sections/instructions.hpp" // Para Instructions
|
||||||
#include "sections/intro.h" // Para Intro
|
#include "sections/intro.hpp" // Para Intro
|
||||||
#include "sections/logo.h" // Para Logo
|
#include "sections/logo.hpp" // Para Logo
|
||||||
#include "sections/title.h" // Para Title
|
#include "sections/title.hpp" // Para Title
|
||||||
#include "shutdown.h" // Para resultToString, shutdownSystem, ShutdownResult
|
#include "shutdown.hpp" // Para resultToString, shutdownSystem, ShutdownResult
|
||||||
#include "system_utils.h" // Para createApplicationFolder, resultToString, Result
|
#include "system_utils.hpp" // Para createApplicationFolder, resultToString, Result
|
||||||
#include "ui/notifier.h" // Para Notifier
|
#include "ui/notifier.hpp" // Para Notifier
|
||||||
#include "ui/service_menu.h" // Para ServiceMenu
|
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||||
#include "utils.h" // Para Overrides, overrides, getPath
|
#include "utils.hpp" // Para Overrides, overrides, getPath
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Director::Director(int argc, std::span<char *> argv) {
|
Director::Director(int argc, std::span<char*> argv) {
|
||||||
#ifdef RECORDING
|
#ifdef RECORDING
|
||||||
Section::name = Section::Name::GAME;
|
Section::name = Section::Name::GAME;
|
||||||
Section::options = Section::Options::GAME_PLAY_1P;
|
Section::options = Section::Options::GAME_PLAY_1P;
|
||||||
@@ -86,7 +86,7 @@ void Director::init() {
|
|||||||
#endif
|
#endif
|
||||||
loadAssets(); // Crea el índice de archivos
|
loadAssets(); // Crea el índice de archivos
|
||||||
Input::init(Asset::get()->get("gamecontrollerdb.txt"), Asset::get()->get("controllers.json")); // Carga configuración de controles
|
Input::init(Asset::get()->get("gamecontrollerdb.txt"), Asset::get()->get("controllers.json")); // Carga configuración de controles
|
||||||
Options::setConfigFile(Asset::get()->get("config_v2.txt")); // Establece el fichero de configuración
|
Options::setConfigFile(Asset::get()->get("config_v2.txt")); // Establece el fichero de configuración
|
||||||
Options::setControllersFile(Asset::get()->get("controllers.json")); // Establece el fichero de configuración de mandos
|
Options::setControllersFile(Asset::get()->get("controllers.json")); // Establece el fichero de configuración de mandos
|
||||||
Options::loadFromFile(); // Carga el archivo de configuración
|
Options::loadFromFile(); // Carga el archivo de configuración
|
||||||
loadParams(); // Carga los parámetros del programa
|
loadParams(); // Carga los parámetros del programa
|
||||||
@@ -173,7 +173,7 @@ void Director::loadAssets() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los parametros del programa
|
// Comprueba los parametros del programa
|
||||||
void Director::checkProgramArguments(int argc, std::span<char *> argv) {
|
void Director::checkProgramArguments(int argc, std::span<char*> argv) {
|
||||||
// Obtener la ruta absoluta del ejecutable
|
// Obtener la ruta absoluta del ejecutable
|
||||||
std::filesystem::path exe_path = std::filesystem::absolute(argv[0]);
|
std::filesystem::path exe_path = std::filesystem::absolute(argv[0]);
|
||||||
executable_path_ = exe_path.parent_path().string();
|
executable_path_ = exe_path.parent_path().string();
|
||||||
@@ -196,7 +196,7 @@ void Director::checkProgramArguments(int argc, std::span<char *> argv) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Crea la carpeta del sistema donde guardar datos
|
// Crea la carpeta del sistema donde guardar datos
|
||||||
void Director::createSystemFolder(const std::string &folder) {
|
void Director::createSystemFolder(const std::string& folder) {
|
||||||
auto result = SystemUtils::createApplicationFolder(folder, system_folder_);
|
auto result = SystemUtils::createApplicationFolder(folder, system_folder_);
|
||||||
|
|
||||||
if (result != SystemUtils::Result::SUCCESS) {
|
if (result != SystemUtils::Result::SUCCESS) {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ enum class Code : int;
|
|||||||
class Director {
|
class Director {
|
||||||
public:
|
public:
|
||||||
// --- Constructor y destructor ---
|
// --- Constructor y destructor ---
|
||||||
Director(int argc, std::span<char *> argv);
|
Director(int argc, std::span<char*> argv);
|
||||||
~Director();
|
~Director();
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Bucle principal ---
|
||||||
@@ -29,11 +29,11 @@ class Director {
|
|||||||
// --- Configuración inicial ---
|
// --- Configuración inicial ---
|
||||||
static void loadParams(); // Carga los parámetros del programa
|
static void loadParams(); // Carga los parámetros del programa
|
||||||
static void loadScoreFile(); // Carga el fichero de puntuaciones
|
static void loadScoreFile(); // Carga el fichero de puntuaciones
|
||||||
void createSystemFolder(const std::string &folder); // Crea la carpeta del sistema
|
void createSystemFolder(const std::string& folder); // Crea la carpeta del sistema
|
||||||
|
|
||||||
// --- Gestión de entrada y archivos ---
|
// --- Gestión de entrada y archivos ---
|
||||||
void loadAssets(); // Crea el índice de archivos disponibles
|
void loadAssets(); // Crea el índice de archivos disponibles
|
||||||
void checkProgramArguments(int argc, std::span<char *> argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays)
|
void checkProgramArguments(int argc, std::span<char*> argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays)
|
||||||
|
|
||||||
// --- Secciones del programa ---
|
// --- Secciones del programa ---
|
||||||
static void runLogo(); // Ejecuta la pantalla con el logo
|
static void runLogo(); // Ejecuta la pantalla con el logo
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "enter_name.h"
|
#include "enter_name.hpp"
|
||||||
|
|
||||||
#include <array> // Para array
|
#include <array> // Para array
|
||||||
#include <cstdlib> // Para rand
|
#include <cstdlib> // Para rand
|
||||||
@@ -10,7 +10,7 @@ EnterName::EnterName()
|
|||||||
selected_index_(0) {}
|
selected_index_(0) {}
|
||||||
|
|
||||||
// Inicializa el objeto
|
// Inicializa el objeto
|
||||||
void EnterName::init(const std::string &name) {
|
void EnterName::init(const std::string& name) {
|
||||||
name_ = sanitizeName(name);
|
name_ = sanitizeName(name);
|
||||||
selected_index_ = 0;
|
selected_index_ = 0;
|
||||||
}
|
}
|
||||||
@@ -80,7 +80,7 @@ auto EnterName::getCarousel(int size) const -> std::string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Valida y limpia el nombre: solo caracteres legales y longitud máxima
|
// Valida y limpia el nombre: solo caracteres legales y longitud máxima
|
||||||
auto EnterName::sanitizeName(const std::string &name) const -> std::string {
|
auto EnterName::sanitizeName(const std::string& name) const -> std::string {
|
||||||
std::string sanitized;
|
std::string sanitized;
|
||||||
|
|
||||||
for (size_t i = 0; i < name.length() && sanitized.length() < MAX_NAME_SIZE; ++i) {
|
for (size_t i = 0; i < name.length() && sanitized.length() < MAX_NAME_SIZE; ++i) {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ class EnterName {
|
|||||||
EnterName();
|
EnterName();
|
||||||
~EnterName() = default;
|
~EnterName() = default;
|
||||||
|
|
||||||
void init(const std::string &name = ""); // Inicializa con nombre opcional (vacío por defecto)
|
void init(const std::string& name = ""); // Inicializa con nombre opcional (vacío por defecto)
|
||||||
|
|
||||||
void incIndex(); // Incrementa el índice del carácter seleccionado en la lista
|
void incIndex(); // Incrementa el índice del carácter seleccionado en la lista
|
||||||
void decIndex(); // Decrementa el índice del carácter seleccionado en la lista
|
void decIndex(); // Decrementa el índice del carácter seleccionado en la lista
|
||||||
@@ -20,11 +20,11 @@ class EnterName {
|
|||||||
void addCharacter(); // Añade el carácter seleccionado al nombre
|
void addCharacter(); // Añade el carácter seleccionado al nombre
|
||||||
void removeLastCharacter(); // Elimina el último carácter del nombre
|
void removeLastCharacter(); // Elimina el último carácter del nombre
|
||||||
|
|
||||||
auto getFinalName() -> std::string; // Obtiene el nombre final (o aleatorio si vacío)
|
auto getFinalName() -> std::string; // Obtiene el nombre final (o aleatorio si vacío)
|
||||||
[[nodiscard]] auto getCurrentName() const -> std::string { return name_; } // Obtiene el nombre actual en proceso
|
[[nodiscard]] auto getCurrentName() const -> std::string { return name_; } // Obtiene el nombre actual en proceso
|
||||||
[[nodiscard]] auto getSelectedCharacter(int offset = 0) const -> std::string; // Devuelve el carácter seleccionado con offset relativo
|
[[nodiscard]] auto getSelectedCharacter(int offset = 0) const -> std::string; // Devuelve el carácter seleccionado con offset relativo
|
||||||
[[nodiscard]] auto getCarousel(int size) const -> std::string; // Devuelve el carrusel de caracteres (size debe ser impar)
|
[[nodiscard]] auto getCarousel(int size) const -> std::string; // Devuelve el carrusel de caracteres (size debe ser impar)
|
||||||
[[nodiscard]] auto getSelectedIndex() const -> int { return selected_index_; } // Obtiene el índice del carácter seleccionado
|
[[nodiscard]] auto getSelectedIndex() const -> int { return selected_index_; } // Obtiene el índice del carácter seleccionado
|
||||||
[[nodiscard]] auto getCharacterList() const -> const std::string& { return character_list_; } // Obtiene la lista completa de caracteres
|
[[nodiscard]] auto getCharacterList() const -> const std::string& { return character_list_; } // Obtiene la lista completa de caracteres
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -33,6 +33,6 @@ class EnterName {
|
|||||||
std::string name_; // Nombre en proceso
|
std::string name_; // Nombre en proceso
|
||||||
int selected_index_ = 0; // Índice del carácter seleccionado en "character_list_"
|
int selected_index_ = 0; // Índice del carácter seleccionado en "character_list_"
|
||||||
|
|
||||||
[[nodiscard]] auto sanitizeName(const std::string &name) const -> std::string; // Valida y limpia el nombre
|
[[nodiscard]] auto sanitizeName(const std::string& name) const -> std::string; // Valida y limpia el nombre
|
||||||
static auto getRandomName() -> std::string; // Devuelve un nombre al azar
|
static auto getRandomName() -> std::string; // Devuelve un nombre al azar
|
||||||
};
|
};
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
#include "explosions.h"
|
#include "explosions.hpp"
|
||||||
|
|
||||||
#include <algorithm> // Para max
|
#include <algorithm> // Para max
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
|
|
||||||
class Texture; // lines 4-4
|
class Texture; // lines 4-4
|
||||||
|
|
||||||
// Actualiza la lógica de la clase (time-based)
|
// Actualiza la lógica de la clase (time-based)
|
||||||
void Explosions::update(float deltaTime) {
|
void Explosions::update(float deltaTime) {
|
||||||
for (auto &explosion : explosions_) {
|
for (auto& explosion : explosions_) {
|
||||||
explosion->update(deltaTime);
|
explosion->update(deltaTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,13 +18,13 @@ void Explosions::update(float deltaTime) {
|
|||||||
|
|
||||||
// Dibuja el objeto en pantalla
|
// Dibuja el objeto en pantalla
|
||||||
void Explosions::render() {
|
void Explosions::render() {
|
||||||
for (auto &explosion : explosions_) {
|
for (auto& explosion : explosions_) {
|
||||||
explosion->render();
|
explosion->render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade texturas al objeto
|
// Añade texturas al objeto
|
||||||
void Explosions::addTexture(int size, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation) {
|
void Explosions::addTexture(int size, const std::shared_ptr<Texture>& texture, const std::vector<std::string>& animation) {
|
||||||
textures_.emplace_back(size, texture, animation);
|
textures_.emplace_back(size, texture, animation);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ struct ExplosionTexture {
|
|||||||
std::shared_ptr<Texture> texture; // Textura para la explosión
|
std::shared_ptr<Texture> texture; // Textura para la explosión
|
||||||
std::vector<std::string> animation; // Animación para la textura
|
std::vector<std::string> animation; // Animación para la textura
|
||||||
|
|
||||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string>& anim)
|
||||||
: size(sz),
|
: size(sz),
|
||||||
texture(std::move(tex)),
|
texture(std::move(tex)),
|
||||||
animation(anim) {}
|
animation(anim) {}
|
||||||
@@ -29,11 +29,11 @@ class Explosions {
|
|||||||
~Explosions() = default; // Destructor por defecto
|
~Explosions() = default; // Destructor por defecto
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(float deltaTime); // Actualiza la lógica de la clase (time-based)
|
void update(float deltaTime); // Actualiza la lógica de la clase (time-based)
|
||||||
void render(); // Dibuja el objeto en pantalla
|
void render(); // Dibuja el objeto en pantalla
|
||||||
|
|
||||||
// --- Configuración ---
|
// --- Configuración ---
|
||||||
void addTexture(int size, const std::shared_ptr<Texture> &texture, const std::vector<std::string> &animation); // Añade texturas al objeto
|
void addTexture(int size, const std::shared_ptr<Texture>& texture, const std::vector<std::string>& animation); // Añade texturas al objeto
|
||||||
void add(int x, int y, int size); // Añade una explosión
|
void add(int x, int y, int size); // Añade una explosión
|
||||||
|
|
||||||
private:
|
private:
|
||||||
2
source/external/gif.cpp
vendored
2
source/external/gif.cpp
vendored
@@ -1,4 +1,4 @@
|
|||||||
#include "gif.h"
|
#include "gif.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogError, SDL_LogCategory, SDL_LogInfo
|
#include <SDL3/SDL.h> // Para SDL_LogError, SDL_LogCategory, SDL_LogInfo
|
||||||
#include <cstring> // Para memcpy, size_t
|
#include <cstring> // Para memcpy, size_t
|
||||||
|
|||||||
2
source/external/stb_image.h
vendored
2
source/external/stb_image.h
vendored
@@ -10,7 +10,7 @@
|
|||||||
#include ...
|
#include ...
|
||||||
#include ...
|
#include ...
|
||||||
#define STB_IMAGE_IMPLEMENTATION
|
#define STB_IMAGE_IMPLEMENTATION
|
||||||
#include "stb_image.h"
|
#include "stb_image.hpp"
|
||||||
|
|
||||||
You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.
|
You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.
|
||||||
And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free
|
And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
#include "fade.h"
|
#include "fade.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_FRect, SDL_GetRenderTarget, SDL_RenderFillRect, SDL_SetRenderDrawBlendMode, SDL_SetRenderDrawColor, Uint8, SDL_GetRenderDrawBlendMode, SDL_BLENDMODE_NONE, SDL_BlendMode, SDL_CreateTexture, SDL_DestroyTexture, SDL_RenderClear, SDL_RenderTexture, SDL_SetTextureAlphaMod, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_TextureAccess
|
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_FRect, SDL_GetRenderTarget, SDL_RenderFillRect, SDL_SetRenderDrawBlendMode, SDL_SetRenderDrawColor, Uint8, SDL_GetRenderDrawBlendMode, SDL_BLENDMODE_NONE, SDL_BlendMode, SDL_CreateTexture, SDL_DestroyTexture, SDL_RenderClear, SDL_RenderTexture, SDL_SetTextureAlphaMod, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_TextureAccess
|
||||||
|
|
||||||
#include <algorithm> // Para min, max
|
#include <algorithm> // Para min, max
|
||||||
#include <cstdlib> // Para rand, size_t
|
#include <cstdlib> // Para rand, size_t
|
||||||
|
|
||||||
#include "color.h" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamFade
|
#include "param.hpp" // Para Param, param, ParamGame, ParamFade
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Fade::Fade()
|
Fade::Fade()
|
||||||
@@ -170,7 +170,7 @@ void Fade::updateCenterFade() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Fade::drawCenterFadeRectangles() {
|
void Fade::drawCenterFadeRectangles() {
|
||||||
auto *temp = SDL_GetRenderTarget(renderer_);
|
auto* temp = SDL_GetRenderTarget(renderer_);
|
||||||
SDL_SetRenderTarget(renderer_, backbuffer_);
|
SDL_SetRenderTarget(renderer_, backbuffer_);
|
||||||
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_);
|
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_);
|
||||||
|
|
||||||
@@ -378,7 +378,7 @@ void Fade::activateDiagonal(int diagonal_index, Uint32 current_time) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Fade::drawDiagonal() {
|
void Fade::drawDiagonal() {
|
||||||
auto *temp = SDL_GetRenderTarget(renderer_);
|
auto* temp = SDL_GetRenderTarget(renderer_);
|
||||||
SDL_SetRenderTarget(renderer_, backbuffer_);
|
SDL_SetRenderTarget(renderer_, backbuffer_);
|
||||||
|
|
||||||
// CRÍTICO: Limpiar la textura antes de dibujar
|
// CRÍTICO: Limpiar la textura antes de dibujar
|
||||||
@@ -425,7 +425,7 @@ void Fade::drawDiagonal() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Fade::drawRandomSquares(int active_count) {
|
void Fade::drawRandomSquares(int active_count) {
|
||||||
auto *temp = SDL_GetRenderTarget(renderer_);
|
auto* temp = SDL_GetRenderTarget(renderer_);
|
||||||
SDL_SetRenderTarget(renderer_, backbuffer_);
|
SDL_SetRenderTarget(renderer_, backbuffer_);
|
||||||
|
|
||||||
SDL_BlendMode blend_mode;
|
SDL_BlendMode blend_mode;
|
||||||
@@ -443,7 +443,7 @@ void Fade::drawRandomSquares(int active_count) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Fade::drawRandomSquares2() {
|
void Fade::drawRandomSquares2() {
|
||||||
auto *temp = SDL_GetRenderTarget(renderer_);
|
auto* temp = SDL_GetRenderTarget(renderer_);
|
||||||
SDL_SetRenderTarget(renderer_, backbuffer_);
|
SDL_SetRenderTarget(renderer_, backbuffer_);
|
||||||
|
|
||||||
// CRÍTICO: Limpiar la textura antes de dibujar
|
// CRÍTICO: Limpiar la textura antes de dibujar
|
||||||
@@ -500,7 +500,7 @@ void Fade::updateVenetianFade() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Fade::drawVenetianBlinds() {
|
void Fade::drawVenetianBlinds() {
|
||||||
auto *temp = SDL_GetRenderTarget(renderer_);
|
auto* temp = SDL_GetRenderTarget(renderer_);
|
||||||
SDL_SetRenderTarget(renderer_, backbuffer_);
|
SDL_SetRenderTarget(renderer_, backbuffer_);
|
||||||
|
|
||||||
SDL_BlendMode blend_mode;
|
SDL_BlendMode blend_mode;
|
||||||
@@ -508,7 +508,7 @@ void Fade::drawVenetianBlinds() {
|
|||||||
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_NONE);
|
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_NONE);
|
||||||
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_);
|
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_);
|
||||||
|
|
||||||
for (const auto &rect : square_) {
|
for (const auto& rect : square_) {
|
||||||
SDL_RenderFillRect(renderer_, &rect);
|
SDL_RenderFillRect(renderer_, &rect);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -525,7 +525,7 @@ void Fade::updateVenetianRectangles() {
|
|||||||
|
|
||||||
void Fade::calculateVenetianProgress() {
|
void Fade::calculateVenetianProgress() {
|
||||||
int completed = 0;
|
int completed = 0;
|
||||||
for (const auto &square : square_) {
|
for (const auto& square : square_) {
|
||||||
if (square.h >= param.fade.venetian_size) {
|
if (square.h >= param.fade.venetian_size) {
|
||||||
++completed;
|
++completed;
|
||||||
}
|
}
|
||||||
@@ -699,7 +699,7 @@ void Fade::setColor(Color color) {
|
|||||||
// Limpia el backbuffer
|
// Limpia el backbuffer
|
||||||
void Fade::cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
|
void Fade::cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
|
||||||
// Dibujamos sobre el backbuffer_
|
// Dibujamos sobre el backbuffer_
|
||||||
auto *temp = SDL_GetRenderTarget(renderer_);
|
auto* temp = SDL_GetRenderTarget(renderer_);
|
||||||
SDL_SetRenderTarget(renderer_, backbuffer_);
|
SDL_SetRenderTarget(renderer_, backbuffer_);
|
||||||
|
|
||||||
// Pintamos la textura con el color del fade
|
// Pintamos la textura con el color del fade
|
||||||
|
|||||||
@@ -58,8 +58,8 @@ class Fade {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // Renderizador de la ventana
|
SDL_Renderer* renderer_; // Renderizador de la ventana
|
||||||
SDL_Texture *backbuffer_; // Backbuffer para efectos
|
SDL_Texture* backbuffer_; // Backbuffer para efectos
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
std::vector<SDL_FRect> square_; // Vector de cuadrados
|
std::vector<SDL_FRect> square_; // Vector de cuadrados
|
||||||
@@ -1,22 +1,22 @@
|
|||||||
#include "game_logo.h"
|
#include "game_logo.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_SetTextureScaleMode, SDL_FlipMode, SDL_ScaleMode
|
#include <SDL3/SDL.h> // Para SDL_SetTextureScaleMode, SDL_FlipMode, SDL_ScaleMode
|
||||||
|
|
||||||
#include <algorithm> // Para max
|
#include <algorithm> // Para max
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "color.h" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamTitle
|
#include "param.hpp" // Para Param, param, ParamGame, ParamTitle
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "smart_sprite.h" // Para SmartSprite
|
#include "smart_sprite.hpp" // Para SmartSprite
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
|
|
||||||
constexpr int ZOOM_FACTOR = 5;
|
constexpr int ZOOM_FACTOR = 5;
|
||||||
constexpr float FLASH_DELAY_S = 0.05f; // 3 frames → 0.05s
|
constexpr float FLASH_DELAY_S = 0.05f; // 3 frames → 0.05s
|
||||||
constexpr float FLASH_DURATION_S = 0.1f; // 6 frames → 0.1s (3 + 3)
|
constexpr float FLASH_DURATION_S = 0.1f; // 6 frames → 0.1s (3 + 3)
|
||||||
constexpr Color FLASH_COLOR = Color(0xFF, 0xFF, 0xFF); // Color blanco para el flash
|
constexpr Color FLASH_COLOR = Color(0xFF, 0xFF, 0xFF); // Color blanco para el flash
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
@@ -193,10 +193,9 @@ void GameLogo::handleArcadeEditionShaking(float deltaTime) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void GameLogo::processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite, float deltaTime) {
|
void GameLogo::processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite, float deltaTime) {
|
||||||
shake_.time_accumulator += deltaTime;
|
shake_.time_accumulator += deltaTime;
|
||||||
|
|
||||||
if (shake_.time_accumulator >= SHAKE_DELAY_S) {
|
if (shake_.time_accumulator >= SHAKE_DELAY_S) {
|
||||||
shake_.time_accumulator -= SHAKE_DELAY_S;
|
shake_.time_accumulator -= SHAKE_DELAY_S;
|
||||||
const auto DISPLACEMENT = calculateShakeDisplacement();
|
const auto DISPLACEMENT = calculateShakeDisplacement();
|
||||||
@@ -211,9 +210,9 @@ void GameLogo::processShakeEffect(SmartSprite* primary_sprite, SmartSprite* seco
|
|||||||
void GameLogo::processArcadeEditionShake(float deltaTime) {
|
void GameLogo::processArcadeEditionShake(float deltaTime) {
|
||||||
// Delay fijo en segundos (shake_.delay era frames, ahora usamos constante)
|
// Delay fijo en segundos (shake_.delay era frames, ahora usamos constante)
|
||||||
float delayTime = SHAKE_DELAY_S;
|
float delayTime = SHAKE_DELAY_S;
|
||||||
|
|
||||||
shake_.time_accumulator += deltaTime;
|
shake_.time_accumulator += deltaTime;
|
||||||
|
|
||||||
if (shake_.time_accumulator >= delayTime) {
|
if (shake_.time_accumulator >= delayTime) {
|
||||||
shake_.time_accumulator -= delayTime;
|
shake_.time_accumulator -= delayTime;
|
||||||
const auto DISPLACEMENT = calculateShakeDisplacement();
|
const auto DISPLACEMENT = calculateShakeDisplacement();
|
||||||
@@ -255,7 +254,6 @@ void GameLogo::updateDustSprites(float deltaTime) {
|
|||||||
void GameLogo::updatePostFinishedCounter(float deltaTime) {
|
void GameLogo::updatePostFinishedCounter(float deltaTime) {
|
||||||
if (coffee_crisis_status_ == Status::FINISHED &&
|
if (coffee_crisis_status_ == Status::FINISHED &&
|
||||||
arcade_edition_status_ == Status::FINISHED) {
|
arcade_edition_status_ == Status::FINISHED) {
|
||||||
|
|
||||||
post_finished_timer_ += deltaTime;
|
post_finished_timer_ += deltaTime;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <memory> // Para unique_ptr, shared_ptr
|
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
|
||||||
#include "smart_sprite.h" // Para SmartSprite
|
|
||||||
#include "sprite.h" // Para Sprite
|
|
||||||
|
|
||||||
class Texture;
|
|
||||||
|
|
||||||
// --- Clase GameLogo: gestor del logo del juego ---
|
|
||||||
class GameLogo {
|
|
||||||
public:
|
|
||||||
// --- Constantes ---
|
|
||||||
static constexpr float COFFEE_VEL_Y = 0.15F * 1000.0F; // Velocidad Y de coffee sprite (pixels/s) - 0.15F * 1000 = 150 pixels/s
|
|
||||||
static constexpr float COFFEE_ACCEL_Y = 0.00036F * 1000000.0F; // Aceleración Y de coffee sprite (pixels/s²) - 0.00036F * 1000000 = 360 pixels/s²
|
|
||||||
static constexpr float CRISIS_VEL_Y = -0.15F * 1000.0F; // Velocidad Y de crisis sprite (pixels/s) - -0.15F * 1000 = -150 pixels/s
|
|
||||||
static constexpr float CRISIS_ACCEL_Y = -0.00036F * 1000000.0F; // Aceleración Y de crisis sprite (pixels/s²) - -0.00036F * 1000000 = -360 pixels/s²
|
|
||||||
static constexpr int CRISIS_OFFSET_X = 15; // Desplazamiento X de crisis sprite
|
|
||||||
static constexpr int DUST_SIZE = 16; // Tamaño de dust sprites
|
|
||||||
static constexpr float ZOOM_DECREMENT_PER_S = 0.006F * 1000.0F; // Decremento de zoom por segundo (0.006F * 1000 = 6.0F per second)
|
|
||||||
static constexpr float SHAKE_DELAY_S = 33.34F / 1000.0F; // Delay de shake en segundos (33.34ms / 1000 = 0.03334s)
|
|
||||||
static constexpr float POST_FINISHED_FRAME_TIME_S = 16.67F / 1000.0F; // Tiempo entre decrementos del counter (16.67ms / 1000 = 0.01667s)
|
|
||||||
|
|
||||||
// --- Constructores y destructor ---
|
|
||||||
GameLogo(int x, int y);
|
|
||||||
~GameLogo() = default;
|
|
||||||
|
|
||||||
// --- Métodos principales ---
|
|
||||||
void render(); // Pinta la clase en pantalla
|
|
||||||
void update(float deltaTime); // Actualiza la lógica de la clase (time-based)
|
|
||||||
void enable(); // Activa la clase
|
|
||||||
|
|
||||||
// --- Getters ---
|
|
||||||
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación
|
|
||||||
|
|
||||||
private:
|
|
||||||
// --- Enums ---
|
|
||||||
enum class Status {
|
|
||||||
DISABLED, // Deshabilitado
|
|
||||||
MOVING, // En movimiento
|
|
||||||
SHAKING, // Temblando
|
|
||||||
FINISHED, // Terminado
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- Estructuras privadas ---
|
|
||||||
struct Shake {
|
|
||||||
int desp = 1; // Pixels de desplazamiento para agitar la pantalla en el eje x
|
|
||||||
int delay = 2; // Retraso entre cada desplazamiento de la pantalla al agitarse (frame-based)
|
|
||||||
int length = 8; // Cantidad de desplazamientos a realizar
|
|
||||||
int remaining = length; // Cantidad de desplazamientos pendientes a realizar
|
|
||||||
int counter = delay; // Contador para el retraso (frame-based)
|
|
||||||
float time_accumulator = 0.0f; // Acumulador de tiempo para deltaTime
|
|
||||||
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
|
||||||
|
|
||||||
Shake() = default;
|
|
||||||
Shake(int d, int de, int l, int o)
|
|
||||||
: desp(d),
|
|
||||||
delay(de),
|
|
||||||
length(l),
|
|
||||||
remaining(l),
|
|
||||||
counter(de),
|
|
||||||
origin(o) {}
|
|
||||||
|
|
||||||
void init(int d, int de, int l, int o) {
|
|
||||||
desp = d;
|
|
||||||
delay = de;
|
|
||||||
length = l;
|
|
||||||
remaining = l;
|
|
||||||
counter = de;
|
|
||||||
time_accumulator = 0.0f;
|
|
||||||
origin = o;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
|
||||||
std::shared_ptr<Texture> dust_texture_; // Textura con los graficos del polvo
|
|
||||||
std::shared_ptr<Texture> coffee_texture_; // Textura con los graficos de la palabra "COFFEE"
|
|
||||||
std::shared_ptr<Texture> crisis_texture_; // Textura con los graficos de la palabra "CRISIS"
|
|
||||||
std::shared_ptr<Texture> arcade_edition_texture_; // Textura con los graficos de "Arcade Edition"
|
|
||||||
|
|
||||||
std::unique_ptr<AnimatedSprite> dust_left_sprite_; // Sprite del polvo (izquierda)
|
|
||||||
std::unique_ptr<AnimatedSprite> dust_right_sprite_; // Sprite del polvo (derecha)
|
|
||||||
std::unique_ptr<SmartSprite> coffee_sprite_; // Sprite de "COFFEE"
|
|
||||||
std::unique_ptr<SmartSprite> crisis_sprite_; // Sprite de "CRISIS"
|
|
||||||
std::unique_ptr<Sprite> arcade_edition_sprite_; // Sprite de "Arcade Edition"
|
|
||||||
|
|
||||||
// --- Variables de estado ---
|
|
||||||
Shake shake_; // Efecto de agitación
|
|
||||||
Status coffee_crisis_status_ = Status::DISABLED; // Estado de "COFFEE CRISIS"
|
|
||||||
Status arcade_edition_status_ = Status::DISABLED; // Estado de "ARCADE EDITION"
|
|
||||||
float x_; // Posición X del logo
|
|
||||||
float y_; // Posición Y del logo
|
|
||||||
float zoom_ = 1.0F; // Zoom aplicado al texto "ARCADE EDITION"
|
|
||||||
float post_finished_delay_s_ = POST_FINISHED_FRAME_TIME_S; // Retraso final tras animaciones (s)
|
|
||||||
float post_finished_timer_ = 0.0f; // Timer acumulado para retraso final (s)
|
|
||||||
|
|
||||||
// --- Inicialización ---
|
|
||||||
void init(); // Inicializa las variables
|
|
||||||
[[nodiscard]] auto getInitialVerticalDesp() const -> int; // Calcula el desplazamiento vertical inicial
|
|
||||||
|
|
||||||
// --- Actualización de estados específicos ---
|
|
||||||
void updateCoffeeCrisis(float deltaTime); // Actualiza el estado de "Coffee Crisis" (time-based)
|
|
||||||
void updateArcadeEdition(float deltaTime); // Actualiza el estado de "Arcade Edition" (time-based)
|
|
||||||
void updatePostFinishedCounter(float deltaTime); // Actualiza el contador tras finalizar una animación (time-based)
|
|
||||||
|
|
||||||
// --- Efectos visuales: movimiento y sacudidas ---
|
|
||||||
void handleCoffeeCrisisMoving(float deltaTime); // Maneja el movimiento de "Coffee Crisis" (time-based)
|
|
||||||
void handleCoffeeCrisisShaking(float deltaTime); // Maneja la sacudida de "Coffee Crisis" (time-based)
|
|
||||||
void handleArcadeEditionMoving(float deltaTime); // Maneja el movimiento de "Arcade Edition" (time-based)
|
|
||||||
void handleArcadeEditionShaking(float deltaTime); // Maneja la sacudida de "Arcade Edition" (time-based)
|
|
||||||
void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite = nullptr); // Procesa el efecto de sacudida en sprites (frame-based)
|
|
||||||
void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite, float deltaTime); // Procesa el efecto de sacudida en sprites (time-based)
|
|
||||||
void processArcadeEditionShake(float deltaTime); // Procesa la sacudida específica de "Arcade Edition" (time-based)
|
|
||||||
[[nodiscard]] auto calculateShakeDisplacement() const -> int; // Calcula el desplazamiento de la sacudida
|
|
||||||
|
|
||||||
// --- Gestión de finalización de efectos ---
|
|
||||||
void handleCoffeeCrisisFinished(float deltaTime); // Maneja el final de la animación "Coffee Crisis" (time-based)
|
|
||||||
void finishCoffeeCrisisShaking(); // Finaliza la sacudida de "Coffee Crisis"
|
|
||||||
void finishArcadeEditionMoving(); // Finaliza el movimiento de "Arcade Edition"
|
|
||||||
|
|
||||||
// --- Utilidades ---
|
|
||||||
static void playTitleEffects(); // Reproduce efectos visuales/sonoros del título
|
|
||||||
void updateDustSprites(float deltaTime); // Actualiza los sprites de polvo (time-based)
|
|
||||||
};
|
|
||||||
125
source/game_logo.hpp
Normal file
125
source/game_logo.hpp
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
|
|
||||||
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
|
#include "smart_sprite.hpp" // Para SmartSprite
|
||||||
|
#include "sprite.hpp" // Para Sprite
|
||||||
|
|
||||||
|
class Texture;
|
||||||
|
|
||||||
|
// --- Clase GameLogo: gestor del logo del juego ---
|
||||||
|
class GameLogo {
|
||||||
|
public:
|
||||||
|
// --- Constantes ---
|
||||||
|
static constexpr float COFFEE_VEL_Y = 0.15F * 1000.0F; // Velocidad Y de coffee sprite (pixels/s) - 0.15F * 1000 = 150 pixels/s
|
||||||
|
static constexpr float COFFEE_ACCEL_Y = 0.00036F * 1000000.0F; // Aceleración Y de coffee sprite (pixels/s²) - 0.00036F * 1000000 = 360 pixels/s²
|
||||||
|
static constexpr float CRISIS_VEL_Y = -0.15F * 1000.0F; // Velocidad Y de crisis sprite (pixels/s) - -0.15F * 1000 = -150 pixels/s
|
||||||
|
static constexpr float CRISIS_ACCEL_Y = -0.00036F * 1000000.0F; // Aceleración Y de crisis sprite (pixels/s²) - -0.00036F * 1000000 = -360 pixels/s²
|
||||||
|
static constexpr int CRISIS_OFFSET_X = 15; // Desplazamiento X de crisis sprite
|
||||||
|
static constexpr int DUST_SIZE = 16; // Tamaño de dust sprites
|
||||||
|
static constexpr float ZOOM_DECREMENT_PER_S = 0.006F * 1000.0F; // Decremento de zoom por segundo (0.006F * 1000 = 6.0F per second)
|
||||||
|
static constexpr float SHAKE_DELAY_S = 33.34F / 1000.0F; // Delay de shake en segundos (33.34ms / 1000 = 0.03334s)
|
||||||
|
static constexpr float POST_FINISHED_FRAME_TIME_S = 16.67F / 1000.0F; // Tiempo entre decrementos del counter (16.67ms / 1000 = 0.01667s)
|
||||||
|
|
||||||
|
// --- Constructores y destructor ---
|
||||||
|
GameLogo(int x, int y);
|
||||||
|
~GameLogo() = default;
|
||||||
|
|
||||||
|
// --- Métodos principales ---
|
||||||
|
void render(); // Pinta la clase en pantalla
|
||||||
|
void update(float deltaTime); // Actualiza la lógica de la clase (time-based)
|
||||||
|
void enable(); // Activa la clase
|
||||||
|
|
||||||
|
// --- Getters ---
|
||||||
|
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación
|
||||||
|
|
||||||
|
private:
|
||||||
|
// --- Enums ---
|
||||||
|
enum class Status {
|
||||||
|
DISABLED, // Deshabilitado
|
||||||
|
MOVING, // En movimiento
|
||||||
|
SHAKING, // Temblando
|
||||||
|
FINISHED, // Terminado
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Estructuras privadas ---
|
||||||
|
struct Shake {
|
||||||
|
int desp = 1; // Pixels de desplazamiento para agitar la pantalla en el eje x
|
||||||
|
int delay = 2; // Retraso entre cada desplazamiento de la pantalla al agitarse (frame-based)
|
||||||
|
int length = 8; // Cantidad de desplazamientos a realizar
|
||||||
|
int remaining = length; // Cantidad de desplazamientos pendientes a realizar
|
||||||
|
int counter = delay; // Contador para el retraso (frame-based)
|
||||||
|
float time_accumulator = 0.0f; // Acumulador de tiempo para deltaTime
|
||||||
|
int origin = 0; // Valor inicial de la pantalla para dejarla igual tras el desplazamiento
|
||||||
|
|
||||||
|
Shake() = default;
|
||||||
|
Shake(int d, int de, int l, int o)
|
||||||
|
: desp(d),
|
||||||
|
delay(de),
|
||||||
|
length(l),
|
||||||
|
remaining(l),
|
||||||
|
counter(de),
|
||||||
|
origin(o) {}
|
||||||
|
|
||||||
|
void init(int d, int de, int l, int o) {
|
||||||
|
desp = d;
|
||||||
|
delay = de;
|
||||||
|
length = l;
|
||||||
|
remaining = l;
|
||||||
|
counter = de;
|
||||||
|
time_accumulator = 0.0f;
|
||||||
|
origin = o;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Objetos y punteros ---
|
||||||
|
std::shared_ptr<Texture> dust_texture_; // Textura con los graficos del polvo
|
||||||
|
std::shared_ptr<Texture> coffee_texture_; // Textura con los graficos de la palabra "COFFEE"
|
||||||
|
std::shared_ptr<Texture> crisis_texture_; // Textura con los graficos de la palabra "CRISIS"
|
||||||
|
std::shared_ptr<Texture> arcade_edition_texture_; // Textura con los graficos de "Arcade Edition"
|
||||||
|
|
||||||
|
std::unique_ptr<AnimatedSprite> dust_left_sprite_; // Sprite del polvo (izquierda)
|
||||||
|
std::unique_ptr<AnimatedSprite> dust_right_sprite_; // Sprite del polvo (derecha)
|
||||||
|
std::unique_ptr<SmartSprite> coffee_sprite_; // Sprite de "COFFEE"
|
||||||
|
std::unique_ptr<SmartSprite> crisis_sprite_; // Sprite de "CRISIS"
|
||||||
|
std::unique_ptr<Sprite> arcade_edition_sprite_; // Sprite de "Arcade Edition"
|
||||||
|
|
||||||
|
// --- Variables de estado ---
|
||||||
|
Shake shake_; // Efecto de agitación
|
||||||
|
Status coffee_crisis_status_ = Status::DISABLED; // Estado de "COFFEE CRISIS"
|
||||||
|
Status arcade_edition_status_ = Status::DISABLED; // Estado de "ARCADE EDITION"
|
||||||
|
float x_; // Posición X del logo
|
||||||
|
float y_; // Posición Y del logo
|
||||||
|
float zoom_ = 1.0F; // Zoom aplicado al texto "ARCADE EDITION"
|
||||||
|
float post_finished_delay_s_ = POST_FINISHED_FRAME_TIME_S; // Retraso final tras animaciones (s)
|
||||||
|
float post_finished_timer_ = 0.0f; // Timer acumulado para retraso final (s)
|
||||||
|
|
||||||
|
// --- Inicialización ---
|
||||||
|
void init(); // Inicializa las variables
|
||||||
|
[[nodiscard]] auto getInitialVerticalDesp() const -> int; // Calcula el desplazamiento vertical inicial
|
||||||
|
|
||||||
|
// --- Actualización de estados específicos ---
|
||||||
|
void updateCoffeeCrisis(float deltaTime); // Actualiza el estado de "Coffee Crisis" (time-based)
|
||||||
|
void updateArcadeEdition(float deltaTime); // Actualiza el estado de "Arcade Edition" (time-based)
|
||||||
|
void updatePostFinishedCounter(float deltaTime); // Actualiza el contador tras finalizar una animación (time-based)
|
||||||
|
|
||||||
|
// --- Efectos visuales: movimiento y sacudidas ---
|
||||||
|
void handleCoffeeCrisisMoving(float deltaTime); // Maneja el movimiento de "Coffee Crisis" (time-based)
|
||||||
|
void handleCoffeeCrisisShaking(float deltaTime); // Maneja la sacudida de "Coffee Crisis" (time-based)
|
||||||
|
void handleArcadeEditionMoving(float deltaTime); // Maneja el movimiento de "Arcade Edition" (time-based)
|
||||||
|
void handleArcadeEditionShaking(float deltaTime); // Maneja la sacudida de "Arcade Edition" (time-based)
|
||||||
|
void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite = nullptr); // Procesa el efecto de sacudida en sprites (frame-based)
|
||||||
|
void processShakeEffect(SmartSprite* primary_sprite, SmartSprite* secondary_sprite, float deltaTime); // Procesa el efecto de sacudida en sprites (time-based)
|
||||||
|
void processArcadeEditionShake(float deltaTime); // Procesa la sacudida específica de "Arcade Edition" (time-based)
|
||||||
|
[[nodiscard]] auto calculateShakeDisplacement() const -> int; // Calcula el desplazamiento de la sacudida
|
||||||
|
|
||||||
|
// --- Gestión de finalización de efectos ---
|
||||||
|
void handleCoffeeCrisisFinished(float deltaTime); // Maneja el final de la animación "Coffee Crisis" (time-based)
|
||||||
|
void finishCoffeeCrisisShaking(); // Finaliza la sacudida de "Coffee Crisis"
|
||||||
|
void finishArcadeEditionMoving(); // Finaliza el movimiento de "Arcade Edition"
|
||||||
|
|
||||||
|
// --- Utilidades ---
|
||||||
|
static void playTitleEffects(); // Reproduce efectos visuales/sonoros del título
|
||||||
|
void updateDustSprites(float deltaTime); // Actualiza los sprites de polvo (time-based)
|
||||||
|
};
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "external/json.hpp"
|
#include "external/json.hpp"
|
||||||
#include "input_types.h" // Solo incluimos los tipos compartidos
|
#include "input_types.hpp" // Solo incluimos los tipos compartidos
|
||||||
|
|
||||||
// --- Estructuras ---
|
// --- Estructuras ---
|
||||||
struct GamepadConfig {
|
struct GamepadConfig {
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "global_events.h"
|
#include "global_events.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_EventType, SDL_Event, SDL_LogInfo, SDL_LogCategory
|
#include <SDL3/SDL.h> // Para SDL_EventType, SDL_Event, SDL_LogInfo, SDL_LogCategory
|
||||||
|
|
||||||
@@ -6,19 +6,19 @@
|
|||||||
#include <string> // Para allocator, operator+, string
|
#include <string> // Para allocator, operator+, string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "lang.h" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "mouse.h" // Para handleEvent
|
#include "mouse.hpp" // Para handleEvent
|
||||||
#include "options.h" // Para GamepadManager, gamepad_manager
|
#include "options.hpp" // Para GamepadManager, gamepad_manager
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "section.hpp" // Para Name, Options, name, options
|
#include "section.hpp" // Para Name, Options, name, options
|
||||||
#include "ui/notifier.h" // Para Notifier
|
#include "ui/notifier.hpp" // Para Notifier
|
||||||
#include "ui/service_menu.h" // Para ServiceMenu
|
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||||
|
|
||||||
namespace GlobalEvents {
|
namespace GlobalEvents {
|
||||||
// Comprueba los eventos de Input y muestra notificaciones
|
// Comprueba los eventos de Input y muestra notificaciones
|
||||||
void handleInputEvents(const SDL_Event &event) {
|
void handleInputEvents(const SDL_Event& event) {
|
||||||
static auto *input_ = Input::get();
|
static auto* input_ = Input::get();
|
||||||
auto message = input_->handleEvent(event);
|
auto message = input_->handleEvent(event);
|
||||||
|
|
||||||
if (message.empty()) {
|
if (message.empty()) {
|
||||||
@@ -41,7 +41,7 @@ void handleInputEvents(const SDL_Event &event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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 handle(const SDL_Event &event) {
|
void handle(const SDL_Event& event) {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case SDL_EVENT_QUIT: // Evento de salida de la aplicación
|
case SDL_EVENT_QUIT: // Evento de salida de la aplicación
|
||||||
Section::name = Section::Name::QUIT;
|
Section::name = Section::Name::QUIT;
|
||||||
|
|||||||
@@ -5,5 +5,5 @@
|
|||||||
// --- Namespace GlobalEvents: maneja eventos globales del juego ---
|
// --- Namespace GlobalEvents: maneja eventos globales del juego ---
|
||||||
namespace GlobalEvents {
|
namespace GlobalEvents {
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void handle(const SDL_Event &event); // Comprueba los eventos que se pueden producir en cualquier sección del juego
|
void handle(const SDL_Event& event); // Comprueba los eventos que se pueden producir en cualquier sección del juego
|
||||||
} // namespace GlobalEvents
|
} // namespace GlobalEvents
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "global_inputs.h"
|
#include "global_inputs.hpp"
|
||||||
|
|
||||||
#include <algorithm> // Para std::ranges::any_of
|
#include <algorithm> // Para std::ranges::any_of
|
||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
@@ -7,16 +7,16 @@
|
|||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "input_types.h" // Para InputAction
|
#include "input_types.hpp" // Para InputAction
|
||||||
#include "lang.h" // Para getText, getLangFile, getLangName, getNextLangCode, loadFromFile
|
#include "lang.hpp" // Para getText, getLangFile, getLangName, getNextLangCode, loadFromFile
|
||||||
#include "options.h" // Para Video, video, Settings, settings, Audio, audio, Window, window
|
#include "options.hpp" // Para Video, video, Settings, settings, Audio, audio, Window, window
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "section.hpp" // Para Name, name, Options, options, AttractMode, attract_mode
|
#include "section.hpp" // Para Name, name, Options, options, AttractMode, attract_mode
|
||||||
#include "ui/notifier.h" // Para Notifier
|
#include "ui/notifier.hpp" // Para Notifier
|
||||||
#include "ui/service_menu.h" // Para ServiceMenu
|
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||||
#include "utils.h" // Para boolToOnOff
|
#include "utils.hpp" // Para boolToOnOff
|
||||||
|
|
||||||
namespace GlobalInputs {
|
namespace GlobalInputs {
|
||||||
// Termina
|
// Termina
|
||||||
|
|||||||
@@ -4,8 +4,8 @@
|
|||||||
|
|
||||||
#include <memory> // Para std::unique_ptr y std::shared_ptr
|
#include <memory> // Para std::unique_ptr y std::shared_ptr
|
||||||
|
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
|
|
||||||
// --- Estructura Hit: representa una colisión o impacto visual ---
|
// --- Estructura Hit: representa una colisión o impacto visual ---
|
||||||
struct Hit {
|
struct Hit {
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "input.h"
|
#include "input.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_GetGamepadAxis, SDL_GetError, SDL_GamepadAxis, SDL_JoystickID, SDL_AddGamepadMappingsFromFile, SDL_Event, SDL_EventType, SDL_GetGamepadButton, SDL_GetKeyboardState, SDL_INIT_GAMEPAD, SDL_InitSubSystem, SDL_LogCategory, SDL_LogError, SDL_LogInfo, SDL_OpenGamepad, SDL_PollEvent, SDL_WasInit, SDL_Gamepad, SDL_Scancode
|
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_GetGamepadAxis, SDL_GetError, SDL_GamepadAxis, SDL_JoystickID, SDL_AddGamepadMappingsFromFile, SDL_Event, SDL_EventType, SDL_GetGamepadButton, SDL_GetKeyboardState, SDL_INIT_GAMEPAD, SDL_InitSubSystem, SDL_LogCategory, SDL_LogError, SDL_LogInfo, SDL_OpenGamepad, SDL_PollEvent, SDL_WasInit, SDL_Gamepad, SDL_Scancode
|
||||||
|
|
||||||
@@ -9,10 +9,10 @@
|
|||||||
#include <utility> // Para pair, move
|
#include <utility> // Para pair, move
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Input *Input::instance = nullptr;
|
Input* Input::instance = nullptr;
|
||||||
|
|
||||||
// Inicializa la instancia única del singleton
|
// Inicializa la instancia única del singleton
|
||||||
void Input::init(const std::string &game_controller_db_path, const std::string &gamepad_configs_file) {
|
void Input::init(const std::string& game_controller_db_path, const std::string& gamepad_configs_file) {
|
||||||
Input::instance = new Input(game_controller_db_path, gamepad_configs_file);
|
Input::instance = new Input(game_controller_db_path, gamepad_configs_file);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ void Input::init(const std::string &game_controller_db_path, const std::string &
|
|||||||
void Input::destroy() { delete Input::instance; }
|
void Input::destroy() { delete Input::instance; }
|
||||||
|
|
||||||
// Obtiene la instancia
|
// Obtiene la instancia
|
||||||
auto Input::get() -> Input * { return Input::instance; }
|
auto Input::get() -> Input* { return Input::instance; }
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Input::Input(std::string game_controller_db_path, std::string gamepad_configs_file)
|
Input::Input(std::string game_controller_db_path, std::string gamepad_configs_file)
|
||||||
@@ -36,21 +36,21 @@ void Input::bindKey(Action action, SDL_Scancode code) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a botones del mando
|
// Asigna inputs a botones del mando
|
||||||
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad> &gamepad, Action action, SDL_GamepadButton button) {
|
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action, SDL_GamepadButton button) {
|
||||||
if (gamepad != nullptr) {
|
if (gamepad != nullptr) {
|
||||||
gamepad->bindings[action].button = button;
|
gamepad->bindings[action].button = button;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Asigna inputs a botones del mando
|
// Asigna inputs a botones del mando
|
||||||
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad> &gamepad, Action action_target, Action action_source) {
|
void Input::bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source) {
|
||||||
if (gamepad != nullptr) {
|
if (gamepad != nullptr) {
|
||||||
gamepad->bindings[action_target].button = gamepad->bindings[action_source].button;
|
gamepad->bindings[action_target].button = gamepad->bindings[action_source].button;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si alguna acción está activa
|
// Comprueba si alguna acción está activa
|
||||||
auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr<Gamepad> &gamepad) -> 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;
|
||||||
|
|
||||||
@@ -82,12 +82,12 @@ auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const s
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba si hay almenos una acción activa
|
// Comprueba si hay almenos una acción activa
|
||||||
auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad> &gamepad) -> bool {
|
auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad>& gamepad) -> bool {
|
||||||
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
|
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
|
||||||
|
|
||||||
// --- Comprobación del Teclado ---
|
// --- Comprobación del Teclado ---
|
||||||
if (check_keyboard) {
|
if (check_keyboard) {
|
||||||
for (const auto &pair : keyboard_.bindings) {
|
for (const auto& pair : keyboard_.bindings) {
|
||||||
// Simplemente leemos el estado pre-calculado por Input::update().
|
// Simplemente leemos el estado pre-calculado por Input::update().
|
||||||
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
|
// Ya no se llama a SDL_GetKeyboardState ni se modifica el estado '.active'.
|
||||||
if (pair.second.just_pressed) {
|
if (pair.second.just_pressed) {
|
||||||
@@ -100,7 +100,7 @@ auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr<Gamepad> &g
|
|||||||
// Comprobamos si hay mandos y si el índice solicitado es válido.
|
// Comprobamos si hay mandos y si el índice solicitado es válido.
|
||||||
if (gamepad != nullptr) {
|
if (gamepad != nullptr) {
|
||||||
// Iteramos sobre todas las acciones, no sobre el número de mandos.
|
// Iteramos sobre todas las acciones, no sobre el número de mandos.
|
||||||
for (const auto &pair : gamepad->bindings) {
|
for (const auto& pair : gamepad->bindings) {
|
||||||
// Leemos el estado pre-calculado para el mando y la acción específicos.
|
// Leemos el estado pre-calculado para el mando y la acción específicos.
|
||||||
if (pair.second.just_pressed) {
|
if (pair.second.just_pressed) {
|
||||||
return true; // Se encontró una acción recién pulsada en el mando.
|
return true; // Se encontró una acción recién pulsada en el mando.
|
||||||
@@ -122,7 +122,7 @@ auto Input::checkAnyButton(bool repeat) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los mandos
|
// Comprueba los mandos
|
||||||
for (const auto &gamepad : gamepads_) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
|
if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -136,14 +136,14 @@ auto Input::checkAnyButton(bool repeat) -> bool {
|
|||||||
auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); }
|
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(const std::shared_ptr<Gamepad> &gamepad) -> std::string {
|
auto Input::getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string {
|
||||||
return gamepad == nullptr ? std::string() : gamepad->name;
|
return gamepad == nullptr ? std::string() : gamepad->name;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la lista de nombres de mandos
|
// Obtiene la lista de nombres de mandos
|
||||||
auto Input::getControllerNames() const -> std::vector<std::string> {
|
auto Input::getControllerNames() const -> std::vector<std::string> {
|
||||||
std::vector<std::string> names;
|
std::vector<std::string> names;
|
||||||
for (const auto &gamepad : gamepads_) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
names.push_back(gamepad->name);
|
names.push_back(gamepad->name);
|
||||||
}
|
}
|
||||||
return names;
|
return names;
|
||||||
@@ -154,7 +154,7 @@ auto Input::getNumGamepads() const -> int { return gamepads_.size(); }
|
|||||||
|
|
||||||
// Obtiene el gamepad a partir de un event.id
|
// Obtiene el gamepad a partir de un event.id
|
||||||
auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Input::Gamepad> {
|
auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Input::Gamepad> {
|
||||||
for (const auto &gamepad : gamepads_) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
if (gamepad->instance_id == id) {
|
if (gamepad->instance_id == id) {
|
||||||
return gamepad;
|
return gamepad;
|
||||||
}
|
}
|
||||||
@@ -162,8 +162,8 @@ auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Input::Gamepa
|
|||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto Input::getGamepadByName(const std::string &name) const -> std::shared_ptr<Input::Gamepad> {
|
auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad> {
|
||||||
for (const auto &gamepad : gamepads_) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
if (gamepad && gamepad->name == name) {
|
if (gamepad && gamepad->name == name) {
|
||||||
return gamepad;
|
return gamepad;
|
||||||
}
|
}
|
||||||
@@ -172,7 +172,7 @@ auto Input::getGamepadByName(const std::string &name) const -> std::shared_ptr<I
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el SDL_GamepadButton asignado a un action
|
// Obtiene el SDL_GamepadButton asignado a un action
|
||||||
auto Input::getControllerBinding(const std::shared_ptr<Gamepad> &gamepad, Action action) -> SDL_GamepadButton {
|
auto Input::getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton {
|
||||||
return static_cast<SDL_GamepadButton>(gamepad->bindings[action].button);
|
return static_cast<SDL_GamepadButton>(gamepad->bindings[action].button);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,7 +195,7 @@ auto Input::inputToString(Action action) -> std::string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Convierte un std::string a InputAction
|
// Convierte un std::string a InputAction
|
||||||
auto Input::stringToInput(const std::string &name) -> Action {
|
auto Input::stringToInput(const std::string& name) -> Action {
|
||||||
static const std::unordered_map<std::string, Action> INPUT_MAP = {
|
static const std::unordered_map<std::string, Action> INPUT_MAP = {
|
||||||
{"input_fire_left", Action::FIRE_LEFT},
|
{"input_fire_left", Action::FIRE_LEFT},
|
||||||
{"input_fire_center", Action::FIRE_CENTER},
|
{"input_fire_center", Action::FIRE_CENTER},
|
||||||
@@ -208,7 +208,7 @@ auto Input::stringToInput(const std::string &name) -> Action {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba el eje del mando
|
// Comprueba el eje del mando
|
||||||
auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad> &gamepad, 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
|
||||||
bool axis_active_now = false;
|
bool axis_active_now = false;
|
||||||
|
|
||||||
@@ -230,7 +230,7 @@ auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad> &gamepa
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Referencia al binding correspondiente
|
// Referencia al binding correspondiente
|
||||||
auto &binding = gamepad->bindings[action];
|
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
|
||||||
@@ -250,7 +250,7 @@ auto Input::checkAxisInput(Action action, const std::shared_ptr<Gamepad> &gamepa
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los triggers del mando como botones digitales
|
// Comprueba los triggers del mando como botones digitales
|
||||||
auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad> &gamepad, bool repeat) -> bool {
|
auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool {
|
||||||
// Solo manejamos botones específicos que pueden ser triggers
|
// Solo manejamos botones específicos que pueden ser triggers
|
||||||
if (gamepad->bindings[action].button != static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)) {
|
if (gamepad->bindings[action].button != static_cast<int>(SDL_GAMEPAD_BUTTON_INVALID)) {
|
||||||
// Solo procesamos L2 y R2 como triggers
|
// Solo procesamos L2 y R2 como triggers
|
||||||
@@ -272,7 +272,7 @@ auto Input::checkTriggerInput(Action action, const std::shared_ptr<Gamepad> &gam
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Referencia al binding correspondiente
|
// Referencia al binding correspondiente
|
||||||
auto &binding = gamepad->bindings[action];
|
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
|
||||||
@@ -325,13 +325,13 @@ void Input::initSDLGamePad() {
|
|||||||
|
|
||||||
void Input::resetInputStates() {
|
void Input::resetInputStates() {
|
||||||
// Resetear todos los KeyBindings.active a false
|
// Resetear todos los KeyBindings.active a false
|
||||||
for (auto &key : keyboard_.bindings) {
|
for (auto& key : keyboard_.bindings) {
|
||||||
key.second.is_held = false;
|
key.second.is_held = false;
|
||||||
key.second.just_pressed = false;
|
key.second.just_pressed = false;
|
||||||
}
|
}
|
||||||
// Resetear todos los ControllerBindings.active a false
|
// Resetear todos los ControllerBindings.active a false
|
||||||
for (auto &gamepad : gamepads_) {
|
for (auto& gamepad : gamepads_) {
|
||||||
for (auto &binding : gamepad->bindings) {
|
for (auto& binding : gamepad->bindings) {
|
||||||
binding.second.is_held = false;
|
binding.second.is_held = false;
|
||||||
binding.second.just_pressed = false;
|
binding.second.just_pressed = false;
|
||||||
binding.second.trigger_active = false;
|
binding.second.trigger_active = false;
|
||||||
@@ -341,9 +341,9 @@ void Input::resetInputStates() {
|
|||||||
|
|
||||||
void Input::update() {
|
void Input::update() {
|
||||||
// --- TECLADO ---
|
// --- TECLADO ---
|
||||||
const bool *key_states = SDL_GetKeyboardState(nullptr);
|
const bool* key_states = SDL_GetKeyboardState(nullptr);
|
||||||
|
|
||||||
for (auto &binding : keyboard_.bindings) {
|
for (auto& binding : keyboard_.bindings) {
|
||||||
bool key_is_down_now = key_states[binding.second.scancode];
|
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
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
||||||
@@ -352,8 +352,8 @@ void Input::update() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- MANDOS ---
|
// --- MANDOS ---
|
||||||
for (const auto &gamepad : gamepads_) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
for (auto &binding : gamepad->bindings) {
|
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;
|
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
|
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
|
||||||
@@ -363,7 +363,7 @@ void Input::update() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
auto Input::handleEvent(const SDL_Event &event) -> std::string {
|
auto Input::handleEvent(const SDL_Event& event) -> std::string {
|
||||||
switch (event.type) {
|
switch (event.type) {
|
||||||
case SDL_EVENT_GAMEPAD_ADDED:
|
case SDL_EVENT_GAMEPAD_ADDED:
|
||||||
return addGamepad(event.gdevice.which);
|
return addGamepad(event.gdevice.which);
|
||||||
@@ -374,7 +374,7 @@ auto Input::handleEvent(const SDL_Event &event) -> std::string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
auto Input::addGamepad(int device_index) -> std::string {
|
auto Input::addGamepad(int device_index) -> std::string {
|
||||||
SDL_Gamepad *pad = SDL_OpenGamepad(device_index);
|
SDL_Gamepad* pad = SDL_OpenGamepad(device_index);
|
||||||
if (pad == nullptr) {
|
if (pad == nullptr) {
|
||||||
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n';
|
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n';
|
||||||
return {};
|
return {};
|
||||||
@@ -390,7 +390,7 @@ auto Input::addGamepad(int device_index) -> std::string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
|
auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
|
||||||
auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad> &gamepad) {
|
auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr<Gamepad>& gamepad) {
|
||||||
return gamepad->instance_id == id;
|
return gamepad->instance_id == id;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -411,7 +411,7 @@ void Input::printConnectedGamepads() const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "Gamepads conectados:\n";
|
std::cout << "Gamepads conectados:\n";
|
||||||
for (const auto &gamepad : gamepads_) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name;
|
std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name;
|
||||||
std::cout << " - ID: " << gamepad->instance_id
|
std::cout << " - ID: " << gamepad->instance_id
|
||||||
<< ", Nombre: " << name << ")" << '\n';
|
<< ", Nombre: " << name << ")" << '\n';
|
||||||
@@ -434,14 +434,14 @@ void Input::applyGamepadConfig(std::shared_ptr<Gamepad> gamepad) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- Buscar configuración por RUTA (path) ---
|
// --- Buscar configuración por RUTA (path) ---
|
||||||
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig &config) {
|
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) {
|
||||||
return config.path == gamepad->path;
|
return config.path == gamepad->path;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (config_it != gamepad_configs_.end()) {
|
if (config_it != gamepad_configs_.end()) {
|
||||||
// Se encontró una configuración específica para este puerto/dispositivo. La aplicamos.
|
// 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';
|
std::cout << "Applying custom config for gamepad at path: " << gamepad->path << '\n';
|
||||||
for (const auto &[action, button] : config_it->bindings) {
|
for (const auto& [action, button] : config_it->bindings) {
|
||||||
if (gamepad->bindings.find(action) != gamepad->bindings.end()) {
|
if (gamepad->bindings.find(action) != gamepad->bindings.end()) {
|
||||||
gamepad->bindings[action].button = button;
|
gamepad->bindings[action].button = button;
|
||||||
}
|
}
|
||||||
@@ -456,7 +456,7 @@ void Input::saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- CAMBIO CLAVE: Buscar si ya existe una configuración por RUTA (path) ---
|
// --- 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) {
|
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad](const GamepadConfig& config) {
|
||||||
return config.path == gamepad->path;
|
return config.path == gamepad->path;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -465,7 +465,7 @@ void Input::saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad) {
|
|||||||
new_config.bindings.clear();
|
new_config.bindings.clear();
|
||||||
|
|
||||||
// Copiar todos los bindings actuales del gamepad
|
// Copiar todos los bindings actuales del gamepad
|
||||||
for (const auto &[action, buttonState] : gamepad->bindings) {
|
for (const auto& [action, buttonState] : gamepad->bindings) {
|
||||||
new_config.bindings[action] = static_cast<SDL_GamepadButton>(buttonState.button);
|
new_config.bindings[action] = static_cast<SDL_GamepadButton>(buttonState.button);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -482,14 +482,14 @@ void Input::saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Método para establecer el archivo de configuración (opcional)
|
// Método para establecer el archivo de configuración (opcional)
|
||||||
void Input::setGamepadConfigsFile(const std::string &filename) {
|
void Input::setGamepadConfigsFile(const std::string& filename) {
|
||||||
gamepad_configs_file_ = filename;
|
gamepad_configs_file_ = filename;
|
||||||
loadGamepadConfigs(); // Recargar con el nuevo archivo
|
loadGamepadConfigs(); // Recargar con el nuevo archivo
|
||||||
}
|
}
|
||||||
|
|
||||||
// Método para obtener configuración de un gamepad específico (opcional)
|
// Método para obtener configuración de un gamepad específico (opcional)
|
||||||
auto Input::getGamepadConfig(const std::string &gamepad_name) -> GamepadConfig * {
|
auto Input::getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig* {
|
||||||
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig &config) {
|
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) {
|
||||||
return config.name == gamepad_name;
|
return config.name == gamepad_name;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -497,8 +497,8 @@ auto Input::getGamepadConfig(const std::string &gamepad_name) -> GamepadConfig *
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Método para eliminar configuración de gamepad (opcional)
|
// Método para eliminar configuración de gamepad (opcional)
|
||||||
auto Input::removeGamepadConfig(const std::string &gamepad_name) -> bool {
|
auto Input::removeGamepadConfig(const std::string& gamepad_name) -> bool {
|
||||||
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig &config) {
|
auto config_it = std::ranges::find_if(gamepad_configs_, [&gamepad_name](const GamepadConfig& config) {
|
||||||
return config.name == gamepad_name;
|
return config.name == gamepad_name;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -511,21 +511,21 @@ auto Input::removeGamepadConfig(const std::string &gamepad_name) -> bool {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto Input::findAvailableGamepadByName(const std::string &gamepad_name) -> std::shared_ptr<Input::Gamepad> {
|
auto Input::findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Input::Gamepad> {
|
||||||
// Si no hay gamepads disponibles, devolver gamepad por defecto
|
// Si no hay gamepads disponibles, devolver gamepad por defecto
|
||||||
if (gamepads_.empty()) {
|
if (gamepads_.empty()) {
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Buscar por nombre
|
// Buscar por nombre
|
||||||
for (const auto &gamepad : gamepads_) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
if (gamepad && gamepad->name == gamepad_name) {
|
if (gamepad && gamepad->name == gamepad_name) {
|
||||||
return gamepad;
|
return gamepad;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si no se encuentra por nombre, devolver el primer gamepad válido
|
// Si no se encuentra por nombre, devolver el primer gamepad válido
|
||||||
for (const auto &gamepad : gamepads_) {
|
for (const auto& gamepad : gamepads_) {
|
||||||
if (gamepad) {
|
if (gamepad) {
|
||||||
return gamepad;
|
return gamepad;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
#include <unordered_map> // Para unordered_map
|
#include <unordered_map> // Para unordered_map
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "gamepad_config_manager.h" // Para GamepadConfig (ptr only), GamepadConfigs
|
#include "gamepad_config_manager.hpp" // Para GamepadConfig (ptr only), GamepadConfigs
|
||||||
#include "input_types.h" // Para InputAction
|
#include "input_types.hpp" // Para InputAction
|
||||||
|
|
||||||
// --- Clase Input: gestiona la entrada de teclado y mandos (singleton) ---
|
// --- Clase Input: gestiona la entrada de teclado y mandos (singleton) ---
|
||||||
class Input {
|
class Input {
|
||||||
@@ -96,13 +96,13 @@ class Input {
|
|||||||
};
|
};
|
||||||
|
|
||||||
struct Gamepad {
|
struct Gamepad {
|
||||||
SDL_Gamepad *pad;
|
SDL_Gamepad* pad;
|
||||||
SDL_JoystickID instance_id;
|
SDL_JoystickID instance_id;
|
||||||
std::string name;
|
std::string name;
|
||||||
std::string path;
|
std::string path;
|
||||||
std::unordered_map<Action, ButtonState> bindings;
|
std::unordered_map<Action, ButtonState> bindings;
|
||||||
|
|
||||||
Gamepad(SDL_Gamepad *gamepad)
|
Gamepad(SDL_Gamepad* gamepad)
|
||||||
: pad(gamepad),
|
: pad(gamepad),
|
||||||
instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))),
|
instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))),
|
||||||
name(std::string(SDL_GetGamepadName(gamepad))),
|
name(std::string(SDL_GetGamepadName(gamepad))),
|
||||||
@@ -143,44 +143,44 @@ class Input {
|
|||||||
using Gamepads = std::vector<std::shared_ptr<Gamepad>>; // Vector de gamepads
|
using Gamepads = std::vector<std::shared_ptr<Gamepad>>; // Vector de gamepads
|
||||||
|
|
||||||
// --- Métodos de singleton ---
|
// --- Métodos de singleton ---
|
||||||
static void init(const std::string &game_controller_db_path, const std::string &gamepad_configs_file);
|
static void init(const std::string& game_controller_db_path, const std::string& gamepad_configs_file);
|
||||||
static void destroy();
|
static void destroy();
|
||||||
static auto get() -> Input *;
|
static auto get() -> Input*;
|
||||||
|
|
||||||
// --- Métodos de configuración de controles ---
|
// --- Métodos de configuración de controles ---
|
||||||
void bindKey(Action action, 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, SDL_GamepadButton button);
|
||||||
static void bindGameControllerButton(const std::shared_ptr<Gamepad> &gamepad, Action action_target, Action action_source);
|
static void bindGameControllerButton(const std::shared_ptr<Gamepad>& gamepad, Action action_target, Action action_source);
|
||||||
|
|
||||||
// --- Métodos de consulta de entrada ---
|
// --- Métodos de consulta de entrada ---
|
||||||
void update();
|
void update();
|
||||||
auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr<Gamepad> &gamepad = nullptr) -> bool;
|
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 checkAnyInput(bool check_keyboard = true, const std::shared_ptr<Gamepad>& gamepad = nullptr) -> bool;
|
||||||
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool;
|
auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool;
|
||||||
|
|
||||||
// --- Métodos de gestión de mandos ---
|
// --- Métodos de gestión de mandos ---
|
||||||
[[nodiscard]] auto gameControllerFound() const -> bool;
|
[[nodiscard]] auto gameControllerFound() const -> bool;
|
||||||
static auto getControllerName(const std::shared_ptr<Gamepad> &gamepad) -> std::string;
|
static auto getControllerName(const std::shared_ptr<Gamepad>& gamepad) -> std::string;
|
||||||
auto getControllerNames() const -> std::vector<std::string>;
|
auto getControllerNames() const -> std::vector<std::string>;
|
||||||
[[nodiscard]] auto getNumGamepads() const -> int;
|
[[nodiscard]] auto getNumGamepads() const -> int;
|
||||||
auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
|
auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr<Gamepad>;
|
||||||
auto getGamepadByName(const std::string &name) const -> std::shared_ptr<Input::Gamepad>;
|
auto getGamepadByName(const std::string& name) const -> std::shared_ptr<Input::Gamepad>;
|
||||||
auto getGamepads() const -> const Gamepads & { return gamepads_; }
|
auto getGamepads() const -> const Gamepads& { return gamepads_; }
|
||||||
|
|
||||||
// --- Métodos de consulta y utilidades ---
|
// --- Métodos de consulta y utilidades ---
|
||||||
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad> &gamepad, Action action) -> SDL_GamepadButton;
|
[[nodiscard]] static auto getControllerBinding(const std::shared_ptr<Gamepad>& gamepad, Action action) -> SDL_GamepadButton;
|
||||||
[[nodiscard]] static auto inputToString(Action action) -> std::string;
|
[[nodiscard]] static auto inputToString(Action action) -> std::string;
|
||||||
[[nodiscard]] static auto stringToInput(const std::string &name) -> Action;
|
[[nodiscard]] static auto stringToInput(const std::string& name) -> Action;
|
||||||
|
|
||||||
// --- Métodos de reseteo de estado de entrada ---
|
// --- Métodos de reseteo de estado de entrada ---
|
||||||
void resetInputStates();
|
void resetInputStates();
|
||||||
|
|
||||||
// --- Eventos ---
|
// --- Eventos ---
|
||||||
auto handleEvent(const SDL_Event &event) -> std::string;
|
auto handleEvent(const SDL_Event& event) -> std::string;
|
||||||
|
|
||||||
void printConnectedGamepads() const;
|
void printConnectedGamepads() const;
|
||||||
|
|
||||||
auto findAvailableGamepadByName(const std::string &gamepad_name) -> std::shared_ptr<Gamepad>;
|
auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr<Gamepad>;
|
||||||
void saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad);
|
void saveGamepadConfigFromGamepad(std::shared_ptr<Gamepad> gamepad);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -198,8 +198,8 @@ class Input {
|
|||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void initSDLGamePad();
|
void initSDLGamePad();
|
||||||
static auto checkAxisInput(Action action, const std::shared_ptr<Gamepad> &gamepad, bool repeat) -> bool;
|
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;
|
static auto checkTriggerInput(Action action, const std::shared_ptr<Gamepad>& gamepad, bool repeat) -> bool;
|
||||||
auto addGamepad(int device_index) -> std::string;
|
auto addGamepad(int device_index) -> std::string;
|
||||||
auto removeGamepad(SDL_JoystickID id) -> std::string;
|
auto removeGamepad(SDL_JoystickID id) -> std::string;
|
||||||
void addGamepadMappingsFromFile();
|
void addGamepadMappingsFromFile();
|
||||||
@@ -211,14 +211,14 @@ class Input {
|
|||||||
void applyGamepadConfig(std::shared_ptr<Gamepad> gamepad);
|
void applyGamepadConfig(std::shared_ptr<Gamepad> gamepad);
|
||||||
|
|
||||||
// Métodos auxiliares opcionales
|
// Métodos auxiliares opcionales
|
||||||
void setGamepadConfigsFile(const std::string &filename);
|
void setGamepadConfigsFile(const std::string& filename);
|
||||||
auto getGamepadConfig(const std::string &gamepad_name) -> GamepadConfig *;
|
auto getGamepadConfig(const std::string& gamepad_name) -> GamepadConfig*;
|
||||||
auto removeGamepadConfig(const std::string &gamepad_name) -> bool;
|
auto removeGamepadConfig(const std::string& gamepad_name) -> bool;
|
||||||
|
|
||||||
// --- Constructor y destructor ---
|
// --- Constructor y destructor ---
|
||||||
explicit Input(std::string game_controller_db_path, std::string gamepad_configs_file);
|
explicit Input(std::string game_controller_db_path, std::string gamepad_configs_file);
|
||||||
~Input() = default;
|
~Input() = default;
|
||||||
|
|
||||||
// --- Singleton ---
|
// --- Singleton ---
|
||||||
static Input *instance;
|
static Input* instance;
|
||||||
};
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "input_types.h"
|
#include "input_types.hpp"
|
||||||
|
|
||||||
// Definición de los mapas
|
// Definición de los mapas
|
||||||
const std::unordered_map<InputAction, std::string> ACTION_TO_STRING = {
|
const std::unordered_map<InputAction, std::string> ACTION_TO_STRING = {
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
#include "item.h"
|
#include "item.hpp"
|
||||||
|
|
||||||
#include <algorithm> // Para clamp
|
#include <algorithm> // Para clamp
|
||||||
#include <cmath> // Para fmod
|
#include <cmath> // Para fmod
|
||||||
#include <cstdlib> // Para rand
|
#include <cstdlib> // Para rand
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "param.hpp" // Para Param, ParamGame, param
|
||||||
|
|
||||||
class Texture; // lines 6-6
|
class Texture; // lines 6-6
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,8 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
#include "utils.h" // Para Circle
|
#include "utils.hpp" // Para Circle
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "lang.h"
|
#include "lang.hpp"
|
||||||
|
|
||||||
#include <cstddef> // Para size_t
|
#include <cstddef> // Para size_t
|
||||||
#include <exception> // Para exception
|
#include <exception> // Para exception
|
||||||
@@ -7,11 +7,11 @@
|
|||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.hpp" // Para Asset
|
||||||
#include "difficulty.h" // Para Difficulty
|
#include "difficulty.hpp" // Para Difficulty
|
||||||
#include "external/json.hpp" // Para basic_json, iteration_proxy_value, oper...
|
#include "external/json.hpp" // Para basic_json, iteration_proxy_value, oper...
|
||||||
#include "options.h" // Para SettingsOpt...
|
#include "options.hpp" // Para SettingsOpt...
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
#include "resource_helper.hpp" // Para ResourceHelper
|
||||||
|
|
||||||
using json = nlohmann::json;
|
using json = nlohmann::json;
|
||||||
|
|
||||||
@@ -25,7 +25,7 @@ std::vector<Language> languages = {
|
|||||||
{Code::ENGLISH, "Ingles", "en_UK.json"}};
|
{Code::ENGLISH, "Ingles", "en_UK.json"}};
|
||||||
|
|
||||||
// Inicializa los textos del juego en el idioma seleccionado
|
// Inicializa los textos del juego en el idioma seleccionado
|
||||||
auto loadFromFile(const std::string &file_path) -> bool {
|
auto loadFromFile(const std::string& file_path) -> bool {
|
||||||
texts.clear();
|
texts.clear();
|
||||||
|
|
||||||
// Intentar cargar desde ResourceHelper primero
|
// Intentar cargar desde ResourceHelper primero
|
||||||
@@ -47,10 +47,10 @@ auto loadFromFile(const std::string &file_path) -> bool {
|
|||||||
rfile >> j;
|
rfile >> j;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const auto &el : j.items()) {
|
for (const auto& el : j.items()) {
|
||||||
texts[el.key()] = el.value();
|
texts[el.key()] = el.value();
|
||||||
}
|
}
|
||||||
} catch (const std::exception &e) {
|
} catch (const std::exception& e) {
|
||||||
// Puedes loguear el error si quieres
|
// Puedes loguear el error si quieres
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -59,7 +59,7 @@ auto loadFromFile(const std::string &file_path) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el texto por clave
|
// Obtiene el texto por clave
|
||||||
auto getText(const std::string &key) -> std::string {
|
auto getText(const std::string& key) -> std::string {
|
||||||
auto it = texts.find(key);
|
auto it = texts.find(key);
|
||||||
if (it != texts.end()) {
|
if (it != texts.end()) {
|
||||||
return it->second;
|
return it->second;
|
||||||
@@ -80,7 +80,7 @@ auto getNextLangCode(Code lang) -> Code {
|
|||||||
|
|
||||||
// Obtiene un idioma del vector de idiomas a partir de un código
|
// Obtiene un idioma del vector de idiomas a partir de un código
|
||||||
auto getLanguage(Code code) -> Language {
|
auto getLanguage(Code code) -> Language {
|
||||||
for (const auto &lang : languages) {
|
for (const auto& lang : languages) {
|
||||||
if (lang.code == code) {
|
if (lang.code == code) {
|
||||||
return lang;
|
return lang;
|
||||||
}
|
}
|
||||||
@@ -90,8 +90,8 @@ auto getLanguage(Code code) -> Language {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el código de un idioma a partir de un nombre
|
// Devuelve el código de un idioma a partir de un nombre
|
||||||
auto getCodeFromName(const std::string &name) -> Code {
|
auto getCodeFromName(const std::string& name) -> Code {
|
||||||
for (const auto &lang : languages) {
|
for (const auto& lang : languages) {
|
||||||
if (lang.name == name) {
|
if (lang.name == name) {
|
||||||
return lang.code;
|
return lang.code;
|
||||||
}
|
}
|
||||||
@@ -102,7 +102,7 @@ auto getCodeFromName(const std::string &name) -> Code {
|
|||||||
|
|
||||||
// Devuelve el nombre de un idioma a partir de un código
|
// Devuelve el nombre de un idioma a partir de un código
|
||||||
auto getNameFromCode(Code code) -> std::string {
|
auto getNameFromCode(Code code) -> std::string {
|
||||||
for (const auto &lang : languages) {
|
for (const auto& lang : languages) {
|
||||||
if (lang.code == code) {
|
if (lang.code == code) {
|
||||||
return lang.name;
|
return lang.name;
|
||||||
}
|
}
|
||||||
@@ -113,7 +113,7 @@ auto getNameFromCode(Code code) -> std::string {
|
|||||||
|
|
||||||
// Actualiza los nombres de los idiomas
|
// Actualiza los nombres de los idiomas
|
||||||
void updateLanguageNames() {
|
void updateLanguageNames() {
|
||||||
for (auto &lang : languages) {
|
for (auto& lang : languages) {
|
||||||
switch (lang.code) {
|
switch (lang.code) {
|
||||||
case Code::SPANISH:
|
case Code::SPANISH:
|
||||||
lang.name = Lang::getText("[SERVICE_MENU] LANG_ES");
|
lang.name = Lang::getText("[SERVICE_MENU] LANG_ES");
|
||||||
@@ -134,10 +134,10 @@ void updateLanguageNames() {
|
|||||||
// Actualiza los nombres de las dificultades
|
// Actualiza los nombres de las dificultades
|
||||||
void updateDifficultyNames() {
|
void updateDifficultyNames() {
|
||||||
// 1. Pide una referencia MODIFICABLE a la lista de dificultades
|
// 1. Pide una referencia MODIFICABLE a la lista de dificultades
|
||||||
auto &difficulties = Difficulty::getDifficulties();
|
auto& difficulties = Difficulty::getDifficulties();
|
||||||
|
|
||||||
// 2. Recorre la lista
|
// 2. Recorre la lista
|
||||||
for (auto &difficulty_info : difficulties) {
|
for (auto& difficulty_info : difficulties) {
|
||||||
// 3. Para cada dificultad, usa su código para obtener el texto traducido y actualizar su nombre
|
// 3. Para cada dificultad, usa su código para obtener el texto traducido y actualizar su nombre
|
||||||
switch (difficulty_info.code) {
|
switch (difficulty_info.code) {
|
||||||
case Difficulty::Code::EASY:
|
case Difficulty::Code::EASY:
|
||||||
@@ -155,7 +155,7 @@ void updateDifficultyNames() {
|
|||||||
|
|
||||||
// Obtiene una fichero a partir de un lang::Code
|
// Obtiene una fichero a partir de un lang::Code
|
||||||
auto getLanguageFileName(Lang::Code code) -> std::string {
|
auto getLanguageFileName(Lang::Code code) -> std::string {
|
||||||
for (const auto &lang : languages) {
|
for (const auto& lang : languages) {
|
||||||
if (lang.code == code) {
|
if (lang.code == code) {
|
||||||
return Asset::get()->get(lang.file_name);
|
return Asset::get()->get(lang.file_name);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,11 +25,11 @@ struct Language {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
auto loadFromFile(const std::string &file_path) -> bool; // Carga los textos desde el fichero JSON especificado
|
auto loadFromFile(const std::string& file_path) -> bool; // Carga los textos desde el fichero JSON especificado
|
||||||
auto getText(const std::string &key) -> std::string; // Obtiene el texto por clave
|
auto getText(const std::string& key) -> std::string; // Obtiene el texto por clave
|
||||||
auto getNextLangCode(Code current_lang) -> Code; // Obtiene el código del siguiente idioma (circular)
|
auto getNextLangCode(Code current_lang) -> Code; // Obtiene el código del siguiente idioma (circular)
|
||||||
auto getLanguage(Code code) -> Language; // Obtiene el idioma correspondiente al código proporcionado
|
auto getLanguage(Code code) -> Language; // Obtiene el idioma correspondiente al código proporcionado
|
||||||
auto getCodeFromName(const std::string &name) -> Code; // Devuelve el código de un idioma a partir de un nombre
|
auto getCodeFromName(const std::string& name) -> Code; // Devuelve el código de un idioma a partir de un nombre
|
||||||
auto getNameFromCode(Code code) -> std::string; // Devuelve el nombre de un idioma a partir de un código
|
auto getNameFromCode(Code code) -> std::string; // Devuelve el nombre de un idioma a partir de un código
|
||||||
void updateLanguageNames(); // Actualiza los nombres de los idiomas
|
void updateLanguageNames(); // Actualiza los nombres de los idiomas
|
||||||
auto getLanguageFileName(Code code) -> std::string; // Obtiene el nombre del fichero de textos asociado a un código de idioma
|
auto getLanguageFileName(Code code) -> std::string; // Obtiene el nombre del fichero de textos asociado a un código de idioma
|
||||||
@@ -10,7 +10,7 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024
|
|||||||
#include <memory> // Para make_unique, unique_ptr
|
#include <memory> // Para make_unique, unique_ptr
|
||||||
#include <span> // Para span
|
#include <span> // Para span
|
||||||
|
|
||||||
#include "director.h" // Para Director
|
#include "director.hpp" // Para Director
|
||||||
|
|
||||||
auto main(int argc, char* argv[]) -> int {
|
auto main(int argc, char* argv[]) -> int {
|
||||||
// Crea el objeto Director
|
// Crea el objeto Director
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
#include "manage_hiscore_table.h"
|
#include "manage_hiscore_table.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_ReadIO, SDL_WriteIO, SDL_CloseIO, SDL_GetError, SDL_IOFromFile, SDL_LogCategory, SDL_LogError, SDL_LogInfo
|
#include <SDL3/SDL.h> // Para SDL_ReadIO, SDL_WriteIO, SDL_CloseIO, SDL_GetError, SDL_IOFromFile, SDL_LogCategory, SDL_LogError, SDL_LogInfo
|
||||||
|
|
||||||
#include <algorithm> // Para find_if, sort
|
#include <algorithm> // Para find_if, sort
|
||||||
#include <iterator> // Para distance
|
#include <iterator> // Para distance
|
||||||
|
|
||||||
#include "utils.h" // Para getFileName
|
#include "utils.hpp" // Para getFileName
|
||||||
|
|
||||||
// Resetea la tabla a los valores por defecto
|
// Resetea la tabla a los valores por defecto
|
||||||
void ManageHiScoreTable::clear() {
|
void ManageHiScoreTable::clear() {
|
||||||
@@ -54,7 +54,7 @@ void ManageHiScoreTable::clear() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Añade un elemento a la tabla
|
// Añade un elemento a la tabla
|
||||||
auto ManageHiScoreTable::add(const HiScoreEntry &entry) -> int {
|
auto ManageHiScoreTable::add(const HiScoreEntry& entry) -> int {
|
||||||
// Añade la entrada a la tabla
|
// Añade la entrada a la tabla
|
||||||
table_.push_back(entry);
|
table_.push_back(entry);
|
||||||
|
|
||||||
@@ -62,7 +62,7 @@ auto ManageHiScoreTable::add(const HiScoreEntry &entry) -> int {
|
|||||||
sort();
|
sort();
|
||||||
|
|
||||||
// Encontrar la posición del nuevo elemento
|
// Encontrar la posición del nuevo elemento
|
||||||
auto it = std::ranges::find_if(table_, [&](const HiScoreEntry &e) {
|
auto it = std::ranges::find_if(table_, [&](const HiScoreEntry& e) {
|
||||||
return e.name == entry.name && e.score == entry.score && e.one_credit_complete == entry.one_credit_complete;
|
return e.name == entry.name && e.score == entry.score && e.one_credit_complete == entry.one_credit_complete;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -89,17 +89,17 @@ auto ManageHiScoreTable::add(const HiScoreEntry &entry) -> int {
|
|||||||
void ManageHiScoreTable::sort() {
|
void ManageHiScoreTable::sort() {
|
||||||
struct
|
struct
|
||||||
{
|
{
|
||||||
auto operator()(const HiScoreEntry &a, const HiScoreEntry &b) const -> bool { return a.score > b.score; }
|
auto operator()(const HiScoreEntry& a, const HiScoreEntry& b) const -> bool { return a.score > b.score; }
|
||||||
} score_descending_comparator;
|
} score_descending_comparator;
|
||||||
|
|
||||||
std::ranges::sort(table_, score_descending_comparator);
|
std::ranges::sort(table_, score_descending_comparator);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga la tabla desde un fichero
|
// Carga la tabla desde un fichero
|
||||||
auto ManageHiScoreTable::loadFromFile(const std::string &file_path) -> bool {
|
auto ManageHiScoreTable::loadFromFile(const std::string& file_path) -> bool {
|
||||||
clear();
|
clear();
|
||||||
auto success = true;
|
auto success = true;
|
||||||
auto *file = SDL_IOFromFile(file_path.c_str(), "rb");
|
auto* file = SDL_IOFromFile(file_path.c_str(), "rb");
|
||||||
|
|
||||||
if (file != nullptr) {
|
if (file != nullptr) {
|
||||||
table_.clear(); // Limpia la tabla actual
|
table_.clear(); // Limpia la tabla actual
|
||||||
@@ -143,9 +143,9 @@ auto ManageHiScoreTable::loadFromFile(const std::string &file_path) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Guarda la tabla en un fichero
|
// Guarda la tabla en un fichero
|
||||||
auto ManageHiScoreTable::saveToFile(const std::string &file_path) -> bool {
|
auto ManageHiScoreTable::saveToFile(const std::string& file_path) -> bool {
|
||||||
auto success = true;
|
auto success = true;
|
||||||
auto *file = SDL_IOFromFile(file_path.c_str(), "w+b");
|
auto* file = SDL_IOFromFile(file_path.c_str(), "w+b");
|
||||||
|
|
||||||
if (file != nullptr) {
|
if (file != nullptr) {
|
||||||
// Guarda el número de entradas en la tabla
|
// Guarda el número de entradas en la tabla
|
||||||
@@ -154,7 +154,7 @@ auto ManageHiScoreTable::saveToFile(const std::string &file_path) -> bool {
|
|||||||
|
|
||||||
// Guarda los datos de cada entrada
|
// Guarda los datos de cada entrada
|
||||||
for (int i = 0; i < table_size; ++i) {
|
for (int i = 0; i < table_size; ++i) {
|
||||||
const HiScoreEntry &entry = table_.at(i);
|
const HiScoreEntry& entry = table_.at(i);
|
||||||
|
|
||||||
// Guarda la puntuación
|
// Guarda la puntuación
|
||||||
SDL_WriteIO(file, &entry.score, sizeof(int));
|
SDL_WriteIO(file, &entry.score, sizeof(int));
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ struct HiScoreEntry {
|
|||||||
bool one_credit_complete; // Indica si se ha conseguido 1CC
|
bool one_credit_complete; // Indica si se ha conseguido 1CC
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit HiScoreEntry(const std::string &name = "", int score = 0, bool one_credit_complete = false)
|
explicit HiScoreEntry(const std::string& name = "", int score = 0, bool one_credit_complete = false)
|
||||||
: name(name.substr(0, 6)),
|
: name(name.substr(0, 6)),
|
||||||
score(score),
|
score(score),
|
||||||
one_credit_complete(one_credit_complete) {}
|
one_credit_complete(one_credit_complete) {}
|
||||||
@@ -26,19 +26,19 @@ class ManageHiScoreTable {
|
|||||||
static constexpr int NO_ENTRY = -1;
|
static constexpr int NO_ENTRY = -1;
|
||||||
|
|
||||||
// --- Constructor y destructor ---
|
// --- Constructor y destructor ---
|
||||||
explicit ManageHiScoreTable(Table &table) // Constructor con referencia a tabla
|
explicit ManageHiScoreTable(Table& table) // Constructor con referencia a tabla
|
||||||
: table_(table) {}
|
: table_(table) {}
|
||||||
~ManageHiScoreTable() = default; // Destructor
|
~ManageHiScoreTable() = default; // Destructor
|
||||||
|
|
||||||
// --- Métodos públicos ---
|
// --- Métodos públicos ---
|
||||||
void clear(); // Resetea la tabla a los valores por defecto
|
void clear(); // Resetea la tabla a los valores por defecto
|
||||||
auto add(const HiScoreEntry &entry) -> int; // Añade un elemento a la tabla (devuelve la posición en la que se inserta)
|
auto add(const HiScoreEntry& entry) -> int; // Añade un elemento a la tabla (devuelve la posición en la que se inserta)
|
||||||
auto loadFromFile(const std::string &file_path) -> bool; // Carga la tabla con los datos de un fichero
|
auto loadFromFile(const std::string& file_path) -> bool; // Carga la tabla con los datos de un fichero
|
||||||
auto saveToFile(const std::string &file_path) -> bool; // Guarda la tabla en un fichero
|
auto saveToFile(const std::string& file_path) -> bool; // Guarda la tabla en un fichero
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Variables privadas ---
|
// --- Variables privadas ---
|
||||||
Table &table_; // Referencia a la tabla con los records
|
Table& table_; // Referencia a la tabla con los records
|
||||||
|
|
||||||
// --- Métodos privados ---
|
// --- Métodos privados ---
|
||||||
void sort(); // Ordena la tabla
|
void sort(); // Ordena la tabla
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "mouse.h"
|
#include "mouse.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, Uint32, SDL_HideCursor, SDL_Show...
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, Uint32, SDL_HideCursor, SDL_Show...
|
||||||
|
|
||||||
@@ -7,7 +7,7 @@ Uint32 cursor_hide_time = 3000; // Tiempo en milisegundos para ocultar el curs
|
|||||||
Uint32 last_mouse_move_time = 0; // Última vez que el ratón se movió
|
Uint32 last_mouse_move_time = 0; // Última vez que el ratón se movió
|
||||||
bool cursor_visible = true; // Estado del cursor
|
bool cursor_visible = true; // Estado del cursor
|
||||||
|
|
||||||
void handleEvent(const SDL_Event &event) {
|
void handleEvent(const SDL_Event& event) {
|
||||||
if (event.type == SDL_EVENT_MOUSE_MOTION) {
|
if (event.type == SDL_EVENT_MOUSE_MOTION) {
|
||||||
last_mouse_move_time = SDL_GetTicks();
|
last_mouse_move_time = SDL_GetTicks();
|
||||||
if (!cursor_visible) {
|
if (!cursor_visible) {
|
||||||
|
|||||||
@@ -10,6 +10,6 @@ extern Uint32 last_mouse_move_time; // Última vez (en ms) que el ratón se mov
|
|||||||
extern bool cursor_visible; // Indica si el cursor está visible
|
extern bool cursor_visible; // Indica si el cursor está visible
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
void handleEvent(const SDL_Event &event); // Procesa eventos de ratón (movimiento, clic, etc.)
|
void handleEvent(const SDL_Event& event); // Procesa eventos de ratón (movimiento, clic, etc.)
|
||||||
void updateCursorVisibility(); // Actualiza la visibilidad del cursor según la inactividad
|
void updateCursorVisibility(); // Actualiza la visibilidad del cursor según la inactividad
|
||||||
} // namespace Mouse
|
} // namespace Mouse
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
#include "moving_sprite.h"
|
#include "moving_sprite.hpp"
|
||||||
|
|
||||||
#include <cmath> // Para std::abs
|
#include <cmath> // Para std::abs
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, Rotate rotate, float horizontal_zoom, float vertical_zoom, SDL_FlipMode flip)
|
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos, Rotate rotate, float horizontal_zoom, float vertical_zoom, SDL_FlipMode flip)
|
||||||
@@ -75,7 +75,7 @@ void MovingSprite::update(float deltaTime) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Muestra el sprite por pantalla
|
// Muestra el sprite por pantalla
|
||||||
void MovingSprite::render() {
|
void MovingSprite::render() {
|
||||||
getTexture()->render(pos_.x, pos_.y, &sprite_clip_, horizontal_zoom_, vertical_zoom_, rotate_.angle, &rotate_.center, flip_);
|
getTexture()->render(pos_.x, pos_.y, &sprite_clip_, horizontal_zoom_, vertical_zoom_, rotate_.angle, &rotate_.center, flip_);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
#include <algorithm> // Para max
|
#include <algorithm> // Para max
|
||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
|
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "options.h"
|
#include "options.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_ScaleMode, SDL_GamepadButton, SDL_LogCategory, SDL_LogInfo, SDL_LogError, SDL_LogWarn
|
#include <SDL3/SDL.h> // Para SDL_ScaleMode, SDL_GamepadButton, SDL_LogCategory, SDL_LogInfo, SDL_LogError, SDL_LogWarn
|
||||||
|
|
||||||
@@ -6,18 +6,18 @@
|
|||||||
#include <cstddef> // Para size_t
|
#include <cstddef> // Para size_t
|
||||||
#include <fstream> // Para basic_ostream, operator<<, basic_ostream::operator<<, basic_ofstream, basic_istream, basic_ifstream, ifstream, ofstream
|
#include <fstream> // Para basic_ostream, operator<<, basic_ostream::operator<<, basic_ofstream, basic_istream, basic_ifstream, ifstream, ofstream
|
||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
#include <sstream> // Para istringstream
|
|
||||||
#include <map> // Para map, operator==, _Rb_tree_const_iterator
|
#include <map> // Para map, operator==, _Rb_tree_const_iterator
|
||||||
#include <ranges> // Para std::ranges::any_of
|
#include <ranges> // Para std::ranges::any_of
|
||||||
|
#include <sstream> // Para istringstream
|
||||||
#include <stdexcept> // Para invalid_argument, out_of_range
|
#include <stdexcept> // Para invalid_argument, out_of_range
|
||||||
#include <string> // Para char_traits, stoi, operator==, operator<<, allocator, string, basic_string, operator<=>, getline
|
#include <string> // Para char_traits, stoi, operator==, operator<<, allocator, string, basic_string, operator<=>, getline
|
||||||
#include <utility> // Para swap, pair
|
#include <utility> // Para swap, pair
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "difficulty.h" // Para Code, init
|
#include "difficulty.hpp" // Para Code, init
|
||||||
#include "input.h" // Para InputDevice
|
#include "input.hpp" // Para InputDevice
|
||||||
#include "lang.h" // Para Code
|
#include "lang.hpp" // Para Code
|
||||||
#include "utils.h" // Para boolToString, stringToBool, getFileName
|
#include "utils.hpp" // Para boolToString, stringToBool, getFileName
|
||||||
|
|
||||||
namespace Options {
|
namespace Options {
|
||||||
// --- Variables globales ---
|
// --- Variables globales ---
|
||||||
@@ -59,7 +59,7 @@ auto loadFromFile() -> bool {
|
|||||||
init();
|
init();
|
||||||
|
|
||||||
std::ifstream file(settings.config_file);
|
std::ifstream file(settings.config_file);
|
||||||
bool file_exists = file.is_open(); // Guardamos si el fichero existía al abrirlo
|
bool file_exists = file.is_open(); // Guardamos si el fichero existía al abrirlo
|
||||||
|
|
||||||
// 2. Si el fichero existe, lo leemos para obtener los nombres de los mandos.
|
// 2. Si el fichero existe, lo leemos para obtener los nombres de los mandos.
|
||||||
if (file_exists) {
|
if (file_exists) {
|
||||||
@@ -105,7 +105,6 @@ auto loadFromFile() -> bool {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Guarda el fichero de configuración
|
// Guarda el fichero de configuración
|
||||||
auto saveToFile() -> bool {
|
auto saveToFile() -> bool {
|
||||||
std::ofstream file(settings.config_file);
|
std::ofstream file(settings.config_file);
|
||||||
|
|||||||
@@ -14,12 +14,12 @@
|
|||||||
#include <utility> // Para swap
|
#include <utility> // Para swap
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "defaults.h" // Para GameDefaults
|
#include "defaults.hpp" // Para GameDefaults
|
||||||
#include "difficulty.h" // Para Code
|
#include "difficulty.hpp" // Para Code
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "lang.h" // Para Code
|
#include "lang.hpp" // Para Code
|
||||||
#include "manage_hiscore_table.h" // Para ManageHiScoreTable, Table
|
#include "manage_hiscore_table.hpp" // Para ManageHiScoreTable, Table
|
||||||
#include "player.h" // Para Player
|
#include "player.hpp" // Para Player
|
||||||
|
|
||||||
// --- Namespace Options: gestión de configuración y opciones del juego ---
|
// --- Namespace Options: gestión de configuración y opciones del juego ---
|
||||||
namespace Options {
|
namespace Options {
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "param.h"
|
#include "param.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogCategory, SDL_LogError, SDL_LogInfo
|
#include <SDL3/SDL.h> // Para SDL_LogCategory, SDL_LogError, SDL_LogInfo
|
||||||
|
|
||||||
@@ -9,9 +9,9 @@
|
|||||||
#include <string> // Para operator==, stoi, char_traits, string, ope...
|
#include <string> // Para operator==, stoi, char_traits, string, ope...
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
|
||||||
#include "color.h"
|
#include "color.hpp"
|
||||||
#include "ui/notifier.h" // Para Notifier::Position
|
#include "ui/notifier.hpp" // Para Notifier::Position
|
||||||
#include "utils.h"
|
#include "utils.hpp"
|
||||||
|
|
||||||
// Variable global - ahora se inicializa automáticamente con valores por defecto
|
// Variable global - ahora se inicializa automáticamente con valores por defecto
|
||||||
Param param;
|
Param param;
|
||||||
@@ -90,7 +90,7 @@ auto setParams(const std::string& var, const std::string& value) -> bool {
|
|||||||
{"game.play_area.rect.x", [](const std::string& v) { param.game.play_area.rect.x = std::stoi(v); }},
|
{"game.play_area.rect.x", [](const std::string& v) { param.game.play_area.rect.x = std::stoi(v); }},
|
||||||
{"game.play_area.rect.y", [](const std::string& v) { param.game.play_area.rect.y = std::stoi(v); }},
|
{"game.play_area.rect.y", [](const std::string& v) { param.game.play_area.rect.y = std::stoi(v); }},
|
||||||
{"game.play_area.rect.w", [](const std::string& v) { param.game.play_area.rect.w = std::stoi(v); }},
|
{"game.play_area.rect.w", [](const std::string& v) { param.game.play_area.rect.w = std::stoi(v); }},
|
||||||
{"game.play_area.rect.h", [](const std::string& v) { param.game.play_area.rect.h = std::stoi(v); }},
|
{"game.play_area.rect.hpp", [](const std::string& v) { param.game.play_area.rect.h = std::stoi(v); }},
|
||||||
{"game.name_entry_idle_time", [](const std::string& v) { param.game.name_entry_idle_time = std::stoi(v); }},
|
{"game.name_entry_idle_time", [](const std::string& v) { param.game.name_entry_idle_time = std::stoi(v); }},
|
||||||
{"game.name_entry_total_time", [](const std::string& v) { param.game.name_entry_total_time = std::stoi(v); }},
|
{"game.name_entry_total_time", [](const std::string& v) { param.game.name_entry_total_time = std::stoi(v); }},
|
||||||
{"game.hit_stop_ms", [](const std::string& v) { param.game.hit_stop_ms = std::stoi(v); }},
|
{"game.hit_stop_ms", [](const std::string& v) { param.game.hit_stop_ms = std::stoi(v); }},
|
||||||
@@ -102,7 +102,7 @@ auto setParams(const std::string& var, const std::string& value) -> bool {
|
|||||||
{"scoreboard.rect.x", [](const std::string& v) { param.scoreboard.rect.x = std::stoi(v); }},
|
{"scoreboard.rect.x", [](const std::string& v) { param.scoreboard.rect.x = std::stoi(v); }},
|
||||||
{"scoreboard.rect.y", [](const std::string& v) { param.scoreboard.rect.y = std::stoi(v); }},
|
{"scoreboard.rect.y", [](const std::string& v) { param.scoreboard.rect.y = std::stoi(v); }},
|
||||||
{"scoreboard.rect.w", [](const std::string& v) { param.scoreboard.rect.w = std::stoi(v); }},
|
{"scoreboard.rect.w", [](const std::string& v) { param.scoreboard.rect.w = std::stoi(v); }},
|
||||||
{"scoreboard.rect.h", [](const std::string& v) { param.scoreboard.rect.h = std::stoi(v); }},
|
{"scoreboard.rect.hpp", [](const std::string& v) { param.scoreboard.rect.h = std::stoi(v); }},
|
||||||
{"scoreboard.skip_countdown_value", [](const std::string& v) { param.scoreboard.skip_countdown_value = std::stoi(v); }},
|
{"scoreboard.skip_countdown_value", [](const std::string& v) { param.scoreboard.skip_countdown_value = std::stoi(v); }},
|
||||||
{"title.press_start_position", [](const std::string& v) { param.title.press_start_position = std::stoi(v); }},
|
{"title.press_start_position", [](const std::string& v) { param.title.press_start_position = std::stoi(v); }},
|
||||||
{"title.arcade_edition_position", [](const std::string& v) { param.title.arcade_edition_position = std::stoi(v); }},
|
{"title.arcade_edition_position", [](const std::string& v) { param.title.arcade_edition_position = std::stoi(v); }},
|
||||||
|
|||||||
@@ -5,10 +5,10 @@
|
|||||||
#include <array> // Para array
|
#include <array> // Para array
|
||||||
#include <string> // Para basic_string, string
|
#include <string> // Para basic_string, string
|
||||||
|
|
||||||
#include "color.h" // Para Color, Zone
|
#include "color.hpp" // Para Color, Zone
|
||||||
#include "defaults.h" // Para los valores por defecto
|
#include "defaults.hpp" // Para los valores por defecto
|
||||||
#include "ui/notifier.h" // Para Notifier::Position
|
#include "ui/notifier.hpp" // Para Notifier::Position
|
||||||
#include "utils.h"
|
#include "utils.hpp"
|
||||||
|
|
||||||
// --- Parámetros del juego ---
|
// --- Parámetros del juego ---
|
||||||
struct ParamGame {
|
struct ParamGame {
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
// IWYU pragma: no_include <bits/std_abs.h>
|
// IWYU pragma: no_include <bits/std_abs.h>
|
||||||
#include "path_sprite.h"
|
#include "path_sprite.hpp"
|
||||||
|
|
||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
|
|
||||||
// Constructor para paths por puntos (convertido a segundos)
|
// Constructor para paths por puntos (convertido a segundos)
|
||||||
Path::Path(const std::vector<SDL_FPoint> &spots_init, float waiting_time_s_init)
|
Path::Path(const std::vector<SDL_FPoint>& spots_init, float waiting_time_s_init)
|
||||||
: spots(spots_init), is_point_path(true) {
|
: spots(spots_init),
|
||||||
|
is_point_path(true) {
|
||||||
waiting_time_s = waiting_time_s_init;
|
waiting_time_s = waiting_time_s_init;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve un vector con los puntos que conforman la ruta
|
// Devuelve un vector con los puntos que conforman la ruta
|
||||||
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint> {
|
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)>& easing_function) -> std::vector<SDL_FPoint> {
|
||||||
std::vector<SDL_FPoint> v;
|
std::vector<SDL_FPoint> v;
|
||||||
v.reserve(steps);
|
v.reserve(steps);
|
||||||
|
|
||||||
@@ -74,50 +75,50 @@ void PathSprite::addPath(Path path, bool centered) {
|
|||||||
switch (path_centered) {
|
switch (path_centered) {
|
||||||
case PathCentered::ON_X: {
|
case PathCentered::ON_X: {
|
||||||
// Centrar en el eje X (para paths Verticales)
|
// Centrar en el eje X (para paths Verticales)
|
||||||
const float X_offset = pos_.w / 2.0f; // Asume que pos_.w está inicializado por el constructor de Sprite
|
const float X_offset = pos_.w / 2.0f; // Asume que pos_.w está inicializado por el constructor de Sprite
|
||||||
if (path.is_point_path) {
|
if (path.is_point_path) {
|
||||||
const float X_base = !path.spots.empty() ? path.spots.front().x : 0.0f;
|
const float X_base = !path.spots.empty() ? path.spots.front().x : 0.0f;
|
||||||
const float X = X_base - X_offset;
|
const float X = X_base - X_offset;
|
||||||
for (auto &spot : path.spots) {
|
for (auto& spot : path.spots) {
|
||||||
spot.x = X;
|
spot.x = X;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Es un path generado, ajustamos la posición fija (que es X)
|
// Es un path generado, ajustamos la posición fija (que es X)
|
||||||
path.fixed_pos -= X_offset;
|
path.fixed_pos -= X_offset;
|
||||||
}
|
}
|
||||||
paths_.emplace_back(std::move(path)); // Usamos std::move
|
paths_.emplace_back(std::move(path)); // Usamos std::move
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case PathCentered::ON_Y: {
|
case PathCentered::ON_Y: {
|
||||||
// Centrar en el eje Y (para paths Horizontales)
|
// Centrar en el eje Y (para paths Horizontales)
|
||||||
const float Y_offset = pos_.h / 2.0f; // Asume que pos_.h está inicializado
|
const float Y_offset = pos_.h / 2.0f; // Asume que pos_.h está inicializado
|
||||||
if (path.is_point_path) {
|
if (path.is_point_path) {
|
||||||
const float Y_base = !path.spots.empty() ? path.spots.front().y : 0.0f;
|
const float Y_base = !path.spots.empty() ? path.spots.front().y : 0.0f;
|
||||||
const float Y = Y_base - Y_offset;
|
const float Y = Y_base - Y_offset;
|
||||||
for (auto &spot : path.spots) {
|
for (auto& spot : path.spots) {
|
||||||
spot.y = Y;
|
spot.y = Y;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Es un path generado, ajustamos la posición fija (que es Y)
|
// Es un path generado, ajustamos la posición fija (que es Y)
|
||||||
path.fixed_pos -= Y_offset;
|
path.fixed_pos -= Y_offset;
|
||||||
}
|
}
|
||||||
paths_.emplace_back(std::move(path)); // Usamos std::move
|
paths_.emplace_back(std::move(path)); // Usamos std::move
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
// Sin centrado
|
// Sin centrado
|
||||||
paths_.emplace_back(std::move(path)); // Usamos std::move
|
paths_.emplace_back(std::move(path)); // Usamos std::move
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade un recorrido generado (en segundos)
|
// Añade un recorrido generado (en segundos)
|
||||||
void PathSprite::addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function<double(double)> &easing_function, float waiting_time_s) {
|
void PathSprite::addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function<double(double)>& easing_function, float waiting_time_s) {
|
||||||
paths_.emplace_back(start, end, type, fixed_pos, duration_s, waiting_time_s, easing_function);
|
paths_.emplace_back(start, end, type, fixed_pos, duration_s, waiting_time_s, easing_function);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade un recorrido por puntos (en segundos)
|
// Añade un recorrido por puntos (en segundos)
|
||||||
void PathSprite::addPath(const std::vector<SDL_FPoint> &spots, float waiting_time_s) {
|
void PathSprite::addPath(const std::vector<SDL_FPoint>& spots, float waiting_time_s) {
|
||||||
paths_.emplace_back(spots, waiting_time_s);
|
paths_.emplace_back(spots, waiting_time_s);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,9 +131,9 @@ void PathSprite::enable() {
|
|||||||
enabled_ = true;
|
enabled_ = true;
|
||||||
|
|
||||||
// Establece la posición inicial
|
// Establece la posición inicial
|
||||||
auto &path = paths_.at(current_path_);
|
auto& path = paths_.at(current_path_);
|
||||||
if (path.is_point_path) {
|
if (path.is_point_path) {
|
||||||
const auto &p = path.spots.at(path.counter);
|
const auto& p = path.spots.at(path.counter);
|
||||||
setPosition(p);
|
setPosition(p);
|
||||||
} else {
|
} else {
|
||||||
// Para paths generados, establecer posición inicial
|
// Para paths generados, establecer posición inicial
|
||||||
@@ -148,11 +149,11 @@ void PathSprite::enable() {
|
|||||||
|
|
||||||
// Coloca el sprite en los diferentes puntos del recorrido
|
// Coloca el sprite en los diferentes puntos del recorrido
|
||||||
void PathSprite::moveThroughCurrentPath(float delta_time) {
|
void PathSprite::moveThroughCurrentPath(float delta_time) {
|
||||||
auto &path = paths_.at(current_path_);
|
auto& path = paths_.at(current_path_);
|
||||||
|
|
||||||
if (path.is_point_path) {
|
if (path.is_point_path) {
|
||||||
// Lógica para paths por puntos (compatibilidad)
|
// Lógica para paths por puntos (compatibilidad)
|
||||||
const auto &p = path.spots.at(path.counter);
|
const auto& p = path.spots.at(path.counter);
|
||||||
setPosition(p);
|
setPosition(p);
|
||||||
|
|
||||||
if (!path.on_destination) {
|
if (!path.on_destination) {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
@@ -24,26 +24,31 @@ enum class PathCentered { // Centrado del recorrido
|
|||||||
};
|
};
|
||||||
|
|
||||||
// --- Estructuras ---
|
// --- Estructuras ---
|
||||||
struct Path { // Define un recorrido para el sprite
|
struct Path { // Define un recorrido para el sprite
|
||||||
float start_pos; // Posición inicial
|
float start_pos; // Posición inicial
|
||||||
float end_pos; // Posición final
|
float end_pos; // Posición final
|
||||||
PathType type; // Tipo de movimiento (horizontal/vertical)
|
PathType type; // Tipo de movimiento (horizontal/vertical)
|
||||||
float fixed_pos; // Posición fija en el eje contrario
|
float fixed_pos; // Posición fija en el eje contrario
|
||||||
float duration_s; // Duración de la animación en segundos
|
float duration_s; // Duración de la animación en segundos
|
||||||
float waiting_time_s; // Tiempo de espera una vez en el destino
|
float waiting_time_s; // Tiempo de espera una vez en el destino
|
||||||
std::function<double(double)> easing_function; // Función de easing
|
std::function<double(double)> easing_function; // Función de easing
|
||||||
float elapsed_time = 0.0f; // Tiempo transcurrido
|
float elapsed_time = 0.0f; // Tiempo transcurrido
|
||||||
float waiting_elapsed = 0.0f; // Tiempo de espera transcurrido
|
float waiting_elapsed = 0.0f; // Tiempo de espera transcurrido
|
||||||
bool on_destination = false; // Indica si ha llegado al destino
|
bool on_destination = false; // Indica si ha llegado al destino
|
||||||
bool finished = false; // Indica si ha terminado de esperarse
|
bool finished = false; // Indica si ha terminado de esperarse
|
||||||
|
|
||||||
// Constructor para paths generados
|
// Constructor para paths generados
|
||||||
Path(float start, float end, PathType path_type, float fixed, float duration, float waiting, std::function<double(double)> easing)
|
Path(float start, float end, PathType path_type, float fixed, float duration, float waiting, std::function<double(double)> easing)
|
||||||
: start_pos(start), end_pos(end), type(path_type), fixed_pos(fixed),
|
: start_pos(start),
|
||||||
duration_s(duration), waiting_time_s(waiting), easing_function(std::move(easing)) {}
|
end_pos(end),
|
||||||
|
type(path_type),
|
||||||
|
fixed_pos(fixed),
|
||||||
|
duration_s(duration),
|
||||||
|
waiting_time_s(waiting),
|
||||||
|
easing_function(std::move(easing)) {}
|
||||||
|
|
||||||
// Constructor para paths por puntos (convertido a segundos)
|
// Constructor para paths por puntos (convertido a segundos)
|
||||||
Path(const std::vector<SDL_FPoint> &spots_init, float waiting_time_s_init);
|
Path(const std::vector<SDL_FPoint>& spots_init, float waiting_time_s_init);
|
||||||
|
|
||||||
// Variables para paths por puntos
|
// Variables para paths por puntos
|
||||||
std::vector<SDL_FPoint> spots; // Solo para paths por puntos
|
std::vector<SDL_FPoint> spots; // Solo para paths por puntos
|
||||||
@@ -52,7 +57,7 @@ struct Path { // Define un re
|
|||||||
};
|
};
|
||||||
|
|
||||||
// --- Funciones ---
|
// --- Funciones ---
|
||||||
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint>; // Devuelve un vector con los puntos que conforman la ruta
|
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)>& easing_function) -> std::vector<SDL_FPoint>; // Devuelve un vector con los puntos que conforman la ruta
|
||||||
|
|
||||||
// --- Clase PathSprite: Sprite que sigue uno o varios recorridos ---
|
// --- Clase PathSprite: Sprite que sigue uno o varios recorridos ---
|
||||||
class PathSprite : public Sprite {
|
class PathSprite : public Sprite {
|
||||||
@@ -63,13 +68,13 @@ class PathSprite : public Sprite {
|
|||||||
~PathSprite() override = default;
|
~PathSprite() override = default;
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(float delta_time); // Actualiza la posición del sprite según el recorrido (delta_time en segundos)
|
void update(float delta_time); // Actualiza la posición del sprite según el recorrido (delta_time en segundos)
|
||||||
void render() override; // Muestra el sprite por pantalla
|
void render() override; // Muestra el sprite por pantalla
|
||||||
|
|
||||||
// --- Gestión de recorridos ---
|
// --- Gestión de recorridos ---
|
||||||
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
|
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
|
||||||
void addPath(const std::vector<SDL_FPoint> &spots, float waiting_time_s = 0.0f); // Añade un recorrido a partir de puntos
|
void addPath(const std::vector<SDL_FPoint>& spots, float waiting_time_s = 0.0f); // Añade un recorrido a partir de puntos
|
||||||
void addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function<double(double)> &easing_function, float waiting_time_s = 0.0f); // Añade un recorrido generado
|
void addPath(float start, float end, PathType type, float fixed_pos, float duration_s, const std::function<double(double)>& easing_function, float waiting_time_s = 0.0f); // Añade un recorrido generado
|
||||||
|
|
||||||
// --- Estado y control ---
|
// --- Estado y control ---
|
||||||
void enable(); // Habilita el objeto
|
void enable(); // Habilita el objeto
|
||||||
@@ -87,5 +92,5 @@ class PathSprite : public Sprite {
|
|||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
void moveThroughCurrentPath(float delta_time); // Coloca el sprite en los diferentes puntos del recorrido
|
void moveThroughCurrentPath(float delta_time); // Coloca el sprite en los diferentes puntos del recorrido
|
||||||
void goToNextPathOrDie(); // Cambia de recorrido o finaliza
|
void goToNextPathOrDie(); // Cambia de recorrido o finaliza
|
||||||
};
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "player.h"
|
#include "player.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_FlipMode
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_FlipMode
|
||||||
|
|
||||||
@@ -6,17 +6,17 @@
|
|||||||
#include <cmath> // Para fmod
|
#include <cmath> // Para fmod
|
||||||
#include <cstdlib> // Para rand
|
#include <cstdlib> // Para rand
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.hpp" // Para Asset
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "input_types.h" // Para InputAction
|
#include "input_types.hpp" // Para InputAction
|
||||||
#include "manage_hiscore_table.h" // Para ManageHiScoreTable, HiScoreEntry
|
#include "manage_hiscore_table.hpp" // Para ManageHiScoreTable, HiScoreEntry
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "param.hpp" // Para Param, ParamGame, param
|
||||||
#include "scoreboard.h" // Para Scoreboard
|
#include "scoreboard.hpp" // Para Scoreboard
|
||||||
#include "stage.h" // Para power_can_be_added
|
#include "stage.hpp" // Para power_can_be_added
|
||||||
#include "stage_interface.h" // Para IStageInfo
|
#include "stage_interface.hpp" // Para IStageInfo
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#endif
|
#endif
|
||||||
@@ -615,7 +615,7 @@ void Player::setPlayingState(State state) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case State::SHOWING_NAME: {
|
case State::SHOWING_NAME: {
|
||||||
showing_name_time_accumulator_ = 0.0f; // Inicializar acumulador time-based
|
showing_name_time_accumulator_ = 0.0f; // Inicializar acumulador time-based
|
||||||
setScoreboardMode(Scoreboard::Mode::ENTER_TO_SHOW_NAME); // Iniciar animación de transición
|
setScoreboardMode(Scoreboard::Mode::ENTER_TO_SHOW_NAME); // Iniciar animación de transición
|
||||||
Scoreboard::get()->setEnterName(scoreboard_panel_, last_enter_name_);
|
Scoreboard::get()->setEnterName(scoreboard_panel_, last_enter_name_);
|
||||||
addScoreToScoreBoard();
|
addScoreToScoreBoard();
|
||||||
|
|||||||
@@ -7,14 +7,14 @@
|
|||||||
#include <utility> // Para pair
|
#include <utility> // Para pair
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimatedSprite
|
#include "animated_sprite.hpp" // Para AnimatedSprite
|
||||||
#include "bullet.h" // Para Bullet
|
#include "bullet.hpp" // Para Bullet
|
||||||
#include "enter_name.h" // Para EnterName
|
#include "enter_name.hpp" // Para EnterName
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "manage_hiscore_table.h" // Para Table
|
#include "manage_hiscore_table.hpp" // Para Table
|
||||||
#include "scoreboard.h" // Para Scoreboard
|
#include "scoreboard.hpp" // Para Scoreboard
|
||||||
#include "stage_interface.h" // Para IStageInfo
|
#include "stage_interface.hpp" // Para IStageInfo
|
||||||
#include "utils.h" // Para Circle
|
#include "utils.hpp" // Para Circle
|
||||||
|
|
||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
#include "opengl_shader.h"
|
#include "opengl_shader.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
@@ -40,12 +41,12 @@ bool OpenGLShader::initGLExtensions() {
|
|||||||
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray");
|
glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)SDL_GL_GetProcAddress("glEnableVertexAttribArray");
|
||||||
|
|
||||||
return glCreateShader && glShaderSource && glCompileShader && glGetShaderiv &&
|
return glCreateShader && glShaderSource && glCompileShader && glGetShaderiv &&
|
||||||
glGetShaderInfoLog && glDeleteShader && glAttachShader && glCreateProgram &&
|
glGetShaderInfoLog && glDeleteShader && glAttachShader && glCreateProgram &&
|
||||||
glLinkProgram && glValidateProgram && glGetProgramiv && glGetProgramInfoLog &&
|
glLinkProgram && glValidateProgram && glGetProgramiv && glGetProgramInfoLog &&
|
||||||
glUseProgram && glDeleteProgram && glGetUniformLocation && glUniform2f &&
|
glUseProgram && glDeleteProgram && glGetUniformLocation && glUniform2f &&
|
||||||
glGenVertexArrays && glBindVertexArray && glDeleteVertexArrays &&
|
glGenVertexArrays && glBindVertexArray && glDeleteVertexArrays &&
|
||||||
glGenBuffers && glBindBuffer && glBufferData && glDeleteBuffers &&
|
glGenBuffers && glBindBuffer && glBufferData && glDeleteBuffers &&
|
||||||
glVertexAttribPointer && glEnableVertexAttribArray;
|
glVertexAttribPointer && glEnableVertexAttribArray;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -53,14 +54,16 @@ void OpenGLShader::checkGLError(const char* operation) {
|
|||||||
GLenum error = glGetError();
|
GLenum error = glGetError();
|
||||||
if (error != GL_NO_ERROR) {
|
if (error != GL_NO_ERROR) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error OpenGL en %s: 0x%x", operation, error);
|
"Error OpenGL en %s: 0x%x",
|
||||||
|
operation,
|
||||||
|
error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type) {
|
GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type) {
|
||||||
if (source.empty()) {
|
if (source.empty()) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"ERROR: El código fuente del shader está vacío");
|
"ERROR: El código fuente del shader está vacío");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,14 +86,15 @@ GLuint OpenGLShader::compileShader(const std::string& source, GLenum shader_type
|
|||||||
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compiled);
|
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compiled);
|
||||||
if (compiled != GL_TRUE) {
|
if (compiled != GL_TRUE) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error en compilación del shader");
|
"Error en compilación del shader");
|
||||||
GLint log_length;
|
GLint log_length;
|
||||||
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &log_length);
|
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &log_length);
|
||||||
if (log_length > 0) {
|
if (log_length > 0) {
|
||||||
std::vector<char> log(log_length);
|
std::vector<char> log(log_length);
|
||||||
glGetShaderInfoLog(shader_id, log_length, &log_length, log.data());
|
glGetShaderInfoLog(shader_id, log_length, &log_length, log.data());
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Log de compilación: %s", log.data());
|
"Log de compilación: %s",
|
||||||
|
log.data());
|
||||||
}
|
}
|
||||||
glDeleteShader(shader_id);
|
glDeleteShader(shader_id);
|
||||||
return 0;
|
return 0;
|
||||||
@@ -103,7 +107,7 @@ GLuint OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) {
|
|||||||
GLuint program = glCreateProgram();
|
GLuint program = glCreateProgram();
|
||||||
if (program == 0) {
|
if (program == 0) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error al crear programa de shaders");
|
"Error al crear programa de shaders");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,14 +124,15 @@ GLuint OpenGLShader::linkProgram(GLuint vertex_shader, GLuint fragment_shader) {
|
|||||||
glGetProgramiv(program, GL_LINK_STATUS, &linked);
|
glGetProgramiv(program, GL_LINK_STATUS, &linked);
|
||||||
if (linked != GL_TRUE) {
|
if (linked != GL_TRUE) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error al enlazar programa");
|
"Error al enlazar programa");
|
||||||
GLint log_length;
|
GLint log_length;
|
||||||
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
|
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
|
||||||
if (log_length > 0) {
|
if (log_length > 0) {
|
||||||
std::vector<char> log(log_length);
|
std::vector<char> log(log_length);
|
||||||
glGetProgramInfoLog(program, log_length, &log_length, log.data());
|
glGetProgramInfoLog(program, log_length, &log_length, log.data());
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Log de enlace: %s", log.data());
|
"Log de enlace: %s",
|
||||||
|
log.data());
|
||||||
}
|
}
|
||||||
glDeleteProgram(program);
|
glDeleteProgram(program);
|
||||||
return 0;
|
return 0;
|
||||||
@@ -144,16 +149,32 @@ void OpenGLShader::createQuadGeometry() {
|
|||||||
// Formato: x, y, u, v
|
// Formato: x, y, u, v
|
||||||
float vertices[] = {
|
float vertices[] = {
|
||||||
// Posición // TexCoords
|
// Posición // TexCoords
|
||||||
-1.0f, -1.0f, 0.0f, 0.0f, // Inferior izquierda
|
-1.0f,
|
||||||
1.0f, -1.0f, 1.0f, 0.0f, // Inferior derecha
|
-1.0f,
|
||||||
1.0f, 1.0f, 1.0f, 1.0f, // Superior derecha
|
0.0f,
|
||||||
-1.0f, 1.0f, 0.0f, 1.0f // Superior izquierda
|
0.0f, // Inferior izquierda
|
||||||
|
1.0f,
|
||||||
|
-1.0f,
|
||||||
|
1.0f,
|
||||||
|
0.0f, // Inferior derecha
|
||||||
|
1.0f,
|
||||||
|
1.0f,
|
||||||
|
1.0f,
|
||||||
|
1.0f, // Superior derecha
|
||||||
|
-1.0f,
|
||||||
|
1.0f,
|
||||||
|
0.0f,
|
||||||
|
1.0f // Superior izquierda
|
||||||
};
|
};
|
||||||
|
|
||||||
// Índices para dibujar el quad con dos triángulos
|
// Índices para dibujar el quad con dos triángulos
|
||||||
unsigned int indices[] = {
|
unsigned int indices[] = {
|
||||||
0, 1, 2, // Primer triángulo
|
0,
|
||||||
2, 3, 0 // Segundo triángulo
|
1,
|
||||||
|
2, // Primer triángulo
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
0 // Segundo triángulo
|
||||||
};
|
};
|
||||||
|
|
||||||
// Generar y configurar VAO
|
// Generar y configurar VAO
|
||||||
@@ -207,7 +228,7 @@ GLuint OpenGLShader::getTextureID(SDL_Texture* texture) {
|
|||||||
|
|
||||||
if (texture_id == 0) {
|
if (texture_id == 0) {
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"No se pudo obtener ID de textura OpenGL, usando 1 por defecto");
|
"No se pudo obtener ID de textura OpenGL, usando 1 por defecto");
|
||||||
texture_id = 1;
|
texture_id = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -215,16 +236,16 @@ GLuint OpenGLShader::getTextureID(SDL_Texture* texture) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool OpenGLShader::init(SDL_Window* window,
|
bool OpenGLShader::init(SDL_Window* window,
|
||||||
SDL_Texture* texture,
|
SDL_Texture* texture,
|
||||||
const std::string& vertex_source,
|
const std::string& vertex_source,
|
||||||
const std::string& fragment_source) {
|
const std::string& fragment_source) {
|
||||||
window_ = window;
|
window_ = window;
|
||||||
back_buffer_ = texture;
|
back_buffer_ = texture;
|
||||||
renderer_ = SDL_GetRenderer(window);
|
renderer_ = SDL_GetRenderer(window);
|
||||||
|
|
||||||
if (!renderer_) {
|
if (!renderer_) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error: No se pudo obtener el renderer");
|
"Error: No se pudo obtener el renderer");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,14 +254,18 @@ bool OpenGLShader::init(SDL_Window* window,
|
|||||||
SDL_GetTextureSize(back_buffer_, &texture_width_, &texture_height_);
|
SDL_GetTextureSize(back_buffer_, &texture_width_, &texture_height_);
|
||||||
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Inicializando shaders: ventana=%dx%d, textura=%.0fx%.0f",
|
"Inicializando shaders: ventana=%dx%d, textura=%.0fx%.0f",
|
||||||
window_width_, window_height_, texture_width_, texture_height_);
|
window_width_,
|
||||||
|
window_height_,
|
||||||
|
texture_width_,
|
||||||
|
texture_height_);
|
||||||
|
|
||||||
// Verificar que es OpenGL
|
// Verificar que es OpenGL
|
||||||
const char* renderer_name = SDL_GetRendererName(renderer_);
|
const char* renderer_name = SDL_GetRendererName(renderer_);
|
||||||
if (!renderer_name || strncmp(renderer_name, "opengl", 6) != 0) {
|
if (!renderer_name || strncmp(renderer_name, "opengl", 6) != 0) {
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Renderer no es OpenGL: %s", renderer_name ? renderer_name : "unknown");
|
"Renderer no es OpenGL: %s",
|
||||||
|
renderer_name ? renderer_name : "unknown");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,7 +273,7 @@ bool OpenGLShader::init(SDL_Window* window,
|
|||||||
// Inicializar extensiones OpenGL en Windows/Linux
|
// Inicializar extensiones OpenGL en Windows/Linux
|
||||||
if (!initGLExtensions()) {
|
if (!initGLExtensions()) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error al inicializar extensiones OpenGL");
|
"Error al inicializar extensiones OpenGL");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -265,7 +290,7 @@ bool OpenGLShader::init(SDL_Window* window,
|
|||||||
|
|
||||||
if (vertex_shader == 0 || fragment_shader == 0) {
|
if (vertex_shader == 0 || fragment_shader == 0) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error al compilar shaders");
|
"Error al compilar shaders");
|
||||||
if (vertex_shader != 0) glDeleteShader(vertex_shader);
|
if (vertex_shader != 0) glDeleteShader(vertex_shader);
|
||||||
if (fragment_shader != 0) glDeleteShader(fragment_shader);
|
if (fragment_shader != 0) glDeleteShader(fragment_shader);
|
||||||
return false;
|
return false;
|
||||||
@@ -280,7 +305,7 @@ bool OpenGLShader::init(SDL_Window* window,
|
|||||||
|
|
||||||
if (program_id_ == 0) {
|
if (program_id_ == 0) {
|
||||||
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Error al crear programa de shaders");
|
"Error al crear programa de shaders");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -292,19 +317,20 @@ bool OpenGLShader::init(SDL_Window* window,
|
|||||||
texture_size_location_ = glGetUniformLocation(program_id_, "TextureSize");
|
texture_size_location_ = glGetUniformLocation(program_id_, "TextureSize");
|
||||||
if (texture_size_location_ != -1) {
|
if (texture_size_location_ != -1) {
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Configurando TextureSize uniform: %.0fx%.0f",
|
"Configurando TextureSize uniform: %.0fx%.0f",
|
||||||
texture_width_, texture_height_);
|
texture_width_,
|
||||||
|
texture_height_);
|
||||||
glUniform2f(texture_size_location_, texture_width_, texture_height_);
|
glUniform2f(texture_size_location_, texture_width_, texture_height_);
|
||||||
checkGLError("glUniform2f(TextureSize)");
|
checkGLError("glUniform2f(TextureSize)");
|
||||||
} else {
|
} else {
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Uniform 'TextureSize' no encontrado en shader");
|
"Uniform 'TextureSize' no encontrado en shader");
|
||||||
}
|
}
|
||||||
glUseProgram(0);
|
glUseProgram(0);
|
||||||
|
|
||||||
is_initialized_ = true;
|
is_initialized_ = true;
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"** OpenGL 3.3 Shader Backend inicializado correctamente");
|
"** OpenGL 3.3 Shader Backend inicializado correctamente");
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -459,4 +485,4 @@ void OpenGLShader::cleanup() {
|
|||||||
back_buffer_ = nullptr;
|
back_buffer_ = nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace Rendering
|
} // namespace Rendering
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include "../shader_backend.h"
|
|
||||||
|
|
||||||
#ifdef __APPLE__
|
|
||||||
#include <OpenGL/gl3.h>
|
|
||||||
#else
|
|
||||||
#include <SDL3/SDL_opengl.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace Rendering {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Backend de shaders usando OpenGL 3.3 Core Profile
|
|
||||||
*
|
|
||||||
* Implementa el renderizado de shaders usando APIs modernas de OpenGL:
|
|
||||||
* - VAO (Vertex Array Objects)
|
|
||||||
* - VBO (Vertex Buffer Objects)
|
|
||||||
* - Shaders GLSL #version 330 core
|
|
||||||
*/
|
|
||||||
class OpenGLShader : public ShaderBackend {
|
|
||||||
public:
|
|
||||||
OpenGLShader() = default;
|
|
||||||
~OpenGLShader() override;
|
|
||||||
|
|
||||||
bool init(SDL_Window* window,
|
|
||||||
SDL_Texture* texture,
|
|
||||||
const std::string& vertex_source,
|
|
||||||
const std::string& fragment_source) override;
|
|
||||||
|
|
||||||
void render() override;
|
|
||||||
void setTextureSize(float width, float height) override;
|
|
||||||
void cleanup() override;
|
|
||||||
bool isHardwareAccelerated() const override { return is_initialized_; }
|
|
||||||
|
|
||||||
private:
|
|
||||||
// Funciones auxiliares
|
|
||||||
bool initGLExtensions();
|
|
||||||
GLuint compileShader(const std::string& source, GLenum shader_type);
|
|
||||||
GLuint linkProgram(GLuint vertex_shader, GLuint fragment_shader);
|
|
||||||
void createQuadGeometry();
|
|
||||||
GLuint getTextureID(SDL_Texture* texture);
|
|
||||||
void checkGLError(const char* operation);
|
|
||||||
|
|
||||||
// Estado SDL
|
|
||||||
SDL_Window* window_ = nullptr;
|
|
||||||
SDL_Renderer* renderer_ = nullptr;
|
|
||||||
SDL_Texture* back_buffer_ = nullptr;
|
|
||||||
|
|
||||||
// Estado OpenGL
|
|
||||||
GLuint program_id_ = 0;
|
|
||||||
GLuint vao_ = 0; // Vertex Array Object
|
|
||||||
GLuint vbo_ = 0; // Vertex Buffer Object
|
|
||||||
GLuint ebo_ = 0; // Element Buffer Object
|
|
||||||
|
|
||||||
// Ubicaciones de uniforms
|
|
||||||
GLint texture_size_location_ = -1;
|
|
||||||
|
|
||||||
// Tamaños
|
|
||||||
int window_width_ = 0;
|
|
||||||
int window_height_ = 0;
|
|
||||||
float texture_width_ = 0.0f;
|
|
||||||
float texture_height_ = 0.0f;
|
|
||||||
|
|
||||||
// Estado
|
|
||||||
bool is_initialized_ = false;
|
|
||||||
|
|
||||||
#ifndef __APPLE__
|
|
||||||
// Punteros a funciones OpenGL en Windows/Linux
|
|
||||||
PFNGLCREATESHADERPROC glCreateShader = nullptr;
|
|
||||||
PFNGLSHADERSOURCEPROC glShaderSource = nullptr;
|
|
||||||
PFNGLCOMPILESHADERPROC glCompileShader = nullptr;
|
|
||||||
PFNGLGETSHADERIVPROC glGetShaderiv = nullptr;
|
|
||||||
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = nullptr;
|
|
||||||
PFNGLDELETESHADERPROC glDeleteShader = nullptr;
|
|
||||||
PFNGLATTACHSHADERPROC glAttachShader = nullptr;
|
|
||||||
PFNGLCREATEPROGRAMPROC glCreateProgram = nullptr;
|
|
||||||
PFNGLLINKPROGRAMPROC glLinkProgram = nullptr;
|
|
||||||
PFNGLVALIDATEPROGRAMPROC glValidateProgram = nullptr;
|
|
||||||
PFNGLGETPROGRAMIVPROC glGetProgramiv = nullptr;
|
|
||||||
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = nullptr;
|
|
||||||
PFNGLUSEPROGRAMPROC glUseProgram = nullptr;
|
|
||||||
PFNGLDELETEPROGRAMPROC glDeleteProgram = nullptr;
|
|
||||||
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation = nullptr;
|
|
||||||
PFNGLUNIFORM2FPROC glUniform2f = nullptr;
|
|
||||||
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays = nullptr;
|
|
||||||
PFNGLBINDVERTEXARRAYPROC glBindVertexArray = nullptr;
|
|
||||||
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays = nullptr;
|
|
||||||
PFNGLGENBUFFERSPROC glGenBuffers = nullptr;
|
|
||||||
PFNGLBINDBUFFERPROC glBindBuffer = nullptr;
|
|
||||||
PFNGLBUFFERDATAPROC glBufferData = nullptr;
|
|
||||||
PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr;
|
|
||||||
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr;
|
|
||||||
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr;
|
|
||||||
#endif
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Rendering
|
|
||||||
98
source/rendering/opengl/opengl_shader.hpp
Normal file
98
source/rendering/opengl/opengl_shader.hpp
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "../shader_backend.hpp"
|
||||||
|
|
||||||
|
#ifdef __APPLE__
|
||||||
|
#include <OpenGL/gl3.h>
|
||||||
|
#else
|
||||||
|
#include <SDL3/SDL_opengl.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace Rendering {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Backend de shaders usando OpenGL 3.3 Core Profile
|
||||||
|
*
|
||||||
|
* Implementa el renderizado de shaders usando APIs modernas de OpenGL:
|
||||||
|
* - VAO (Vertex Array Objects)
|
||||||
|
* - VBO (Vertex Buffer Objects)
|
||||||
|
* - Shaders GLSL #version 330 core
|
||||||
|
*/
|
||||||
|
class OpenGLShader : public ShaderBackend {
|
||||||
|
public:
|
||||||
|
OpenGLShader() = default;
|
||||||
|
~OpenGLShader() override;
|
||||||
|
|
||||||
|
bool init(SDL_Window* window,
|
||||||
|
SDL_Texture* texture,
|
||||||
|
const std::string& vertex_source,
|
||||||
|
const std::string& fragment_source) override;
|
||||||
|
|
||||||
|
void render() override;
|
||||||
|
void setTextureSize(float width, float height) override;
|
||||||
|
void cleanup() override;
|
||||||
|
bool isHardwareAccelerated() const override { return is_initialized_; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Funciones auxiliares
|
||||||
|
bool initGLExtensions();
|
||||||
|
GLuint compileShader(const std::string& source, GLenum shader_type);
|
||||||
|
GLuint linkProgram(GLuint vertex_shader, GLuint fragment_shader);
|
||||||
|
void createQuadGeometry();
|
||||||
|
GLuint getTextureID(SDL_Texture* texture);
|
||||||
|
void checkGLError(const char* operation);
|
||||||
|
|
||||||
|
// Estado SDL
|
||||||
|
SDL_Window* window_ = nullptr;
|
||||||
|
SDL_Renderer* renderer_ = nullptr;
|
||||||
|
SDL_Texture* back_buffer_ = nullptr;
|
||||||
|
|
||||||
|
// Estado OpenGL
|
||||||
|
GLuint program_id_ = 0;
|
||||||
|
GLuint vao_ = 0; // Vertex Array Object
|
||||||
|
GLuint vbo_ = 0; // Vertex Buffer Object
|
||||||
|
GLuint ebo_ = 0; // Element Buffer Object
|
||||||
|
|
||||||
|
// Ubicaciones de uniforms
|
||||||
|
GLint texture_size_location_ = -1;
|
||||||
|
|
||||||
|
// Tamaños
|
||||||
|
int window_width_ = 0;
|
||||||
|
int window_height_ = 0;
|
||||||
|
float texture_width_ = 0.0f;
|
||||||
|
float texture_height_ = 0.0f;
|
||||||
|
|
||||||
|
// Estado
|
||||||
|
bool is_initialized_ = false;
|
||||||
|
|
||||||
|
#ifndef __APPLE__
|
||||||
|
// Punteros a funciones OpenGL en Windows/Linux
|
||||||
|
PFNGLCREATESHADERPROC glCreateShader = nullptr;
|
||||||
|
PFNGLSHADERSOURCEPROC glShaderSource = nullptr;
|
||||||
|
PFNGLCOMPILESHADERPROC glCompileShader = nullptr;
|
||||||
|
PFNGLGETSHADERIVPROC glGetShaderiv = nullptr;
|
||||||
|
PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog = nullptr;
|
||||||
|
PFNGLDELETESHADERPROC glDeleteShader = nullptr;
|
||||||
|
PFNGLATTACHSHADERPROC glAttachShader = nullptr;
|
||||||
|
PFNGLCREATEPROGRAMPROC glCreateProgram = nullptr;
|
||||||
|
PFNGLLINKPROGRAMPROC glLinkProgram = nullptr;
|
||||||
|
PFNGLVALIDATEPROGRAMPROC glValidateProgram = nullptr;
|
||||||
|
PFNGLGETPROGRAMIVPROC glGetProgramiv = nullptr;
|
||||||
|
PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog = nullptr;
|
||||||
|
PFNGLUSEPROGRAMPROC glUseProgram = nullptr;
|
||||||
|
PFNGLDELETEPROGRAMPROC glDeleteProgram = nullptr;
|
||||||
|
PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation = nullptr;
|
||||||
|
PFNGLUNIFORM2FPROC glUniform2f = nullptr;
|
||||||
|
PFNGLGENVERTEXARRAYSPROC glGenVertexArrays = nullptr;
|
||||||
|
PFNGLBINDVERTEXARRAYPROC glBindVertexArray = nullptr;
|
||||||
|
PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays = nullptr;
|
||||||
|
PFNGLGENBUFFERSPROC glGenBuffers = nullptr;
|
||||||
|
PFNGLBINDBUFFERPROC glBindBuffer = nullptr;
|
||||||
|
PFNGLBUFFERDATAPROC glBufferData = nullptr;
|
||||||
|
PFNGLDELETEBUFFERSPROC glDeleteBuffers = nullptr;
|
||||||
|
PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer = nullptr;
|
||||||
|
PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray = nullptr;
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Rendering
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <SDL3/SDL.h>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
namespace Rendering {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Interfaz abstracta para backends de renderizado con shaders
|
|
||||||
*
|
|
||||||
* Esta interfaz define el contrato que todos los backends de shaders
|
|
||||||
* deben cumplir (OpenGL, Metal, Vulkan, etc.)
|
|
||||||
*/
|
|
||||||
class ShaderBackend {
|
|
||||||
public:
|
|
||||||
virtual ~ShaderBackend() = default;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Inicializa el backend de shaders
|
|
||||||
* @param window Ventana SDL
|
|
||||||
* @param texture Textura de backbuffer a la que aplicar shaders
|
|
||||||
* @param vertex_source Código fuente del vertex shader
|
|
||||||
* @param fragment_source Código fuente del fragment shader
|
|
||||||
* @return true si la inicialización fue exitosa
|
|
||||||
*/
|
|
||||||
virtual bool init(SDL_Window* window,
|
|
||||||
SDL_Texture* texture,
|
|
||||||
const std::string& vertex_source,
|
|
||||||
const std::string& fragment_source) = 0;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Renderiza la textura con los shaders aplicados
|
|
||||||
*/
|
|
||||||
virtual void render() = 0;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Establece el tamaño de la textura como parámetro del shader
|
|
||||||
* @param width Ancho de la textura
|
|
||||||
* @param height Alto de la textura
|
|
||||||
*/
|
|
||||||
virtual void setTextureSize(float width, float height) = 0;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Limpia y libera recursos del backend
|
|
||||||
*/
|
|
||||||
virtual void cleanup() = 0;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Verifica si el backend está usando aceleración por hardware
|
|
||||||
* @return true si usa aceleración (OpenGL/Metal/Vulkan)
|
|
||||||
*/
|
|
||||||
virtual bool isHardwareAccelerated() const = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Rendering
|
|
||||||
56
source/rendering/shader_backend.hpp
Normal file
56
source/rendering/shader_backend.hpp
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace Rendering {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Interfaz abstracta para backends de renderizado con shaders
|
||||||
|
*
|
||||||
|
* Esta interfaz define el contrato que todos los backends de shaders
|
||||||
|
* deben cumplir (OpenGL, Metal, Vulkan, etc.)
|
||||||
|
*/
|
||||||
|
class ShaderBackend {
|
||||||
|
public:
|
||||||
|
virtual ~ShaderBackend() = default;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Inicializa el backend de shaders
|
||||||
|
* @param window Ventana SDL
|
||||||
|
* @param texture Textura de backbuffer a la que aplicar shaders
|
||||||
|
* @param vertex_source Código fuente del vertex shader
|
||||||
|
* @param fragment_source Código fuente del fragment shader
|
||||||
|
* @return true si la inicialización fue exitosa
|
||||||
|
*/
|
||||||
|
virtual bool init(SDL_Window* window,
|
||||||
|
SDL_Texture* texture,
|
||||||
|
const std::string& vertex_source,
|
||||||
|
const std::string& fragment_source) = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Renderiza la textura con los shaders aplicados
|
||||||
|
*/
|
||||||
|
virtual void render() = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Establece el tamaño de la textura como parámetro del shader
|
||||||
|
* @param width Ancho de la textura
|
||||||
|
* @param height Alto de la textura
|
||||||
|
*/
|
||||||
|
virtual void setTextureSize(float width, float height) = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Limpia y libera recursos del backend
|
||||||
|
*/
|
||||||
|
virtual void cleanup() = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Verifica si el backend está usando aceleración por hardware
|
||||||
|
* @return true si usa aceleración (OpenGL/Metal/Vulkan)
|
||||||
|
*/
|
||||||
|
virtual bool isHardwareAccelerated() const = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace Rendering
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "resource.h"
|
#include "resource.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError, SDL_SetRenderDrawColor, SDL_EventType, SDL_PollEvent, SDL_RenderFillRect, SDL_RenderRect, SDLK_ESCAPE, SDL_Event
|
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError, SDL_SetRenderDrawColor, SDL_EventType, SDL_PollEvent, SDL_RenderFillRect, SDL_RenderRect, SDLK_ESCAPE, SDL_Event
|
||||||
|
|
||||||
@@ -10,14 +10,14 @@
|
|||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
|
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.hpp" // Para Asset
|
||||||
#include "color.h" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
#include "external/jail_audio.h" // Para JA_LoadMusic, JA_LoadSound, JA_DeleteMusic, JA_DeleteSound
|
#include "external/jail_audio.h" // Para JA_LoadMusic, JA_LoadSound, JA_DeleteMusic, JA_DeleteSound
|
||||||
#include "lang.h" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "param.h" // Para Param, param, ParamResource, ParamGame
|
#include "param.hpp" // Para Param, param, ParamResource, ParamGame
|
||||||
#include "resource_helper.h" // Para ResourceHelper
|
#include "resource_helper.hpp" // Para ResourceHelper
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "text.h" // Para Text
|
#include "text.hpp" // Para Text
|
||||||
#include "version.h" // Para Version::APP_NAME y Version::GIT_HASH
|
#include "version.h" // Para Version::APP_NAME y Version::GIT_HASH
|
||||||
|
|
||||||
struct JA_Music_t; // lines 11-11
|
struct JA_Music_t; // lines 11-11
|
||||||
|
|||||||
@@ -8,10 +8,10 @@
|
|||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "animated_sprite.h" // Para AnimationsFileBuffer
|
#include "animated_sprite.hpp" // Para AnimationsFileBuffer
|
||||||
#include "text.h" // Para Text, TextFile
|
#include "demo.hpp" // Para DemoData
|
||||||
#include "texture.h" // Para Texture
|
#include "text.hpp" // Para Text, TextFile
|
||||||
#include "demo.h" // Para DemoData
|
#include "texture.hpp" // Para Texture
|
||||||
|
|
||||||
struct JA_Music_t;
|
struct JA_Music_t;
|
||||||
struct JA_Sound_t;
|
struct JA_Sound_t;
|
||||||
@@ -28,16 +28,16 @@ class Resource {
|
|||||||
// --- Métodos de singleton ---
|
// --- Métodos de singleton ---
|
||||||
static void init(LoadingMode mode = LoadingMode::PRELOAD); // Inicializa el objeto Resource con modo de carga
|
static void init(LoadingMode mode = LoadingMode::PRELOAD); // Inicializa el objeto Resource con modo de carga
|
||||||
static void destroy(); // Libera el objeto Resource
|
static void destroy(); // Libera el objeto Resource
|
||||||
static auto get() -> Resource *; // Obtiene el puntero al objeto Resource
|
static auto get() -> Resource*; // Obtiene el puntero al objeto Resource
|
||||||
|
|
||||||
// --- Métodos de acceso a recursos ---
|
// --- Métodos de acceso a recursos ---
|
||||||
auto getSound(const std::string &name) -> JA_Sound_t *; // Obtiene el sonido por nombre
|
auto getSound(const std::string& name) -> JA_Sound_t*; // Obtiene el sonido por nombre
|
||||||
auto getMusic(const std::string &name) -> JA_Music_t *; // Obtiene la música por nombre
|
auto getMusic(const std::string& name) -> JA_Music_t*; // Obtiene la música por nombre
|
||||||
auto getTexture(const std::string &name) -> std::shared_ptr<Texture>; // Obtiene la textura por nombre
|
auto getTexture(const std::string& name) -> std::shared_ptr<Texture>; // Obtiene la textura por nombre
|
||||||
auto getTextFile(const std::string &name) -> std::shared_ptr<Text::File>; // Obtiene el fichero de texto por nombre
|
auto getTextFile(const std::string& name) -> std::shared_ptr<Text::File>; // Obtiene el fichero de texto por nombre
|
||||||
auto getText(const std::string &name) -> std::shared_ptr<Text>; // Obtiene el objeto de texto por nombre
|
auto getText(const std::string& name) -> std::shared_ptr<Text>; // Obtiene el objeto de texto por nombre
|
||||||
auto getAnimation(const std::string &name) -> AnimationsFileBuffer &; // Obtiene la animación por nombre
|
auto getAnimation(const std::string& name) -> AnimationsFileBuffer&; // Obtiene la animación por nombre
|
||||||
auto getDemoData(int index) -> DemoData &; // Obtiene los datos de demo por índice
|
auto getDemoData(int index) -> DemoData&; // Obtiene los datos de demo por índice
|
||||||
|
|
||||||
// --- Métodos de recarga de recursos ---
|
// --- Métodos de recarga de recursos ---
|
||||||
void reload(); // Recarga todos los recursos
|
void reload(); // Recarga todos los recursos
|
||||||
@@ -49,18 +49,18 @@ class Resource {
|
|||||||
// --- Estructuras para recursos individuales ---
|
// --- Estructuras para recursos individuales ---
|
||||||
struct ResourceSound {
|
struct ResourceSound {
|
||||||
std::string name; // Nombre del sonido
|
std::string name; // Nombre del sonido
|
||||||
JA_Sound_t *sound; // Objeto con el sonido
|
JA_Sound_t* sound; // Objeto con el sonido
|
||||||
|
|
||||||
ResourceSound(std::string name, JA_Sound_t *sound = nullptr)
|
ResourceSound(std::string name, JA_Sound_t* sound = nullptr)
|
||||||
: name(std::move(name)),
|
: name(std::move(name)),
|
||||||
sound(sound) {}
|
sound(sound) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ResourceMusic {
|
struct ResourceMusic {
|
||||||
std::string name; // Nombre de la música
|
std::string name; // Nombre de la música
|
||||||
JA_Music_t *music; // Objeto con la música
|
JA_Music_t* music; // Objeto con la música
|
||||||
|
|
||||||
ResourceMusic(std::string name, JA_Music_t *music = nullptr)
|
ResourceMusic(std::string name, JA_Music_t* music = nullptr)
|
||||||
: name(std::move(name)),
|
: name(std::move(name)),
|
||||||
music(music) {}
|
music(music) {}
|
||||||
};
|
};
|
||||||
@@ -169,12 +169,12 @@ class Resource {
|
|||||||
|
|
||||||
// --- Métodos para carga perezosa ---
|
// --- Métodos para carga perezosa ---
|
||||||
void initResourceLists(); // Inicializa las listas de recursos sin cargar el contenido
|
void initResourceLists(); // Inicializa las listas de recursos sin cargar el contenido
|
||||||
static auto loadSoundLazy(const std::string &name) -> JA_Sound_t *; // Carga un sonido específico bajo demanda
|
static auto loadSoundLazy(const std::string& name) -> JA_Sound_t*; // Carga un sonido específico bajo demanda
|
||||||
static auto loadMusicLazy(const std::string &name) -> JA_Music_t *; // Carga una música específica bajo demanda
|
static auto loadMusicLazy(const std::string& name) -> JA_Music_t*; // Carga una música específica bajo demanda
|
||||||
static auto loadTextureLazy(const std::string &name) -> std::shared_ptr<Texture>; // Carga una textura específica bajo demanda
|
static auto loadTextureLazy(const std::string& name) -> std::shared_ptr<Texture>; // Carga una textura específica bajo demanda
|
||||||
static auto loadTextFileLazy(const std::string &name) -> std::shared_ptr<Text::File>; // Carga un fichero de texto específico bajo demanda
|
static auto loadTextFileLazy(const std::string& name) -> std::shared_ptr<Text::File>; // Carga un fichero de texto específico bajo demanda
|
||||||
auto loadTextLazy(const std::string &name) -> std::shared_ptr<Text>; // Carga un objeto de texto específico bajo demanda
|
auto loadTextLazy(const std::string& name) -> std::shared_ptr<Text>; // Carga un objeto de texto específico bajo demanda
|
||||||
static auto loadAnimationLazy(const std::string &name) -> AnimationsFileBuffer; // Carga una animación específica bajo demanda
|
static auto loadAnimationLazy(const std::string& name) -> AnimationsFileBuffer; // Carga una animación específica bajo demanda
|
||||||
|
|
||||||
// --- Métodos internos para gestionar el progreso ---
|
// --- Métodos internos para gestionar el progreso ---
|
||||||
void calculateTotalResources(); // Calcula el número de recursos para cargar
|
void calculateTotalResources(); // Calcula el número de recursos para cargar
|
||||||
@@ -189,5 +189,5 @@ class Resource {
|
|||||||
~Resource(); // Destructor privado
|
~Resource(); // Destructor privado
|
||||||
|
|
||||||
// --- Instancia singleton ---
|
// --- Instancia singleton ---
|
||||||
static Resource *instance; // Instancia única de Resource
|
static Resource* instance; // Instancia única de Resource
|
||||||
};
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "resource_helper.h"
|
#include "resource_helper.hpp"
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "resource_loader.h"
|
#include "resource_loader.hpp"
|
||||||
|
|
||||||
// Helper functions para integrar ResourceLoader con el sistema existente
|
// Helper functions para integrar ResourceLoader con el sistema existente
|
||||||
namespace ResourceHelper {
|
namespace ResourceHelper {
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "resource_loader.h"
|
#include "resource_loader.hpp"
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
#include "resource_pack.h"
|
#include "resource_pack.hpp"
|
||||||
|
|
||||||
class ResourceLoader {
|
class ResourceLoader {
|
||||||
private:
|
private:
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "resource_pack.h"
|
#include "resource_pack.hpp"
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "scoreboard.h"
|
#include "scoreboard.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_DestroyTexture, SDL_SetRenderDrawColor, SDL_SetRenderTarget, SDL_CreateTexture, SDL_GetRenderTarget, SDL_GetTicks, SDL_RenderClear, SDL_RenderLine, SDL_RenderTexture, SDL_SetTextureBlendMode, SDL_FRect, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_Texture, SDL_TextureAccess
|
#include <SDL3/SDL.h> // Para SDL_DestroyTexture, SDL_SetRenderDrawColor, SDL_SetRenderTarget, SDL_CreateTexture, SDL_GetRenderTarget, SDL_GetTicks, SDL_RenderClear, SDL_RenderLine, SDL_RenderTexture, SDL_SetTextureBlendMode, SDL_FRect, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_Texture, SDL_TextureAccess
|
||||||
|
|
||||||
@@ -7,16 +7,16 @@
|
|||||||
#include <iomanip> // Para operator<<, setfill, setw
|
#include <iomanip> // Para operator<<, setfill, setw
|
||||||
#include <sstream> // Para basic_ostream, basic_ostringstream, basic_ostream::operator<<, ostringstream
|
#include <sstream> // Para basic_ostream, basic_ostringstream, basic_ostream::operator<<, ostringstream
|
||||||
|
|
||||||
#include "color.h"
|
#include "color.hpp"
|
||||||
#include "enter_name.h" // Para NAME_SIZE
|
#include "enter_name.hpp" // Para NAME_SIZE
|
||||||
#include "lang.h" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "param.h" // Para Param, ParamScoreboard, param
|
#include "param.hpp" // Para Param, ParamScoreboard, param
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "text.h" // Para Text, Text::CENTER, Text::COLOR
|
#include "text.hpp" // Para Text, Text::CENTER, Text::COLOR
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "utils.h" // Para easeOutCubic
|
#include "utils.hpp" // Para easeOutCubic
|
||||||
|
|
||||||
// .at(SINGLETON) Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
// .at(SINGLETON) Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
||||||
Scoreboard* Scoreboard::instance = nullptr;
|
Scoreboard* Scoreboard::instance = nullptr;
|
||||||
@@ -125,7 +125,7 @@ void Scoreboard::setCarouselAnimation(Id id, int selected_index, EnterName* ente
|
|||||||
if (direction > LIST_SIZE / 2) {
|
if (direction > LIST_SIZE / 2) {
|
||||||
direction = -(LIST_SIZE - direction); // Wrap backward (ej: Z → A)
|
direction = -(LIST_SIZE - direction); // Wrap backward (ej: Z → A)
|
||||||
} else if (direction < -LIST_SIZE / 2) {
|
} else if (direction < -LIST_SIZE / 2) {
|
||||||
direction = LIST_SIZE + direction; // Wrap forward (ej: A → Z)
|
direction = LIST_SIZE + direction; // Wrap forward (ej: A → Z)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Normalizar a -1 o +1
|
// Normalizar a -1 o +1
|
||||||
@@ -447,21 +447,17 @@ void Scoreboard::renderScoreToEnterNameMode(size_t panel_index) {
|
|||||||
|
|
||||||
// ========== Texto que SALE hacia arriba ==========
|
// ========== Texto que SALE hacia arriba ==========
|
||||||
// name_ (sale desde ROW1 hacia arriba)
|
// name_ (sale desde ROW1 hacia arriba)
|
||||||
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y - t * delta_1_to_2,
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y - t * delta_1_to_2, name_.at(panel_index), 1, text_color1_);
|
||||||
name_.at(panel_index), 1, text_color1_);
|
|
||||||
|
|
||||||
// ========== Textos que SE MUEVEN hacia arriba ==========
|
// ========== Textos que SE MUEVEN hacia arriba ==========
|
||||||
// score_ (se mueve de ROW2 a ROW1)
|
// score_ (se mueve de ROW2 a ROW1)
|
||||||
text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y - t * delta_1_to_2,
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y - t * delta_1_to_2, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
||||||
updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
|
||||||
|
|
||||||
// "ENTER NAME" (se mueve de ROW3 a ROW2)
|
// "ENTER NAME" (se mueve de ROW3 a ROW2)
|
||||||
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - t * delta_2_to_3,
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y - t * delta_2_to_3, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
||||||
Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
|
||||||
|
|
||||||
// enter_name_ (se mueve de ROW4 a ROW3)
|
// enter_name_ (se mueve de ROW4 a ROW3)
|
||||||
text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - t * delta_3_to_4,
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_4_.x, slot4_4_.y - t * delta_3_to_4, enter_name_.at(panel_index), 1, text_color2_);
|
||||||
enter_name_.at(panel_index), 1, text_color2_);
|
|
||||||
|
|
||||||
// ========== Elemento que ENTRA desde abajo ==========
|
// ========== Elemento que ENTRA desde abajo ==========
|
||||||
// CARRUSEL (entra desde debajo de ROW4 hacia ROW4)
|
// CARRUSEL (entra desde debajo de ROW4 hacia ROW4)
|
||||||
@@ -505,21 +501,17 @@ void Scoreboard::renderEnterToShowNameMode(size_t panel_index) {
|
|||||||
// ========== Texto que ENTRA desde arriba ==========
|
// ========== Texto que ENTRA desde arriba ==========
|
||||||
// name_ (entra desde arriba hacia ROW1)
|
// name_ (entra desde arriba hacia ROW1)
|
||||||
// Debe venir desde donde estaría ROW0, que está a delta_1_to_2 píxeles arriba de ROW1
|
// Debe venir desde donde estaría ROW0, que está a delta_1_to_2 píxeles arriba de ROW1
|
||||||
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + t * delta_1_to_2 - delta_1_to_2,
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + t * delta_1_to_2 - delta_1_to_2, name_.at(panel_index), 1, text_color1_);
|
||||||
name_.at(panel_index), 1, text_color1_);
|
|
||||||
|
|
||||||
// ========== Textos que SE MUEVEN (renderizar UNA sola vez) ==========
|
// ========== Textos que SE MUEVEN (renderizar UNA sola vez) ==========
|
||||||
// SCORE (se mueve de ROW1 a ROW2)
|
// SCORE (se mueve de ROW1 a ROW2)
|
||||||
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + t * delta_1_to_2,
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_1_.x, slot4_1_.y + t * delta_1_to_2, updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
||||||
updateScoreText(score_.at(panel_index)), 1, text_color2_);
|
|
||||||
|
|
||||||
// "ENTER NAME" (se mueve de ROW2 a ROW3)
|
// "ENTER NAME" (se mueve de ROW2 a ROW3)
|
||||||
text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y + t * delta_2_to_3,
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_2_.x, slot4_2_.y + t * delta_2_to_3, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
||||||
Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
|
|
||||||
|
|
||||||
// enter_name_ (se mueve de ROW3 a ROW4)
|
// enter_name_ (se mueve de ROW3 a ROW4)
|
||||||
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y + t * delta_3_to_4,
|
text_->writeDX(Text::CENTER | Text::COLOR, slot4_3_.x, slot4_3_.y + t * delta_3_to_4, enter_name_.at(panel_index), 1, text_color2_);
|
||||||
enter_name_.at(panel_index), 1, text_color2_);
|
|
||||||
|
|
||||||
// ========== Elemento que SALE hacia abajo ==========
|
// ========== Elemento que SALE hacia abajo ==========
|
||||||
// CARRUSEL (sale desde ROW4 hacia abajo, fuera de pantalla)
|
// CARRUSEL (sale desde ROW4 hacia abajo, fuera de pantalla)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
// Forward declarations
|
// Forward declarations
|
||||||
class EnterName;
|
class EnterName;
|
||||||
|
|
||||||
#include "color.h" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
|
|
||||||
class Sprite;
|
class Sprite;
|
||||||
class Text;
|
class Text;
|
||||||
@@ -37,7 +37,7 @@ class Scoreboard {
|
|||||||
DEMO,
|
DEMO,
|
||||||
SCORE_TO_ENTER_NAME, // Transición animada: SCORE → ENTER_NAME
|
SCORE_TO_ENTER_NAME, // Transición animada: SCORE → ENTER_NAME
|
||||||
ENTER_NAME,
|
ENTER_NAME,
|
||||||
ENTER_TO_SHOW_NAME, // Transición animada: ENTER_NAME → SHOW_NAME
|
ENTER_TO_SHOW_NAME, // Transición animada: ENTER_NAME → SHOW_NAME
|
||||||
SHOW_NAME,
|
SHOW_NAME,
|
||||||
GAME_COMPLETED,
|
GAME_COMPLETED,
|
||||||
NUM_MODES,
|
NUM_MODES,
|
||||||
@@ -88,11 +88,11 @@ class Scoreboard {
|
|||||||
std::array<std::string, static_cast<int>(Id::SIZE)> name_ = {}; // Nombre de cada jugador
|
std::array<std::string, static_cast<int>(Id::SIZE)> name_ = {}; // Nombre de cada jugador
|
||||||
std::array<std::string, static_cast<int>(Id::SIZE)> enter_name_ = {}; // Nombre introducido para la tabla de records
|
std::array<std::string, static_cast<int>(Id::SIZE)> enter_name_ = {}; // Nombre introducido para la tabla de records
|
||||||
std::array<std::string, static_cast<int>(Id::SIZE)> character_selected_ = {}; // Caracter seleccionado
|
std::array<std::string, static_cast<int>(Id::SIZE)> character_selected_ = {}; // Caracter seleccionado
|
||||||
std::array<EnterName*, static_cast<int>(Id::SIZE)> enter_name_ref_ = {}; // Referencias a EnterName para obtener character_list_
|
std::array<EnterName*, static_cast<int>(Id::SIZE)> enter_name_ref_ = {}; // Referencias a EnterName para obtener character_list_
|
||||||
std::array<float, static_cast<int>(Id::SIZE)> carousel_position_ = {}; // Posición actual del carrusel (índice en character_list_)
|
std::array<float, static_cast<int>(Id::SIZE)> carousel_position_ = {}; // Posición actual del carrusel (índice en character_list_)
|
||||||
std::array<float, static_cast<int>(Id::SIZE)> carousel_target_ = {}; // Posición objetivo del carrusel
|
std::array<float, static_cast<int>(Id::SIZE)> carousel_target_ = {}; // Posición objetivo del carrusel
|
||||||
std::array<int, static_cast<int>(Id::SIZE)> carousel_prev_index_ = {}; // Índice previo para detectar cambios
|
std::array<int, static_cast<int>(Id::SIZE)> carousel_prev_index_ = {}; // Índice previo para detectar cambios
|
||||||
std::array<float, static_cast<int>(Id::SIZE)> text_slide_offset_ = {}; // Progreso de animación de deslizamiento (0.0 a 1.0)
|
std::array<float, static_cast<int>(Id::SIZE)> text_slide_offset_ = {}; // Progreso de animación de deslizamiento (0.0 a 1.0)
|
||||||
std::array<Panel, static_cast<int>(Id::SIZE)> panel_ = {}; // Lista con todos los paneles del marcador
|
std::array<Panel, static_cast<int>(Id::SIZE)> panel_ = {}; // Lista con todos los paneles del marcador
|
||||||
Colors::Cycle name_color_cycle_; // Ciclo de colores para destacar el nombre una vez introducido
|
Colors::Cycle name_color_cycle_; // Ciclo de colores para destacar el nombre una vez introducido
|
||||||
Color animated_color_; // Color actual animado (ciclo automático cada 100ms)
|
Color animated_color_; // Color actual animado (ciclo automático cada 100ms)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "screen.h"
|
#include "screen.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_LogCategory, SDL_LogInfo, SDL_RenderTexture, SDL_SetRenderDrawColor, SDL_SetRenderVSync, SDL_GetError, SDL_LogError, SDL_RendererLogicalPresentation, SDL_SetRenderLogicalPresentation, SDL_CreateTexture, SDL_DestroyTexture, SDL_DestroyWindow, SDL_GetTicks, SDL_Quit, SDL_RENDERER_VSYNC_DISABLED, SDL_RenderClear, SDL_CreateRenderer, SDL_CreateWindow, SDL_DestroyRenderer, SDL_DisplayID, SDL_FRect, SDL_GetCurrentDisplayMode, SDL_GetDisplayName, SDL_GetDisplays, SDL_GetRenderTarget, SDL_GetWindowPosition, SDL_GetWindowSize, SDL_Init, SDL_LogWarn, SDL_PixelFormat, SDL_RenderFillRect, SDL_RenderPresent, SDL_SetHint, SDL_SetRenderDrawBlendMode, SDL_SetTextureScaleMode, SDL_SetWindowFullscreen, SDL_SetWindowPosition, SDL_SetWindowSize, SDL_TextureAccess, SDL_free, SDL_BLENDMODE_BLEND, SDL_HINT_RENDER_DRIVER, SDL_INIT_VIDEO, SDL_PRIu32, SDL_ScaleMode, SDL_WINDOW_FULLSCREEN, SDL_WINDOW_OPENGL, SDL_WindowFlags
|
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_LogCategory, SDL_LogInfo, SDL_RenderTexture, SDL_SetRenderDrawColor, SDL_SetRenderVSync, SDL_GetError, SDL_LogError, SDL_RendererLogicalPresentation, SDL_SetRenderLogicalPresentation, SDL_CreateTexture, SDL_DestroyTexture, SDL_DestroyWindow, SDL_GetTicks, SDL_Quit, SDL_RENDERER_VSYNC_DISABLED, SDL_RenderClear, SDL_CreateRenderer, SDL_CreateWindow, SDL_DestroyRenderer, SDL_DisplayID, SDL_FRect, SDL_GetCurrentDisplayMode, SDL_GetDisplayName, SDL_GetDisplays, SDL_GetRenderTarget, SDL_GetWindowPosition, SDL_GetWindowSize, SDL_Init, SDL_LogWarn, SDL_PixelFormat, SDL_RenderFillRect, SDL_RenderPresent, SDL_SetHint, SDL_SetRenderDrawBlendMode, SDL_SetTextureScaleMode, SDL_SetWindowFullscreen, SDL_SetWindowPosition, SDL_SetWindowSize, SDL_TextureAccess, SDL_free, SDL_BLENDMODE_BLEND, SDL_HINT_RENDER_DRIVER, SDL_INIT_VIDEO, SDL_PRIu32, SDL_ScaleMode, SDL_WINDOW_FULLSCREEN, SDL_WINDOW_OPENGL, SDL_WindowFlags
|
||||||
|
|
||||||
@@ -8,19 +8,19 @@
|
|||||||
#include <memory> // Para allocator, shared_ptr, make_shared, __shared_ptr_access
|
#include <memory> // Para allocator, shared_ptr, make_shared, __shared_ptr_access
|
||||||
#include <string> // Para operator+, char_traits, to_string, string
|
#include <string> // Para operator+, char_traits, to_string, string
|
||||||
|
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.hpp" // Para Asset
|
||||||
#include "mouse.h" // Para updateCursorVisibility
|
#include "mouse.hpp" // Para updateCursorVisibility
|
||||||
#include "rendering/opengl/opengl_shader.h" // Para OpenGLShader
|
#include "options.hpp" // Para VideoOptions, video, WindowOptions, window
|
||||||
#include "options.h" // Para VideoOptions, video, WindowOptions, window
|
#include "param.hpp" // Para Param, param, ParamGame, ParamDebug
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamDebug
|
#include "rendering/opengl/opengl_shader.hpp" // Para OpenGLShader
|
||||||
#include "text.h" // Para Text, Text::COLOR, Text::STROKE
|
#include "text.hpp" // Para Text, Text::COLOR, Text::STROKE
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "ui/notifier.h" // Para Notifier
|
#include "ui/notifier.hpp" // Para Notifier
|
||||||
#include "ui/service_menu.h" // Para ServiceMenu
|
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||||
#include "utils.h" // Para Zone
|
#include "utils.hpp" // Para Zone
|
||||||
|
|
||||||
// Singleton
|
// Singleton
|
||||||
Screen *Screen::instance = nullptr;
|
Screen* Screen::instance = nullptr;
|
||||||
|
|
||||||
// Inicializa la instancia única del singleton
|
// Inicializa la instancia única del singleton
|
||||||
void Screen::init() { Screen::instance = new Screen(); }
|
void Screen::init() { Screen::instance = new Screen(); }
|
||||||
@@ -29,7 +29,7 @@ void Screen::init() { Screen::instance = new Screen(); }
|
|||||||
void Screen::destroy() { delete Screen::instance; }
|
void Screen::destroy() { delete Screen::instance; }
|
||||||
|
|
||||||
// Obtiene la instancia
|
// Obtiene la instancia
|
||||||
auto Screen::get() -> Screen * { return Screen::instance; }
|
auto Screen::get() -> Screen* { return Screen::instance; }
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Screen::Screen()
|
Screen::Screen()
|
||||||
@@ -189,10 +189,10 @@ void Screen::renderFlash() {
|
|||||||
void Screen::renderShake() {
|
void Screen::renderShake() {
|
||||||
if (shake_effect_.enabled) {
|
if (shake_effect_.enabled) {
|
||||||
// Guarda el renderizador actual para dejarlo despues como estaba
|
// Guarda el renderizador actual para dejarlo despues como estaba
|
||||||
auto *current_target = SDL_GetRenderTarget(renderer_);
|
auto* current_target = SDL_GetRenderTarget(renderer_);
|
||||||
|
|
||||||
// Crea una textura temporal
|
// Crea una textura temporal
|
||||||
auto *temp_texture = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
|
auto* temp_texture = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
|
||||||
|
|
||||||
// Vuelca game_canvas_ a la textura temporal
|
// Vuelca game_canvas_ a la textura temporal
|
||||||
SDL_SetRenderTarget(renderer_, temp_texture);
|
SDL_SetRenderTarget(renderer_, temp_texture);
|
||||||
@@ -221,7 +221,7 @@ void Screen::renderInfo() {
|
|||||||
debug_info_.text->writeDX(Text::COLOR | Text::STROKE, param.game.width - debug_info_.text->length(FPS_TEXT) - 2, 1 + debug_info_.text->getCharacterSize(), FPS_TEXT, 1, param.debug.color, 1, param.debug.color.DARKEN(150));
|
debug_info_.text->writeDX(Text::COLOR | Text::STROKE, param.game.width - debug_info_.text->length(FPS_TEXT) - 2, 1 + debug_info_.text->getCharacterSize(), FPS_TEXT, 1, param.debug.color, 1, param.debug.color.DARKEN(150));
|
||||||
#ifdef RECORDING
|
#ifdef RECORDING
|
||||||
// RECORDING
|
// RECORDING
|
||||||
debug_info_.text->writeDX(Text::COLOR | Text::STROKE, param.game.width - debug_info_.text->length("RECORDING"), 2*(1 + debug_info_.text->getCharacterSize()), "RECORDING", 1, param.debug.color, 1, param.debug.color.DARKEN(150));
|
debug_info_.text->writeDX(Text::COLOR | Text::STROKE, param.game.width - debug_info_.text->length("RECORDING"), 2 * (1 + debug_info_.text->getCharacterSize()), "RECORDING", 1, param.debug.color, 1, param.debug.color.DARKEN(150));
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -239,10 +239,10 @@ void Screen::loadShaders() {
|
|||||||
VERTEX_FILE = "crtpi_vertex.glsl";
|
VERTEX_FILE = "crtpi_vertex.glsl";
|
||||||
data = Asset::get()->loadData(VERTEX_FILE);
|
data = Asset::get()->loadData(VERTEX_FILE);
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Usando shaders OpenGL Desktop 3.3");
|
"Usando shaders OpenGL Desktop 3.3");
|
||||||
} else {
|
} else {
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Usando shaders OpenGL ES 3.0 (Raspberry Pi)");
|
"Usando shaders OpenGL ES 3.0 (Raspberry Pi)");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!data.empty()) {
|
if (!data.empty()) {
|
||||||
@@ -280,7 +280,7 @@ void Screen::initShaders() {
|
|||||||
// En macOS, OpenGL está deprecated y rinde mal
|
// En macOS, OpenGL está deprecated y rinde mal
|
||||||
// TODO: Implementar backend de Metal para shaders en macOS
|
// TODO: Implementar backend de Metal para shaders en macOS
|
||||||
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION,
|
||||||
"Shaders no disponibles en macOS (OpenGL deprecated). Usa Metal backend.");
|
"Shaders no disponibles en macOS (OpenGL deprecated). Usa Metal backend.");
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -415,19 +415,19 @@ auto Screen::initSDLVideo() -> bool {
|
|||||||
void Screen::getDisplayInfo() {
|
void Screen::getDisplayInfo() {
|
||||||
int i;
|
int i;
|
||||||
int num_displays = 0;
|
int num_displays = 0;
|
||||||
SDL_DisplayID *displays = SDL_GetDisplays(&num_displays);
|
SDL_DisplayID* displays = SDL_GetDisplays(&num_displays);
|
||||||
if (displays != nullptr) {
|
if (displays != nullptr) {
|
||||||
for (i = 0; i < num_displays; ++i) {
|
for (i = 0; i < num_displays; ++i) {
|
||||||
SDL_DisplayID instance_id = displays[i];
|
SDL_DisplayID instance_id = displays[i];
|
||||||
const char *name = SDL_GetDisplayName(instance_id);
|
const char* name = SDL_GetDisplayName(instance_id);
|
||||||
|
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Display %" SDL_PRIu32 ": %s", instance_id, (name != nullptr) ? name : "Unknown");
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Display %" SDL_PRIu32 ": %s", instance_id, (name != nullptr) ? name : "Unknown");
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto *dm = SDL_GetCurrentDisplayMode(displays[0]);
|
const auto* dm = SDL_GetCurrentDisplayMode(displays[0]);
|
||||||
|
|
||||||
// Guarda información del monitor en display_monitor_
|
// Guarda información del monitor en display_monitor_
|
||||||
const char *first_display_name = SDL_GetDisplayName(displays[0]);
|
const char* first_display_name = SDL_GetDisplayName(displays[0]);
|
||||||
display_monitor_.name = (first_display_name != nullptr) ? first_display_name : "Unknown";
|
display_monitor_.name = (first_display_name != nullptr) ? first_display_name : "Unknown";
|
||||||
display_monitor_.width = static_cast<int>(dm->w);
|
display_monitor_.width = static_cast<int>(dm->w);
|
||||||
display_monitor_.height = static_cast<int>(dm->h);
|
display_monitor_.height = static_cast<int>(dm->h);
|
||||||
|
|||||||
@@ -5,8 +5,8 @@
|
|||||||
#include <memory> // Para shared_ptr
|
#include <memory> // Para shared_ptr
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
|
||||||
#include "color.h" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
#include "options.h" // Para VideoOptions, video
|
#include "options.hpp" // Para VideoOptions, video
|
||||||
|
|
||||||
// Forward declarations
|
// Forward declarations
|
||||||
class Notifier;
|
class Notifier;
|
||||||
@@ -14,16 +14,16 @@ class ServiceMenu;
|
|||||||
class Text;
|
class Text;
|
||||||
|
|
||||||
namespace Rendering {
|
namespace Rendering {
|
||||||
class ShaderBackend;
|
class ShaderBackend;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Clase Screen: gestiona la ventana, el renderizador y los efectos visuales globales (singleton) ---
|
// --- Clase Screen: gestiona la ventana, el renderizador y los efectos visuales globales (singleton) ---
|
||||||
class Screen {
|
class Screen {
|
||||||
public:
|
public:
|
||||||
// --- Métodos de singleton ---
|
// --- Métodos de singleton ---
|
||||||
static void init(); // Inicializa el objeto Screen
|
static void init(); // Inicializa el objeto Screen
|
||||||
static void destroy(); // Libera el objeto Screen
|
static void destroy(); // Libera el objeto Screen
|
||||||
static auto get() -> Screen *; // Obtiene el puntero al objeto Screen
|
static auto get() -> Screen*; // Obtiene el puntero al objeto Screen
|
||||||
|
|
||||||
// --- Métodos principales ---
|
// --- Métodos principales ---
|
||||||
void update(float delta_time); // Recibe deltaTime de las secciones y actualiza la lógica
|
void update(float delta_time); // Recibe deltaTime de las secciones y actualiza la lógica
|
||||||
@@ -44,15 +44,15 @@ class Screen {
|
|||||||
|
|
||||||
// --- Efectos visuales ---
|
// --- Efectos visuales ---
|
||||||
void shake(int desp = 2, float delay_s = 0.05f, float duration_s = 0.133f) { shake_effect_.enable(src_rect_, dst_rect_, desp, delay_s, duration_s); } // Agita la pantalla (tiempo en segundos)
|
void shake(int desp = 2, float delay_s = 0.05f, float duration_s = 0.133f) { shake_effect_.enable(src_rect_, dst_rect_, desp, delay_s, duration_s); } // Agita la pantalla (tiempo en segundos)
|
||||||
void flash(Color color, float duration_s = 0.167f, float delay_s = 0.0f) { flash_effect_ = FlashEffect(true, duration_s, delay_s, color); } // Pone la pantalla de color (tiempo en segundos)
|
void flash(Color color, float duration_s = 0.167f, float delay_s = 0.0f) { flash_effect_ = FlashEffect(true, duration_s, delay_s, color); } // Pone la pantalla de color (tiempo en segundos)
|
||||||
void toggleShaders(); // Alterna entre activar y desactivar los shaders
|
void toggleShaders(); // Alterna entre activar y desactivar los shaders
|
||||||
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
|
void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
|
||||||
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
|
void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
|
||||||
void setVSync(bool enabled); // Establece el estado del V-Sync
|
void setVSync(bool enabled); // Establece el estado del V-Sync
|
||||||
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
|
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
|
||||||
|
|
||||||
// --- Getters ---
|
// --- Getters ---
|
||||||
auto getRenderer() -> SDL_Renderer * { return renderer_; } // Obtiene el renderizador
|
auto getRenderer() -> SDL_Renderer* { return renderer_; } // Obtiene el renderizador
|
||||||
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
|
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
|
||||||
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
|
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
|
||||||
void getSingletons(); // Obtiene los punteros a los singletones
|
void getSingletons(); // Obtiene los punteros a los singletones
|
||||||
@@ -101,11 +101,11 @@ class Screen {
|
|||||||
|
|
||||||
// Efecto de flash en pantalla: pinta la pantalla de un color durante un tiempo
|
// Efecto de flash en pantalla: pinta la pantalla de un color durante un tiempo
|
||||||
struct FlashEffect {
|
struct FlashEffect {
|
||||||
bool enabled; // Indica si el efecto está activo
|
bool enabled; // Indica si el efecto está activo
|
||||||
float duration_s; // Duración total del efecto en segundos
|
float duration_s; // Duración total del efecto en segundos
|
||||||
float delay_s; // Retraso antes de mostrar el flash en segundos
|
float delay_s; // Retraso antes de mostrar el flash en segundos
|
||||||
float timer_s; // Timer en segundos (contador decreciente)
|
float timer_s; // Timer en segundos (contador decreciente)
|
||||||
Color color; // Color del flash
|
Color color; // Color del flash
|
||||||
|
|
||||||
explicit FlashEffect(bool enabled = false, float duration_s = 0.0f, float delay_s = 0.0f, Color color = Color(0xFF, 0xFF, 0xFF))
|
explicit FlashEffect(bool enabled = false, float duration_s = 0.0f, float delay_s = 0.0f, Color color = Color(0xFF, 0xFF, 0xFF))
|
||||||
: enabled(enabled),
|
: enabled(enabled),
|
||||||
@@ -127,14 +127,14 @@ class Screen {
|
|||||||
|
|
||||||
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
|
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
|
||||||
struct ShakeEffect {
|
struct ShakeEffect {
|
||||||
int desp; // Desplazamiento máximo de la sacudida (en píxeles)
|
int desp; // Desplazamiento máximo de la sacudida (en píxeles)
|
||||||
float delay_s; // Segundos entre cada movimiento de sacudida
|
float delay_s; // Segundos entre cada movimiento de sacudida
|
||||||
float counter_s; // Timer para el siguiente movimiento (decreciente)
|
float counter_s; // Timer para el siguiente movimiento (decreciente)
|
||||||
float duration_s; // Duración total del efecto en segundos
|
float duration_s; // Duración total del efecto en segundos
|
||||||
float remaining_s; // Tiempo restante de sacudida
|
float remaining_s; // Tiempo restante de sacudida
|
||||||
int original_pos; // Posición original de la imagen (x)
|
int original_pos; // Posición original de la imagen (x)
|
||||||
int original_width; // Ancho original de la imagen
|
int original_width; // Ancho original de la imagen
|
||||||
bool enabled; // Indica si el efecto está activo
|
bool enabled; // Indica si el efecto está activo
|
||||||
|
|
||||||
explicit ShakeEffect(bool en = false, int dp = 2, float dl_s = 0.05f, float cnt_s = 0.0f, float len_s = 0.133f, float rem_s = 0.0f, int orig_pos = 0, int orig_width = 800)
|
explicit ShakeEffect(bool en = false, int dp = 2, float dl_s = 0.05f, float cnt_s = 0.0f, float len_s = 0.133f, float rem_s = 0.0f, int orig_pos = 0, int orig_width = 800)
|
||||||
: desp(dp),
|
: desp(dp),
|
||||||
@@ -147,7 +147,7 @@ class Screen {
|
|||||||
enabled(en) {}
|
enabled(en) {}
|
||||||
|
|
||||||
// Activa el efecto de sacudida y guarda la posición y tamaño originales
|
// Activa el efecto de sacudida y guarda la posición y tamaño originales
|
||||||
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, float new_delay_s = -1.0f, float new_duration_s = -1.0f) {
|
void enable(SDL_FRect& src_rect, SDL_FRect& dst_rect, int new_desp = -1, float new_delay_s = -1.0f, float new_duration_s = -1.0f) {
|
||||||
if (!enabled) {
|
if (!enabled) {
|
||||||
enabled = true;
|
enabled = true;
|
||||||
original_pos = src_rect.x;
|
original_pos = src_rect.x;
|
||||||
@@ -172,13 +172,13 @@ class Screen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el estado del efecto de sacudida
|
// Actualiza el estado del efecto de sacudida
|
||||||
void update(SDL_FRect &src_rect, SDL_FRect &dst_rect, float delta_time) {
|
void update(SDL_FRect& src_rect, SDL_FRect& dst_rect, float delta_time) {
|
||||||
if (enabled) {
|
if (enabled) {
|
||||||
counter_s -= delta_time;
|
counter_s -= delta_time;
|
||||||
if (counter_s <= 0.0f) {
|
if (counter_s <= 0.0f) {
|
||||||
counter_s = delay_s;
|
counter_s = delay_s;
|
||||||
// Alternar desplazamiento basado en tiempo restante
|
// Alternar desplazamiento basado en tiempo restante
|
||||||
const bool SHAKE_LEFT = static_cast<int>(remaining_s * 30.0f) % 2 == 0; // ~30 cambios por segundo
|
const bool SHAKE_LEFT = static_cast<int>(remaining_s * 30.0f) % 2 == 0; // ~30 cambios por segundo
|
||||||
const auto SRC_DESP = SHAKE_LEFT ? 0 : desp;
|
const auto SRC_DESP = SHAKE_LEFT ? 0 : desp;
|
||||||
const auto DST_DESP = SHAKE_LEFT ? desp : 0;
|
const auto DST_DESP = SHAKE_LEFT ? desp : 0;
|
||||||
src_rect.x = original_pos + SRC_DESP;
|
src_rect.x = original_pos + SRC_DESP;
|
||||||
@@ -208,45 +208,45 @@ class Screen {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Window *window_; // Ventana de la aplicación
|
SDL_Window* window_; // Ventana de la aplicación
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer* renderer_; // El renderizador de la ventana
|
||||||
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
|
SDL_Texture* game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
|
||||||
ServiceMenu *service_menu_; // Objeto para mostrar el menú de servicio
|
ServiceMenu* service_menu_; // Objeto para mostrar el menú de servicio
|
||||||
Notifier *notifier_; // Objeto para mostrar las notificaciones por pantalla
|
Notifier* notifier_; // Objeto para mostrar las notificaciones por pantalla
|
||||||
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
|
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
|
||||||
std::unique_ptr<Rendering::ShaderBackend> shader_backend_; // Backend de shaders (OpenGL/Metal/Vulkan)
|
std::unique_ptr<Rendering::ShaderBackend> shader_backend_; // Backend de shaders (OpenGL/Metal/Vulkan)
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego
|
SDL_FRect src_rect_; // Coordenadas de origen para dibujar la textura del juego
|
||||||
SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego
|
SDL_FRect dst_rect_; // Coordenadas destino para dibujar la textura del juego
|
||||||
std::string vertex_shader_source_; // Almacena el vertex shader
|
std::string vertex_shader_source_; // Almacena el vertex shader
|
||||||
std::string fragment_shader_source_; // Almacena el fragment shader
|
std::string fragment_shader_source_; // Almacena el fragment shader
|
||||||
FPS fps_; // Gestión de frames por segundo
|
FPS fps_; // Gestión de frames por segundo
|
||||||
FlashEffect flash_effect_; // Efecto de flash en pantalla
|
FlashEffect flash_effect_; // Efecto de flash en pantalla
|
||||||
ShakeEffect shake_effect_; // Efecto de agitar la pantalla
|
ShakeEffect shake_effect_; // Efecto de agitar la pantalla
|
||||||
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
||||||
DisplayMonitor display_monitor_; // Información del monitor actual
|
DisplayMonitor display_monitor_; // Información del monitor actual
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
Debug debug_info_; // Información de debug
|
Debug debug_info_; // Información de debug
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
|
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
|
||||||
void renderFlash(); // Dibuja el efecto de flash en la pantalla
|
void renderFlash(); // Dibuja el efecto de flash en la pantalla
|
||||||
void renderShake(); // Aplica el efecto de agitar la pantalla
|
void renderShake(); // Aplica el efecto de agitar la pantalla
|
||||||
void renderInfo(); // Muestra información por pantalla
|
void renderInfo(); // Muestra información por pantalla
|
||||||
void renderPresent(); // Selecciona y ejecuta el método de renderizado adecuado
|
void renderPresent(); // Selecciona y ejecuta el método de renderizado adecuado
|
||||||
void loadShaders(); // Carga el contenido del archivo GLSL
|
void loadShaders(); // Carga el contenido del archivo GLSL
|
||||||
void adjustWindowSize(); // Calcula el tamaño de la ventana
|
void adjustWindowSize(); // Calcula el tamaño de la ventana
|
||||||
void getDisplayInfo(); // Obtiene información sobre la pantalla
|
void getDisplayInfo(); // Obtiene información sobre la pantalla
|
||||||
void renderOverlays(); // Renderiza todos los overlays y efectos
|
void renderOverlays(); // Renderiza todos los overlays y efectos
|
||||||
void renderAttenuate(); // Atenúa la pantalla
|
void renderAttenuate(); // Atenúa la pantalla
|
||||||
void createText(); // Crea el objeto de texto
|
void createText(); // Crea el objeto de texto
|
||||||
|
|
||||||
// --- Constructores y destructor privados (singleton) ---
|
// --- Constructores y destructor privados (singleton) ---
|
||||||
Screen(); // Constructor privado
|
Screen(); // Constructor privado
|
||||||
~Screen(); // Destructor privado
|
~Screen(); // Destructor privado
|
||||||
|
|
||||||
// --- Instancia singleton ---
|
// --- Instancia singleton ---
|
||||||
static Screen *instance; // Instancia única de Screen
|
static Screen* instance; // Instancia única de Screen
|
||||||
};
|
};
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// IWYU pragma: no_include <bits/std_abs.h>
|
// IWYU pragma: no_include <bits/std_abs.h>
|
||||||
#include "credits.h"
|
#include "credits.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_RenderFillRect, SDL_RenderTexture, SDL_SetRenderTarget, SDL_SetRenderDrawColor, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetTicks, SDL_GetRenderTarget, SDL_PixelFormat, SDL_PollEvent, SDL_RenderClear, SDL_RenderRect, SDL_SetTextureBlendMode, SDL_TextureAccess, SDL_BLENDMODE_BLEND, SDL_Event
|
#include <SDL3/SDL.h> // Para SDL_RenderFillRect, SDL_RenderTexture, SDL_SetRenderTarget, SDL_SetRenderDrawColor, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetTicks, SDL_GetRenderTarget, SDL_PixelFormat, SDL_PollEvent, SDL_RenderClear, SDL_RenderRect, SDL_SetTextureBlendMode, SDL_TextureAccess, SDL_BLENDMODE_BLEND, SDL_Event
|
||||||
|
|
||||||
@@ -10,25 +10,25 @@
|
|||||||
#include <string_view> // Para string_view
|
#include <string_view> // Para string_view
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "balloon_manager.h" // Para BalloonManager
|
#include "balloon_manager.hpp" // Para BalloonManager
|
||||||
#include "color.h" // Para Zone, Colors::SHADOW_TEXT, Colors::NO_COLOR_MOD, Color
|
#include "color.hpp" // Para Zone, Colors::SHADOW_TEXT, Colors::NO_COLOR_MOD, Color
|
||||||
#include "fade.h" // Para Fade, FadeType, FadeMode
|
#include "fade.hpp" // Para Fade, FadeType, FadeMode
|
||||||
#include "global_events.h" // Para check
|
#include "global_events.hpp" // Para check
|
||||||
#include "global_inputs.h" // Para check
|
#include "global_inputs.hpp" // Para check
|
||||||
#include "input.h" // Para Input, Input::ALLOW_REPEAT
|
#include "input.hpp" // Para Input, Input::ALLOW_REPEAT
|
||||||
#include "lang.h" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamFade
|
#include "param.hpp" // Para Param, param, ParamGame, ParamFade
|
||||||
#include "player.h" // Para Player, PlayerState
|
#include "player.hpp" // Para Player, PlayerState
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "section.hpp" // Para Name, name
|
#include "section.hpp" // Para Name, name
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "text.h" // Para Text, Text::CENTER, Text::SHADOW
|
#include "text.hpp" // Para Text, Text::CENTER, Text::SHADOW
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "tiled_bg.h" // Para TiledBG, TiledBGMode
|
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
||||||
#include "ui/service_menu.h" // Para ServiceMenu
|
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||||
#include "utils.h"
|
#include "utils.hpp"
|
||||||
|
|
||||||
// Textos
|
// Textos
|
||||||
constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner";
|
constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner";
|
||||||
@@ -105,7 +105,7 @@ void Credits::update(float deltaTime) {
|
|||||||
const float multiplier = want_to_pass_ ? 4.0f : 1.0f;
|
const float multiplier = want_to_pass_ ? 4.0f : 1.0f;
|
||||||
const float adjusted_delta_time = deltaTime * multiplier;
|
const float adjusted_delta_time = deltaTime * multiplier;
|
||||||
|
|
||||||
static auto *const SCREEN = Screen::get();
|
static auto* const SCREEN = Screen::get();
|
||||||
SCREEN->update(deltaTime); // Actualiza el objeto screen
|
SCREEN->update(deltaTime); // Actualiza el objeto screen
|
||||||
Audio::update(); // Actualiza el objeto audio
|
Audio::update(); // Actualiza el objeto audio
|
||||||
|
|
||||||
@@ -126,7 +126,7 @@ void Credits::update(float deltaTime) {
|
|||||||
|
|
||||||
// Dibuja Credits::en patalla
|
// Dibuja Credits::en patalla
|
||||||
void Credits::render() {
|
void Credits::render() {
|
||||||
static auto *const SCREEN = Screen::get();
|
static auto* const SCREEN = Screen::get();
|
||||||
|
|
||||||
SCREEN->start(); // Prepara para empezar a dibujar en la textura de juego
|
SCREEN->start(); // Prepara para empezar a dibujar en la textura de juego
|
||||||
SDL_RenderTexture(SCREEN->getRenderer(), canvas_, nullptr, nullptr); // Copia la textura con la zona de juego a la pantalla
|
SDL_RenderTexture(SCREEN->getRenderer(), canvas_, nullptr, nullptr); // Copia la textura con la zona de juego a la pantalla
|
||||||
@@ -251,7 +251,7 @@ void Credits::fillTextTexture() {
|
|||||||
// Dibuja todos los sprites en la textura
|
// Dibuja todos los sprites en la textura
|
||||||
void Credits::fillCanvas() {
|
void Credits::fillCanvas() {
|
||||||
// Cambia el destino del renderizador
|
// Cambia el destino del renderizador
|
||||||
auto *temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
|
auto* temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
|
||||||
SDL_SetRenderTarget(Screen::get()->getRenderer(), canvas_);
|
SDL_SetRenderTarget(Screen::get()->getRenderer(), canvas_);
|
||||||
|
|
||||||
// Dibuja el fondo, los globos y los jugadores
|
// Dibuja el fondo, los globos y los jugadores
|
||||||
@@ -411,7 +411,7 @@ void Credits::initPlayers() {
|
|||||||
players_.back()->setPlayingState(Player::State::CREDITS);
|
players_.back()->setPlayingState(Player::State::CREDITS);
|
||||||
|
|
||||||
// Registra los jugadores en Options
|
// Registra los jugadores en Options
|
||||||
for (const auto &player : players_) {
|
for (const auto& player : players_) {
|
||||||
Options::keyboard.addPlayer(player);
|
Options::keyboard.addPlayer(player);
|
||||||
Options::gamepad_manager.addPlayer(player);
|
Options::gamepad_manager.addPlayer(player);
|
||||||
}
|
}
|
||||||
@@ -541,14 +541,14 @@ void Credits::cycleColors() {
|
|||||||
|
|
||||||
// Actualza los jugadores (time-based)
|
// Actualza los jugadores (time-based)
|
||||||
void Credits::updatePlayers(float deltaTime) {
|
void Credits::updatePlayers(float deltaTime) {
|
||||||
for (auto &player : players_) {
|
for (auto& player : players_) {
|
||||||
player->update(deltaTime);
|
player->update(deltaTime);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Renderiza los jugadores
|
// Renderiza los jugadores
|
||||||
void Credits::renderPlayers() {
|
void Credits::renderPlayers() {
|
||||||
for (auto const &player : players_) {
|
for (auto const& player : players_) {
|
||||||
player->render();
|
player->render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,10 @@
|
|||||||
#include <memory> // Para unique_ptr, shared_ptr
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "color.h" // Para Zone, Color
|
#include "color.hpp" // Para Zone, Color
|
||||||
#include "options.h" // Para AudioOptions, MusicOptions, audio
|
#include "options.hpp" // Para AudioOptions, MusicOptions, audio
|
||||||
#include "param.h" // Para Param, ParamGame, param
|
#include "param.hpp" // Para Param, ParamGame, param
|
||||||
#include "utils.h"
|
#include "utils.hpp"
|
||||||
|
|
||||||
// Declaraciones adelantadas
|
// Declaraciones adelantadas
|
||||||
class BalloonManager;
|
class BalloonManager;
|
||||||
@@ -27,7 +27,7 @@ class Credits {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
// --- Métodos del bucle principal ---
|
// --- Métodos del bucle principal ---
|
||||||
void update(float deltaTime); // Actualización principal de la lógica (time-based)
|
void update(float deltaTime); // Actualización principal de la lógica (time-based)
|
||||||
auto calculateDeltaTime() -> float; // Calcula el deltatime
|
auto calculateDeltaTime() -> float; // Calcula el deltatime
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -42,14 +42,14 @@ class Credits {
|
|||||||
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
|
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
|
||||||
|
|
||||||
// --- Gestión de texturas ---
|
// --- Gestión de texturas ---
|
||||||
SDL_Texture *text_texture_; // Textura con el texto de créditos
|
SDL_Texture* text_texture_; // Textura con el texto de créditos
|
||||||
SDL_Texture *canvas_; // Textura donde se dibuja todo
|
SDL_Texture* canvas_; // Textura donde se dibuja todo
|
||||||
|
|
||||||
// --- Temporización y contadores ---
|
// --- Temporización y contadores ---
|
||||||
Uint64 last_time_ = 0; // Último tiempo registrado para deltaTime
|
Uint64 last_time_ = 0; // Último tiempo registrado para deltaTime
|
||||||
float counter_ = 0; // Contador principal de lógica
|
float counter_ = 0; // Contador principal de lógica
|
||||||
float counter_pre_fade_ = 0; // Activación del fundido final
|
float counter_pre_fade_ = 0; // Activación del fundido final
|
||||||
float counter_prevent_endless_ = 0; // Prevención de bucle infinito
|
float counter_prevent_endless_ = 0; // Prevención de bucle infinito
|
||||||
|
|
||||||
// --- Variables de estado ---
|
// --- Variables de estado ---
|
||||||
bool fading_ = false; // Estado del fade final
|
bool fading_ = false; // Estado del fade final
|
||||||
@@ -67,16 +67,16 @@ class Credits {
|
|||||||
|
|
||||||
// --- Estado de acumuladores para animaciones ---
|
// --- Estado de acumuladores para animaciones ---
|
||||||
struct CreditsState {
|
struct CreditsState {
|
||||||
float texture_accumulator = 0.0f;
|
float texture_accumulator = 0.0f;
|
||||||
float balloon_accumulator = 0.0f;
|
float balloon_accumulator = 0.0f;
|
||||||
float powerball_accumulator = 0.0f;
|
float powerball_accumulator = 0.0f;
|
||||||
float black_rect_accumulator = 0.0f;
|
float black_rect_accumulator = 0.0f;
|
||||||
float r = 255.0f; // UPPER_LIMIT
|
float r = 255.0f; // UPPER_LIMIT
|
||||||
float g = 0.0f; // LOWER_LIMIT
|
float g = 0.0f; // LOWER_LIMIT
|
||||||
float b = 0.0f; // LOWER_LIMIT
|
float b = 0.0f; // LOWER_LIMIT
|
||||||
float step_r = -0.5f;
|
float step_r = -0.5f;
|
||||||
float step_g = 0.3f;
|
float step_g = 0.3f;
|
||||||
float step_b = 0.1f;
|
float step_b = 0.1f;
|
||||||
} credits_state_;
|
} credits_state_;
|
||||||
|
|
||||||
// --- Rectángulos de renderizado ---
|
// --- Rectángulos de renderizado ---
|
||||||
@@ -125,25 +125,25 @@ class Credits {
|
|||||||
void checkInput(); // Procesamiento de entrada
|
void checkInput(); // Procesamiento de entrada
|
||||||
|
|
||||||
// --- Métodos de renderizado ---
|
// --- Métodos de renderizado ---
|
||||||
void fillTextTexture(); // Crear textura de texto de créditos
|
void fillTextTexture(); // Crear textura de texto de créditos
|
||||||
void fillCanvas(); // Renderizar todos los sprites y fondos
|
void fillCanvas(); // Renderizar todos los sprites y fondos
|
||||||
void renderPlayers(); // Renderiza los jugadores
|
void renderPlayers(); // Renderiza los jugadores
|
||||||
|
|
||||||
// --- Métodos de lógica del juego ---
|
// --- Métodos de lógica del juego ---
|
||||||
void throwBalloons(); // Lanzar globos al escenario (frame-based)
|
void throwBalloons(); // Lanzar globos al escenario (frame-based)
|
||||||
void throwBalloons(float deltaTime); // Lanzar globos al escenario (time-based)
|
void throwBalloons(float deltaTime); // Lanzar globos al escenario (time-based)
|
||||||
void initPlayers(); // Inicializar jugadores
|
void initPlayers(); // Inicializar jugadores
|
||||||
void updateAllFades(); // Actualizar estados de fade (frame-based)
|
void updateAllFades(); // Actualizar estados de fade (frame-based)
|
||||||
void updateAllFades(float deltaTime); // Actualizar estados de fade (time-based)
|
void updateAllFades(float deltaTime); // Actualizar estados de fade (time-based)
|
||||||
void cycleColors(); // Cambiar colores de fondo
|
void cycleColors(); // Cambiar colores de fondo
|
||||||
void updatePlayers(float deltaTime); // Actualza los jugadores (time-based)
|
void updatePlayers(float deltaTime); // Actualza los jugadores (time-based)
|
||||||
|
|
||||||
// --- Métodos de interfaz ---
|
// --- Métodos de interfaz ---
|
||||||
void updateBlackRects(); // Actualizar rectángulos negros (letterbox) (frame-based)
|
void updateBlackRects(); // Actualizar rectángulos negros (letterbox) (frame-based)
|
||||||
void updateBlackRects(float deltaTime); // Actualizar rectángulos negros (letterbox) (time-based)
|
void updateBlackRects(float deltaTime); // Actualizar rectángulos negros (letterbox) (time-based)
|
||||||
void updateRedRect(); // Actualizar rectángulo rojo (borde)
|
void updateRedRect(); // Actualizar rectángulo rojo (borde)
|
||||||
void updateTextureDstRects(); // Actualizar destinos de texturas (frame-based)
|
void updateTextureDstRects(); // Actualizar destinos de texturas (frame-based)
|
||||||
void updateTextureDstRects(float deltaTime); // Actualizar destinos de texturas (time-based)
|
void updateTextureDstRects(float deltaTime); // Actualizar destinos de texturas (time-based)
|
||||||
|
|
||||||
// --- Métodos de audio ---
|
// --- Métodos de audio ---
|
||||||
static void setVolume(int amount); // Establecer volumen
|
static void setVolume(int amount); // Establecer volumen
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "game.h"
|
#include "game.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget, SDL_CreateTexture, SDL_Delay, SDL_DestroyTexture, SDL_EventType, SDL_GetRenderTarget, SDL_PollEvent, SDL_RenderTexture, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_Event, SDL_PixelFormat, SDL_Point, SDL_TextureAccess
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget, SDL_CreateTexture, SDL_Delay, SDL_DestroyTexture, SDL_EventType, SDL_GetRenderTarget, SDL_PollEvent, SDL_RenderTexture, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_Event, SDL_PixelFormat, SDL_Point, SDL_TextureAccess
|
||||||
|
|
||||||
@@ -11,42 +11,42 @@
|
|||||||
#include <random> // std::random_device, std::default_random_engine
|
#include <random> // std::random_device, std::default_random_engine
|
||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
|
|
||||||
#include "asset.h" // Para Asset
|
#include "asset.hpp" // Para Asset
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "background.h" // Para Background
|
#include "background.hpp" // Para Background
|
||||||
#include "balloon.h" // Para Balloon
|
#include "balloon.hpp" // Para Balloon
|
||||||
#include "balloon_manager.h" // Para BalloonManager
|
#include "balloon_manager.hpp" // Para BalloonManager
|
||||||
#include "bullet.h" // Para Bullet, Bullet::Type, BulletMoveStatus
|
#include "bullet.hpp" // Para Bullet, Bullet::Type, BulletMoveStatus
|
||||||
#include "bullet_manager.h" // Para BulletManager
|
#include "bullet_manager.hpp" // Para BulletManager
|
||||||
#include "color.h" // Para Color, Colors::FLASH
|
#include "color.hpp" // Para Color, Colors::FLASH
|
||||||
#include "difficulty.h" // Para Code
|
#include "difficulty.hpp" // Para Code
|
||||||
#include "fade.h" // Para Fade, FadeType, FadeMode
|
#include "fade.hpp" // Para Fade, FadeType, FadeMode
|
||||||
#include "global_events.h" // Para check
|
#include "global_events.hpp" // Para check
|
||||||
#include "global_inputs.h" // Para check
|
#include "global_inputs.hpp" // Para check
|
||||||
#include "hit.h" // Para Hit
|
#include "hit.hpp" // Para Hit
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "input_types.h" // Para InputAction
|
#include "input_types.hpp" // Para InputAction
|
||||||
#include "item.h" // Para Item, ItemType
|
#include "item.hpp" // Para Item, ItemType
|
||||||
#include "lang.h" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "manage_hiscore_table.h" // Para HiScoreEntry, ManageHiScoreTable
|
#include "manage_hiscore_table.hpp" // Para HiScoreEntry, ManageHiScoreTable
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamScoreboard, ParamFade, ParamBalloon
|
#include "param.hpp" // Para Param, param, ParamGame, ParamScoreboard, ParamFade, ParamBalloon
|
||||||
#include "path_sprite.h" // Para Path, PathSprite, createPath, PathType
|
#include "path_sprite.hpp" // Para Path, PathSprite, createPath, PathType
|
||||||
#include "pause_manager.h" // Para PauseManager
|
#include "pause_manager.hpp" // Para PauseManager
|
||||||
#include "player.h" // Para Player
|
#include "player.hpp" // Para Player
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "scoreboard.h" // Para Scoreboard
|
#include "scoreboard.hpp" // Para Scoreboard
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "section.hpp" // Para Name, name, AttractMode, Options, attract_mode, options
|
#include "section.hpp" // Para Name, name, AttractMode, Options, attract_mode, options
|
||||||
#include "smart_sprite.h" // Para SmartSprite
|
#include "smart_sprite.hpp" // Para SmartSprite
|
||||||
#include "stage.h" // Para number, Stage, get, total_power, power, init, power_can_be_added, stages
|
#include "stage.hpp" // Para number, Stage, get, total_power, power, init, power_can_be_added, stages
|
||||||
#include "tabe.h" // Para Tabe
|
#include "tabe.hpp" // Para Tabe
|
||||||
#include "text.h" // Para Text
|
#include "text.hpp" // Para Text
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "ui/service_menu.h" // Para ServiceMenu
|
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
#include <iostream> // Para std::cout
|
#include <iostream> // Para std::cout
|
||||||
|
|
||||||
#include "ui/notifier.h" // Para Notifier
|
#include "ui/notifier.hpp" // Para Notifier
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
@@ -902,8 +902,8 @@ void Game::render() {
|
|||||||
fade_in_->render(); // Dibuja el fade de entrada
|
fade_in_->render(); // Dibuja el fade de entrada
|
||||||
fade_out_->render(); // Dibuja el fade de salida
|
fade_out_->render(); // Dibuja el fade de salida
|
||||||
|
|
||||||
//SDL_SetRenderDrawColor(renderer_, 255, 0, 0, 255);
|
// SDL_SetRenderDrawColor(renderer_, 255, 0, 0, 255);
|
||||||
//SDL_RenderLine(renderer_, param.game.play_area.rect.x, param.game.play_area.center_y, param.game.play_area.rect.w, param.game.play_area.center_y);
|
// SDL_RenderLine(renderer_, param.game.play_area.rect.x, param.game.play_area.center_y, param.game.play_area.rect.w, param.game.play_area.center_y);
|
||||||
|
|
||||||
screen_->render(); // Vuelca el contenido del renderizador en pantalla
|
screen_->render(); // Vuelca el contenido del renderizador en pantalla
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,18 +6,18 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "bullet.h" // Para Bullet
|
#include "bullet.hpp" // Para Bullet
|
||||||
#include "bullet_manager.h" // Para BulletManager
|
#include "bullet_manager.hpp" // Para BulletManager
|
||||||
#include "hit.h" // Para Hit
|
#include "demo.hpp" // Para Demo
|
||||||
#include "item.h" // Para Item, ItemType
|
#include "hit.hpp" // Para Hit
|
||||||
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
#include "item.hpp" // Para Item, ItemType
|
||||||
#include "options.h" // Para Settings, settings
|
#include "manage_hiscore_table.hpp" // Para HiScoreEntry
|
||||||
#include "path_sprite.h" // Para PathSprite, Path
|
#include "options.hpp" // Para Settings, settings
|
||||||
#include "player.h" // Para Player
|
#include "path_sprite.hpp" // Para PathSprite, Path
|
||||||
#include "smart_sprite.h" // Para SmartSprite
|
#include "player.hpp" // Para Player
|
||||||
#include "stage.h" // Para StageManager
|
#include "smart_sprite.hpp" // Para SmartSprite
|
||||||
#include "demo.h" // Para Demo
|
#include "stage.hpp" // Para StageManager
|
||||||
#include "utils.h" // Para otras utilidades
|
#include "utils.hpp" // Para otras utilidades
|
||||||
|
|
||||||
class Background;
|
class Background;
|
||||||
class Balloon;
|
class Balloon;
|
||||||
@@ -316,10 +316,10 @@ class Game {
|
|||||||
void setMenace(); // Calcula y establece amenaza según globos activos
|
void setMenace(); // Calcula y establece amenaza según globos activos
|
||||||
|
|
||||||
// --- Puntuación y marcador ---
|
// --- Puntuación y marcador ---
|
||||||
void updateHiScore(); // Actualiza el récord máximo si es necesario
|
void updateHiScore(); // Actualiza el récord máximo si es necesario
|
||||||
void updateScoreboard(float deltaTime); // Actualiza la visualización del marcador
|
void updateScoreboard(float deltaTime); // Actualiza la visualización del marcador
|
||||||
void updateHiScoreName(); // Pone en el marcador el nombre del primer jugador de la tabla
|
void updateHiScoreName(); // Pone en el marcador el nombre del primer jugador de la tabla
|
||||||
void initScoreboard(); // Inicializa el sistema de puntuación
|
void initScoreboard(); // Inicializa el sistema de puntuación
|
||||||
|
|
||||||
// --- Modo demostración ---
|
// --- Modo demostración ---
|
||||||
void initDemo(Player::Id player_id); // Inicializa variables para el modo demostración
|
void initDemo(Player::Id player_id); // Inicializa variables para el modo demostración
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "hiscore_table.h"
|
#include "hiscore_table.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
|
||||||
|
|
||||||
@@ -7,25 +7,25 @@
|
|||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "background.h" // Para Background
|
#include "background.hpp" // Para Background
|
||||||
#include "color.h" // Para Color, easeOutQuint, Colors::NO_COLOR_MOD
|
#include "color.hpp" // Para Color, easeOutQuint, Colors::NO_COLOR_MOD
|
||||||
#include "fade.h" // Para Fade, FadeMode, FadeType
|
#include "fade.hpp" // Para Fade, FadeMode, FadeType
|
||||||
#include "global_events.h" // Para check
|
#include "global_events.hpp" // Para check
|
||||||
#include "global_inputs.h" // Para check
|
#include "global_inputs.hpp" // Para check
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "lang.h" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "manage_hiscore_table.h" // Para HiScoreEntry
|
#include "manage_hiscore_table.hpp" // Para HiScoreEntry
|
||||||
#include "options.h" // Para SettingsOptions, settings
|
#include "options.hpp" // Para SettingsOptions, settings
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamFade
|
#include "param.hpp" // Para Param, param, ParamGame, ParamFade
|
||||||
#include "path_sprite.h" // Para PathSprite, Path, PathType
|
#include "path_sprite.hpp" // Para PathSprite, Path, PathType
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "section.hpp" // Para Name, name, Options, options
|
#include "section.hpp" // Para Name, name, Options, options
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "text.h" // Para Text, Text::SHADOW, Text::COLOR
|
#include "text.hpp" // Para Text, Text::SHADOW, Text::COLOR
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "utils.h"
|
#include "utils.hpp"
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
HiScoreTable::HiScoreTable()
|
HiScoreTable::HiScoreTable()
|
||||||
@@ -54,9 +54,9 @@ HiScoreTable::~HiScoreTable() {
|
|||||||
|
|
||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void HiScoreTable::update(float delta_time) {
|
void HiScoreTable::update(float delta_time) {
|
||||||
elapsed_time_ += delta_time; // Incrementa el tiempo transcurrido
|
elapsed_time_ += delta_time; // Incrementa el tiempo transcurrido
|
||||||
|
|
||||||
static auto *const SCREEN = Screen::get();
|
static auto* const SCREEN = Screen::get();
|
||||||
SCREEN->update(delta_time); // Actualiza el objeto screen
|
SCREEN->update(delta_time); // Actualiza el objeto screen
|
||||||
Audio::update(); // Actualiza el objeto audio
|
Audio::update(); // Actualiza el objeto audio
|
||||||
|
|
||||||
@@ -69,16 +69,16 @@ void HiScoreTable::update(float delta_time) {
|
|||||||
|
|
||||||
// Pinta en pantalla
|
// Pinta en pantalla
|
||||||
void HiScoreTable::render() {
|
void HiScoreTable::render() {
|
||||||
static auto *const SCREEN = Screen::get();
|
static auto* const SCREEN = Screen::get();
|
||||||
|
|
||||||
SCREEN->start(); // Prepara para empezar a dibujar en la textura de juego
|
SCREEN->start(); // Prepara para empezar a dibujar en la textura de juego
|
||||||
SCREEN->clean(); // Limpia la pantalla
|
SCREEN->clean(); // Limpia la pantalla
|
||||||
|
|
||||||
background_->render(); // Pinta el fondo
|
background_->render(); // Pinta el fondo
|
||||||
float counter_equivalent = elapsed_time_ * 60.0f; // Convertir tiempo a equivalente frame para UI
|
float counter_equivalent = elapsed_time_ * 60.0f; // Convertir tiempo a equivalente frame para UI
|
||||||
view_area_.y = std::max(0.0F, param.game.height - counter_equivalent + 100); // Establece la ventana del backbuffer
|
view_area_.y = std::max(0.0F, param.game.height - counter_equivalent + 100); // Establece la ventana del backbuffer
|
||||||
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); // Copia el backbuffer al renderizador
|
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); // Copia el backbuffer al renderizador
|
||||||
fade_->render(); // Renderiza el fade
|
fade_->render(); // Renderiza el fade
|
||||||
|
|
||||||
SCREEN->render(); // Vuelca el contenido del renderizador en pantalla
|
SCREEN->render(); // Vuelca el contenido del renderizador en pantalla
|
||||||
}
|
}
|
||||||
@@ -86,7 +86,7 @@ void HiScoreTable::render() {
|
|||||||
// Dibuja los sprites en la textura
|
// Dibuja los sprites en la textura
|
||||||
void HiScoreTable::fillTexture() {
|
void HiScoreTable::fillTexture() {
|
||||||
// Pinta en el backbuffer el texto y los sprites
|
// Pinta en el backbuffer el texto y los sprites
|
||||||
auto *temp = SDL_GetRenderTarget(renderer_);
|
auto* temp = SDL_GetRenderTarget(renderer_);
|
||||||
SDL_SetRenderTarget(renderer_, backbuffer_);
|
SDL_SetRenderTarget(renderer_, backbuffer_);
|
||||||
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0);
|
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0);
|
||||||
SDL_RenderClear(renderer_);
|
SDL_RenderClear(renderer_);
|
||||||
@@ -95,7 +95,7 @@ void HiScoreTable::fillTexture() {
|
|||||||
header_->render();
|
header_->render();
|
||||||
|
|
||||||
// Escribe los nombres de la tabla de puntuaciones
|
// Escribe los nombres de la tabla de puntuaciones
|
||||||
for (auto const &entry : entry_names_) {
|
for (auto const& entry : entry_names_) {
|
||||||
entry->render();
|
entry->render();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -209,7 +209,7 @@ void HiScoreTable::createSprites() {
|
|||||||
const auto TABLE_POSITION = format(i + 1) + ". ";
|
const auto TABLE_POSITION = format(i + 1) + ". ";
|
||||||
const auto SCORE = format(Options::settings.hi_score_table.at(i).score);
|
const auto SCORE = format(Options::settings.hi_score_table.at(i).score);
|
||||||
const auto NUM_DOTS = ENTRY_LENGTH - Options::settings.hi_score_table.at(i).name.size() - SCORE.size();
|
const auto NUM_DOTS = ENTRY_LENGTH - Options::settings.hi_score_table.at(i).name.size() - SCORE.size();
|
||||||
const auto *const ONE_CC = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : "";
|
const auto* const ONE_CC = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : "";
|
||||||
std::string dots;
|
std::string dots;
|
||||||
for (int j = 0; j < (int)NUM_DOTS; ++j) {
|
for (int j = 0; j < (int)NUM_DOTS; ++j) {
|
||||||
dots = dots + ".";
|
dots = dots + ".";
|
||||||
@@ -272,7 +272,7 @@ void HiScoreTable::updateSprites(float delta_time) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (auto const &entry : entry_names_) {
|
for (auto const& entry : entry_names_) {
|
||||||
entry->update(delta_time);
|
entry->update(delta_time);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -359,7 +359,7 @@ void HiScoreTable::iniEntryColors() {
|
|||||||
void HiScoreTable::glowEntryNames() {
|
void HiScoreTable::glowEntryNames() {
|
||||||
int color_counter = static_cast<int>(elapsed_time_ * 60.0f / 5.0f); // Convertir tiempo a equivalente frame
|
int color_counter = static_cast<int>(elapsed_time_ * 60.0f / 5.0f); // Convertir tiempo a equivalente frame
|
||||||
const Color ENTRY_COLOR = getEntryColor(color_counter);
|
const Color ENTRY_COLOR = getEntryColor(color_counter);
|
||||||
for (const auto &entry_index : Options::settings.glowing_entries) {
|
for (const auto& entry_index : Options::settings.glowing_entries) {
|
||||||
if (entry_index != -1) {
|
if (entry_index != -1) {
|
||||||
entry_names_.at(entry_index)->getTexture()->setColor(ENTRY_COLOR);
|
entry_names_.at(entry_index)->getTexture()->setColor(ENTRY_COLOR);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,9 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "color.h" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
#include "fade.h" // Para Fade
|
#include "fade.hpp" // Para Fade
|
||||||
#include "path_sprite.h" // Para Path, PathSprite (ptr only)
|
#include "path_sprite.hpp" // Para Path, PathSprite (ptr only)
|
||||||
|
|
||||||
class Background;
|
class Background;
|
||||||
class Sprite;
|
class Sprite;
|
||||||
@@ -39,8 +39,8 @@ class HiScoreTable {
|
|||||||
static constexpr float CLOUDS_SPEED = -6.0f; // Velocidad nubes (pixels/s)
|
static constexpr float CLOUDS_SPEED = -6.0f; // Velocidad nubes (pixels/s)
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer* renderer_; // El renderizador de la ventana
|
||||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
SDL_Texture* backbuffer_; // Textura para usar como backbuffer
|
||||||
|
|
||||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||||
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
|
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
|
||||||
@@ -58,13 +58,13 @@ class HiScoreTable {
|
|||||||
|
|
||||||
// --- Flags para eventos basados en tiempo ---
|
// --- Flags para eventos basados en tiempo ---
|
||||||
struct HiScoreFlags {
|
struct HiScoreFlags {
|
||||||
bool background_changed = false;
|
bool background_changed = false;
|
||||||
bool fade_activated = false;
|
bool fade_activated = false;
|
||||||
|
|
||||||
void reset() {
|
void reset() {
|
||||||
background_changed = false;
|
background_changed = false;
|
||||||
fade_activated = false;
|
fade_activated = false;
|
||||||
}
|
}
|
||||||
} hiscore_flags_;
|
} hiscore_flags_;
|
||||||
|
|
||||||
// --- Métodos internos ---
|
// --- Métodos internos ---
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "instructions.h"
|
#include "instructions.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget, SDL_Re...
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget, SDL_Re...
|
||||||
|
|
||||||
@@ -8,22 +8,22 @@
|
|||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "color.h" // Para Color, Colors::SHADOW_TEXT, Zone, NO_TEXT_C...
|
#include "color.hpp" // Para Color, Colors::SHADOW_TEXT, Zone, NO_TEXT_C...
|
||||||
#include "fade.h" // Para Fade, FadeMode, FadeType
|
#include "fade.hpp" // Para Fade, FadeMode, FadeType
|
||||||
#include "global_events.h" // Para check
|
#include "global_events.hpp" // Para check
|
||||||
#include "global_inputs.h" // Para check
|
#include "global_inputs.hpp" // Para check
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "item.h" // Para Item
|
#include "item.hpp" // Para Item
|
||||||
#include "lang.h" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamFade, Param...
|
#include "param.hpp" // Para Param, param, ParamGame, ParamFade, Param...
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "section.hpp" // Para Name, name, Options, options
|
#include "section.hpp" // Para Name, name, Options, options
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "text.h" // Para Text, Text::CENTER, Text::COLOR, Text::SHADOW
|
#include "text.hpp" // Para Text, Text::CENTER, Text::COLOR, Text::SHADOW
|
||||||
#include "tiled_bg.h" // Para TiledBG, TiledBGMode
|
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
||||||
#include "utils.h"
|
#include "utils.hpp"
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Instructions::Instructions()
|
Instructions::Instructions()
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
#include <memory> // Para unique_ptr, shared_ptr
|
#include <memory> // Para unique_ptr, shared_ptr
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
|
|
||||||
#include "sprite.h" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
|
|
||||||
class Fade;
|
class Fade;
|
||||||
class Text;
|
class Text;
|
||||||
@@ -57,9 +57,9 @@ class Instructions {
|
|||||||
static constexpr float LINE_START_DELAY_MS = 5.0f; // Retraso entre líneas (5ms)
|
static constexpr float LINE_START_DELAY_MS = 5.0f; // Retraso entre líneas (5ms)
|
||||||
|
|
||||||
// --- Objetos y punteros ---
|
// --- Objetos y punteros ---
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer* renderer_; // El renderizador de la ventana
|
||||||
SDL_Texture *texture_; // Textura fija con el texto
|
SDL_Texture* texture_; // Textura fija con el texto
|
||||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
SDL_Texture* backbuffer_; // Textura para usar como backbuffer
|
||||||
|
|
||||||
std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
|
std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
|
||||||
std::vector<std::unique_ptr<Sprite>> sprites_; // Vector con los sprites de los items
|
std::vector<std::unique_ptr<Sprite>> sprites_; // Vector con los sprites de los items
|
||||||
@@ -88,8 +88,8 @@ class Instructions {
|
|||||||
void iniSprites(); // Inicializa los sprites de los items
|
void iniSprites(); // Inicializa los sprites de los items
|
||||||
void updateSprites(); // Actualiza los sprites
|
void updateSprites(); // Actualiza los sprites
|
||||||
static auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
|
static auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
|
||||||
static auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas (ya usa tiempo real)
|
static auto moveLines(std::vector<Line>& lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas (ya usa tiempo real)
|
||||||
static void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
|
static void renderLines(SDL_Renderer* renderer, SDL_Texture* texture, const std::vector<Line>& lines); // Renderiza las líneas
|
||||||
void updateBackbuffer(float delta_time); // Gestiona la textura con los gráficos
|
void updateBackbuffer(float delta_time); // Gestiona la textura con los gráficos
|
||||||
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
|
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
|
||||||
};
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include "intro.h"
|
#include "intro.hpp"
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderDrawColor, SDL_FRect, SDL_RenderFillRect, SDL_GetRenderTarget, SDL_RenderClear, SDL_RenderRect, SDL_SetRenderTarget, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_PollEvent, SDL_RenderTexture, SDL_TextureAccess, SDL_Event, Uint32
|
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderDrawColor, SDL_FRect, SDL_RenderFillRect, SDL_GetRenderTarget, SDL_RenderClear, SDL_RenderRect, SDL_SetRenderTarget, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_PollEvent, SDL_RenderTexture, SDL_TextureAccess, SDL_Event, Uint32
|
||||||
|
|
||||||
@@ -8,22 +8,22 @@
|
|||||||
#include <string> // Para basic_string, string
|
#include <string> // Para basic_string, string
|
||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
|
|
||||||
#include "audio.h" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "color.h" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
#include "global_events.h" // Para check
|
#include "global_events.hpp" // Para check
|
||||||
#include "global_inputs.h" // Para check
|
#include "global_inputs.hpp" // Para check
|
||||||
#include "input.h" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "lang.h" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "param.h" // Para Param, param, ParamGame, ParamIntro, ParamTitle
|
#include "param.hpp" // Para Param, param, ParamGame, ParamIntro, ParamTitle
|
||||||
#include "path_sprite.h" // Para PathSprite, PathType
|
#include "path_sprite.hpp" // Para PathSprite, PathType
|
||||||
#include "resource.h" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "screen.h" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "section.hpp" // Para Name, name, Options, options
|
#include "section.hpp" // Para Name, name, Options, options
|
||||||
#include "text.h" // Para Text
|
#include "text.hpp" // Para Text
|
||||||
#include "texture.h" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "tiled_bg.h" // Para TiledBG, TiledBGMode
|
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
||||||
#include "utils.h" // Para Zone, easeInOutExpo, easeInElastic, easeOutBounce, easeOutElastic, easeOutQuad, easeOutQuint
|
#include "utils.hpp" // Para Zone, easeInOutExpo, easeInElastic, easeOutBounce, easeOutElastic, easeOutQuad, easeOutQuint
|
||||||
#include "writer.h" // Para Writer
|
#include "writer.hpp" // Para Writer
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Intro::Intro()
|
Intro::Intro()
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user