treball en curs: correccions de tidy

This commit is contained in:
2026-05-16 17:45:32 +02:00
parent ee2dd0bc2c
commit 9f6d38cf48
22 changed files with 813 additions and 1074 deletions
-1
View File
@@ -3,7 +3,6 @@
#include <cmath> // Para lround
#include <cstdint> // Para int8_t, uint8_t
#include <string> // Para string
#include <utility> // Para move
// --- Clase Audio: gestor de audio (singleton) ---
// Implementació canònica, byte-idèntica entre projectes.
+16 -16
View File
@@ -59,12 +59,12 @@ class Input {
~Input(); // Destructor
void update(); // Actualiza el estado del objeto
void bindKey(Uint8 input, SDL_Scancode code); // Asigna inputs a teclas
void update(); // Actualiza el estado del objeto
void bindKey(Uint8 input, SDL_Scancode code); // Asigna inputs a teclas
void bindGameControllerButton(Uint8 input, SDL_GamepadButton button); // Asigna inputs a botones del mando
auto checkInput(Uint8 input, bool repeat = true, int device = INPUT_USE_ANY, int index = 0) -> bool; // Comprueba si un input esta activo
auto checkAnyInput(int device = INPUT_USE_ANY, int index = 0) -> bool; // Comprueba si hay almenos un input activo
auto checkAnyInput(int device = INPUT_USE_ANY, int index = 0) -> bool; // Comprueba si hay almenos un input activo
auto discoverGameController() -> bool; // Busca si hay un mando conectado
@@ -80,9 +80,9 @@ class Input {
[[nodiscard]] auto getNumControllers() const -> int; // Obten el numero de mandos conectados
auto getControllerName(int index) -> std::string; // Obten el nombre de un mando de juego
void setVerbose(bool value); // Establece si ha de mostrar mensajes
void disableUntil(InputDisable value); // Deshabilita las entradas durante un periodo de tiempo
void enable(); // Hablita las entradas
void setVerbose(bool value); // Establece si ha de mostrar mensajes
void disableUntil(InputDisable value); // Deshabilita las entradas durante un periodo de tiempo
void enable(); // Hablita las entradas
private:
struct KeyBindings {
@@ -96,18 +96,18 @@ class Input {
};
// Objetos y punteros
std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados
std::vector<SDL_JoystickID> connected_controller_ids_; // Instance IDs paralelos para mapear eventos
std::vector<SDL_Gamepad *> connected_controllers_; // Vector con todos los mandos conectados
std::vector<SDL_JoystickID> connected_controller_ids_; // Instance IDs paralelos para mapear eventos
// Variables
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<GameControllerBindings> game_controller_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
int num_gamepads_{0}; // Numero de mandos conectados
std::string db_path_; // Ruta al archivo gamecontrollerdb.txt
bool verbose_{true}; // Indica si ha de mostrar mensajes
InputDisable disabled_until_{NOT_DISABLED}; // Tiempo que esta deshabilitado
bool enabled_{true}; // Indica si está habilitado
std::vector<KeyBindings> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<GameControllerBindings> game_controller_bindings_; // Vector con las teclas asociadas a los inputs predefinidos
std::vector<std::string> controller_names_; // Vector con los nombres de los mandos
int num_gamepads_{0}; // Numero de mandos conectados
std::string db_path_; // Ruta al archivo gamecontrollerdb.txt
bool verbose_{true}; // Indica si ha de mostrar mensajes
InputDisable disabled_until_{NOT_DISABLED}; // Tiempo que esta deshabilitado
bool enabled_{true}; // Indica si está habilitado
static Input *instance; // Instancia única
+2 -2
View File
@@ -1,9 +1,9 @@
#include "core/input/mouse.hpp"
namespace Mouse {
Uint32 cursor_hide_time = 3000; // Tiempo en milisegundos para ocultar el cursor por inactividad
Uint32 cursor_hide_time = 3000; // Tiempo en milisegundos para ocultar el cursor por inactividad
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, bool fullscreen) {
if (event.type == SDL_EVENT_MOUSE_MOTION) {
+2 -2
View File
@@ -24,8 +24,8 @@ class Lang {
~Lang(); // Destructor
auto setLang(Code lang) -> bool; // Inicializa los textos del juego en el idioma seleccionado
auto getText(int index) -> std::string; // Obtiene la cadena de texto del indice
auto setLang(Code lang) -> bool; // Inicializa los textos del juego en el idioma seleccionado
auto getText(int index) -> std::string; // Obtiene la cadena de texto del indice
static auto nextLanguage(Code c) -> Code; // Devuelve el siguiente idioma del ciclo
+7 -7
View File
@@ -15,7 +15,7 @@ struct Animation {
int speed; // Velocidad de la animación
int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed; // Indica si ha finalizado la animación
int current_frame; // Frame actual
int current_frame; // Frame actual
int counter; // Contador para las animaciones
};
@@ -37,9 +37,9 @@ class AnimatedSprite : public MovingSprite {
~AnimatedSprite() override; // Destructor
void animate(); // Calcula el frame correspondiente a la animación actual
auto getNumFrames() -> int; // Obtiene el numero de frames de la animación actual
void setCurrentFrame(int num); // Establece el frame actual de la animación
void animate(); // Calcula el frame correspondiente a la animación actual
auto getNumFrames() -> int; // Obtiene el numero de frames de la animación actual
void setCurrentFrame(int num); // Establece el frame actual de la animación
void setAnimationCounter(const std::string &name, int num); // Establece el valor del contador
void setAnimationSpeed(const std::string &name, int speed); // Establece la velocidad de una animación
@@ -56,7 +56,7 @@ class AnimatedSprite : public MovingSprite {
auto getAnimationClip(const std::string &name = "default", Uint8 index = 0) -> SDL_Rect; // Devuelve el rectangulo de una animación y frame concreto
auto getAnimationClip(int index_a = 0, Uint8 index_f = 0) -> SDL_Rect;
auto getIndex(const std::string &name) -> int; // Obtiene el indice de la animación a partir del nombre
auto getIndex(const std::string &name) -> int; // Obtiene el indice de la animación a partir del nombre
auto loadFromVector(std::vector<std::string> *source) -> bool; // Carga la animación desde un vector
void setCurrentAnimation(const std::string &name = "default"); // Establece la animacion actual
@@ -65,12 +65,12 @@ class AnimatedSprite : public MovingSprite {
void update() override; // Actualiza las variables del objeto
void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h); // OLD - Establece el rectangulo para un frame de una animación
void setAnimationCounter(int value); // OLD - Establece el contador para todas las animaciones
void setAnimationCounter(int value); // OLD - Establece el contador para todas las animaciones
void resetAnimation(); // Reinicia la animación
private:
// Variables
std::vector<Animation> animation_; // Vector con las diferentes animaciones
int current_animation_; // Animacion activa
int current_animation_; // Animacion activa
};
+12 -12
View File
@@ -24,17 +24,17 @@ class Fade {
void setFadeType(Uint8 fade_type); // Establece el tipo de fade
private:
SDL_Renderer *renderer_ = nullptr; // El renderizador de la ventana
SDL_Texture *backbuffer_ = nullptr; // Textura para usar como backbuffer
Uint8 fade_type_ = FADE_FULLSCREEN; // Tipo de fade a realizar
Uint16 counter_ = 0; // Contador interno
bool enabled_ = false; // Indica si el fade está activo
bool finished_ = false; // Indica si ha terminado la transición
Uint8 r_ = 0, g_ = 0, b_ = 0; // Colores para el fade
SDL_Renderer *renderer_ = nullptr; // El renderizador de la ventana
SDL_Texture *backbuffer_ = nullptr; // Textura para usar como backbuffer
Uint8 fade_type_ = FADE_FULLSCREEN; // Tipo de fade a realizar
Uint16 counter_ = 0; // Contador interno
bool enabled_ = false; // Indica si el fade está activo
bool finished_ = false; // Indica si ha terminado la transición
Uint8 r_ = 0, g_ = 0, b_ = 0; // Colores para el fade
Uint8 r_original_ = 0, g_original_ = 0, b_original_ = 0; // Colores originales para FADE_RANDOM_SQUARE
Uint32 last_square_ticks_ = 0; // Ticks del último cuadrado dibujado (FADE_RANDOM_SQUARE)
Uint16 squares_drawn_ = 0; // Número de cuadrados dibujados (FADE_RANDOM_SQUARE)
bool fullscreen_done_ = false; // Indica si el fade fullscreen ha terminado la fase de fundido
SDL_Rect rect1_{}; // Rectangulo usado para crear los efectos de transición
SDL_Rect rect2_{}; // Rectangulo usado para crear los efectos de transición
Uint32 last_square_ticks_ = 0; // Ticks del último cuadrado dibujado (FADE_RANDOM_SQUARE)
Uint16 squares_drawn_ = 0; // Número de cuadrados dibujados (FADE_RANDOM_SQUARE)
bool fullscreen_done_ = false; // Indica si el fade fullscreen ha terminado la fase de fundido
SDL_Rect rect1_{}; // Rectangulo usado para crear los efectos de transición
SDL_Rect rect2_{}; // Rectangulo usado para crear los efectos de transición
};
+12 -12
View File
@@ -21,15 +21,15 @@ class MovingSprite : public Sprite {
// cppcheck-suppress duplInheritedMember
[[nodiscard]] auto getPosY() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getVelX() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getVelY() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getAccelX() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getAccelY() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getZoomW() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getZoomH() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getAngle() const -> double; // Obten el valor de la variable
[[nodiscard]] auto getRotate() const -> bool; // Obtiene el valor de la variable
[[nodiscard]] auto getRotateSpeed() const -> Uint16; // Obtiene el valor de la variable
[[nodiscard]] auto getVelX() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getVelY() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getAccelX() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getAccelY() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getZoomW() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getZoomH() const -> float; // Obten el valor de la variable
[[nodiscard]] auto getAngle() const -> double; // Obten el valor de la variable
[[nodiscard]] auto getRotate() const -> bool; // Obtiene el valor de la variable
[[nodiscard]] auto getRotateSpeed() const -> Uint16; // Obtiene el valor de la variable
void setRect(SDL_Rect rect) override; // Establece la posición y el tamaño del objeto
void setPosX(float value); // Establece el valor de la variable
@@ -50,9 +50,9 @@ class MovingSprite : public Sprite {
void disableRotate(); // Quita el efecto de rotación y deja el sprite en su angulo inicial.
void switchRotate(); // Cambia el sentido de la rotación
void setFlip(SDL_FlipMode flip); // Establece el valor de la variable
void flip(); // Gira el sprite horizontalmente
auto getFlip() -> SDL_FlipMode; // Obtiene el valor de la variable
void setFlip(SDL_FlipMode flip); // Establece el valor de la variable
void flip(); // Gira el sprite horizontalmente
auto getFlip() -> SDL_FlipMode; // Obtiene el valor de la variable
auto getRect() -> SDL_Rect override; // Devuelve el rectangulo donde está el sprite
+21 -21
View File
@@ -43,25 +43,25 @@ class Screen {
void blit(); // Vuelca el contenido del renderizador en pantalla
// Video y ventana
void setVideoMode(bool fullscreen); // Establece el modo de video
void toggleVideoMode(); // Cambia entre pantalla completa y ventana
void handleCanvasResized(); // En Emscripten, reaplica setVideoMode tras un cambio del navegador (salida de fullscreen con Esc, rotación). No-op fuera de Emscripten
void setVideoMode(bool fullscreen); // Establece el modo de video
void toggleVideoMode(); // Cambia entre pantalla completa y ventana
void handleCanvasResized(); // En Emscripten, reaplica setVideoMode tras un cambio del navegador (salida de fullscreen con Esc, rotación). No-op fuera de Emscripten
static void syncFullscreenFlagFromBrowser(bool is_fullscreen); // Sincroniza el flag interno de fullscreen con el estado real del navegador. Debe llamarse antes de diferir handleCanvasResized. No-op fuera de Emscripten
void toggleIntegerScale(); // Alterna el escalado entero
void setIntegerScale(bool enabled); // Establece el escalado entero
void toggleVSync(); // Alterna el V-Sync
void setVSync(bool enabled); // Establece el V-Sync
auto decWindowZoom() -> bool; // Reduce el zoom de la ventana (devuelve true si cambió)
auto incWindowZoom() -> bool; // Aumenta el zoom de la ventana (devuelve true si cambió)
auto setWindowZoom(int zoom) -> bool; // Establece el zoom de la ventana (devuelve true si cambió)
void toggleIntegerScale(); // Alterna el escalado entero
void setIntegerScale(bool enabled); // Establece el escalado entero
void toggleVSync(); // Alterna el V-Sync
void setVSync(bool enabled); // Establece el V-Sync
auto decWindowZoom() -> bool; // Reduce el zoom de la ventana (devuelve true si cambió)
auto incWindowZoom() -> bool; // Aumenta el zoom de la ventana (devuelve true si cambió)
auto setWindowZoom(int zoom) -> bool; // Establece el zoom de la ventana (devuelve true si cambió)
// Borde
void setBorderColor(Color color); // Cambia el color del borde
// Notificaciones
void initNotifications(); // Enllaça el Text de notificacions amb `Resource`. A cridar després de `Resource::init(...)`.
void initNotifications(); // Enllaça el Text de notificacions amb `Resource`. A cridar després de `Resource::init(...)`.
void notify(const std::string &text, Color text_color, Color outline_color, Uint32 duration_ms); // Muestra una notificación en la línea superior del canvas durante durationMs. Sobrescribe cualquier notificación activa (sin apilación).
void clearNotification(); // Limpia la notificación actual
void clearNotification(); // Limpia la notificación actual
// GPU / shaders (post-procesado). En builds con NO_SHADERS (Emscripten) son no-op.
void initShaders(); // Crea el backend GPU si no existe y lo inicializa
@@ -111,24 +111,24 @@ class Screen {
#endif
// Objetos y punteros
SDL_Window *window_; // Ventana de la aplicación
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Window *window_; // Ventana de la aplicación
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *game_canvas_; // Textura para completar la ventana de juego hasta la pantalla completa
// Variables
int window_width_; // Ancho de la pantalla o ventana
int window_height_; // Alto de la pantalla o ventana
int window_width_; // Ancho de la pantalla o ventana
int window_height_; // Alto de la pantalla o ventana
int game_canvas_width_; // Resolución interna del juego. Es el ancho de la textura donde se dibuja el juego
int game_canvas_height_; // Resolución interna del juego. Es el alto de la textura donde se dibuja el juego
SDL_Rect dest_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
Color border_color_; // Color del borde añadido a la textura de juego para rellenar la pantalla
SDL_Rect dest_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
Color border_color_; // Color del borde añadido a la textura de juego para rellenar la pantalla
// Notificaciones - una sola activa, sin apilación ni animaciones
Text *notification_text_; // Fuente 8bithud dedicada a las notificaciones
std::string notification_message_; // Texto a mostrar
Color notification_text_color_; // Color del texto
Color notification_outline_color_; // Color del outline
Uint32 notification_end_time_; // SDL_GetTicks() hasta el cual se muestra
Color notification_text_color_; // Color del texto
Color notification_outline_color_; // Color del outline
Uint32 notification_end_time_; // SDL_GetTicks() hasta el cual se muestra
int notification_y_; // Fila vertical en el canvas virtual
#ifndef NO_SHADERS
+1 -1
View File
@@ -29,7 +29,7 @@ class SmartSprite : public AnimatedSprite {
int dest_x_; // Posicion de destino en el eje X
int dest_y_; // Posicion de destino en el eje Y
int enabled_counter_; // Contador para deshabilitarlo
bool finished_; // Indica si ya ha terminado
bool finished_; // Indica si ya ha terminado
void checkMove(); // Comprueba el movimiento
void checkFinished(); // Comprueba si ha terminado
+11 -11
View File
@@ -24,21 +24,21 @@ class Sprite {
void setWidth(int w); // Establece el valor de la variable
void setHeight(int h); // Establece el valor de la variable
auto getSpriteClip() -> SDL_Rect; // Obten el valor de la variable
void setSpriteClip(SDL_Rect rect); // Establece el valor de la variable
void setSpriteClip(int x, int y, int w, int h); // Establece el valor de la variable
auto getSpriteClip() -> SDL_Rect; // Obten el valor de la variable
void setSpriteClip(SDL_Rect rect); // Establece el valor de la variable
void setSpriteClip(int x, int y, int w, int h); // Establece el valor de la variable
auto getTexture() -> Texture *; // Obten el valor de la variable
void setTexture(Texture *texture); // Establece el valor de la variable
auto getTexture() -> Texture *; // Obten el valor de la variable
void setTexture(Texture *texture); // Establece el valor de la variable
auto getRenderer() -> SDL_Renderer *; // Obten el valor de la variable
void setRenderer(SDL_Renderer *renderer); // Establece el valor de la variable
auto getRenderer() -> SDL_Renderer *; // Obten el valor de la variable
void setRenderer(SDL_Renderer *renderer); // Establece el valor de la variable
virtual void setEnabled(bool value); // Establece el valor de la variable
virtual auto isEnabled() -> bool; // Comprueba si el objeto está habilitado
virtual void setEnabled(bool value); // Establece el valor de la variable
virtual auto isEnabled() -> bool; // Comprueba si el objeto está habilitado
virtual auto getRect() -> SDL_Rect; // Devuelve el rectangulo donde está el sprite
virtual void setRect(SDL_Rect rect); // Establece los valores de posición y tamaño del sprite
virtual auto getRect() -> SDL_Rect; // Devuelve el rectangulo donde está el sprite
virtual void setRect(SDL_Rect rect); // Establece los valores de posición y tamaño del sprite
protected:
int x_; // Posición en el eje X donde dibujar el sprite
+9 -9
View File
@@ -47,18 +47,18 @@ class Text {
Text(const Text &) = delete;
auto operator=(const Text &) -> Text & = delete;
void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1); // Escribe el texto con colores
void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra
void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x
void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1); // Escribe el texto con colores
void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra
void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x
void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color text_color = Color(255, 255, 255), Uint8 shadow_distance = 1, Color shadow_color = Color(0, 0, 0), int lenght = -1); // Escribe texto con extras
auto lenght(const std::string &text, int kerning = 1) -> int; // Obtiene la longitud en pixels de una cadena
[[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el valor de la variable
void reLoadTexture(); // Recarga la textura
void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra
void reLoadTexture(); // Recarga la textura
void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra
private:
// Objetos y punteros
@@ -66,8 +66,8 @@ class Text {
Texture *texture_; // Textura con los bitmaps del texto
// Variables
int box_width_; // Anchura de la caja de cada caracter en el png
int box_height_; // Altura de la caja de cada caracter en el png
bool fixed_width_; // Indica si el texto se ha de escribir con longitud fija en todas las letras
int box_width_; // Anchura de la caja de cada caracter en el png
int box_height_; // Altura de la caja de cada caracter en el png
bool fixed_width_; // Indica si el texto se ha de escribir con longitud fija en todas las letras
Offset offset_[128]; // Vector con las posiciones y ancho de cada letra
};
+12 -12
View File
@@ -12,26 +12,26 @@ class Texture {
static void setGlobalScaleMode(SDL_ScaleMode mode); // Establece el modo de escalado global para nuevas texturas
explicit Texture(SDL_Renderer *renderer, const std::string &path = "", bool verbose = false); // Constructor
Texture(SDL_Renderer *renderer, const std::vector<uint8_t> &bytes, bool verbose = false); // Constructor desde bytes (PNG en memoria)
~Texture(); // Destructor
explicit Texture(SDL_Renderer *renderer, const std::string &path = "", bool verbose = false); // Constructor
Texture(SDL_Renderer *renderer, const std::vector<uint8_t> &bytes, bool verbose = false); // Constructor desde bytes (PNG en memoria)
~Texture(); // Destructor
auto loadFromFile(const std::string &path, SDL_Renderer *renderer, bool verbose = false) -> bool; // Carga una imagen desde un fichero
auto loadFromMemory(const uint8_t *data, size_t size, SDL_Renderer *renderer, bool verbose = false) -> bool; // Carga una imagen desde bytes en memoria
auto createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess /*access*/ = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
void unload(); // Libera la memoria de la textura
auto loadFromFile(const std::string &path, SDL_Renderer *renderer, bool verbose = false) -> bool; // Carga una imagen desde un fichero
auto loadFromMemory(const uint8_t *data, size_t size, SDL_Renderer *renderer, bool verbose = false) -> bool; // Carga una imagen desde bytes en memoria
auto createBlank(SDL_Renderer *renderer, int width, int height, SDL_TextureAccess /*access*/ = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
void unload(); // Libera la memoria de la textura
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulacion
void setBlendMode(SDL_BlendMode blending); // Establece el blending
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulacion
void setBlendMode(SDL_BlendMode blending); // Establece el blending
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
void render(SDL_Renderer *renderer, int x, int y, SDL_Rect *clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_Point *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado
void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado
[[nodiscard]] auto getWidth() const -> int; // Obtiene el ancho de la imagen
[[nodiscard]] auto getHeight() const -> int; // Obtiene el alto de la imagen
auto reLoad() -> bool; // Recarga la textura
auto reLoad() -> bool; // Recarga la textura
auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura
private:
+9 -9
View File
@@ -19,7 +19,7 @@ class Writer {
void setEnabled(bool value); // Establece el valor de la variable
[[nodiscard]] auto isEnabled() const -> bool; // Obtiene el valor de la variable
void setEnabledCounter(int time); // Establece el valor de la variable
void setEnabledCounter(int time); // Establece el valor de la variable
[[nodiscard]] auto getEnabledCounter() const -> int; // Obtiene el valor de la variable
void center(int x); // Centra la cadena de texto a un punto X
@@ -32,14 +32,14 @@ class Writer {
// Variables
int pos_x_{0}; // Posicion en el eje X donde empezar a escribir el texto
int pos_y_{0}; // Posicion en el eje Y donde empezar a escribir el texto
int kerning_{0}; // Kerning del texto, es decir, espaciado entre caracteres
std::string caption_; // El texto para escribir
int speed_{0}; // Velocidad de escritura
int kerning_{0}; // Kerning del texto, es decir, espaciado entre caracteres
std::string caption_; // El texto para escribir
int speed_{0}; // Velocidad de escritura
int writing_counter_{0}; // Temporizador de escritura para cada caracter
int index_{0}; // Posición del texto que se está escribiendo
int length_{0}; // Longitud de la cadena a escribir
bool completed_{false}; // Indica si se ha escrito todo el texto
bool enabled_{false}; // Indica si el objeto está habilitado
int index_{0}; // Posición del texto que se está escribiendo
int length_{0}; // Longitud de la cadena a escribir
bool completed_{false}; // Indica si se ha escrito todo el texto
bool enabled_{false}; // Indica si el objeto está habilitado
int enabled_counter_{0}; // Temporizador para deshabilitar el objeto
bool finished_{false}; // Indica si ya ha terminado
bool finished_{false}; // Indica si ya ha terminado
};
+20 -10
View File
@@ -147,17 +147,27 @@ auto Asset::checkFile(const std::string &path) const -> bool {
// Devuelve el nombre del tipo de recurso
auto Asset::getTypeName(Type type) -> std::string {
switch (type) {
case Type::BITMAP: return "BITMAP";
case Type::MUSIC: return "MUSIC";
case Type::SOUND: return "SOUND";
case Type::FONT: return "FONT";
case Type::LANG: return "LANG";
case Type::DATA: return "DATA";
case Type::ROOM: return "ROOM";
case Type::ENEMY: return "ENEMY";
case Type::ITEM: return "ITEM";
case Type::BITMAP:
return "BITMAP";
case Type::MUSIC:
return "MUSIC";
case Type::SOUND:
return "SOUND";
case Type::FONT:
return "FONT";
case Type::LANG:
return "LANG";
case Type::DATA:
return "DATA";
case Type::ROOM:
return "ROOM";
case Type::ENEMY:
return "ENEMY";
case Type::ITEM:
return "ITEM";
case Type::COUNT:
default: return "ERROR";
default:
return "ERROR";
}
}
+7 -8
View File
@@ -9,14 +9,6 @@
class ResourcePack;
class ResourceLoader {
private:
static std::unique_ptr<ResourceLoader> instance;
ResourcePack* resource_pack_{nullptr};
std::string pack_path_;
bool fallback_to_files_{true};
ResourceLoader();
public:
static auto getInstance() -> ResourceLoader&;
~ResourceLoader();
@@ -34,6 +26,13 @@ class ResourceLoader {
[[nodiscard]] auto getAvailableResources() const -> std::vector<std::string>;
private:
ResourceLoader(); // Constructor privado (singleton)
static auto loadFromFile(const std::string& filename) -> std::vector<uint8_t>;
static auto getDataPath(const std::string& filename) -> std::string;
static std::unique_ptr<ResourceLoader> instance;
ResourcePack* resource_pack_{nullptr};
std::string pack_path_;
bool fallback_to_files_{true};
};
+9 -9
View File
@@ -14,15 +14,6 @@ struct ResourceEntry {
};
class ResourcePack {
private:
std::unordered_map<std::string, ResourceEntry> resources_;
std::vector<uint8_t> data_;
bool loaded_{false};
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t;
static void encryptData(std::vector<uint8_t>& data, const std::string& key);
static void decryptData(std::vector<uint8_t>& data, const std::string& key);
public:
ResourcePack();
~ResourcePack();
@@ -41,4 +32,13 @@ class ResourcePack {
auto getResourceList() const -> std::vector<std::string>;
static const std::string DEFAULT_ENCRYPT_KEY;
private:
static auto calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t;
static void encryptData(std::vector<uint8_t>& data, const std::string& key);
static void decryptData(std::vector<uint8_t>& data, const std::string& key);
std::unordered_map<std::string, ResourceEntry> resources_;
std::vector<uint8_t> data_;
bool loaded_{false};
};
+78 -78
View File
@@ -41,8 +41,8 @@
Director::Director(int argc, const char *argv[]) {
std::cout << "Game start" << '\n';
// Inicializa variables
section = new Section();
section->name = SECTION_PROG_LOGO;
section_ = new Section();
section_->name = SECTION_PROG_LOGO;
// Inicializa las opciones del programa (defaults + dispositivos d'entrada)
Options::init();
@@ -54,7 +54,7 @@ Director::Director(int argc, const char *argv[]) {
executablePath = "";
#else
const char *base_path = SDL_GetBasePath();
executablePath = (base_path != nullptr) ? base_path : "";
executable_path_ = (base_path != nullptr) ? base_path : "";
#endif
// Comprueba los parametros del programa (pot activar console)
@@ -70,13 +70,13 @@ Director::Director(int argc, const char *argv[]) {
// Estableix el fitxer de configuració i carrega les opcions (o crea el
// YAML amb defaults si no existeix).
Options::setConfigFile(systemFolder + "/config.yaml");
Options::setConfigFile(system_folder_ + "/config.yaml");
Options::loadFromFile();
// Presets de shaders (creats amb defaults si no existeixen).
Options::setPostFXFile(systemFolder + "/postfx.yaml");
Options::setPostFXFile(system_folder_ + "/postfx.yaml");
Options::loadPostFXFromFile();
Options::setCrtPiFile(systemFolder + "/crtpi.yaml");
Options::setCrtPiFile(system_folder_ + "/crtpi.yaml");
Options::loadCrtPiFromFile();
// Inicializa el sistema de recursos (pack + fallback).
@@ -93,7 +93,7 @@ Director::Director(int argc, const char *argv[]) {
#ifdef MACOS_BUNDLE
const std::string PACK_PATH = executablePath + "../Resources/resources.pack";
#else
const std::string PACK_PATH = executablePath + "resources.pack";
const std::string PACK_PATH = executable_path_ + "resources.pack";
#endif
if (!ResourceHelper::initializeResourceSystem(PACK_PATH, ENABLE_FALLBACK)) {
std::cerr << "Fatal: resource system init failed (missing resources.pack?)" << '\n';
@@ -102,7 +102,7 @@ Director::Director(int argc, const char *argv[]) {
}
// Crea el objeto que controla los ficheros de recursos
Asset::init(executablePath);
Asset::init(executable_path_);
Asset::get()->setVerbose(Options::settings.console);
// Si falta algún fichero no inicia el programa
@@ -127,7 +127,7 @@ Director::Director(int argc, const char *argv[]) {
Input::init("/gamecontrollerdb.txt");
#else
{
const std::string BIN_DIR = std::filesystem::path(executablePath).parent_path().string();
const std::string BIN_DIR = std::filesystem::path(executable_path_).parent_path().string();
#ifdef MACOS_BUNDLE
Input::init(BIN_DIR + "/../Resources/gamecontrollerdb.txt");
#else
@@ -145,7 +145,7 @@ Director::Director(int argc, const char *argv[]) {
//
// Por eso el constructor de Screen NO carga notificationText desde
// Resource; se enlaza después vía `Screen::get()->initNotifications()`.
Screen::init(window, renderer);
Screen::init(window_, renderer_);
#ifndef NO_SHADERS
if (Options::video.gpu.acceleration) {
@@ -155,13 +155,13 @@ Director::Director(int argc, const char *argv[]) {
// Ahora sí, precarga todos los recursos en memoria (texturas, sonidos,
// música, ...). Vivirán durante toda la vida de la app.
Resource::init(renderer);
Resource::init(renderer_);
// Completa el enlazado de Screen con recursos que necesitan Resource
// inicializado (actualmente sólo el Text de las notificaciones).
Screen::get()->initNotifications();
activeSection = ActiveSection::None;
active_section_ = ActiveSection::NONE;
}
Director::~Director() {
@@ -170,10 +170,10 @@ Director::~Director() {
// Libera las secciones primero: sus destructores tocan audio/render SDL
// (p.ej. Intro::~Intro llama a JA_DeleteMusic) y deben ejecutarse antes
// de SDL_Quit().
logo.reset();
intro.reset();
title.reset();
game.reset();
logo_.reset();
intro_.reset();
title_.reset();
game_.reset();
// Screen puede tener referencias a Text propiedad de Resource: destruir
// Screen antes que Resource.
@@ -185,12 +185,12 @@ Director::~Director() {
Asset::destroy();
Input::destroy();
Lang::destroy();
delete section;
delete section_;
Audio::destroy();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer_);
SDL_DestroyWindow(window_);
SDL_Quit();
@@ -270,23 +270,23 @@ auto Director::initSDL() -> bool {
std::srand(static_cast<unsigned int>(SDL_GetTicks()));
// Crea la ventana
window = SDL_CreateWindow(
window_ = SDL_CreateWindow(
Options::window.caption.c_str(),
GAMECANVAS_WIDTH * Options::window.zoom,
GAMECANVAS_HEIGHT * Options::window.zoom,
0);
if (window == nullptr) {
if (window_ == nullptr) {
if (Options::settings.console) {
std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << '\n';
}
success = false;
} else {
SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
SDL_SetWindowPosition(window_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
// Crea un renderizador para la ventana
renderer = SDL_CreateRenderer(window, nullptr);
renderer_ = SDL_CreateRenderer(window_, nullptr);
if (renderer == nullptr) {
if (renderer_ == nullptr) {
if (Options::settings.console) {
std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << '\n';
}
@@ -294,21 +294,21 @@ auto Director::initSDL() -> bool {
} else {
// Modo de blending por defecto (consistente con CCAE):
// permite alpha blending para fades y notificaciones.
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
// Activa vsync si es necesario
if (Options::video.vsync) {
SDL_SetRenderVSync(renderer, 1);
SDL_SetRenderVSync(renderer_, 1);
}
// Inicializa el color de renderizado
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF);
SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF);
// Establece el tamaño del buffer de renderizado
SDL_SetRenderLogicalPresentation(renderer, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT, SDL_LOGICAL_PRESENTATION_LETTERBOX);
SDL_SetRenderLogicalPresentation(renderer_, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT, SDL_LOGICAL_PRESENTATION_LETTERBOX);
// Establece el modo de mezcla
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND);
}
}
}
@@ -328,7 +328,7 @@ auto Director::setFileList() -> bool {
#endif
// Ficheros de configuración
Asset::get()->add(systemFolder + "/score.bin", Asset::Type::DATA, false, true);
Asset::get()->add(system_folder_ + "/score.bin", Asset::Type::DATA, false, true);
Asset::get()->add(PREFIX + "/data/demo/demo.bin", Asset::Type::DATA);
// Musicas
@@ -470,7 +470,7 @@ void Director::createSystemFolder(const std::string &folder) {
#elif __linux__
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
systemFolder = std::string(homedir) + "/.config/" + folder;
system_folder_ = std::string(homedir) + "/.config/" + folder;
{
// Intenta crear ".config", per si no existeix
@@ -488,12 +488,12 @@ void Director::createSystemFolder(const std::string &folder) {
(void)folder;
#else
struct stat st = {.st_dev = 0};
if (stat(systemFolder.c_str(), &st) == -1) {
if (stat(system_folder_.c_str(), &st) == -1) {
errno = 0;
#ifdef _WIN32
int ret = mkdir(systemFolder.c_str());
#else
int ret = mkdir(systemFolder.c_str(), S_IRWXU);
int ret = mkdir(system_folder_.c_str(), S_IRWXU);
#endif
if (ret == -1) {
@@ -522,53 +522,53 @@ void Director::createSystemFolder(const std::string &folder) {
// Gestiona las transiciones entre secciones
void Director::handleSectionTransition() {
// Determina qué sección debería estar activa
ActiveSection target_section = ActiveSection::None;
switch (section->name) {
ActiveSection target_section = ActiveSection::NONE;
switch (section_->name) {
case SECTION_PROG_LOGO:
target_section = ActiveSection::Logo;
target_section = ActiveSection::LOGO;
break;
case SECTION_PROG_INTRO:
target_section = ActiveSection::Intro;
target_section = ActiveSection::INTRO;
break;
case SECTION_PROG_TITLE:
target_section = ActiveSection::Title;
target_section = ActiveSection::TITLE;
break;
case SECTION_PROG_GAME:
target_section = ActiveSection::Game;
target_section = ActiveSection::GAME;
break;
default:
break;
}
// Si no ha cambiado, no hay nada que hacer
if (target_section == activeSection) {
if (target_section == active_section_) {
return;
}
// Destruye la sección anterior
logo.reset();
intro.reset();
title.reset();
game.reset();
logo_.reset();
intro_.reset();
title_.reset();
game_.reset();
// Crea la nueva sección
activeSection = target_section;
switch (activeSection) {
case ActiveSection::Logo:
logo = std::make_unique<Logo>(renderer, section);
active_section_ = target_section;
switch (active_section_) {
case ActiveSection::LOGO:
logo_ = std::make_unique<Logo>(renderer_, section_);
break;
case ActiveSection::Intro:
intro = std::make_unique<Intro>(renderer, section);
case ActiveSection::INTRO:
intro_ = std::make_unique<Intro>(renderer_, section_);
break;
case ActiveSection::Title:
title = std::make_unique<Title>(renderer, section);
case ActiveSection::TITLE:
title_ = std::make_unique<Title>(renderer_, section_);
break;
case ActiveSection::Game: {
const int NUM_PLAYERS = section->subsection == SUBSECTION_GAME_PLAY_1P ? 1 : 2;
game = std::make_unique<Game>(NUM_PLAYERS, 0, renderer, false, section);
case ActiveSection::GAME: {
const int NUM_PLAYERS = section_->subsection == SUBSECTION_GAME_PLAY_1P ? 1 : 2;
game_ = std::make_unique<Game>(NUM_PLAYERS, 0, renderer_, false, section_);
break;
}
case ActiveSection::None:
case ActiveSection::NONE:
break;
}
}
@@ -581,7 +581,7 @@ auto Director::iterate() -> SDL_AppResult {
section->name = SECTION_PROG_LOGO;
}
#else
if (section->name == SECTION_PROG_QUIT) {
if (section_->name == SECTION_PROG_QUIT) {
return SDL_APP_SUCCESS;
}
#endif
@@ -593,20 +593,20 @@ auto Director::iterate() -> SDL_AppResult {
handleSectionTransition();
// Ejecuta un frame de la sección activa
switch (activeSection) {
case ActiveSection::Logo:
logo->iterate();
switch (active_section_) {
case ActiveSection::LOGO:
logo_->iterate();
break;
case ActiveSection::Intro:
intro->iterate();
case ActiveSection::INTRO:
intro_->iterate();
break;
case ActiveSection::Title:
title->iterate();
case ActiveSection::TITLE:
title_->iterate();
break;
case ActiveSection::Game:
game->iterate();
case ActiveSection::GAME:
game_->iterate();
break;
case ActiveSection::None:
case ActiveSection::NONE:
break;
}
@@ -618,7 +618,7 @@ auto Director::handleEvent(SDL_Event *event) -> SDL_AppResult {
#ifndef __EMSCRIPTEN__
// Evento de salida de la aplicación
if (event->type == SDL_EVENT_QUIT) {
section->name = SECTION_PROG_QUIT;
section_->name = SECTION_PROG_QUIT;
return SDL_APP_SUCCESS;
}
#endif
@@ -646,20 +646,20 @@ auto Director::handleEvent(SDL_Event *event) -> SDL_AppResult {
Mouse::handleEvent(*event, Options::video.fullscreen);
// Reenvía el evento a la sección activa
switch (activeSection) {
case ActiveSection::Logo:
logo->handleEvent(event);
switch (active_section_) {
case ActiveSection::LOGO:
logo_->handleEvent(event);
break;
case ActiveSection::Intro:
intro->handleEvent(event);
case ActiveSection::INTRO:
intro_->handleEvent(event);
break;
case ActiveSection::Title:
title->handleEvent(event);
case ActiveSection::TITLE:
title_->handleEvent(event);
break;
case ActiveSection::Game:
game->handleEvent(event);
case ActiveSection::GAME:
game_->handleEvent(event);
break;
case ActiveSection::None:
case ActiveSection::NONE:
break;
}
+37 -54
View File
@@ -11,65 +11,48 @@ class Logo;
class Title;
struct Section;
// Secciones activas del Director
enum class ActiveSection : std::uint8_t { None,
Logo,
Intro,
Title,
Game };
class Director {
private:
// Objetos y punteros
SDL_Window *window; // La ventana donde dibujamos
SDL_Renderer *renderer; // El renderizador de la ventana
Section *section; // Sección y subsección actual del programa;
// Secciones del juego
ActiveSection activeSection;
std::unique_ptr<Logo> logo;
std::unique_ptr<Intro> intro;
std::unique_ptr<Title> title;
std::unique_ptr<Game> game;
// Variables
std::string executablePath; // Path del ejecutable
std::string systemFolder; // Carpeta del sistema donde guardar datos
// Inicializa jail_audio
static void initJailAudio();
// Arranca SDL y crea la ventana
auto initSDL() -> bool;
// Inicializa el objeto input
static void initInput();
// Crea el indice de ficheros
auto setFileList() -> bool;
// Comprueba los parametros del programa
static void checkProgramArguments(int argc, const char *argv[]);
// Crea la carpeta del sistema donde guardar datos
void createSystemFolder(const std::string &folder);
// Gestiona las transiciones entre secciones
void handleSectionTransition();
public:
// Constructor
Director(int argc, const char *argv[]);
// Destructor
~Director();
Director(int argc, const char *argv[]); // Constructor
~Director(); // Destructor
Director(const Director &) = delete;
auto operator=(const Director &) -> Director & = delete;
// Ejecuta un frame del juego
auto iterate() -> SDL_AppResult;
auto iterate() -> SDL_AppResult; // Ejecuta un frame del juego
auto handleEvent(SDL_Event *event) -> SDL_AppResult; // Procesa un evento
// Procesa un evento
auto handleEvent(SDL_Event *event) -> SDL_AppResult;
private:
// Secciones activas del Director
enum class ActiveSection : std::uint8_t {
NONE,
LOGO,
INTRO,
TITLE,
GAME
};
static void initJailAudio(); // Inicializa jail_audio
auto initSDL() -> bool; // Arranca SDL y crea la ventana
static void initInput(); // Inicializa el objeto input
auto setFileList() -> bool; // Crea el indice de ficheros
static void checkProgramArguments(int argc, const char *argv[]); // Comprueba los parametros del programa
void createSystemFolder(const std::string &folder); // Crea la carpeta del sistema donde guardar datos
void handleSectionTransition(); // Gestiona las transiciones entre secciones
// Objetos y punteros
SDL_Window *window_; // La ventana donde dibujamos
SDL_Renderer *renderer_; // El renderizador de la ventana
Section *section_; // Sección y subsección actual del programa;
// Secciones del juego
ActiveSection active_section_;
std::unique_ptr<Logo> logo_;
std::unique_ptr<Intro> intro_;
std::unique_ptr<Title> title_;
std::unique_ptr<Game> game_;
// Variables
std::string executable_path_; // Path del ejecutable
std::string system_folder_; // Carpeta del sistema donde guardar datos
};