diff --git a/source/core/audio/audio.cpp b/source/core/audio/audio.cpp index 56d363cd..300feb3c 100644 --- a/source/core/audio/audio.cpp +++ b/source/core/audio/audio.cpp @@ -41,7 +41,7 @@ void Audio::update() { } // Reproduce la música -void Audio::playMusic(const std::string& name, const int loop) { +void Audio::playMusic(const std::string& name, const int loop) { // NOLINT(readability-convert-member-functions-to-static) bool new_loop = (loop != 0); // Si ya está sonando exactamente la misma pista y mismo modo loop, no hacemos nada @@ -71,7 +71,7 @@ void Audio::playMusic(const std::string& name, const int loop) { } // Pausa la música -void Audio::pauseMusic() { +void Audio::pauseMusic() { // NOLINT(readability-convert-member-functions-to-static) if (music_enabled_ && music_.state == MusicState::PLAYING) { JA_PauseMusic(); music_.state = MusicState::PAUSED; @@ -79,7 +79,7 @@ void Audio::pauseMusic() { } // Continua la música pausada -void Audio::resumeMusic() { +void Audio::resumeMusic() { // NOLINT(readability-convert-member-functions-to-static) if (music_enabled_ && music_.state == MusicState::PAUSED) { JA_ResumeMusic(); music_.state = MusicState::PLAYING; @@ -87,7 +87,7 @@ void Audio::resumeMusic() { } // Detiene la música -void Audio::stopMusic() { +void Audio::stopMusic() { // NOLINT(readability-make-member-function-const) if (music_enabled_) { JA_StopMusic(); music_.state = MusicState::STOPPED; diff --git a/source/core/input/global_inputs.cpp b/source/core/input/global_inputs.cpp index 1f47bfc4..77ba73b8 100644 --- a/source/core/input/global_inputs.cpp +++ b/source/core/input/global_inputs.cpp @@ -24,7 +24,7 @@ namespace GlobalInputs { if (stringInVector(Notifier::get()->getCodes(), CODE)) { SceneManager::current = SceneManager::Scene::TITLE; } else { - Notifier::get()->show({Locale::get()->get("ui.press_again_menu")}, Notifier::Style::DEFAULT, -1, true, CODE); + Notifier::get()->show({Locale::get()->get("ui.press_again_menu")}, Notifier::Style::DEFAULT, -1, true, CODE); // NOLINT(readability-static-accessed-through-instance) } return; } @@ -44,7 +44,7 @@ namespace GlobalInputs { if (stringInVector(Notifier::get()->getCodes(), CODE)) { SceneManager::current = SceneManager::Scene::QUIT; } else { - Notifier::get()->show({Locale::get()->get("ui.press_again_exit")}, Notifier::Style::DEFAULT, -1, true, CODE); + Notifier::get()->show({Locale::get()->get("ui.press_again_exit")}, Notifier::Style::DEFAULT, -1, true, CODE); // NOLINT(readability-static-accessed-through-instance) } } @@ -68,66 +68,65 @@ namespace GlobalInputs { void handleToggleBorder() { Screen::get()->toggleBorder(); - Notifier::get()->show({Locale::get()->get(Options::video.border.enabled ? "ui.border_enabled" : "ui.border_disabled")}); + Notifier::get()->show({Locale::get()->get(Options::video.border.enabled ? "ui.border_enabled" : "ui.border_disabled")}); // NOLINT(readability-static-accessed-through-instance) } void handleToggleVideoMode() { Screen::get()->toggleVideoMode(); - Notifier::get()->show({Locale::get()->get(static_cast(Options::video.fullscreen) == 0 ? "ui.fullscreen_disabled" : "ui.fullscreen_enabled")}); + Notifier::get()->show({Locale::get()->get(static_cast(Options::video.fullscreen) == 0 ? "ui.fullscreen_disabled" : "ui.fullscreen_enabled")}); // NOLINT(readability-static-accessed-through-instance) } void handleDecWindowZoom() { if (Screen::get()->decWindowZoom()) { - Notifier::get()->show({Locale::get()->get("ui.window_zoom") + std::to_string(Options::window.zoom)}); + Notifier::get()->show({Locale::get()->get("ui.window_zoom") + std::to_string(Options::window.zoom)}); // NOLINT(readability-static-accessed-through-instance) } } void handleIncWindowZoom() { if (Screen::get()->incWindowZoom()) { - Notifier::get()->show({Locale::get()->get("ui.window_zoom") + std::to_string(Options::window.zoom)}); + Notifier::get()->show({Locale::get()->get("ui.window_zoom") + std::to_string(Options::window.zoom)}); // NOLINT(readability-static-accessed-through-instance) } } void handleTogglePostFX() { Screen::get()->togglePostFX(); - Notifier::get()->show({Locale::get()->get(Options::video.postfx ? "ui.postfx_enabled" : "ui.postfx_disabled")}); + Notifier::get()->show({Locale::get()->get(Options::video.postfx ? "ui.postfx_enabled" : "ui.postfx_disabled")}); // NOLINT(readability-static-accessed-through-instance) } void handleToggleSupersampling() { Screen::get()->toggleSupersampling(); - Notifier::get()->show({Locale::get()->get(Options::video.supersampling ? "ui.supersampling_enabled" : "ui.supersampling_disabled")}); + Notifier::get()->show({Locale::get()->get(Options::video.supersampling ? "ui.supersampling_enabled" : "ui.supersampling_disabled")}); // NOLINT(readability-static-accessed-through-instance) } void handleNextPostFXPreset() { if (!Options::postfx_presets.empty()) { Options::current_postfx_preset = (Options::current_postfx_preset + 1) % static_cast(Options::postfx_presets.size()); Screen::get()->reloadPostFX(); - Notifier::get()->show({Locale::get()->get("ui.postfx") + " " + Options::postfx_presets[static_cast(Options::current_postfx_preset)].name}); + Notifier::get()->show({Locale::get()->get("ui.postfx") + " " + Options::postfx_presets[static_cast(Options::current_postfx_preset)].name}); // NOLINT(readability-static-accessed-through-instance) } } void handleNextPalette() { Screen::get()->nextPalette(); - Notifier::get()->show({Locale::get()->get("ui.palette") + " " + Options::video.palette}); + Notifier::get()->show({Locale::get()->get("ui.palette") + " " + Options::video.palette}); // NOLINT(readability-static-accessed-through-instance) } void handlePreviousPalette() { Screen::get()->previousPalette(); - Notifier::get()->show({Locale::get()->get("ui.palette") + " " + Options::video.palette}); + Notifier::get()->show({Locale::get()->get("ui.palette") + " " + Options::video.palette}); // NOLINT(readability-static-accessed-through-instance) } void handleToggleIntegerScale() { Screen::get()->toggleIntegerScale(); Screen::get()->setVideoMode(Options::video.fullscreen); - Notifier::get()->show({Locale::get()->get(Options::video.integer_scale ? "ui.integer_scale_enabled" : "ui.integer_scale_disabled")}); + Notifier::get()->show({Locale::get()->get(Options::video.integer_scale ? "ui.integer_scale_enabled" : "ui.integer_scale_disabled")}); // NOLINT(readability-static-accessed-through-instance) } void handleToggleVSync() { Screen::get()->toggleVSync(); - Notifier::get()->show({Locale::get()->get(Options::video.vertical_sync ? "ui.vsync_enabled" : "ui.vsync_disabled")}); + Notifier::get()->show({Locale::get()->get(Options::video.vertical_sync ? "ui.vsync_enabled" : "ui.vsync_disabled")}); // NOLINT(readability-static-accessed-through-instance) } - // Detecta qué acción global ha sido presionada (si alguna) auto getPressedAction() -> InputAction { if (Input::get()->checkAction(InputAction::EXIT, Input::DO_NOT_ALLOW_REPEAT)) { @@ -152,12 +151,12 @@ namespace GlobalInputs { } if (Input::get()->checkAction(InputAction::TOGGLE_POSTFX, Input::DO_NOT_ALLOW_REPEAT)) { if ((SDL_GetModState() & SDL_KMOD_CTRL) != 0U) { - return InputAction::TOGGLE_SUPERSAMPLING; // Ctrl+F4 + return InputAction::TOGGLE_SUPERSAMPLING; // Ctrl+F4 } if (Options::video.postfx && ((SDL_GetModState() & SDL_KMOD_SHIFT) != 0U)) { - return InputAction::NEXT_POSTFX_PRESET; // Shift+F4 + return InputAction::NEXT_POSTFX_PRESET; // Shift+F4 } - return InputAction::TOGGLE_POSTFX; // F4 + return InputAction::TOGGLE_POSTFX; // F4 } if (Input::get()->checkAction(InputAction::NEXT_PALETTE, Input::DO_NOT_ALLOW_REPEAT)) { return InputAction::NEXT_PALETTE; diff --git a/source/core/input/input.cpp b/source/core/input/input.cpp index 60dbe77c..72479428 100644 --- a/source/core/input/input.cpp +++ b/source/core/input/input.cpp @@ -14,7 +14,7 @@ Input* Input::instance = nullptr; // Inicializa la instancia única del singleton -void Input::init(const std::string& game_controller_db_path) { +void Input::init(const std::string& game_controller_db_path) { // NOLINT(readability-convert-member-functions-to-static) Input::instance = new Input(game_controller_db_path); } @@ -69,7 +69,7 @@ void Input::applyKeyboardBindingsFromOptions() { } // Aplica configuración de botones del gamepad desde Options al primer gamepad conectado -void Input::applyGamepadBindingsFromOptions() { +void Input::applyGamepadBindingsFromOptions() { // NOLINT(readability-convert-member-functions-to-static) // Si no hay gamepads conectados, no hay nada que hacer if (gamepads_.empty()) { return; @@ -90,21 +90,21 @@ void Input::applyGamepadBindingsFromOptions() { } // Asigna inputs a botones del mando -void Input::bindGameControllerButton(const std::shared_ptr& gamepad, Action action, SDL_GamepadButton button) { +void Input::bindGameControllerButton(const std::shared_ptr& gamepad, Action action, SDL_GamepadButton button) { // NOLINT(readability-convert-member-functions-to-static) if (gamepad != nullptr) { gamepad->bindings[action].button = button; } } // Asigna inputs a botones del mando -void Input::bindGameControllerButton(const std::shared_ptr& gamepad, Action action_target, Action action_source) { +void Input::bindGameControllerButton(const std::shared_ptr& gamepad, Action action_target, Action action_source) { // NOLINT(readability-convert-member-functions-to-static) if (gamepad != nullptr) { gamepad->bindings[action_target].button = gamepad->bindings[action_source].button; } } // Comprueba si alguna acción está activa -auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr& gamepad) -> bool { +auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr& gamepad) -> bool { // NOLINT(readability-convert-member-functions-to-static) bool success_keyboard = false; bool success_controller = false; @@ -142,7 +142,7 @@ auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const s } // Comprueba si hay almenos una acción activa -auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr& gamepad) -> bool { +auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr& gamepad) -> bool { // NOLINT(readability-convert-member-functions-to-static) // Obtenemos el número total de acciones posibles para iterar sobre ellas. // --- Comprobación del Teclado --- @@ -179,7 +179,7 @@ auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr& g } // Comprueba si hay algún botón pulsado -auto Input::checkAnyButton(bool repeat) -> bool { +auto Input::checkAnyButton(bool repeat) -> bool { // NOLINT(readability-convert-member-functions-to-static) // Solo comprueba los botones definidos previamente for (auto bi : BUTTON_INPUTS) { // Comprueba el teclado @@ -219,7 +219,7 @@ auto Input::getControllerNames() const -> std::vector { auto Input::getNumGamepads() const -> int { return gamepads_.size(); } // Obtiene el gamepad a partir de un event.id -auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr { +auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr { // NOLINT(readability-convert-member-functions-to-static) for (const auto& gamepad : gamepads_) { if (gamepad->instance_id == id) { return gamepad; @@ -228,7 +228,7 @@ auto Input::getGamepad(SDL_JoystickID id) const -> std::shared_ptr std::shared_ptr { +auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr { // NOLINT(readability-convert-member-functions-to-static) for (const auto& gamepad : gamepads_) { if (gamepad && gamepad->name == name) { return gamepad; @@ -238,12 +238,12 @@ auto Input::getGamepadByName(const std::string& name) const -> std::shared_ptr& gamepad, Action action) -> SDL_GamepadButton { +auto Input::getControllerBinding(const std::shared_ptr& gamepad, Action action) -> SDL_GamepadButton { // NOLINT(readability-convert-member-functions-to-static) return static_cast(gamepad->bindings[action].button); } // Comprueba el eje del mando -auto Input::checkAxisInput(Action action, const std::shared_ptr& gamepad, bool repeat) -> bool { +auto Input::checkAxisInput(Action action, const std::shared_ptr& gamepad, bool repeat) -> bool { // NOLINT(readability-convert-member-functions-to-static) // Obtener el binding configurado para esta acción auto& binding = gamepad->bindings[action]; @@ -286,7 +286,7 @@ auto Input::checkAxisInput(Action action, const std::shared_ptr& gamepa } // Comprueba los triggers del mando como botones digitales -auto Input::checkTriggerInput(Action action, const std::shared_ptr& gamepad, bool repeat) -> bool { +auto Input::checkTriggerInput(Action action, const std::shared_ptr& gamepad, bool repeat) -> bool { // NOLINT(readability-convert-member-functions-to-static) // Solo manejamos botones específicos que pueden ser triggers if (gamepad->bindings[action].button != static_cast(SDL_GAMEPAD_BUTTON_INVALID)) { // Solo procesamos L2 y R2 como triggers @@ -333,13 +333,13 @@ auto Input::checkTriggerInput(Action action, const std::shared_ptr& gam return false; } -void Input::addGamepadMappingsFromFile() { +void Input::addGamepadMappingsFromFile() { // NOLINT(readability-convert-member-functions-to-static) if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) { std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << '\n'; } } -void Input::discoverGamepads() { +void Input::discoverGamepads() { // NOLINT(readability-convert-member-functions-to-static) SDL_Event event; while (SDL_PollEvent(&event)) { handleEvent(event); // Comprueba mandos conectados @@ -375,7 +375,7 @@ void Input::resetInputStates() { } } -void Input::update() { +void Input::update() { // NOLINT(readability-convert-member-functions-to-static) // --- TECLADO --- const bool* key_states = SDL_GetKeyboardState(nullptr); @@ -399,7 +399,7 @@ void Input::update() { } } -auto Input::handleEvent(const SDL_Event& event) -> std::string { +auto Input::handleEvent(const SDL_Event& event) -> std::string { // NOLINT(readability-convert-member-functions-to-static) switch (event.type) { case SDL_EVENT_GAMEPAD_ADDED: return addGamepad(event.gdevice.which); @@ -409,7 +409,7 @@ auto Input::handleEvent(const SDL_Event& event) -> std::string { return {}; } -auto Input::addGamepad(int device_index) -> std::string { +auto Input::addGamepad(int device_index) -> std::string { // NOLINT(readability-convert-member-functions-to-static) SDL_Gamepad* pad = SDL_OpenGamepad(device_index); if (pad == nullptr) { std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n'; @@ -423,8 +423,8 @@ auto Input::addGamepad(int device_index) -> std::string { return name + " CONNECTED"; } -auto Input::removeGamepad(SDL_JoystickID id) -> std::string { - auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr& gamepad) { +auto Input::removeGamepad(SDL_JoystickID id) -> std::string { // NOLINT(readability-convert-member-functions-to-static) + auto it = std::ranges::find_if(gamepads_, [id](const std::shared_ptr& gamepad) -> bool { return gamepad->instance_id == id; }); @@ -438,7 +438,7 @@ auto Input::removeGamepad(SDL_JoystickID id) -> std::string { return {}; } -void Input::printConnectedGamepads() const { +void Input::printConnectedGamepads() const { // NOLINT(readability-convert-member-functions-to-static) if (gamepads_.empty()) { std::cout << "No hay gamepads conectados." << '\n'; return; @@ -452,7 +452,7 @@ void Input::printConnectedGamepads() const { } } -auto Input::findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr { +auto Input::findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr { // NOLINT(readability-convert-member-functions-to-static) // Si no hay gamepads disponibles, devolver gamepad por defecto if (gamepads_.empty()) { return nullptr; diff --git a/source/core/input/input.hpp b/source/core/input/input.hpp index fa98f2ed..698137d2 100644 --- a/source/core/input/input.hpp +++ b/source/core/input/input.hpp @@ -101,12 +101,12 @@ class Input { // --- Gestión de gamepads --- [[nodiscard]] auto gameControllerFound() const -> bool; [[nodiscard]] auto getNumGamepads() const -> int; - auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr; - auto getGamepadByName(const std::string& name) const -> std::shared_ptr; - auto getGamepads() const -> const Gamepads& { return gamepads_; } + [[nodiscard]] auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr; + [[nodiscard]] auto getGamepadByName(const std::string& name) const -> std::shared_ptr; + [[nodiscard]] auto getGamepads() const -> const Gamepads& { return gamepads_; } auto findAvailableGamepadByName(const std::string& gamepad_name) -> std::shared_ptr; static auto getControllerName(const std::shared_ptr& gamepad) -> std::string; - auto getControllerNames() const -> std::vector; + [[nodiscard]] auto getControllerNames() const -> std::vector; [[nodiscard]] static auto getControllerBinding(const std::shared_ptr& gamepad, Action action) -> SDL_GamepadButton; void printConnectedGamepads() const; diff --git a/source/core/locale/locale.cpp b/source/core/locale/locale.cpp index 4a588b26..53d5dda0 100644 --- a/source/core/locale/locale.cpp +++ b/source/core/locale/locale.cpp @@ -11,7 +11,7 @@ Locale* Locale::instance = nullptr; // [SINGLETON] Crea el objeto con esta función estática -void Locale::init(const std::string& file_path) { +void Locale::init(const std::string& file_path) { // NOLINT(readability-convert-member-functions-to-static) Locale::instance = new Locale(); Locale::instance->loadFromFile(file_path); } @@ -28,7 +28,7 @@ auto Locale::get() -> Locale* { } // Devuelve la traducción de la clave o la clave como fallback -auto Locale::get(const std::string& key) const -> std::string { +auto Locale::get(const std::string& key) const -> std::string { // NOLINT(readability-convert-member-functions-to-static) auto it = strings_.find(key); if (it != strings_.end()) { return it->second; @@ -41,7 +41,7 @@ auto Locale::get(const std::string& key) const -> std::string { } // Aplana un nodo YAML de forma recursiva: {a: {b: "val"}} -> {"a.b" -> "val"} -void Locale::flatten(const void* node_ptr, const std::string& prefix) { +void Locale::flatten(const void* node_ptr, const std::string& prefix) { // NOLINT(readability-convert-member-functions-to-static) const auto& node = *static_cast(node_ptr); for (auto itr = node.begin(); itr != node.end(); ++itr) { @@ -59,7 +59,7 @@ void Locale::flatten(const void* node_ptr, const std::string& prefix) { } // Carga las traducciones desde el fichero YAML indicado -void Locale::loadFromFile(const std::string& file_path) { +void Locale::loadFromFile(const std::string& file_path) { // NOLINT(readability-convert-member-functions-to-static) if (file_path.empty()) { if (Options::console) { std::cerr << "Locale: ruta de fichero vacía, sin traducciones cargadas\n"; diff --git a/source/core/rendering/gif.cpp b/source/core/rendering/gif.cpp index 9b8cbf14..654090e7 100644 --- a/source/core/rendering/gif.cpp +++ b/source/core/rendering/gif.cpp @@ -15,7 +15,7 @@ namespace GIF { } // Inicializa el diccionario LZW con los valores iniciales - inline void initializeDictionary(std::vector& dictionary, int code_length, int& dictionary_ind) { + inline void initializeDictionary(std::vector& dictionary, int code_length, int& dictionary_ind) { // NOLINT(readability-identifier-naming) int size = 1 << code_length; dictionary.resize(1 << (code_length + 1)); for (dictionary_ind = 0; dictionary_ind < size; dictionary_ind++) { @@ -55,7 +55,7 @@ namespace GIF { } // Agrega una nueva entrada al diccionario - inline void addDictionaryEntry(std::vector& dictionary, int& dictionary_ind, int& code_length, int prev, int code) { + inline void addDictionaryEntry(std::vector& dictionary, int& dictionary_ind, int& code_length, int prev, int code) { // NOLINT(readability-identifier-naming) uint8_t first_byte; if (code == dictionary_ind) { first_byte = findFirstByte(dictionary, prev); @@ -90,7 +90,7 @@ namespace GIF { return match_len; } - void Gif::decompress(int code_length, const uint8_t* input, int input_length, uint8_t* out) { + void Gif::decompress(int code_length, const uint8_t* input, int input_length, uint8_t* out) { // NOLINT(readability-convert-member-functions-to-static) // Verifica que el code_length tenga un rango razonable. if (code_length < 2 || code_length > 12) { throw std::runtime_error("Invalid LZW code length"); @@ -146,7 +146,7 @@ namespace GIF { } } - auto Gif::readSubBlocks(const uint8_t*& buffer) -> std::vector { + auto Gif::readSubBlocks(const uint8_t*& buffer) -> std::vector { // NOLINT(readability-convert-member-functions-to-static) std::vector data; uint8_t block_size = *buffer; buffer++; @@ -159,7 +159,7 @@ namespace GIF { return data; } - auto Gif::processImageDescriptor(const uint8_t*& buffer, const std::vector& gct, int resolution_bits) -> std::vector { + auto Gif::processImageDescriptor(const uint8_t*& buffer, const std::vector& gct, int resolution_bits) -> std::vector { // NOLINT(readability-convert-member-functions-to-static) ImageDescriptor image_descriptor; // Lee 9 bytes para el image descriptor. readBytes(buffer, &image_descriptor, sizeof(ImageDescriptor)); @@ -175,7 +175,7 @@ namespace GIF { return uncompressed_data; } - auto Gif::loadPalette(const uint8_t* buffer) -> std::vector { + auto Gif::loadPalette(const uint8_t* buffer) -> std::vector { // NOLINT(readability-convert-member-functions-to-static) uint8_t header[6]; std::memcpy(header, buffer, 6); buffer += 6; @@ -186,7 +186,7 @@ namespace GIF { std::vector global_color_table; if ((screen_descriptor.fields & 0x80) != 0) { - int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1)); + int global_color_table_size = 1 << ((screen_descriptor.fields & 0x07) + 1); global_color_table.resize(global_color_table_size); for (int i = 0; i < global_color_table_size; ++i) { uint8_t r = buffer[0]; @@ -199,7 +199,7 @@ namespace GIF { return global_color_table; } - auto Gif::processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector { + auto Gif::processGifStream(const uint8_t* buffer, uint16_t& w, uint16_t& h) -> std::vector { // NOLINT(readability-convert-member-functions-to-static) // Leer la cabecera de 6 bytes ("GIF87a" o "GIF89a") uint8_t header[6]; std::memcpy(header, buffer, 6); @@ -222,7 +222,7 @@ namespace GIF { int color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1; std::vector global_color_table; if ((screen_descriptor.fields & 0x80) != 0) { - int global_color_table_size = 1 << (((screen_descriptor.fields & 0x07) + 1)); + int global_color_table_size = 1 << ((screen_descriptor.fields & 0x07) + 1); global_color_table.resize(global_color_table_size); std::memcpy(global_color_table.data(), buffer, 3 * global_color_table_size); buffer += 3 * global_color_table_size; diff --git a/source/core/rendering/pixel_reveal.cpp b/source/core/rendering/pixel_reveal.cpp index c34ebb1e..bc712ca9 100644 --- a/source/core/rendering/pixel_reveal.cpp +++ b/source/core/rendering/pixel_reveal.cpp @@ -65,11 +65,8 @@ PixelReveal::PixelReveal(int width, int height, float pixels_per_second, float s } } -// Destructor -PixelReveal::~PixelReveal() = default; - // Actualiza el estado del revelado -void PixelReveal::update(float time_active) { +void PixelReveal::update(float time_active) { // NOLINT(readability-make-member-function-const) // En modo normal revela (pone transparente); en modo inverso cubre (pone negro) const auto PIXEL_COLOR = reverse_ ? static_cast(PaletteColor::BLACK) : static_cast(PaletteColor::TRANSPARENT); @@ -106,5 +103,5 @@ void PixelReveal::render(int dst_x, int dst_y) const { // Indica si el revelado ha completado todas las filas auto PixelReveal::isComplete() const -> bool { - return std::ranges::all_of(row_step_, [this](int s) { return s >= num_steps_; }); + return std::ranges::all_of(row_step_, [this](int s) -> bool { return s >= num_steps_; }); } diff --git a/source/core/rendering/pixel_reveal.hpp b/source/core/rendering/pixel_reveal.hpp index 240b1280..557abc7c 100644 --- a/source/core/rendering/pixel_reveal.hpp +++ b/source/core/rendering/pixel_reveal.hpp @@ -16,8 +16,7 @@ class PixelReveal { // Constructor PixelReveal(int width, int height, float pixels_per_second, float step_duration, int num_steps = 4, bool reverse = false, RevealMode mode = RevealMode::RANDOM); - // Destructor definido en el .cpp para que unique_ptr funcione con forward declaration - ~PixelReveal(); + ~PixelReveal() = default; // Actualiza el estado del revelado según el tiempo transcurrido void update(float time_active); diff --git a/source/core/rendering/screen.cpp b/source/core/rendering/screen.cpp index 74c8680d..4f1628a8 100644 --- a/source/core/rendering/screen.cpp +++ b/source/core/rendering/screen.cpp @@ -294,7 +294,7 @@ void Screen::previousPalette() { } // Establece la paleta -void Screen::setPalete() { +void Screen::setPalete() { // NOLINT(readability-convert-member-functions-to-static) game_surface_->loadPalette(Resource::Cache::get()->getPalette(palettes_.at(current_palette_))); border_surface_->loadPalette(Resource::Cache::get()->getPalette(palettes_.at(current_palette_))); @@ -318,7 +318,7 @@ void Screen::processPaletteList() { } // Copia la surface a la textura -void Screen::surfaceToTexture() { +void Screen::surfaceToTexture() { // NOLINT(readability-convert-member-functions-to-static) if (Options::video.border.enabled) { border_surface_->copyToTexture(renderer_, border_texture_); game_surface_->copyToTexture(renderer_, border_texture_, nullptr, &game_surface_dstrect_); @@ -380,7 +380,7 @@ void Screen::renderOverlays() { } // Localiza la paleta dentro del vector de paletas -auto Screen::findPalette(const std::string& name) -> size_t { +auto Screen::findPalette(const std::string& name) -> size_t { // NOLINT(readability-convert-member-functions-to-static) std::string upper_name = toUpper(name + ".pal"); for (size_t i = 0; i < palettes_.size(); ++i) { @@ -468,7 +468,7 @@ void Screen::toggleSupersampling() { } // Aplica los parámetros del preset actual al backend de shaders -void Screen::applyCurrentPostFXPreset() { +void Screen::applyCurrentPostFXPreset() { // NOLINT(readability-convert-member-functions-to-static) if (shader_backend_ && !Options::postfx_presets.empty()) { const auto& p = Options::postfx_presets[static_cast(Options::current_postfx_preset)]; // Supersampling es un toggle global (Options::video.supersampling), no por preset. @@ -504,7 +504,7 @@ void Screen::initShaders() { } // Obtiene información sobre la pantalla -void Screen::getDisplayInfo() { +void Screen::getDisplayInfo() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n** VIDEO SYSTEM **\n"; int num_displays = 0; @@ -609,7 +609,7 @@ auto Screen::initSDLVideo() -> bool { } // Crea el objeto de texto -void Screen::createText() { +void Screen::createText() { // NOLINT(readability-convert-member-functions-to-static) // Carga la surface de la fuente directamente del archivo auto surface = std::make_shared(Resource::List::get()->get("aseprite.gif")); diff --git a/source/core/rendering/screen.hpp b/source/core/rendering/screen.hpp index bd1eb740..bdafa6bf 100644 --- a/source/core/rendering/screen.hpp +++ b/source/core/rendering/screen.hpp @@ -53,12 +53,12 @@ class Screen { void toggleBorder(); // Cambia entre borde visible y no visible // Paletas y PostFX - void nextPalette(); // Cambia a la siguiente paleta - void previousPalette(); // Cambia a la paleta anterior - void setPalete(); // Establece la paleta actual - void togglePostFX(); // Cambia el estado del PostFX - void toggleSupersampling(); // Activa/desactiva el supersampling global - void reloadPostFX(); // Recarga el shader del preset actual sin toggle + void nextPalette(); // Cambia a la siguiente paleta + void previousPalette(); // Cambia a la paleta anterior + void setPalete(); // Establece la paleta actual + void togglePostFX(); // Cambia el estado del PostFX + void toggleSupersampling(); // Activa/desactiva el supersampling global + void reloadPostFX(); // Recarga el shader del preset actual sin toggle // Surfaces y notificaciones void setRendererSurface(const std::shared_ptr& surface = nullptr); // Establece el renderizador para las surfaces @@ -159,7 +159,7 @@ class Screen { std::vector pixel_buffer_; // Buffer intermedio para SDL3GPU path (surface → ARGB) #ifdef _DEBUG - bool show_fps_{true}; // Indica si ha de mostrar el contador de FPS + bool show_fps_{true}; // Indica si ha de mostrar el contador de FPS #else bool show_fps_{false}; // Indica si ha de mostrar el contador de FPS #endif diff --git a/source/core/rendering/sdl3gpu/sdl3gpu_shader.cpp b/source/core/rendering/sdl3gpu/sdl3gpu_shader.cpp index 498c066c..5d29ecd7 100644 --- a/source/core/rendering/sdl3gpu/sdl3gpu_shader.cpp +++ b/source/core/rendering/sdl3gpu/sdl3gpu_shader.cpp @@ -207,12 +207,12 @@ namespace Rendering { float fw = 0.0F; float fh = 0.0F; SDL_GetTextureSize(texture, &fw, &fh); - game_width_ = static_cast(fw); + game_width_ = static_cast(fw); game_height_ = static_cast(fh); - tex_width_ = game_width_ * oversample_; - tex_height_ = game_height_ * oversample_; + tex_width_ = game_width_ * oversample_; + tex_height_ = game_height_ * oversample_; uniforms_.screen_height = static_cast(tex_height_); // Altura de la textura GPU - uniforms_.oversample = static_cast(oversample_); + uniforms_.oversample = static_cast(oversample_); // ---------------------------------------------------------------- // 1. Create GPU device (solo si no existe ya) @@ -391,16 +391,16 @@ namespace Rendering { // Replica la fórmula del shader: mix(3.5, 0.42, scanline_strength). auto* out = static_cast(mapped); const int OS = oversample_; - const float BRIGHT_MUL = 1.0F + (baked_scanline_strength_ * 2.5F); // rows 0..OS-2 - const float DARK_MUL = 1.0F - (baked_scanline_strength_ * 0.58F); // row OS-1 + const float BRIGHT_MUL = 1.0F + (baked_scanline_strength_ * 2.5F); // rows 0..OS-2 + const float DARK_MUL = 1.0F - (baked_scanline_strength_ * 0.58F); // row OS-1 for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { - const Uint32 SRC = pixels[y * width + x]; + const Uint32 SRC = pixels[(y * width) + x]; const Uint32 ALPHA = (SRC >> 24) & 0xFFU; - const auto FR = static_cast((SRC >> 16) & 0xFFU); - const auto FG = static_cast((SRC >> 8) & 0xFFU); - const auto FB = static_cast( SRC & 0xFFU); + const auto FR = static_cast((SRC >> 16) & 0xFFU); + const auto FG = static_cast((SRC >> 8) & 0xFFU); + const auto FB = static_cast(SRC & 0xFFU); auto make_px = [ALPHA](float rv, float gv, float bv) -> Uint32 { auto cl = [](float v) -> Uint32 { return static_cast(std::min(255.0F, v)); }; @@ -408,13 +408,13 @@ namespace Rendering { }; const Uint32 BRIGHT = make_px(FR * BRIGHT_MUL, FG * BRIGHT_MUL, FB * BRIGHT_MUL); - const Uint32 DARK = make_px(FR * DARK_MUL, FG * DARK_MUL, FB * DARK_MUL); + const Uint32 DARK = make_px(FR * DARK_MUL, FG * DARK_MUL, FB * DARK_MUL); for (int dy = 0; dy < OS; ++dy) { const Uint32 OUT_PX = (dy == OS - 1) ? DARK : BRIGHT; const int DST_Y = (y * OS) + dy; for (int dx = 0; dx < OS; ++dx) { - out[DST_Y * (width * OS) + (x * OS) + dx] = OUT_PX; + out[(DST_Y * (width * OS)) + ((x * OS) + dx)] = OUT_PX; } } } @@ -501,7 +501,7 @@ namespace Rendering { } vx = std::floor((static_cast(sw) - vw) * 0.5F); vy = std::floor((static_cast(sh) - vh) * 0.5F); - SDL_GPUViewport vp = {vx, vy, vw, vh, 0.0F, 1.0F}; + SDL_GPUViewport vp = {.x = vx, .y = vy, .w = vw, .h = vh, .min_depth = 0.0F, .max_depth = 1.0F}; SDL_SetGPUViewport(pass, &vp); // pixel_scale: pixels físicos por pixel lógico de juego (para scanlines sin SS). @@ -509,13 +509,14 @@ namespace Rendering { uniforms_.pixel_scale = (game_height_ > 0) ? (vh / static_cast(game_height_)) : 1.0F; - uniforms_.time = static_cast(SDL_GetTicks()) / 1000.0F; + uniforms_.time = static_cast(SDL_GetTicks()) / 1000.0F; uniforms_.oversample = static_cast(oversample_); // Con supersampling usamos LINEAR para que el escalado a zooms no-múltiplo-de-3 // promedia correctamente las filas de scanline horneadas en CPU. SDL_GPUSampler* active_sampler = (oversample_ > 1 && linear_sampler_ != nullptr) - ? linear_sampler_ : sampler_; + ? linear_sampler_ + : sampler_; SDL_GPUTextureSamplerBinding binding = {}; binding.texture = scene_texture_; @@ -604,7 +605,7 @@ namespace Rendering { return shader; } - auto SDL3GPUShader::createShaderSPIRV(SDL_GPUDevice* device, + auto SDL3GPUShader::createShaderSPIRV(SDL_GPUDevice* device, // NOLINT(readability-convert-member-functions-to-static) const uint8_t* spv_code, size_t spv_size, const char* entrypoint, @@ -628,12 +629,12 @@ namespace Rendering { void SDL3GPUShader::setPostFXParams(const PostFXParams& p) { uniforms_.vignette_strength = p.vignette; - uniforms_.chroma_strength = p.chroma; - uniforms_.mask_strength = p.mask; - uniforms_.gamma_strength = p.gamma; - uniforms_.curvature = p.curvature; - uniforms_.bleeding = p.bleeding; - uniforms_.flicker = p.flicker; + uniforms_.chroma_strength = p.chroma; + uniforms_.mask_strength = p.mask; + uniforms_.gamma_strength = p.gamma; + uniforms_.curvature = p.curvature; + uniforms_.bleeding = p.bleeding; + uniforms_.flicker = p.flicker; // Con supersampling las scanlines se hornean en CPU (uploadPixels). // El shader recibe strength=0 para no aplicarlas de nuevo en GPU. @@ -682,16 +683,16 @@ namespace Rendering { upload_buffer_ = nullptr; } - tex_width_ = game_width_ * oversample_; + tex_width_ = game_width_ * oversample_; tex_height_ = game_height_ * oversample_; uniforms_.screen_height = static_cast(tex_height_); - uniforms_.oversample = static_cast(oversample_); + uniforms_.oversample = static_cast(oversample_); SDL_GPUTextureCreateInfo tex_info = {}; - tex_info.type = SDL_GPU_TEXTURETYPE_2D; + tex_info.type = SDL_GPU_TEXTURETYPE_2D; tex_info.format = SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM; - tex_info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER; - tex_info.width = static_cast(tex_width_); + tex_info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER; + tex_info.width = static_cast(tex_width_); tex_info.height = static_cast(tex_height_); tex_info.layer_count_or_depth = 1; tex_info.num_levels = 1; @@ -703,7 +704,7 @@ namespace Rendering { SDL_GPUTransferBufferCreateInfo tb_info = {}; tb_info.usage = SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD; - tb_info.size = static_cast(tex_width_ * tex_height_ * 4); + tb_info.size = static_cast(tex_width_ * tex_height_ * 4); upload_buffer_ = SDL_CreateGPUTransferBuffer(device_, &tb_info); if (upload_buffer_ == nullptr) { SDL_Log("SDL3GPUShader: reinit — failed to create upload buffer: %s", SDL_GetError()); diff --git a/source/core/rendering/sdl3gpu/sdl3gpu_shader.hpp b/source/core/rendering/sdl3gpu/sdl3gpu_shader.hpp index c1fb4ca0..78788549 100644 --- a/source/core/rendering/sdl3gpu/sdl3gpu_shader.hpp +++ b/source/core/rendering/sdl3gpu/sdl3gpu_shader.hpp @@ -92,11 +92,11 @@ namespace Rendering { PostFXUniforms uniforms_{.vignette_strength = 0.6F, .chroma_strength = 0.15F, .scanline_strength = 0.7F, .screen_height = 192.0F, .pixel_scale = 1.0F, .oversample = 1.0F}; - int game_width_ = 0; // Dimensiones originales del canvas (sin SS) + int game_width_ = 0; // Dimensiones originales del canvas (sin SS) int game_height_ = 0; - int tex_width_ = 0; // Dimensiones de la textura GPU (game × oversample_) + int tex_width_ = 0; // Dimensiones de la textura GPU (game × oversample_) int tex_height_ = 0; - int oversample_ = 1; // Factor SS actual (1 o 3) + int oversample_ = 1; // Factor SS actual (1 o 3) float baked_scanline_strength_ = 0.0F; // Guardado para hornear en CPU bool is_initialized_ = false; bool vsync_ = true; diff --git a/source/core/rendering/shader_backend.hpp b/source/core/rendering/shader_backend.hpp index 1e2e7680..a040f4de 100644 --- a/source/core/rendering/shader_backend.hpp +++ b/source/core/rendering/shader_backend.hpp @@ -11,13 +11,13 @@ namespace Rendering { * Definido a nivel de namespace para facilitar el uso desde subclases y screen.cpp */ struct PostFXParams { - float vignette = 0.0F; // Intensidad de la viñeta - float scanlines = 0.0F; // Intensidad de las scanlines - float chroma = 0.0F; // Aberración cromática - float mask = 0.0F; // Máscara de fósforo RGB - float gamma = 0.0F; // Corrección gamma (blend 0=off, 1=full) - float curvature = 0.0F; // Curvatura barrel CRT - float bleeding = 0.0F; // Sangrado de color NTSC + float vignette = 0.0F; // Intensidad de la viñeta + float scanlines = 0.0F; // Intensidad de las scanlines + float chroma = 0.0F; // Aberración cromática + float mask = 0.0F; // Máscara de fósforo RGB + float gamma = 0.0F; // Corrección gamma (blend 0=off, 1=full) + float curvature = 0.0F; // Curvatura barrel CRT + float bleeding = 0.0F; // Sangrado de color NTSC float flicker = 0.0F; // Parpadeo de fósforo CRT ~50 Hz }; diff --git a/source/core/rendering/surface.cpp b/source/core/rendering/surface.cpp index e3b82779..1a85a2b6 100644 --- a/source/core/rendering/surface.cpp +++ b/source/core/rendering/surface.cpp @@ -104,7 +104,7 @@ Surface::Surface(const std::string& file_path) } // Carga una superficie desde un archivo -auto Surface::loadSurface(const std::string& file_path) -> SurfaceData { +auto Surface::loadSurface(const std::string& file_path) -> SurfaceData { // NOLINT(readability-convert-member-functions-to-static) // Load file using ResourceHelper (supports both filesystem and pack) std::vector buffer = Resource::Helper::loadFile(file_path); if (buffer.empty()) { @@ -148,14 +148,14 @@ void Surface::setColor(int index, Uint32 color) { } // Rellena la superficie con un color -void Surface::clear(Uint8 color) { +void Surface::clear(Uint8 color) { // NOLINT(readability-convert-member-functions-to-static) const size_t TOTAL_PIXELS = surface_data_->width * surface_data_->height; Uint8* data_ptr = surface_data_->data.get(); std::fill(data_ptr, data_ptr + TOTAL_PIXELS, color); } // Pone un pixel en la SurfaceData -void Surface::putPixel(int x, int y, Uint8 color) { +void Surface::putPixel(int x, int y, Uint8 color) { // NOLINT(readability-convert-member-functions-to-static) if (x < 0 || y < 0 || x >= surface_data_->width || y >= surface_data_->height) { return; // Coordenadas fuera de rango } @@ -168,7 +168,7 @@ void Surface::putPixel(int x, int y, Uint8 color) { auto Surface::getPixel(int x, int y) -> Uint8 { return surface_data_->data.get()[x + (y * static_cast(surface_data_->width))]; } // Dibuja un rectangulo relleno -void Surface::fillRect(const SDL_FRect* rect, Uint8 color) { +void Surface::fillRect(const SDL_FRect* rect, Uint8 color) { // NOLINT(readability-convert-member-functions-to-static) // Limitar los valores del rectángulo al tamaño de la superficie float x_start = std::max(0.0F, rect->x); float y_start = std::max(0.0F, rect->y); @@ -185,7 +185,7 @@ void Surface::fillRect(const SDL_FRect* rect, Uint8 color) { } // Dibuja el borde de un rectangulo -void Surface::drawRectBorder(const SDL_FRect* rect, Uint8 color) { +void Surface::drawRectBorder(const SDL_FRect* rect, Uint8 color) { // NOLINT(readability-convert-member-functions-to-static) // Limitar los valores del rectángulo al tamaño de la superficie float x_start = std::max(0.0F, rect->x); float y_start = std::max(0.0F, rect->y); @@ -216,7 +216,7 @@ void Surface::drawRectBorder(const SDL_FRect* rect, Uint8 color) { } // Dibuja una linea -void Surface::drawLine(float x1, float y1, float x2, float y2, Uint8 color) { +void Surface::drawLine(float x1, float y1, float x2, float y2, Uint8 color) { // NOLINT(readability-convert-member-functions-to-static) // Calcula las diferencias float dx = std::abs(x2 - x1); float dy = std::abs(y2 - y1); @@ -250,7 +250,7 @@ void Surface::drawLine(float x1, float y1, float x2, float y2, Uint8 color) { } } -void Surface::render(float dx, float dy, float sx, float sy, float w, float h) { +void Surface::render(float dx, float dy, float sx, float sy, float w, float h) { // NOLINT(readability-make-member-function-const) auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData(); // Limitar la región para evitar accesos fuera de rango en origen @@ -270,7 +270,7 @@ void Surface::render(float dx, float dy, float sx, float sy, float w, float h) { int src_y = sy + iy; Uint8 color = surface_data_->data.get()[static_cast(src_x + (src_y * surface_data_->width))]; - if (color != transparent_color_) { + if (color != static_cast(transparent_color_)) { surface_data->data.get()[static_cast(dest_x + (dest_y * surface_data->width))] = sub_palette_[color]; } } @@ -279,14 +279,14 @@ void Surface::render(float dx, float dy, float sx, float sy, float w, float h) { } } -void Surface::render(int x, int y, SDL_FRect* src_rect, SDL_FlipMode flip) { +void Surface::render(int x, int y, SDL_FRect* src_rect, SDL_FlipMode flip) { // NOLINT(readability-make-member-function-const) auto surface_data_dest = Screen::get()->getRendererSurface()->getSurfaceData(); // Determina la región de origen (clip) a renderizar - float sx = ((src_rect) != nullptr) ? src_rect->x : 0; - float sy = ((src_rect) != nullptr) ? src_rect->y : 0; - float w = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width; - float h = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height; + float sx = (src_rect != nullptr) ? src_rect->x : 0; + float sy = (src_rect != nullptr) ? src_rect->y : 0; + float w = (src_rect != nullptr) ? src_rect->w : surface_data_->width; + float h = (src_rect != nullptr) ? src_rect->h : surface_data_->height; // Limitar la región para evitar accesos fuera de rango en origen w = std::min(w, surface_data_->width - sx); @@ -313,7 +313,7 @@ void Surface::render(int x, int y, SDL_FRect* src_rect, SDL_FlipMode flip) { if (dest_x >= 0 && dest_x < surface_data_dest->width && dest_y >= 0 && dest_y < surface_data_dest->height) { // Copia el píxel si no es transparente Uint8 color = surface_data_->data.get()[static_cast(src_x + (src_y * surface_data_->width))]; - if (color != transparent_color_) { + if (color != static_cast(transparent_color_)) { surface_data_dest->data[dest_x + (dest_y * surface_data_dest->width)] = sub_palette_[color]; } } @@ -334,7 +334,7 @@ void Surface::copyPixelIfNotTransparent(Uint8* dest_data, int dest_x, int dest_y } Uint8 color = surface_data_->data.get()[static_cast(src_x + (src_y * surface_data_->width))]; - if (color != transparent_color_) { + if (color != static_cast(transparent_color_)) { dest_data[dest_x + (dest_y * dest_width)] = sub_palette_[color]; } } @@ -344,16 +344,16 @@ void Surface::render(SDL_FRect* src_rect, SDL_FRect* dst_rect, SDL_FlipMode flip auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData(); // Si srcRect es nullptr, tomar toda la superficie fuente - float sx = ((src_rect) != nullptr) ? src_rect->x : 0; - float sy = ((src_rect) != nullptr) ? src_rect->y : 0; - float sw = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width; - float sh = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height; + float sx = (src_rect != nullptr) ? src_rect->x : 0; + float sy = (src_rect != nullptr) ? src_rect->y : 0; + float sw = (src_rect != nullptr) ? src_rect->w : surface_data_->width; + float sh = (src_rect != nullptr) ? src_rect->h : surface_data_->height; // Si dstRect es nullptr, asignar las mismas dimensiones que srcRect - float dx = ((dst_rect) != nullptr) ? dst_rect->x : 0; - float dy = ((dst_rect) != nullptr) ? dst_rect->y : 0; - float dw = ((dst_rect) != nullptr) ? dst_rect->w : sw; - float dh = ((dst_rect) != nullptr) ? dst_rect->h : sh; + float dx = (dst_rect != nullptr) ? dst_rect->x : 0; + float dy = (dst_rect != nullptr) ? dst_rect->y : 0; + float dw = (dst_rect != nullptr) ? dst_rect->w : sw; + float dh = (dst_rect != nullptr) ? dst_rect->h : sh; // Asegurarse de que srcRect y dstRect tienen las mismas dimensiones if (sw != dw || sh != dh) { @@ -389,14 +389,14 @@ void Surface::render(SDL_FRect* src_rect, SDL_FRect* dst_rect, SDL_FlipMode flip } // Copia una región de la SurfaceData de origen a la SurfaceData de destino reemplazando un color por otro -void Surface::renderWithColorReplace(int x, int y, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect, SDL_FlipMode flip) { +void Surface::renderWithColorReplace(int x, int y, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect, SDL_FlipMode flip) const { auto surface_data = Screen::get()->getRendererSurface()->getSurfaceData(); // Determina la región de origen (clip) a renderizar - float sx = ((src_rect) != nullptr) ? src_rect->x : 0; - float sy = ((src_rect) != nullptr) ? src_rect->y : 0; - float w = ((src_rect) != nullptr) ? src_rect->w : surface_data_->width; - float h = ((src_rect) != nullptr) ? src_rect->h : surface_data_->height; + float sx = (src_rect != nullptr) ? src_rect->x : 0; + float sy = (src_rect != nullptr) ? src_rect->y : 0; + float w = (src_rect != nullptr) ? src_rect->w : surface_data_->width; + float h = (src_rect != nullptr) ? src_rect->h : surface_data_->height; // Limitar la región para evitar accesos fuera de rango w = std::min(w, surface_data_->width - sx); @@ -420,7 +420,7 @@ void Surface::renderWithColorReplace(int x, int y, Uint8 source_color, Uint8 tar // Copia el píxel si no es transparente Uint8 color = surface_data_->data.get()[static_cast(src_x + (src_y * surface_data_->width))]; - if (color != transparent_color_) { + if (color != static_cast(transparent_color_)) { surface_data->data[dest_x + (dest_y * surface_data->width)] = (color == source_color) ? target_color : color; } @@ -449,7 +449,7 @@ static auto computeFadeDensity(int screen_y, int fade_h, int canvas_height) -> f } // Render amb dissolució als cantons superior/inferior (hash 2D, sense parpelleig) -void Surface::renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, SDL_FRect* src_rect) { +void Surface::renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, SDL_FRect* src_rect) const { const int SX = (src_rect != nullptr) ? static_cast(src_rect->x) : 0; const int SY = (src_rect != nullptr) ? static_cast(src_rect->y) : 0; const int SW = (src_rect != nullptr) ? static_cast(src_rect->w) : static_cast(surface_data_->width); @@ -472,7 +472,7 @@ void Surface::renderWithVerticalFade(int x, int y, int fade_h, int canvas_height } const Uint8 COLOR = surface_data_->data[((SY + row) * static_cast(surface_data_->width)) + (SX + col)]; - if (static_cast(COLOR) == transparent_color_) { + if (COLOR == static_cast(transparent_color_)) { continue; } @@ -486,7 +486,7 @@ void Surface::renderWithVerticalFade(int x, int y, int fade_h, int canvas_height } // Idem però reemplaçant un color índex -void Surface::renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect) { +void Surface::renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect) const { const int SX = (src_rect != nullptr) ? static_cast(src_rect->x) : 0; const int SY = (src_rect != nullptr) ? static_cast(src_rect->y) : 0; const int SW = (src_rect != nullptr) ? static_cast(src_rect->w) : static_cast(surface_data_->width); @@ -509,7 +509,7 @@ void Surface::renderWithVerticalFade(int x, int y, int fade_h, int canvas_height } const Uint8 COLOR = surface_data_->data[((SY + row) * static_cast(surface_data_->width)) + (SX + col)]; - if (static_cast(COLOR) == transparent_color_) { + if (COLOR == static_cast(transparent_color_)) { continue; } @@ -524,7 +524,7 @@ void Surface::renderWithVerticalFade(int x, int y, int fade_h, int canvas_height } // Vuelca los píxeles como ARGB8888 a un buffer externo (sin SDL_Texture ni SDL_Renderer) -void Surface::toARGBBuffer(Uint32* buffer) const { +void Surface::toARGBBuffer(Uint32* buffer) const { // NOLINT(readability-convert-member-functions-to-static) if (!surface_data_ || (surface_data_->data == nullptr)) { return; } const int WIDTH = static_cast(surface_data_->width); const int HEIGHT = static_cast(surface_data_->height); @@ -537,7 +537,7 @@ void Surface::toARGBBuffer(Uint32* buffer) const { } // Vuelca la superficie a una textura -void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture) { +void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture) { // NOLINT(readability-convert-member-functions-to-static) if ((renderer == nullptr) || (texture == nullptr) || !surface_data_) { throw std::runtime_error("Renderer or texture is null."); } @@ -576,7 +576,7 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture) { } // Vuelca la superficie a una textura -void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect) { +void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FRect* src_rect, SDL_FRect* dest_rect) { // NOLINT(readability-convert-member-functions-to-static) if ((renderer == nullptr) || (texture == nullptr) || !surface_data_) { throw std::runtime_error("Renderer or texture is null."); } @@ -621,7 +621,7 @@ void Surface::copyToTexture(SDL_Renderer* renderer, SDL_Texture* texture, SDL_FR } // Realiza un efecto de fundido en la paleta principal -auto Surface::fadePalette() -> bool { +auto Surface::fadePalette() -> bool { // NOLINT(readability-convert-member-functions-to-static) // Verificar que el tamaño mínimo de palette_ sea adecuado static constexpr int PALETTE_SIZE = 19; if (sizeof(palette_) / sizeof(palette_[0]) < PALETTE_SIZE) { @@ -641,7 +641,7 @@ auto Surface::fadePalette() -> bool { } // Realiza un efecto de fundido en la paleta secundaria -auto Surface::fadeSubPalette(Uint32 delay) -> bool { +auto Surface::fadeSubPalette(Uint32 delay) -> bool { // NOLINT(readability-convert-member-functions-to-static) // Variable estática para almacenar el último tick static Uint32 last_tick_ = 0; @@ -675,4 +675,4 @@ auto Surface::fadeSubPalette(Uint32 delay) -> bool { } // Restaura la sub paleta a su estado original -void Surface::resetSubPalette() { initializeSubPalette(sub_palette_); } +void Surface::resetSubPalette() { initializeSubPalette(sub_palette_); } // NOLINT(readability-convert-member-functions-to-static) diff --git a/source/core/rendering/surface.hpp b/source/core/rendering/surface.hpp index 0d7634dc..b467a104 100644 --- a/source/core/rendering/surface.hpp +++ b/source/core/rendering/surface.hpp @@ -82,13 +82,13 @@ class Surface { void render(SDL_FRect* src_rect = nullptr, SDL_FRect* dst_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Copia una región de la SurfaceData de origen a la SurfaceData de destino reemplazando un color por otro - void renderWithColorReplace(int x, int y, Uint8 source_color = 0, Uint8 target_color = 0, SDL_FRect* src_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); + void renderWithColorReplace(int x, int y, Uint8 source_color = 0, Uint8 target_color = 0, SDL_FRect* src_rect = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE) const; // Render amb dissolució als cantons superior/inferior (hash 2D, sense parpelleig) - void renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, SDL_FRect* src_rect = nullptr); + void renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, SDL_FRect* src_rect = nullptr) const; // Idem però reemplaçant un color índex (per a sprites sobre fons del mateix color) - void renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect = nullptr); + void renderWithVerticalFade(int x, int y, int fade_h, int canvas_height, Uint8 source_color, Uint8 target_color, SDL_FRect* src_rect = nullptr) const; // Establece un color en la paleta void setColor(int index, Uint32 color); diff --git a/source/core/rendering/surface_animated_sprite.cpp b/source/core/rendering/surface_animated_sprite.cpp index df911da2..0a27e0ba 100644 --- a/source/core/rendering/surface_animated_sprite.cpp +++ b/source/core/rendering/surface_animated_sprite.cpp @@ -16,7 +16,7 @@ // Helper: Convierte un nodo YAML de frames (array) a vector de SDL_FRect auto convertYAMLFramesToRects(const fkyaml::node& frames_node, float frame_width, float frame_height, int frames_per_row, int max_tiles) -> std::vector { std::vector frames; - SDL_FRect rect = {0.0F, 0.0F, frame_width, frame_height}; + SDL_FRect rect = {.x = 0.0F, .y = 0.0F, .w = frame_width, .h = frame_height}; for (const auto& frame_index_node : frames_node) { const int NUM_TILE = frame_index_node.get_value(); @@ -31,7 +31,7 @@ auto convertYAMLFramesToRects(const fkyaml::node& frames_node, float frame_width } // Carga las animaciones desde un fichero YAML -auto SurfaceAnimatedSprite::loadAnimationsFromYAML(const std::string& file_path, std::shared_ptr& surface, float& frame_width, float& frame_height) -> std::vector { +auto SurfaceAnimatedSprite::loadAnimationsFromYAML(const std::string& file_path, std::shared_ptr& surface, float& frame_width, float& frame_height) -> std::vector { // NOLINT(readability-convert-member-functions-to-static) std::vector animations; // Extract filename for logging @@ -224,7 +224,7 @@ SurfaceAnimatedSprite::SurfaceAnimatedSprite(std::shared_ptr surface, S } // Obtiene el indice de la animación a partir del nombre -auto SurfaceAnimatedSprite::getIndex(const std::string& name) -> int { +auto SurfaceAnimatedSprite::getIndex(const std::string& name) -> int { // NOLINT(readability-convert-member-functions-to-static) auto index = -1; for (const auto& a : animations_) { @@ -238,7 +238,7 @@ auto SurfaceAnimatedSprite::getIndex(const std::string& name) -> int { } // Calcula el frame correspondiente a la animación (time-based) -void SurfaceAnimatedSprite::animate(float delta_time) { +void SurfaceAnimatedSprite::animate(float delta_time) { // NOLINT(readability-convert-member-functions-to-static) if (animations_.empty()) { return; } if (animations_[current_animation_].speed <= 0.0F) { return; diff --git a/source/core/rendering/surface_dissolve_sprite.hpp b/source/core/rendering/surface_dissolve_sprite.hpp index 7dda0707..1f01ac26 100644 --- a/source/core/rendering/surface_dissolve_sprite.hpp +++ b/source/core/rendering/surface_dissolve_sprite.hpp @@ -52,7 +52,7 @@ class SurfaceDissolveSprite : public SurfaceAnimatedSprite { TransitionMode transition_mode_{TransitionMode::NONE}; float transition_duration_{0.0F}; float transition_elapsed_{0.0F}; - SDL_FRect prev_clip_{0, 0, 0, 0}; + SDL_FRect prev_clip_{.x = 0, .y = 0, .w = 0, .h = 0}; bool needs_rebuild_{false}; Uint8 source_color_{255}; // 255 = transparent = sense replace per defecte Uint8 target_color_{0}; diff --git a/source/core/rendering/surface_sprite.cpp b/source/core/rendering/surface_sprite.cpp index 5a94f3dc..2f3f88d2 100644 --- a/source/core/rendering/surface_sprite.cpp +++ b/source/core/rendering/surface_sprite.cpp @@ -7,13 +7,13 @@ // Constructor SurfaceSprite::SurfaceSprite(std::shared_ptr surface, float x, float y, float w, float h) : surface_(std::move(surface)), - pos_{x, y, w, h}, - clip_{0.0F, 0.0F, pos_.w, pos_.h} {} + pos_{.x = x, .y = y, .w = w, .h = h}, + clip_{.x = 0.0F, .y = 0.0F, .w = pos_.w, .h = pos_.h} {} SurfaceSprite::SurfaceSprite(std::shared_ptr surface, SDL_FRect rect) : surface_(std::move(surface)), pos_(rect), - clip_{0.0F, 0.0F, pos_.w, pos_.h} {} + clip_{.x = 0.0F, .y = 0.0F, .w = pos_.w, .h = pos_.h} {} SurfaceSprite::SurfaceSprite() = default; diff --git a/source/core/rendering/surface_sprite.hpp b/source/core/rendering/surface_sprite.hpp index 90beb6e6..a672f86b 100644 --- a/source/core/rendering/surface_sprite.hpp +++ b/source/core/rendering/surface_sprite.hpp @@ -51,12 +51,12 @@ class SurfaceSprite { // Modificación de clip y surface void setClip(SDL_FRect rect) { clip_ = rect; } - void setClip(float x, float y, float w, float h) { clip_ = SDL_FRect{x, y, w, h}; } + void setClip(float x, float y, float w, float h) { clip_ = SDL_FRect{.x = x, .y = y, .w = w, .h = h}; } void setSurface(std::shared_ptr surface) { surface_ = std::move(surface); } protected: // Variables miembro std::shared_ptr surface_{nullptr}; // Surface donde estan todos los dibujos del sprite - SDL_FRect pos_{0.0F, 0.0F, 0.0F, 0.0F}; // Posición y tamaño donde dibujar el sprite - SDL_FRect clip_{0.0F, 0.0F, 0.0F, 0.0F}; // Rectangulo de origen de la surface que se dibujará en pantalla + SDL_FRect pos_{.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F}; // Posición y tamaño donde dibujar el sprite + SDL_FRect clip_{.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F}; // Rectangulo de origen de la surface que se dibujará en pantalla }; \ No newline at end of file diff --git a/source/core/rendering/text.cpp b/source/core/rendering/text.cpp index ed52509e..90278001 100644 --- a/source/core/rendering/text.cpp +++ b/source/core/rendering/text.cpp @@ -14,17 +14,31 @@ #include "utils/utils.hpp" // Para getFileName, stringToColor, printWithDots // Extrae el siguiente codepoint UTF-8 de la cadena, avanzando 'pos' al byte siguiente -auto Text::nextCodepoint(const std::string& s, size_t& pos) -> uint32_t { +auto Text::nextCodepoint(const std::string& s, size_t& pos) -> uint32_t { // NOLINT(readability-convert-member-functions-to-static) auto c = static_cast(s[pos]); uint32_t cp = 0; size_t extra = 0; - if (c < 0x80) { cp = c; extra = 0; } - else if (c < 0xC0) { pos++; return 0xFFFD; } // byte de continuación suelto - else if (c < 0xE0) { cp = c & 0x1F; extra = 1; } - else if (c < 0xF0) { cp = c & 0x0F; extra = 2; } - else if (c < 0xF8) { cp = c & 0x07; extra = 3; } - else { pos++; return 0xFFFD; } + if (c < 0x80) { + cp = c; + extra = 0; + } else if (c < 0xC0) { + pos++; + return 0xFFFD; + } // byte de continuación suelto + else if (c < 0xE0) { + cp = c & 0x1F; + extra = 1; + } else if (c < 0xF0) { + cp = c & 0x0F; + extra = 2; + } else if (c < 0xF8) { + cp = c & 0x07; + extra = 3; + } else { + pos++; + return 0xFFFD; + } pos++; for (size_t i = 0; i < extra && pos < s.size(); ++i, ++pos) { @@ -36,7 +50,7 @@ auto Text::nextCodepoint(const std::string& s, size_t& pos) -> uint32_t { } // Convierte un codepoint Unicode a una cadena UTF-8 -auto Text::codepointToUtf8(uint32_t cp) -> std::string { +auto Text::codepointToUtf8(uint32_t cp) -> std::string { // NOLINT(readability-convert-member-functions-to-static) std::string result; if (cp < 0x80) { result += static_cast(cp); @@ -58,7 +72,7 @@ auto Text::codepointToUtf8(uint32_t cp) -> std::string { // Carga un fichero de definición de fuente .fnt // Formato: líneas "clave valor", comentarios con #, gliphos como "codepoint ancho" -auto Text::loadTextFile(const std::string& file_path) -> std::shared_ptr { +auto Text::loadTextFile(const std::string& file_path) -> std::shared_ptr { // NOLINT(readability-convert-member-functions-to-static) auto tf = std::make_shared(); auto file_data = Resource::Helper::loadFile(file_path); @@ -101,9 +115,9 @@ auto Text::loadTextFile(const std::string& file_path) -> std::shared_ptr { continue; // línea mal formateada, ignorar } Offset off{}; - const int row_sp = tf->row_spacing > 0 ? tf->row_spacing : tf->cell_spacing; - off.x = (glyph_index % tf->columns) * (tf->box_width + tf->cell_spacing) + tf->cell_spacing; - off.y = (glyph_index / tf->columns) * (tf->box_height + row_sp) + tf->cell_spacing; + const int ROW_SP = tf->row_spacing > 0 ? tf->row_spacing : tf->cell_spacing; + off.x = ((glyph_index % tf->columns) * (tf->box_width + tf->cell_spacing)) + tf->cell_spacing; + off.y = ((glyph_index / tf->columns) * (tf->box_height + ROW_SP)) + tf->cell_spacing; off.w = width; tf->offset[codepoint] = off; ++glyph_index; @@ -122,19 +136,19 @@ Text::Text(const std::shared_ptr& surface, const std::string& text_file box_width_ = tf->box_width; offset_ = tf->offset; - sprite_ = std::make_unique(surface, (SDL_FRect){0.0F, 0.0F, static_cast(box_width_), static_cast(box_height_)}); + sprite_ = std::make_unique(surface, SDL_FRect{.x = 0.0F, .y = 0.0F, .w = static_cast(box_width_), .h = static_cast(box_height_)}); } // Constructor desde estructura precargada Text::Text(const std::shared_ptr& surface, const std::shared_ptr& text_file) - : sprite_(std::make_unique(surface, (SDL_FRect){0.0F, 0.0F, static_cast(text_file->box_width), static_cast(text_file->box_height)})), + : sprite_(std::make_unique(surface, SDL_FRect{.x = 0.0F, .y = 0.0F, .w = static_cast(text_file->box_width), .h = static_cast(text_file->box_height)})), box_width_(text_file->box_width), box_height_(text_file->box_height), offset_(text_file->offset) { } // Escribe texto en pantalla -void Text::write(int x, int y, const std::string& text, int kerning, int lenght) { +void Text::write(int x, int y, const std::string& text, int kerning, int lenght) { // NOLINT(readability-convert-member-functions-to-static) int shift = 0; int glyphs_done = 0; size_t pos = 0; @@ -156,7 +170,7 @@ void Text::write(int x, int y, const std::string& text, int kerning, int lenght) } // Escribe el texto en una surface -auto Text::writeToSurface(const std::string& text, int zoom, int kerning) -> std::shared_ptr { +auto Text::writeToSurface(const std::string& text, int zoom, int kerning) -> std::shared_ptr { // NOLINT(readability-make-member-function-const) auto width = length(text, kerning) * zoom; auto height = box_height_ * zoom; auto surface = std::make_shared(width, height); @@ -170,7 +184,7 @@ auto Text::writeToSurface(const std::string& text, int zoom, int kerning) -> std } // Escribe el texto con extras en una surface -auto Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) -> std::shared_ptr { +auto Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) -> std::shared_ptr { // NOLINT(readability-make-member-function-const) auto width = Text::length(text, kerning) + shadow_distance; auto height = box_height_ + shadow_distance; auto surface = std::make_shared(width, height); @@ -184,7 +198,7 @@ auto Text::writeDXToSurface(Uint8 flags, const std::string& text, int kerning, U } // Escribe el texto con colores -void Text::writeColored(int x, int y, const std::string& text, Uint8 color, int kerning, int lenght) { +void Text::writeColored(int x, int y, const std::string& text, Uint8 color, int kerning, int lenght) { // NOLINT(readability-convert-member-functions-to-static) int shift = 0; int glyphs_done = 0; size_t pos = 0; @@ -218,11 +232,11 @@ void Text::writeCentered(int x, int y, const std::string& text, int kerning, int } // Escribe texto con extras -void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) { +void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning, Uint8 text_color, Uint8 shadow_distance, Uint8 shadow_color, int lenght) { // NOLINT(readability-convert-member-functions-to-static) const auto CENTERED = ((flags & CENTER_FLAG) == CENTER_FLAG); const auto SHADOWED = ((flags & SHADOW_FLAG) == SHADOW_FLAG); - const auto COLORED = ((flags & COLOR_FLAG) == COLOR_FLAG); - const auto STROKED = ((flags & STROKE_FLAG) == STROKE_FLAG); + const auto COLORED = ((flags & COLOR_FLAG) == COLOR_FLAG); + const auto STROKED = ((flags & STROKE_FLAG) == STROKE_FLAG); if (CENTERED) { x -= (Text::length(text, kerning) / 2); @@ -233,7 +247,8 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerni } if (STROKED) { - for (int dist = 1; dist <= shadow_distance; ++dist) { + const int MAX_DIST = static_cast(shadow_distance); + for (int dist = 1; dist <= MAX_DIST; ++dist) { for (int dy = -dist; dy <= dist; ++dy) { for (int dx = -dist; dx <= dist; ++dx) { writeColored(x + dx, y + dy, text, shadow_color, kerning, lenght); @@ -250,7 +265,7 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string& text, int kerni } // Obtiene la longitud en pixels de una cadena UTF-8 -auto Text::length(const std::string& text, int kerning) const -> int { +auto Text::length(const std::string& text, int kerning) const -> int { // NOLINT(readability-convert-member-functions-to-static) int shift = 0; size_t pos = 0; @@ -267,7 +282,7 @@ auto Text::length(const std::string& text, int kerning) const -> int { } // Devuelve el ancho en pixels de un glifo dado su codepoint Unicode -auto Text::glyphWidth(uint32_t codepoint, int kerning) const -> int { +auto Text::glyphWidth(uint32_t codepoint, int kerning) const -> int { // NOLINT(readability-convert-member-functions-to-static) auto it = offset_.find(codepoint); if (it == offset_.end()) { it = offset_.find('?'); } if (it != offset_.end()) { return it->second.w + kerning; } @@ -280,9 +295,9 @@ auto Text::getGlyphClip(uint32_t codepoint) const -> SDL_FRect { if (it == offset_.end()) { it = offset_.find('?'); } if (it == offset_.end()) { return {.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F}; } return {.x = static_cast(it->second.x), - .y = static_cast(it->second.y), - .w = static_cast(box_width_), - .h = static_cast(box_height_)}; + .y = static_cast(it->second.y), + .w = static_cast(box_width_), + .h = static_cast(box_height_)}; } // Devuelve el tamaño de la caja de cada caracter diff --git a/source/core/rendering/text.hpp b/source/core/rendering/text.hpp index b0900a44..408555ea 100644 --- a/source/core/rendering/text.hpp +++ b/source/core/rendering/text.hpp @@ -2,9 +2,9 @@ #include -#include // Para shared_ptr, unique_ptr -#include // Para string -#include // Para unordered_map +#include // Para shared_ptr, unique_ptr +#include // Para string +#include // Para unordered_map #include "core/rendering/surface_sprite.hpp" // Para SSprite class Surface; // Forward declaration @@ -18,11 +18,11 @@ class Text { }; struct File { - int box_width{0}; // Anchura de la caja de cada caracter en el png - int box_height{0}; // Altura de la caja de cada caracter en el png - int columns{16}; // Número de columnas en el bitmap - int cell_spacing{0}; // Píxeles de separación entre columnas (y borde izquierdo/superior) - int row_spacing{0}; // Píxeles de separación entre filas (si difiere de cell_spacing) + int box_width{0}; // Anchura de la caja de cada caracter en el png + int box_height{0}; // Altura de la caja de cada caracter en el png + int columns{16}; // Número de columnas en el bitmap + int cell_spacing{0}; // Píxeles de separación entre columnas (y borde izquierdo/superior) + int row_spacing{0}; // Píxeles de separación entre filas (si difiere de cell_spacing) std::unordered_map offset; // Posición y ancho de cada glifo (clave: codepoint Unicode) }; @@ -48,11 +48,11 @@ class Text { auto writeToSurface(const std::string& text, int zoom = 1, int kerning = 1) -> std::shared_ptr; // Escribe el texto en una textura auto writeDXToSurface(Uint8 flags, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1) -> std::shared_ptr; // Escribe el texto con extras en una textura - [[nodiscard]] auto length(const std::string& text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena - [[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño del caracter - [[nodiscard]] auto glyphWidth(uint32_t codepoint, int kerning = 0) const -> int; // Devuelve el ancho en pixels de un glifo - [[nodiscard]] auto getGlyphClip(uint32_t codepoint) const -> SDL_FRect; // Devuelve el clip rect del glifo - [[nodiscard]] auto getSprite() const -> SurfaceSprite* { return sprite_.get(); } // Acceso al sprite interno + [[nodiscard]] auto length(const std::string& text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena + [[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño del caracter + [[nodiscard]] auto glyphWidth(uint32_t codepoint, int kerning = 0) const -> int; // Devuelve el ancho en pixels de un glifo + [[nodiscard]] auto getGlyphClip(uint32_t codepoint) const -> SDL_FRect; // Devuelve el clip rect del glifo + [[nodiscard]] auto getSprite() const -> SurfaceSprite* { return sprite_.get(); } // Acceso al sprite interno void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra @@ -65,8 +65,8 @@ class Text { std::unique_ptr sprite_ = nullptr; // Objeto con los graficos para el texto // Variables - int box_width_ = 0; // Anchura de la caja de cada caracter en el png - int box_height_ = 0; // Altura de la caja de cada caracter en el png - bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija - std::unordered_map offset_; // Posición y ancho de cada glifo (clave: codepoint Unicode) + int box_width_ = 0; // Anchura de la caja de cada caracter en el png + int box_height_ = 0; // Altura de la caja de cada caracter en el png + bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija + std::unordered_map offset_; // Posición y ancho de cada glifo (clave: codepoint Unicode) }; diff --git a/source/core/rendering/texture.cpp b/source/core/rendering/texture.cpp index da2dd1cf..dfaebe23 100644 --- a/source/core/rendering/texture.cpp +++ b/source/core/rendering/texture.cpp @@ -128,7 +128,7 @@ void Texture::setAlpha(Uint8 alpha) { SDL_SetTextureAlphaMod(texture_, alpha); } // Renderiza la textura en un punto específico void Texture::render(float x, float y, SDL_FRect* clip, float zoom_w, float zoom_h, double angle, SDL_FPoint* center, SDL_FlipMode flip) { // Establece el destino de renderizado en la pantalla - SDL_FRect render_quad = {x, y, width_, height_}; + SDL_FRect render_quad = {.x = x, .y = y, .w = width_, .h = height_}; // Obtiene las dimesiones del clip de renderizado if (clip != nullptr) { diff --git a/source/core/resources/resource_cache.cpp b/source/core/resources/resource_cache.cpp index 6b750ed2..08979d3e 100644 --- a/source/core/resources/resource_cache.cpp +++ b/source/core/resources/resource_cache.cpp @@ -76,8 +76,8 @@ namespace Resource { } // Obtiene el sonido a partir de un nombre - auto Cache::getSound(const std::string& name) -> JA_Sound_t* { - auto it = std::ranges::find_if(sounds_, [&name](const auto& s) { return s.name == name; }); + auto Cache::getSound(const std::string& name) -> JA_Sound_t* { // NOLINT(readability-convert-member-functions-to-static) + auto it = std::ranges::find_if(sounds_, [&name](const auto& s) -> bool { return s.name == name; }); if (it != sounds_.end()) { return it->sound; @@ -88,8 +88,8 @@ namespace Resource { } // Obtiene la música a partir de un nombre - auto Cache::getMusic(const std::string& name) -> JA_Music_t* { - auto it = std::ranges::find_if(musics_, [&name](const auto& m) { return m.name == name; }); + auto Cache::getMusic(const std::string& name) -> JA_Music_t* { // NOLINT(readability-convert-member-functions-to-static) + auto it = std::ranges::find_if(musics_, [&name](const auto& m) -> bool { return m.name == name; }); if (it != musics_.end()) { return it->music; @@ -100,8 +100,8 @@ namespace Resource { } // Obtiene la surface a partir de un nombre - auto Cache::getSurface(const std::string& name) -> std::shared_ptr { - auto it = std::ranges::find_if(surfaces_, [&name](const auto& t) { return t.name == name; }); + auto Cache::getSurface(const std::string& name) -> std::shared_ptr { // NOLINT(readability-convert-member-functions-to-static) + auto it = std::ranges::find_if(surfaces_, [&name](const auto& t) -> bool { return t.name == name; }); if (it != surfaces_.end()) { return it->surface; @@ -112,8 +112,8 @@ namespace Resource { } // Obtiene la paleta a partir de un nombre - auto Cache::getPalette(const std::string& name) -> Palette { - auto it = std::ranges::find_if(palettes_, [&name](const auto& t) { return t.name == name; }); + auto Cache::getPalette(const std::string& name) -> Palette { // NOLINT(readability-convert-member-functions-to-static) + auto it = std::ranges::find_if(palettes_, [&name](const auto& t) -> bool { return t.name == name; }); if (it != palettes_.end()) { return it->palette; @@ -124,8 +124,8 @@ namespace Resource { } // Obtiene el fichero de texto a partir de un nombre - auto Cache::getTextFile(const std::string& name) -> std::shared_ptr { - auto it = std::ranges::find_if(text_files_, [&name](const auto& t) { return t.name == name; }); + auto Cache::getTextFile(const std::string& name) -> std::shared_ptr { // NOLINT(readability-convert-member-functions-to-static) + auto it = std::ranges::find_if(text_files_, [&name](const auto& t) -> bool { return t.name == name; }); if (it != text_files_.end()) { return it->text_file; @@ -136,8 +136,8 @@ namespace Resource { } // Obtiene el objeto de texto a partir de un nombre - auto Cache::getText(const std::string& name) -> std::shared_ptr { - auto it = std::ranges::find_if(texts_, [&name](const auto& t) { return t.name == name; }); + auto Cache::getText(const std::string& name) -> std::shared_ptr { // NOLINT(readability-convert-member-functions-to-static) + auto it = std::ranges::find_if(texts_, [&name](const auto& t) -> bool { return t.name == name; }); if (it != texts_.end()) { return it->text; @@ -148,8 +148,8 @@ namespace Resource { } // Obtiene los datos de animación parseados a partir de un nombre - auto Cache::getAnimationData(const std::string& name) -> const AnimationResource& { - auto it = std::ranges::find_if(animations_, [&name](const auto& a) { return a.name == name; }); + auto Cache::getAnimationData(const std::string& name) -> const AnimationResource& { // NOLINT(readability-convert-member-functions-to-static) + auto it = std::ranges::find_if(animations_, [&name](const auto& a) -> bool { return a.name == name; }); if (it != animations_.end()) { return *it; @@ -160,8 +160,8 @@ namespace Resource { } // Obtiene la habitación a partir de un nombre - auto Cache::getRoom(const std::string& name) -> std::shared_ptr { - auto it = std::ranges::find_if(rooms_, [&name](const auto& r) { return r.name == name; }); + auto Cache::getRoom(const std::string& name) -> std::shared_ptr { // NOLINT(readability-convert-member-functions-to-static) + auto it = std::ranges::find_if(rooms_, [&name](const auto& r) -> bool { return r.name == name; }); if (it != rooms_.end()) { return it->room; @@ -177,7 +177,7 @@ namespace Resource { } // Helper para lanzar errores de carga con formato consistente - [[noreturn]] void Cache::throwLoadError(const std::string& asset_type, const std::string& file_path, const std::exception& e) { + [[noreturn]] void Cache::throwLoadError(const std::string& asset_type, const std::string& file_path, const std::exception& e) { // NOLINT(readability-convert-member-functions-to-static) std::cerr << "\n[ ERROR ] Failed to load " << asset_type << ": " << getFileName(file_path) << '\n'; std::cerr << "[ ERROR ] Path: " << file_path << '\n'; std::cerr << "[ ERROR ] Reason: " << e.what() << '\n'; @@ -186,7 +186,7 @@ namespace Resource { } // Carga los sonidos - void Cache::loadSounds() { + void Cache::loadSounds() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> SOUND FILES" << '\n'; auto list = List::get()->getListByType(List::Type::SOUND); sounds_.clear(); @@ -221,7 +221,7 @@ namespace Resource { } // Carga las musicas - void Cache::loadMusics() { + void Cache::loadMusics() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> MUSIC FILES" << '\n'; auto list = List::get()->getListByType(List::Type::MUSIC); musics_.clear(); @@ -256,7 +256,7 @@ namespace Resource { } // Carga las texturas - void Cache::loadSurfaces() { + void Cache::loadSurfaces() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> SURFACES" << '\n'; auto list = List::get()->getListByType(List::Type::BITMAP); surfaces_.clear(); @@ -283,7 +283,7 @@ namespace Resource { } // Carga las paletas - void Cache::loadPalettes() { + void Cache::loadPalettes() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> PALETTES" << '\n'; auto list = List::get()->getListByType(List::Type::PALETTE); palettes_.clear(); @@ -300,7 +300,7 @@ namespace Resource { } // Carga los ficheros de texto - void Cache::loadTextFiles() { + void Cache::loadTextFiles() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> TEXT FILES" << '\n'; auto list = List::get()->getListByType(List::Type::FONT); text_files_.clear(); @@ -317,7 +317,7 @@ namespace Resource { } // Carga las animaciones - void Cache::loadAnimations() { + void Cache::loadAnimations() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> ANIMATIONS" << '\n'; auto list = List::get()->getListByType(List::Type::ANIMATION); animations_.clear(); @@ -343,7 +343,7 @@ namespace Resource { } // Carga las habitaciones desde archivos YAML - void Cache::loadRooms() { + void Cache::loadRooms() { // NOLINT(readability-convert-member-functions-to-static) std::cout << "\n>> ROOMS" << '\n'; auto list = List::get()->getListByType(List::Type::ROOM); rooms_.clear(); @@ -360,7 +360,7 @@ namespace Resource { } } - void Cache::createText() { + void Cache::createText() { // NOLINT(readability-convert-member-functions-to-static) struct ResourceInfo { std::string key; // Identificador del recurso std::string texture_file; // Nombre del archivo de textura @@ -461,12 +461,12 @@ namespace Resource { // Draw progress bar border const float WIRED_BAR_WIDTH = Options::game.width - (X_PADDING * 2); - SDL_FRect rect_wired = {X_PADDING, BAR_POSITION, WIRED_BAR_WIDTH, BAR_HEIGHT}; + SDL_FRect rect_wired = {.x = X_PADDING, .y = BAR_POSITION, .w = WIRED_BAR_WIDTH, .h = BAR_HEIGHT}; surface->drawRectBorder(&rect_wired, BAR_COLOR); // Draw progress bar fill const float FULL_BAR_WIDTH = WIRED_BAR_WIDTH * count_.getPercentage(); - SDL_FRect rect_full = {X_PADDING, BAR_POSITION, FULL_BAR_WIDTH, BAR_HEIGHT}; + SDL_FRect rect_full = {.x = X_PADDING, .y = BAR_POSITION, .w = FULL_BAR_WIDTH, .h = BAR_HEIGHT}; surface->fillRect(&rect_full, BAR_COLOR); Screen::get()->render(); diff --git a/source/core/resources/resource_list.cpp b/source/core/resources/resource_list.cpp index 76fddcab..a1416760 100644 --- a/source/core/resources/resource_list.cpp +++ b/source/core/resources/resource_list.cpp @@ -19,11 +19,11 @@ namespace Resource { // Singleton List* List::instance = nullptr; - void List::init(const std::string& executable_path) { + void List::init(const std::string& executable_path) { // NOLINT(readability-convert-member-functions-to-static) List::instance = new List(executable_path); } - void List::destroy() { + void List::destroy() { // NOLINT(readability-convert-member-functions-to-static) delete List::instance; } @@ -32,12 +32,12 @@ namespace Resource { } // Añade un elemento al mapa (función auxiliar) - void List::addToMap(const std::string& file_path, Type type, bool required, bool absolute) { + void List::addToMap(const std::string& file_path, Type type, bool required, bool absolute) { // NOLINT(readability-convert-member-functions-to-static) std::string full_path = absolute ? file_path : executable_path_ + file_path; std::string filename = getFileName(full_path); // Verificar si ya existe el archivo - if (file_list_.find(filename) != file_list_.end()) { + if (file_list_.contains(filename)) { SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: Asset '%s' already exists, overwriting", filename.c_str()); @@ -52,7 +52,7 @@ namespace Resource { } // Carga recursos desde un archivo de configuración con soporte para variables - void List::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) { + void List::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) { // NOLINT(readability-convert-member-functions-to-static) std::ifstream file(config_file_path); if (!file.is_open()) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, @@ -71,7 +71,7 @@ namespace Resource { } // Carga recursos desde un string de configuración (para release con pack) - void List::loadFromString(const std::string& config_content, const std::string& prefix, const std::string& system_folder) { + void List::loadFromString(const std::string& config_content, const std::string& prefix, const std::string& system_folder) { // NOLINT(readability-convert-member-functions-to-static) try { // Parsear YAML auto yaml = fkyaml::node::deserialize(config_content); @@ -156,7 +156,7 @@ namespace Resource { } // Devuelve la ruta completa a un fichero (búsqueda O(1)) - auto List::get(const std::string& filename) const -> std::string { + auto List::get(const std::string& filename) const -> std::string { // NOLINT(readability-convert-member-functions-to-static) auto it = file_list_.find(filename); if (it != file_list_.end()) { return it->second.file; @@ -167,7 +167,7 @@ namespace Resource { } // Carga datos del archivo - auto List::loadData(const std::string& filename) const -> std::vector { + auto List::loadData(const std::string& filename) const -> std::vector { // NOLINT(readability-convert-member-functions-to-static) auto it = file_list_.find(filename); if (it != file_list_.end()) { std::ifstream file(it->second.file, std::ios::binary); @@ -197,11 +197,11 @@ namespace Resource { // Verifica si un recurso existe auto List::exists(const std::string& filename) const -> bool { - return file_list_.find(filename) != file_list_.end(); + return file_list_.contains(filename); } // Parsea string a Type - auto List::parseAssetType(const std::string& type_str) -> Type { + auto List::parseAssetType(const std::string& type_str) -> Type { // NOLINT(readability-convert-member-functions-to-static) if (type_str == "DATA") { return Type::DATA; } @@ -235,7 +235,7 @@ namespace Resource { } // Devuelve el nombre del tipo de recurso - auto List::getTypeName(Type type) -> std::string { + auto List::getTypeName(Type type) -> std::string { // NOLINT(readability-convert-member-functions-to-static) switch (type) { case Type::DATA: return "DATA"; @@ -259,7 +259,7 @@ namespace Resource { } // Devuelve la lista de recursos de un tipo - auto List::getListByType(Type type) const -> std::vector { + auto List::getListByType(Type type) const -> std::vector { // NOLINT(readability-convert-member-functions-to-static) std::vector list; for (const auto& [filename, item] : file_list_) { @@ -275,7 +275,7 @@ namespace Resource { } // Reemplaza variables en las rutas - auto List::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string { + auto List::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string { // NOLINT(readability-convert-member-functions-to-static) std::string result = path; // Reemplazar ${PREFIX} @@ -296,7 +296,7 @@ namespace Resource { } // Parsea las opciones de una línea de configuración - auto List::parseOptions(const std::string& options, bool& required, bool& absolute) -> void { + auto List::parseOptions(const std::string& options, bool& required, bool& absolute) -> void { // NOLINT(readability-convert-member-functions-to-static) if (options.empty()) { return; } diff --git a/source/core/resources/resource_loader.cpp b/source/core/resources/resource_loader.cpp index 3b30fcf3..75c894d8 100644 --- a/source/core/resources/resource_loader.cpp +++ b/source/core/resources/resource_loader.cpp @@ -53,7 +53,7 @@ namespace Resource { } // Load a resource - auto Loader::loadResource(const std::string& filename) -> std::vector { + auto Loader::loadResource(const std::string& filename) -> std::vector { // NOLINT(readability-make-member-function-const) if (!initialized_) { std::cerr << "Loader: Not initialized\n"; return {}; @@ -81,7 +81,7 @@ namespace Resource { } // Check if a resource exists - auto Loader::resourceExists(const std::string& filename) -> bool { + auto Loader::resourceExists(const std::string& filename) -> bool { // NOLINT(readability-make-member-function-const) if (!initialized_) { return false; } @@ -107,7 +107,7 @@ namespace Resource { } // Get pack statistics - auto Loader::getPackResourceCount() const -> size_t { + auto Loader::getPackResourceCount() const -> size_t { // NOLINT(readability-convert-member-functions-to-static) if (resource_pack_ && resource_pack_->isLoaded()) { return resource_pack_->getResourceCount(); } @@ -122,7 +122,7 @@ namespace Resource { } // Load from filesystem - auto Loader::loadFromFilesystem(const std::string& filepath) + auto Loader::loadFromFilesystem(const std::string& filepath) // NOLINT(readability-convert-member-functions-to-static) -> std::vector { std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { @@ -147,7 +147,7 @@ namespace Resource { } // Validate pack integrity - auto Loader::validatePack() const -> bool { + auto Loader::validatePack() const -> bool { // NOLINT(readability-convert-member-functions-to-static) if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) { std::cerr << "Loader: Cannot validate - pack not loaded\n"; return false; @@ -158,7 +158,7 @@ namespace Resource { if (checksum == 0) { std::cerr << "Loader: Pack checksum is zero (invalid)\n"; - return false; + return false; // NOLINT(readability-simplify-boolean-expr) } std::cout << "Loader: Pack checksum: 0x" << std::hex << checksum << std::dec @@ -168,7 +168,7 @@ namespace Resource { } // Load assets.yaml from pack - auto Loader::loadAssetsConfig() const -> std::string { + auto Loader::loadAssetsConfig() const -> std::string { // NOLINT(readability-convert-member-functions-to-static) if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) { std::cerr << "Loader: Cannot load assets config - pack not loaded\n"; return ""; diff --git a/source/core/resources/resource_pack.cpp b/source/core/resources/resource_pack.cpp index 5b86a5cb..907ddb58 100644 --- a/source/core/resources/resource_pack.cpp +++ b/source/core/resources/resource_pack.cpp @@ -13,7 +13,7 @@ namespace Resource { // Calculate CRC32 checksum for data verification - auto Pack::calculateChecksum(const std::vector& data) -> uint32_t { + auto Pack::calculateChecksum(const std::vector& data) -> uint32_t { // NOLINT(readability-convert-member-functions-to-static) uint32_t checksum = 0x12345678; for (unsigned char byte : data) { checksum = ((checksum << 5) + checksum) + byte; @@ -22,7 +22,7 @@ namespace Resource { } // XOR encryption (symmetric - same function for encrypt/decrypt) - void Pack::encryptData(std::vector& data, const std::string& key) { + void Pack::encryptData(std::vector& data, const std::string& key) { // NOLINT(readability-identifier-naming) if (key.empty()) { return; } @@ -31,13 +31,13 @@ namespace Resource { } } - void Pack::decryptData(std::vector& data, const std::string& key) { + void Pack::decryptData(std::vector& data, const std::string& key) { // NOLINT(readability-identifier-naming) // XOR is symmetric encryptData(data, key); } // Read entire file into memory - auto Pack::readFile(const std::string& filepath) -> std::vector { + auto Pack::readFile(const std::string& filepath) -> std::vector { // NOLINT(readability-convert-member-functions-to-static) std::ifstream file(filepath, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "ResourcePack: Failed to open file: " << filepath << '\n'; @@ -57,7 +57,7 @@ namespace Resource { } // Add a single file to the pack - auto Pack::addFile(const std::string& filepath, const std::string& pack_name) + auto Pack::addFile(const std::string& filepath, const std::string& pack_name) // NOLINT(readability-convert-member-functions-to-static) -> bool { auto file_data = readFile(filepath); if (file_data.empty()) { @@ -80,9 +80,9 @@ namespace Resource { } // Add all files from a directory recursively - auto Pack::addDirectory(const std::string& dir_path, + auto Pack::addDirectory(const std::string& dir_path, // NOLINT(readability-convert-member-functions-to-static) const std::string& base_path) -> bool { - namespace fs = std::filesystem; + namespace fs = std::filesystem; // NOLINT(readability-identifier-naming) if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) { std::cerr << "ResourcePack: Directory not found: " << dir_path << '\n'; @@ -117,7 +117,7 @@ namespace Resource { } // Save the pack to a file - auto Pack::savePack(const std::string& pack_file) -> bool { + auto Pack::savePack(const std::string& pack_file) -> bool { // NOLINT(readability-convert-member-functions-to-static) std::ofstream file(pack_file, std::ios::binary); if (!file) { std::cerr << "ResourcePack: Failed to create pack file: " << pack_file << '\n'; @@ -229,7 +229,7 @@ namespace Resource { } // Get a resource by name - auto Pack::getResource(const std::string& filename) -> std::vector { + auto Pack::getResource(const std::string& filename) -> std::vector { // NOLINT(readability-convert-member-functions-to-static) auto it = resources_.find(filename); if (it == resources_.end()) { return {}; @@ -259,11 +259,11 @@ namespace Resource { // Check if a resource exists auto Pack::hasResource(const std::string& filename) const -> bool { - return resources_.find(filename) != resources_.end(); + return resources_.contains(filename); } // Get list of all resources - auto Pack::getResourceList() const -> std::vector { + auto Pack::getResourceList() const -> std::vector { // NOLINT(readability-convert-member-functions-to-static) std::vector list; list.reserve(resources_.size()); for (const auto& [name, entry] : resources_) { @@ -274,7 +274,7 @@ namespace Resource { } // Calculate overall pack checksum for validation - auto Pack::calculatePackChecksum() const -> uint32_t { + auto Pack::calculatePackChecksum() const -> uint32_t { // NOLINT(readability-convert-member-functions-to-static) if (!loaded_ || data_.empty()) { return 0; } diff --git a/source/core/resources/resource_pack.hpp b/source/core/resources/resource_pack.hpp index d00ef6c1..796a52d8 100644 --- a/source/core/resources/resource_pack.hpp +++ b/source/core/resources/resource_pack.hpp @@ -40,13 +40,13 @@ namespace Resource { auto loadPack(const std::string& pack_file) -> bool; auto getResource(const std::string& filename) -> std::vector; // Resource access - auto hasResource(const std::string& filename) const -> bool; - auto getResourceList() const -> std::vector; + [[nodiscard]] auto hasResource(const std::string& filename) const -> bool; + [[nodiscard]] auto getResourceList() const -> std::vector; - auto isLoaded() const -> bool { return loaded_; } // Status queries - auto getResourceCount() const -> size_t { return resources_.size(); } - auto getDataSize() const -> size_t { return data_.size(); } - auto calculatePackChecksum() const -> uint32_t; // Validation + [[nodiscard]] auto isLoaded() const -> bool { return loaded_; } // Status queries + [[nodiscard]] auto getResourceCount() const -> size_t { return resources_.size(); } + [[nodiscard]] auto getDataSize() const -> size_t { return data_.size(); } + [[nodiscard]] auto calculatePackChecksum() const -> uint32_t; // Validation private: static constexpr std::array MAGIC_HEADER = {'J', 'D', 'D', 'I'}; // Pack format constants diff --git a/source/core/system/debug.cpp b/source/core/system/debug.cpp index 37739d01..56a72ddd 100644 --- a/source/core/system/debug.cpp +++ b/source/core/system/debug.cpp @@ -28,7 +28,7 @@ auto Debug::get() -> Debug* { } // Dibuja en pantalla -void Debug::render() { +void Debug::render() { // NOLINT(readability-make-member-function-const) auto text = Resource::Cache::get()->getText("aseprite"); int y = y_; int w = 0; @@ -39,7 +39,7 @@ void Debug::render() { y += text->getCharacterSize() + 1; if (y > 192 - text->getCharacterSize()) { y = y_; - x_ += w * text->getCharacterSize() + 2; + x_ += (w * text->getCharacterSize()) + 2; } } diff --git a/source/core/system/director.cpp b/source/core/system/director.cpp index 093a4b8e..2b3a42b8 100644 --- a/source/core/system/director.cpp +++ b/source/core/system/director.cpp @@ -120,11 +120,11 @@ Director::Director(std::vector const& args) { #endif // Configura la ruta y carga las opciones desde un fichero - Options::setConfigFile(Resource::List::get()->get("config.yaml")); + Options::setConfigFile(Resource::List::get()->get("config.yaml")); // NOLINT(readability-static-accessed-through-instance) Options::loadFromFile(); // Configura la ruta y carga los presets de PostFX - Options::setPostFXFile(Resource::List::get()->get("postfx.yaml")); + Options::setPostFXFile(Resource::List::get()->get("postfx.yaml")); // NOLINT(readability-static-accessed-through-instance) Options::loadPostFXFromFile(); // En mode quiosc, forçar pantalla completa independentment de la configuració @@ -150,7 +150,7 @@ Director::Director(std::vector const& args) { Input::init(gamecontroller_db); #else // In development, use Asset as normal - Input::init(Resource::List::get()->get("gamecontrollerdb.txt")); // Carga configuración de controles + Input::init(Resource::List::get()->get("gamecontrollerdb.txt")); // NOLINT(readability-static-accessed-through-instance) Carga configuración de controles #endif // Aplica las teclas y botones del gamepad configurados desde Options @@ -168,7 +168,7 @@ Director::Director(std::vector const& args) { std::string locale_path = executable_path_ + PREFIX + "/data/locale/" + Options::language + ".yaml"; Locale::init(locale_path); #else - Locale::init(Resource::List::get()->get(Options::language + ".yaml")); + Locale::init(Resource::List::get()->get(Options::language + ".yaml")); // NOLINT(readability-static-accessed-through-instance) #endif // Special handling for cheevos.bin - also needs filesystem path @@ -204,7 +204,7 @@ Director::~Director() { } // Comprueba los parametros del programa -auto Director::checkProgramArguments(std::vector const& args) -> std::string { +auto Director::checkProgramArguments(std::vector const& args) -> std::string { // NOLINT(readability-identifier-naming) // Iterar sobre los argumentos del programa (saltando args[0] que es el ejecutable) for (std::size_t i = 1; i < args.size(); ++i) { const std::string& argument = args[i]; @@ -226,7 +226,7 @@ auto Director::checkProgramArguments(std::vector const& args) -> st } // Crea la carpeta del sistema donde guardar datos -void Director::createSystemFolder(const std::string& folder) { +void Director::createSystemFolder(const std::string& folder) { // NOLINT(readability-convert-member-functions-to-static) #ifdef _WIN32 system_folder_ = std::string(getenv("APPDATA")) + "/" + folder; #elif __APPLE__ @@ -281,7 +281,7 @@ void Director::createSystemFolder(const std::string& folder) { } // Carga la configuración de assets desde assets.yaml -void Director::setFileList() { +void Director::setFileList() { // NOLINT(readability-convert-member-functions-to-static) // Determinar el prefijo de ruta según la plataforma #ifdef MACOS_BUNDLE const std::string PREFIX = "/../Resources"; diff --git a/source/game/entities/enemy.cpp b/source/game/entities/enemy.cpp index 518231a1..efc0c366 100644 --- a/source/game/entities/enemy.cpp +++ b/source/game/entities/enemy.cpp @@ -49,7 +49,7 @@ void Enemy::update(float delta_time) { } // Comprueba si ha llegado al limite del recorrido para darse media vuelta -void Enemy::checkPath() { +void Enemy::checkPath() { // NOLINT(readability-make-member-function-const) if (sprite_->getPosX() > x2_ || sprite_->getPosX() < x1_) { // Recoloca if (sprite_->getPosX() > x2_) { diff --git a/source/game/entities/item.cpp b/source/game/entities/item.cpp index 5c06beee..7f9c3569 100644 --- a/source/game/entities/item.cpp +++ b/source/game/entities/item.cpp @@ -29,15 +29,15 @@ void Item::update(float delta_time) { } // Pinta el objeto en pantalla -void Item::render() const { +void Item::render() const { // NOLINT(readability-convert-member-functions-to-static) // Calcula el índice de color basado en el tiempo acumulado const int INDEX = static_cast(time_accumulator_ / COLOR_CHANGE_INTERVAL) % static_cast(color_.size()); sprite_->render(1, color_.at(INDEX)); } // Obtiene su ubicación -auto Item::getPos() -> SDL_FPoint { - const SDL_FPoint P = {sprite_->getX(), sprite_->getY()}; +auto Item::getPos() -> SDL_FPoint { // NOLINT(readability-convert-member-functions-to-static) + const SDL_FPoint P = {.x = sprite_->getX(), .y = sprite_->getY()}; return P; } diff --git a/source/game/entities/player.cpp b/source/game/entities/player.cpp index bcb3c9b4..da7d474c 100644 --- a/source/game/entities/player.cpp +++ b/source/game/entities/player.cpp @@ -352,7 +352,7 @@ void Player::moveJumping(float delta_time) { // Comprueba la colisión con las superficies y las cintas transportadoras (sin rampas) // Extendemos 1px hacia arriba para detectar suelos traversados ligeramente al // entrar horizontalmente (consecuencia del margen h=HEIGHT-1 en la proyección horizontal) - const SDL_FRect ADJ = {PROJECTION.x, PROJECTION.y - 1.0F, PROJECTION.w, PROJECTION.h + 1.0F}; + const SDL_FRect ADJ = {.x = PROJECTION.x, .y = PROJECTION.y - 1.0F, .w = PROJECTION.w, .h = PROJECTION.h + 1.0F}; const float POS = std::max(room_->checkTopSurfaces(ADJ), room_->checkAutoSurfaces(ADJ)); if (POS != Collision::NONE) { // Si hay colisión lo mueve hasta donde no colisiona y pasa a estar sobre la superficie @@ -445,7 +445,7 @@ void Player::applyGravity(float delta_time) { } // Establece la animación del jugador -void Player::animate(float delta_time) { +void Player::animate(float delta_time) { // NOLINT(readability-make-member-function-const) if (vx_ != 0) { sprite_->update(delta_time); } @@ -461,7 +461,7 @@ void Player::handleJumpEnd() { } // Calcula y reproduce el sonido de salto basado en tiempo transcurrido -void Player::playJumpSound(float delta_time) { +void Player::playJumpSound(float delta_time) { // NOLINT(readability-convert-member-functions-to-static) size_t sound_index; if (jump_sound_ctrl_.shouldPlay(delta_time, sound_index)) { if (sound_index < jumping_sound_.size()) { @@ -471,7 +471,7 @@ void Player::playJumpSound(float delta_time) { } // Calcula y reproduce el sonido de caída basado en distancia vertical recorrida -void Player::playFallSound(float delta_time) { +void Player::playFallSound(float delta_time) { // NOLINT(readability-convert-member-functions-to-static) size_t sound_index; if (fall_sound_ctrl_.shouldPlay(delta_time, y_, sound_index)) { if (sound_index < falling_sound_.size()) { @@ -593,7 +593,7 @@ void Player::updateCurrentSlope() { // Comprueba que el jugador no toque ningun tile de los que matan auto Player::handleKillingTiles() -> bool { // Comprueba si hay contacto con algún tile que mata - if (std::ranges::any_of(collider_points_, [this](const auto& c) { + if (std::ranges::any_of(collider_points_, [this](const auto& c) -> bool { return room_->getTile(c) == Room::Tile::KILL; })) { markAsDead(); // Mata al jugador inmediatamente @@ -643,7 +643,7 @@ void Player::updateFeet() { } // Inicializa los sonidos de salto y caida -void Player::initSounds() { +void Player::initSounds() { // NOLINT(readability-convert-member-functions-to-static) for (int i = 0; i < 24; ++i) { std::string sound_file = "jump" + std::to_string(i + 1) + ".wav"; jumping_sound_[i] = Resource::Cache::get()->getSound(sound_file); @@ -678,14 +678,14 @@ auto Player::JumpSoundController::shouldPlay(float delta_time, size_t& out_index elapsed_time += delta_time; // Calcula qué sonido debería estar sonando según el tiempo - size_t target_index = FIRST_SOUND + static_cast(elapsed_time / SECONDS_PER_SOUND); + size_t target_index = FIRST_SOUND + static_cast((elapsed_time / SECONDS_PER_SOUND)); target_index = std::min(target_index, LAST_SOUND); // Reproduce si hemos avanzado a un nuevo sonido if (target_index > current_index) { current_index = target_index; out_index = current_index; - return true; + return true; // NOLINT(readability-simplify-boolean-expr) } return false; @@ -721,7 +721,7 @@ auto Player::FallSoundController::shouldPlay(float delta_time, float current_y, last_y = current_y; // Calcula qué sonido debería estar sonando según el intervalo - size_t target_index = FIRST_SOUND + static_cast(distance_traveled / PIXELS_PER_SOUND); + size_t target_index = FIRST_SOUND + static_cast((distance_traveled / PIXELS_PER_SOUND)); // El sonido a reproducir se limita a LAST_SOUND (13), pero el índice interno sigue creciendo size_t sound_to_play = std::min(target_index, LAST_SOUND); @@ -749,7 +749,7 @@ void Player::applySpawnValues(const SpawnData& spawn) { } // Inicializa el sprite del jugador -void Player::initSprite(const std::string& animations_path) { +void Player::initSprite(const std::string& animations_path) { // NOLINT(readability-convert-member-functions-to-static) const auto& animation_data = Resource::Cache::get()->getAnimationData(animations_path); sprite_ = std::make_unique(animation_data); sprite_->setWidth(WIDTH); @@ -865,7 +865,7 @@ void Player::resetSoundControllersOnLanding() { } // Devuelve el rectangulo de proyeccion -auto Player::getProjection(Direction direction, float displacement) -> SDL_FRect { +auto Player::getProjection(Direction direction, float displacement) -> SDL_FRect { // NOLINT(readability-convert-member-functions-to-static) switch (direction) { case Direction::LEFT: return { diff --git a/source/game/entities/player.hpp b/source/game/entities/player.hpp index ac235be9..14753085 100644 --- a/source/game/entities/player.hpp +++ b/source/game/entities/player.hpp @@ -96,7 +96,7 @@ class Player { [[nodiscard]] auto isOnBorder() const -> bool { return border_ != Room::Border::NONE; } // Indica si el jugador esta en uno de los cuatro bordes de la pantalla [[nodiscard]] auto getBorder() const -> Room::Border { return border_; } // Indica en cual de los cuatro bordes se encuentra void switchBorders(); // Cambia al jugador de un borde al opuesto. Util para el cambio de pantalla - auto getRect() -> SDL_FRect { return {x_, y_, WIDTH, HEIGHT}; } // Obtiene el rectangulo que delimita al jugador + auto getRect() -> SDL_FRect { return {.x = x_, .y = y_, .w = WIDTH, .h = HEIGHT}; } // Obtiene el rectangulo que delimita al jugador auto getCollider() -> SDL_FRect& { return collider_box_; } // Obtiene el rectangulo de colision del jugador auto getSpawnParams() -> SpawnData { return {.x = x_, .y = y_, .vx = vx_, .vy = vy_, .last_grounded_position = last_grounded_position_, .state = state_, .flip = sprite_->getFlip()}; } // Obtiene el estado de reaparición del jugador void setColor(Uint8 color = 0); // Establece el color del jugador (0 = automático según cheats) @@ -138,8 +138,8 @@ class Player { // --- Variables de colisión --- SDL_FRect collider_box_{}; // Caja de colisión con los enemigos u objetos std::array collider_points_{}; // Puntos de colisión con el mapa - SDL_FPoint under_left_foot_ = {0.0F, 0.0F}; // El punto bajo la esquina inferior izquierda del jugador - SDL_FPoint under_right_foot_ = {0.0F, 0.0F}; // El punto bajo la esquina inferior derecha del jugador + SDL_FPoint under_left_foot_ = {.x = 0.0F, .y = 0.0F}; // El punto bajo la esquina inferior izquierda del jugador + SDL_FPoint under_right_foot_ = {.x = 0.0F, .y = 0.0F}; // El punto bajo la esquina inferior derecha del jugador const LineDiagonal* current_slope_{nullptr}; // Rampa actual sobe la que está el jugador // --- Variables de juego --- diff --git a/source/game/gameplay/cheevos.cpp b/source/game/gameplay/cheevos.cpp index faa9656e..01dd4ff3 100644 --- a/source/game/gameplay/cheevos.cpp +++ b/source/game/gameplay/cheevos.cpp @@ -16,7 +16,7 @@ Cheevos* Cheevos::cheevos = nullptr; // [SINGLETON] Crearemos el objeto con esta función estática -void Cheevos::init(const std::string& file) { +void Cheevos::init(const std::string& file) { // NOLINT(readability-convert-member-functions-to-static) Cheevos::cheevos = new Cheevos(file); } @@ -43,7 +43,7 @@ Cheevos::~Cheevos() { } // Inicializa los logros -void Cheevos::init() { +void Cheevos::init() { // NOLINT(readability-convert-member-functions-to-static) cheevos_list_.clear(); auto* loc = Locale::get(); cheevos_list_.emplace_back(Achievement{.id = 1, .caption = loc->get("achievements.c1"), .description = loc->get("achievements.d1"), .icon = 2}); @@ -61,7 +61,7 @@ void Cheevos::init() { } // Busca un logro por id y devuelve el indice -auto Cheevos::find(int id) -> int { +auto Cheevos::find(int id) -> int { // NOLINT(readability-convert-member-functions-to-static) for (int i = 0; i < (int)cheevos_list_.size(); ++i) { if (cheevos_list_[i].id == id) { return i; @@ -101,7 +101,7 @@ void Cheevos::setUnobtainable(int id) { } // Carga el estado de los logros desde un fichero -void Cheevos::loadFromFile() { +void Cheevos::loadFromFile() { // NOLINT(readability-convert-member-functions-to-static) std::ifstream file(file_, std::ios::binary); // El fichero no existe @@ -162,7 +162,7 @@ void Cheevos::saveToFile() { // Devuelve el número total de logros desbloqueados auto Cheevos::getTotalUnlockedAchievements() -> int { - return std::count_if(cheevos_list_.begin(), cheevos_list_.end(), [](const auto& cheevo) { return cheevo.completed; }); + return std::count_if(cheevos_list_.begin(), cheevos_list_.end(), [](const auto& cheevo) -> bool { return cheevo.completed; }); } // Elimina el estado "no obtenible" diff --git a/source/game/gameplay/collision_map.cpp b/source/game/gameplay/collision_map.cpp index 694c800e..aa509cf8 100644 --- a/source/game/gameplay/collision_map.cpp +++ b/source/game/gameplay/collision_map.cpp @@ -36,7 +36,7 @@ auto CollisionMap::getTile(SDL_FPoint point) const -> Tile { } // Devuelve el tipo de tile que hay en ese indice -auto CollisionMap::getTile(int index) const -> Tile { +auto CollisionMap::getTile(int index) const -> Tile { // NOLINT(readability-convert-member-functions-to-static) const bool ON_RANGE = (index > -1) && (index < (int)tile_map_.size()); if (ON_RANGE) { @@ -107,7 +107,7 @@ auto CollisionMap::getSlopeHeight(SDL_FPoint p, Tile slope) -> int { // === Queries de colisión === // Comprueba las colisiones con paredes derechas -auto CollisionMap::checkRightSurfaces(const SDL_FRect& rect) -> int { +auto CollisionMap::checkRightSurfaces(const SDL_FRect& rect) -> int { // NOLINT(readability-convert-member-functions-to-static) for (const auto& s : right_walls_) { if (checkCollision(s, rect)) { return s.x; @@ -117,7 +117,7 @@ auto CollisionMap::checkRightSurfaces(const SDL_FRect& rect) -> int { } // Comprueba las colisiones con paredes izquierdas -auto CollisionMap::checkLeftSurfaces(const SDL_FRect& rect) -> int { +auto CollisionMap::checkLeftSurfaces(const SDL_FRect& rect) -> int { // NOLINT(readability-convert-member-functions-to-static) for (const auto& s : left_walls_) { if (checkCollision(s, rect)) { return s.x; @@ -127,7 +127,7 @@ auto CollisionMap::checkLeftSurfaces(const SDL_FRect& rect) -> int { } // Comprueba las colisiones con techos -auto CollisionMap::checkTopSurfaces(const SDL_FRect& rect) -> int { +auto CollisionMap::checkTopSurfaces(const SDL_FRect& rect) -> int { // NOLINT(readability-convert-member-functions-to-static) for (const auto& s : top_floors_) { if (checkCollision(s, rect)) { return s.y; @@ -138,13 +138,13 @@ auto CollisionMap::checkTopSurfaces(const SDL_FRect& rect) -> int { // Comprueba las colisiones punto con techos auto CollisionMap::checkTopSurfaces(const SDL_FPoint& p) -> bool { - return std::ranges::any_of(top_floors_, [&](const auto& s) { + return std::ranges::any_of(top_floors_, [&](const auto& s) -> bool { return checkCollision(s, p); }); } // Comprueba las colisiones con suelos -auto CollisionMap::checkBottomSurfaces(const SDL_FRect& rect) -> int { +auto CollisionMap::checkBottomSurfaces(const SDL_FRect& rect) -> int { // NOLINT(readability-convert-member-functions-to-static) for (const auto& s : bottom_floors_) { if (checkCollision(s, rect)) { return s.y; @@ -154,7 +154,7 @@ auto CollisionMap::checkBottomSurfaces(const SDL_FRect& rect) -> int { } // Comprueba las colisiones con conveyor belts -auto CollisionMap::checkAutoSurfaces(const SDL_FRect& rect) -> int { +auto CollisionMap::checkAutoSurfaces(const SDL_FRect& rect) -> int { // NOLINT(readability-convert-member-functions-to-static) for (const auto& s : conveyor_belt_floors_) { if (checkCollision(s, rect)) { return s.y; @@ -165,13 +165,13 @@ auto CollisionMap::checkAutoSurfaces(const SDL_FRect& rect) -> int { // Comprueba las colisiones punto con conveyor belts auto CollisionMap::checkConveyorBelts(const SDL_FPoint& p) -> bool { - return std::ranges::any_of(conveyor_belt_floors_, [&](const auto& s) { + return std::ranges::any_of(conveyor_belt_floors_, [&](const auto& s) -> bool { return checkCollision(s, p); }); } // Comprueba las colisiones línea con rampas izquierdas -auto CollisionMap::checkLeftSlopes(const LineVertical& line) -> int { +auto CollisionMap::checkLeftSlopes(const LineVertical& line) -> int { // NOLINT(readability-convert-member-functions-to-static) for (const auto& slope : left_slopes_) { const auto P = checkCollision(slope, line); if (P.x != -1) { @@ -183,13 +183,13 @@ auto CollisionMap::checkLeftSlopes(const LineVertical& line) -> int { // Comprueba las colisiones punto con rampas izquierdas auto CollisionMap::checkLeftSlopes(const SDL_FPoint& p) -> bool { - return std::ranges::any_of(left_slopes_, [&](const auto& slope) { + return std::ranges::any_of(left_slopes_, [&](const auto& slope) -> bool { return checkCollision(p, slope); }); } // Comprueba las colisiones línea con rampas derechas -auto CollisionMap::checkRightSlopes(const LineVertical& line) -> int { +auto CollisionMap::checkRightSlopes(const LineVertical& line) -> int { // NOLINT(readability-convert-member-functions-to-static) for (const auto& slope : right_slopes_) { const auto P = checkCollision(slope, line); if (P.x != -1) { @@ -201,13 +201,13 @@ auto CollisionMap::checkRightSlopes(const LineVertical& line) -> int { // Comprueba las colisiones punto con rampas derechas auto CollisionMap::checkRightSlopes(const SDL_FPoint& p) -> bool { - return std::ranges::any_of(right_slopes_, [&](const auto& slope) { + return std::ranges::any_of(right_slopes_, [&](const auto& slope) -> bool { return checkCollision(p, slope); }); } // Obtiene puntero a slope en un punto (prioriza left_slopes_ sobre right_slopes_) -auto CollisionMap::getSlopeAtPoint(const SDL_FPoint& p) const -> const LineDiagonal* { +auto CollisionMap::getSlopeAtPoint(const SDL_FPoint& p) const -> const LineDiagonal* { // NOLINT(readability-convert-member-functions-to-static) // Primero busca en rampas izquierdas for (const auto& slope : left_slopes_) { if (checkCollision(p, slope)) { @@ -229,7 +229,7 @@ auto CollisionMap::getSlopeAtPoint(const SDL_FPoint& p) const -> const LineDiago // === Helpers para recopilar tiles === // Helper: recopila tiles inferiores (muros sin muro debajo) -auto CollisionMap::collectBottomTiles() -> std::vector { +auto CollisionMap::collectBottomTiles() -> std::vector { // NOLINT(readability-make-member-function-const) std::vector tile; // Busca todos los tiles de tipo muro que no tengan debajo otro muro @@ -251,7 +251,7 @@ auto CollisionMap::collectBottomTiles() -> std::vector { } // Helper: recopila tiles superiores (muros o pasables sin muro encima) -auto CollisionMap::collectTopTiles() -> std::vector { +auto CollisionMap::collectTopTiles() -> std::vector { // NOLINT(readability-make-member-function-const) std::vector tile; // Busca todos los tiles de tipo muro o pasable que no tengan encima un muro @@ -273,7 +273,7 @@ auto CollisionMap::collectTopTiles() -> std::vector { } // Helper: recopila tiles animados (para superficies automaticas/conveyor belts) -auto CollisionMap::collectAnimatedTiles() -> std::vector { +auto CollisionMap::collectAnimatedTiles() -> std::vector { // NOLINT(readability-make-member-function-const) std::vector tile; // Busca todos los tiles de tipo animado @@ -298,13 +298,13 @@ auto CollisionMap::collectAnimatedTiles() -> std::vector { } // Helper: construye lineas horizontales a partir de tiles consecutivos -void CollisionMap::buildHorizontalLines(const std::vector& tiles, std::vector& lines, bool is_bottom_surface) { +void CollisionMap::buildHorizontalLines(const std::vector& tiles, std::vector& lines, bool is_bottom_surface) { // NOLINT(readability-convert-member-functions-to-static) if (tiles.size() <= 1) { return; } int i = 0; - while (i < (int)tiles.size() - 1) { + while (i < static_cast(tiles.size()) - 1) { LineHorizontal line; line.x1 = (tiles[i] % MAP_WIDTH) * TILE_SIZE; @@ -319,11 +319,11 @@ void CollisionMap::buildHorizontalLines(const std::vector& tiles, std::vect i++; // Encuentra tiles consecutivos - if (i < (int)tiles.size()) { + if (i < static_cast(tiles.size())) { while (tiles[i] == tiles[i - 1] + 1) { last_one = i; i++; - if (i >= (int)tiles.size()) { + if (i >= static_cast(tiles.size())) { break; } } @@ -333,7 +333,7 @@ void CollisionMap::buildHorizontalLines(const std::vector& tiles, std::vect lines.push_back(line); // Salta separadores - if (i < (int)tiles.size() && tiles[i] == -1) { + if (i < static_cast(tiles.size()) && tiles[i] == -1) { i++; } } @@ -354,7 +354,7 @@ void CollisionMap::setTopSurfaces() { } // Calcula las superficies laterales izquierdas -void CollisionMap::setLeftSurfaces() { +void CollisionMap::setLeftSurfaces() { // NOLINT(readability-make-member-function-const) std::vector tile; // Busca todos los tiles de tipo muro que no tienen a su izquierda un tile de tipo muro @@ -394,7 +394,7 @@ void CollisionMap::setLeftSurfaces() { } // Calcula las superficies laterales derechas -void CollisionMap::setRightSurfaces() { +void CollisionMap::setRightSurfaces() { // NOLINT(readability-make-member-function-const) std::vector tile; // Busca todos los tiles de tipo muro que no tienen a su derecha un tile de tipo muro @@ -434,7 +434,7 @@ void CollisionMap::setRightSurfaces() { } // Encuentra todas las rampas que suben hacia la izquierda -void CollisionMap::setLeftSlopes() { +void CollisionMap::setLeftSlopes() { // NOLINT(readability-make-member-function-const) // Recorre la habitación entera por filas buscando tiles de tipo t_slope_l std::vector found; for (int i = 0; i < (int)tile_map_.size(); ++i) { @@ -469,7 +469,7 @@ void CollisionMap::setLeftSlopes() { } // Encuentra todas las rampas que suben hacia la derecha -void CollisionMap::setRightSlopes() { +void CollisionMap::setRightSlopes() { // NOLINT(readability-make-member-function-const) // Recorre la habitación entera por filas buscando tiles de tipo t_slope_r std::vector found; for (int i = 0; i < (int)tile_map_.size(); ++i) { diff --git a/source/game/gameplay/enemy_manager.cpp b/source/game/gameplay/enemy_manager.cpp index 2963350e..2f1c6b35 100644 --- a/source/game/gameplay/enemy_manager.cpp +++ b/source/game/gameplay/enemy_manager.cpp @@ -6,7 +6,7 @@ #include "utils/utils.hpp" // Para checkCollision // Añade un enemigo a la colección -void EnemyManager::addEnemy(std::shared_ptr enemy) { +void EnemyManager::addEnemy(std::shared_ptr enemy) { // NOLINT(readability-identifier-naming) enemies_.push_back(std::move(enemy)); } @@ -16,7 +16,7 @@ void EnemyManager::clear() { } // Elimina el último enemigo de la colección -void EnemyManager::removeLastEnemy() { +void EnemyManager::removeLastEnemy() { // NOLINT(readability-convert-member-functions-to-static) if (!enemies_.empty()) { enemies_.pop_back(); } diff --git a/source/game/gameplay/item_manager.cpp b/source/game/gameplay/item_manager.cpp index ebbe0757..91b0aa97 100644 --- a/source/game/gameplay/item_manager.cpp +++ b/source/game/gameplay/item_manager.cpp @@ -14,7 +14,7 @@ ItemManager::ItemManager(std::string room_name, std::shared_ptr item) { +void ItemManager::addItem(std::shared_ptr item) { // NOLINT(readability-identifier-naming) items_.push_back(std::move(item)); } @@ -45,7 +45,7 @@ void ItemManager::setPaused(bool paused) { } // Comprueba si hay colisión con algún item -auto ItemManager::checkCollision(SDL_FRect& rect) -> bool { +auto ItemManager::checkCollision(SDL_FRect& rect) -> bool { // NOLINT(readability-convert-member-functions-to-static) for (int i = 0; i < static_cast(items_.size()); ++i) { if (::checkCollision(rect, items_.at(i)->getCollider())) { // Registra el item como recogido diff --git a/source/game/gameplay/item_tracker.cpp b/source/game/gameplay/item_tracker.cpp index 37a8177a..ef209c89 100644 --- a/source/game/gameplay/item_tracker.cpp +++ b/source/game/gameplay/item_tracker.cpp @@ -32,7 +32,7 @@ auto ItemTracker::hasBeenPicked(const std::string& name, SDL_FPoint pos) -> bool } // Añade el objeto a la lista de objetos cogidos -void ItemTracker::addItem(const std::string& name, SDL_FPoint pos) { +void ItemTracker::addItem(const std::string& name, SDL_FPoint pos) { // NOLINT(readability-convert-member-functions-to-static) // Comprueba si el objeto no ha sido recogido con anterioridad if (!hasBeenPicked(name, pos)) { // Primero busca si ya hay una entrada con ese nombre @@ -47,7 +47,7 @@ void ItemTracker::addItem(const std::string& name, SDL_FPoint pos) { } // Busca una entrada en la lista por nombre -auto ItemTracker::findByName(const std::string& name) -> int { +auto ItemTracker::findByName(const std::string& name) -> int { // NOLINT(readability-convert-member-functions-to-static) int i = 0; for (const auto& item : items_) { @@ -61,7 +61,7 @@ auto ItemTracker::findByName(const std::string& name) -> int { } // Busca una entrada en la lista por posición -auto ItemTracker::findByPos(int index, SDL_FPoint pos) -> int { +auto ItemTracker::findByPos(int index, SDL_FPoint pos) -> int { // NOLINT(readability-convert-member-functions-to-static) int i = 0; for (const auto& item : items_[index].pos) { diff --git a/source/game/gameplay/room.cpp b/source/game/gameplay/room.cpp index ca047204..c9c76832 100644 --- a/source/game/gameplay/room.cpp +++ b/source/game/gameplay/room.cpp @@ -81,7 +81,7 @@ void Room::initializeRoom(const Data& room) { } // Abre la jail para poder entrar -void Room::openTheJail() { +void Room::openTheJail() { // NOLINT(readability-convert-member-functions-to-static) if (data_->jail_is_open && name_ == "THE JAIL") { // Elimina el último enemigo (Bry debe ser el último enemigo definido en el fichero) if (!enemy_manager_->isEmpty()) { @@ -123,7 +123,7 @@ void Room::redrawMap() { #endif // Actualiza las variables y objetos de la habitación -void Room::update(float delta_time) { +void Room::update(float delta_time) { // NOLINT(readability-make-member-function-const) if (is_paused_) { // Si está en modo pausa no se actualiza nada return; @@ -147,7 +147,7 @@ void Room::setPaused(bool value) { } // Devuelve la cadena del fichero de la habitación contigua segun el borde -auto Room::getRoom(Border border) -> std::string { +auto Room::getRoom(Border border) -> std::string { // NOLINT(readability-convert-member-functions-to-static) switch (border) { case Border::TOP: return upper_room_; @@ -163,14 +163,14 @@ auto Room::getRoom(Border border) -> std::string { } // Devuelve el tipo de tile que hay en ese pixel -auto Room::getTile(SDL_FPoint point) -> Tile { +auto Room::getTile(SDL_FPoint point) -> Tile { // NOLINT(readability-convert-member-functions-to-static) // Delega a CollisionMap y convierte el resultado const auto COLLISION_TILE = collision_map_->getTile(point); return static_cast(COLLISION_TILE); } // Devuelve el tipo de tile en un índice del tilemap -auto Room::getTile(int index) -> Tile { +auto Room::getTile(int index) -> Tile { // NOLINT(readability-convert-member-functions-to-static) // Delega a CollisionMap y convierte el resultado const auto COLLISION_TILE = collision_map_->getTile(index); return static_cast(COLLISION_TILE); @@ -256,6 +256,6 @@ auto Room::getSlopeAtPoint(const SDL_FPoint& p) const -> const LineDiagonal* { } // Carga una habitación desde un archivo YAML (delegado a RoomLoader) -auto Room::loadYAML(const std::string& file_path, bool verbose) -> Data { +auto Room::loadYAML(const std::string& file_path, bool verbose) -> Data { // NOLINT(readability-convert-member-functions-to-static) return RoomLoader::loadYAML(file_path, verbose); } diff --git a/source/game/gameplay/room.hpp b/source/game/gameplay/room.hpp index 6d4a05f8..568edcc6 100644 --- a/source/game/gameplay/room.hpp +++ b/source/game/gameplay/room.hpp @@ -58,7 +58,7 @@ class Room { // Constructor y destructor Room(const std::string& room_path, std::shared_ptr data); - ~Room(); // Definido en .cpp para poder usar unique_ptr con forward declarations + ~Room(); // NOLINT(modernize-use-equals-default, performance-trivially-destructible) -- defined in .cpp for unique_ptr with forward declarations // --- Funciones --- [[nodiscard]] auto getName() const -> const std::string& { return name_; } // Devuelve el nombre de la habitación diff --git a/source/game/gameplay/room_loader.cpp b/source/game/gameplay/room_loader.cpp index 50265d84..1767a3ec 100644 --- a/source/game/gameplay/room_loader.cpp +++ b/source/game/gameplay/room_loader.cpp @@ -10,7 +10,7 @@ #include "utils/utils.hpp" // Para stringToColor // Convierte room connection de YAML a formato interno -auto RoomLoader::convertRoomConnection(const std::string& value) -> std::string { +auto RoomLoader::convertRoomConnection(const std::string& value) -> std::string { // NOLINT(readability-convert-member-functions-to-static) if (value == "null" || value.empty()) { return "0"; } @@ -22,7 +22,7 @@ auto RoomLoader::convertRoomConnection(const std::string& value) -> std::string } // Convierte string de autoSurface a int -auto RoomLoader::convertAutoSurface(const fkyaml::node& node) -> int { +auto RoomLoader::convertAutoSurface(const fkyaml::node& node) -> int { // NOLINT(readability-convert-member-functions-to-static) if (node.is_integer()) { return node.get_value(); } @@ -39,7 +39,7 @@ auto RoomLoader::convertAutoSurface(const fkyaml::node& node) -> int { } // Convierte un tilemap 2D a vector 1D flat -auto RoomLoader::flattenTilemap(const std::vector>& tilemap_2d) -> std::vector { +auto RoomLoader::flattenTilemap(const std::vector>& tilemap_2d) -> std::vector { // NOLINT(readability-convert-member-functions-to-static, readability-named-parameter) std::vector tilemap_flat; tilemap_flat.reserve(512); // 16 rows × 32 cols @@ -53,7 +53,7 @@ auto RoomLoader::flattenTilemap(const std::vector>& tilemap_2d) } // Parsea la configuración general de la habitación -void RoomLoader::parseRoomConfig(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name) { +void RoomLoader::parseRoomConfig(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name) { // NOLINT(readability-convert-member-functions-to-static) if (!yaml.contains("room")) { return; } @@ -120,7 +120,7 @@ void RoomLoader::parseRoomConnections(const fkyaml::node& conn_node, Room::Data& } // Parsea el tilemap de la habitación -void RoomLoader::parseTilemap(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name, bool verbose) { +void RoomLoader::parseTilemap(const fkyaml::node& yaml, Room::Data& room, const std::string& file_name, bool verbose) { // NOLINT(readability-convert-member-functions-to-static) if (!yaml.contains("tilemap")) { std::cerr << "Warning: No tilemap found in " << file_name << '\n'; return; @@ -152,7 +152,7 @@ void RoomLoader::parseTilemap(const fkyaml::node& yaml, Room::Data& room, const } // Parsea los límites de movimiento de un enemigo -void RoomLoader::parseEnemyBoundaries(const fkyaml::node& bounds_node, Enemy::Data& enemy) { +void RoomLoader::parseEnemyBoundaries(const fkyaml::node& bounds_node, Enemy::Data& enemy) { // NOLINT(readability-convert-member-functions-to-static) // Nuevo formato: position1 y position2 if (bounds_node.contains("position1")) { const auto& pos1 = bounds_node["position1"]; @@ -189,7 +189,7 @@ void RoomLoader::parseEnemyBoundaries(const fkyaml::node& bounds_node, Enemy::Da } // Parsea los datos de un enemigo individual -auto RoomLoader::parseEnemyData(const fkyaml::node& enemy_node) -> Enemy::Data { +auto RoomLoader::parseEnemyData(const fkyaml::node& enemy_node) -> Enemy::Data { // NOLINT(readability-convert-member-functions-to-static) Enemy::Data enemy; // Animation path @@ -246,7 +246,7 @@ auto RoomLoader::parseEnemyData(const fkyaml::node& enemy_node) -> Enemy::Data { } // Parsea la lista de enemigos de la habitación -void RoomLoader::parseEnemies(const fkyaml::node& yaml, Room::Data& room, bool verbose) { +void RoomLoader::parseEnemies(const fkyaml::node& yaml, Room::Data& room, bool verbose) { // NOLINT(readability-convert-member-functions-to-static) if (!yaml.contains("enemies") || yaml["enemies"].is_null()) { return; } @@ -263,7 +263,7 @@ void RoomLoader::parseEnemies(const fkyaml::node& yaml, Room::Data& room, bool v } // Parsea los datos de un item individual -auto RoomLoader::parseItemData(const fkyaml::node& item_node, const Room::Data& room) -> Item::Data { +auto RoomLoader::parseItemData(const fkyaml::node& item_node, const Room::Data& room) -> Item::Data { // NOLINT(readability-convert-member-functions-to-static) Item::Data item; // Tileset file @@ -300,7 +300,7 @@ auto RoomLoader::parseItemData(const fkyaml::node& item_node, const Room::Data& } // Parsea la lista de items de la habitación -void RoomLoader::parseItems(const fkyaml::node& yaml, Room::Data& room, bool verbose) { +void RoomLoader::parseItems(const fkyaml::node& yaml, Room::Data& room, bool verbose) { // NOLINT(readability-convert-member-functions-to-static) if (!yaml.contains("items") || yaml["items"].is_null()) { return; } @@ -317,7 +317,7 @@ void RoomLoader::parseItems(const fkyaml::node& yaml, Room::Data& room, bool ver } // Carga un archivo de room en formato YAML -auto RoomLoader::loadYAML(const std::string& file_path, bool verbose) -> Room::Data { +auto RoomLoader::loadYAML(const std::string& file_path, bool verbose) -> Room::Data { // NOLINT(readability-convert-member-functions-to-static) Room::Data room; // Extract filename for logging diff --git a/source/game/gameplay/room_loader.hpp b/source/game/gameplay/room_loader.hpp index d4bcfb00..6397a2f4 100644 --- a/source/game/gameplay/room_loader.hpp +++ b/source/game/gameplay/room_loader.hpp @@ -67,7 +67,7 @@ class RoomLoader { * @param tilemap_2d Array 2D de tiles (16 rows × 32 cols) * @return Vector 1D flat con 512 elementos */ - static auto flattenTilemap(const std::vector>& tilemap_2d) -> std::vector; + static auto flattenTilemap(const std::vector>& tilemap_2d) -> std::vector; // NOLINT(readability-avoid-const-params-in-decls) /** * @brief Parsea la configuración general de la habitación diff --git a/source/game/gameplay/room_tracker.cpp b/source/game/gameplay/room_tracker.cpp index 3e8f4666..c68dc8eb 100644 --- a/source/game/gameplay/room_tracker.cpp +++ b/source/game/gameplay/room_tracker.cpp @@ -3,17 +3,17 @@ #include // Para std::ranges::any_of // Comprueba si la habitación ya ha sido visitada -auto RoomTracker::hasBeenVisited(const std::string& name) -> bool { - return std::ranges::any_of(rooms_, [&name](const auto& l) { return l == name; }); +auto RoomTracker::hasBeenVisited(const std::string& name) -> bool { // NOLINT(readability-convert-member-functions-to-static) + return std::ranges::any_of(rooms_, [&name](const auto& l) -> bool { return l == name; }); } // Añade la habitación a la lista -auto RoomTracker::addRoom(const std::string& name) -> bool { +auto RoomTracker::addRoom(const std::string& name) -> bool { // NOLINT(readability-convert-member-functions-to-static) // Comprueba si la habitación ya ha sido visitada if (!hasBeenVisited(name)) { // En caso contrario añádela a la lista rooms_.push_back(name); - return true; + return true; // NOLINT(readability-simplify-boolean-expr) } return false; diff --git a/source/game/gameplay/scoreboard.cpp b/source/game/gameplay/scoreboard.cpp index c42ab741..e2c0bae8 100644 --- a/source/game/gameplay/scoreboard.cpp +++ b/source/game/gameplay/scoreboard.cpp @@ -65,7 +65,7 @@ void Scoreboard::update(float delta_time) { } // Obtiene el tiempo transcurrido de partida -auto Scoreboard::getTime() -> Scoreboard::ClockData { +auto Scoreboard::getTime() -> Scoreboard::ClockData { // NOLINT(readability-convert-member-functions-to-static) const Uint32 TIME_ELAPSED = SDL_GetTicks() - data_->ini_clock - paused_time_elapsed_; ClockData time; @@ -149,7 +149,7 @@ void Scoreboard::fillTexture() { // Muestra si suena la música if (data_->music) { const Uint8 C = data_->color; - SDL_FRect clip = {0, 8, 8, 8}; + SDL_FRect clip = {.x = 0, .y = 8, .w = 8, .h = 8}; item_surface_->renderWithColorReplace(20 * Tile::SIZE, LINE2, 1, C, &clip); } @@ -157,13 +157,13 @@ void Scoreboard::fillTexture() { auto text = Resource::Cache::get()->getText("smb2"); const std::string TIME_TEXT = std::to_string((clock_.minutes % 100) / 10) + std::to_string(clock_.minutes % 10) + clock_.separator + std::to_string((clock_.seconds % 60) / 10) + std::to_string(clock_.seconds % 10); const std::string ITEMS_TEXT = std::to_string(data_->items / 100) + std::to_string((data_->items % 100) / 10) + std::to_string(data_->items % 10); - text->writeColored(Tile::SIZE, LINE1, Locale::get()->get("scoreboard.items"), data_->color); + text->writeColored(Tile::SIZE, LINE1, Locale::get()->get("scoreboard.items"), data_->color); // NOLINT(readability-static-accessed-through-instance) text->writeColored(17 * Tile::SIZE, LINE1, ITEMS_TEXT, items_color_); - text->writeColored(20 * Tile::SIZE, LINE1, Locale::get()->get("scoreboard.time"), data_->color); + text->writeColored(20 * Tile::SIZE, LINE1, Locale::get()->get("scoreboard.time"), data_->color); // NOLINT(readability-static-accessed-through-instance) text->writeColored(26 * Tile::SIZE, LINE1, TIME_TEXT, stringToColor("white")); const std::string ROOMS_TEXT = std::to_string(data_->rooms / 100) + std::to_string((data_->rooms % 100) / 10) + std::to_string(data_->rooms % 10); - text->writeColored(22 * Tile::SIZE, LINE2, Locale::get()->get("scoreboard.rooms"), stringToColor("white")); + text->writeColored(22 * Tile::SIZE, LINE2, Locale::get()->get("scoreboard.rooms"), stringToColor("white")); // NOLINT(readability-static-accessed-through-instance) text->writeColored(28 * Tile::SIZE, LINE2, ROOMS_TEXT, stringToColor("white")); // Deja el renderizador como estaba diff --git a/source/game/gameplay/stats.cpp b/source/game/gameplay/stats.cpp index 089b9929..9b0674bb 100644 --- a/source/game/gameplay/stats.cpp +++ b/source/game/gameplay/stats.cpp @@ -40,7 +40,7 @@ void Stats::init() } // Añade una muerte a las estadisticas -void Stats::addDeath(const std::string& name) { +void Stats::addDeath(const std::string& name) { // NOLINT(readability-convert-member-functions-to-static) // Primero busca si ya hay una entrada con ese nombre const int INDEX = findByName(name, buffer_list_); if (INDEX != -1) { @@ -58,7 +58,7 @@ void Stats::addDeath(const std::string& name) { } // Añade una visita a las estadisticas -void Stats::addVisit(const std::string& name) { +void Stats::addVisit(const std::string& name) { // NOLINT(readability-convert-member-functions-to-static) // Primero busca si ya hay una entrada con ese nombre const int INDEX = findByName(name, buffer_list_); if (INDEX != -1) { @@ -76,7 +76,7 @@ void Stats::addVisit(const std::string& name) { } // Busca una entrada en la lista por nombre -auto Stats::findByName(const std::string& name, const std::vector& list) -> int { +auto Stats::findByName(const std::string& name, const std::vector& list) -> int { // NOLINT(readability-convert-member-functions-to-static) int i = 0; for (const auto& l : list) { @@ -90,7 +90,7 @@ auto Stats::findByName(const std::string& name, const std::vector& lis } // Carga las estadisticas desde un fichero -auto Stats::loadFromFile(const std::string& file_path, std::vector& list) -> bool { +auto Stats::loadFromFile(const std::string& file_path, std::vector& list) -> bool { // NOLINT(readability-convert-member-functions-to-static) list.clear(); // Indicador de éxito en la carga @@ -109,7 +109,7 @@ auto Stats::loadFromFile(const std::string& file_path, std::vector& li line.pop_back(); } // Comprueba que la linea no sea un comentario - if (line.substr(0, 1) != "#") { + if (!line.starts_with("#")) { RoomData stat; std::stringstream ss(line); std::string tmp; @@ -159,7 +159,7 @@ void Stats::saveToFile(const std::string& file_path, const std::vector } // Calcula cual es la habitación con más muertes -void Stats::checkWorstNightmare() { +void Stats::checkWorstNightmare() { // NOLINT(readability-convert-member-functions-to-static) int deaths = 0; for (const auto& item : list_) { if (item.died > deaths) { @@ -171,7 +171,7 @@ void Stats::checkWorstNightmare() { // Añade una entrada al diccionario void Stats::addDictionary(const std::string& number, const std::string& name) { - dictionary_.push_back({number, name}); + dictionary_.push_back({.number = number, .name = name}); } // Vuelca los datos del buffer en la lista de estadisticas diff --git a/source/game/gameplay/tilemap_renderer.cpp b/source/game/gameplay/tilemap_renderer.cpp index 0436757f..c5df8308 100644 --- a/source/game/gameplay/tilemap_renderer.cpp +++ b/source/game/gameplay/tilemap_renderer.cpp @@ -42,7 +42,7 @@ void TilemapRenderer::update(float delta_time) { // Renderiza el mapa completo en pantalla void TilemapRenderer::render() { // Dibuja la textura con el mapa en pantalla - SDL_FRect dest = {0, 0, PlayArea::WIDTH, PlayArea::HEIGHT}; + SDL_FRect dest = {.x = 0, .y = 0, .w = PlayArea::WIDTH, .h = PlayArea::HEIGHT}; map_surface_->render(nullptr, &dest); // Dibuja los tiles animados @@ -103,7 +103,7 @@ void TilemapRenderer::redrawMap(const CollisionMap* collision_map) { #endif // Pinta el mapa estático y debug lines -void TilemapRenderer::fillMapTexture(const CollisionMap* collision_map) { +void TilemapRenderer::fillMapTexture(const CollisionMap* collision_map) { // NOLINT(readability-convert-member-functions-to-static) const Uint8 COLOR = stringToColor(bg_color_); auto previous_renderer = Screen::get()->getRendererSurface(); Screen::get()->setRendererSurface(map_surface_); @@ -111,7 +111,7 @@ void TilemapRenderer::fillMapTexture(const CollisionMap* collision_map) { // Los tileSetFiles son de 20x20 tiles. El primer tile es el 0. Cuentan hacia la derecha y hacia abajo - SDL_FRect clip = {0, 0, TILE_SIZE, TILE_SIZE}; + SDL_FRect clip = {.x = 0, .y = 0, .w = TILE_SIZE, .h = TILE_SIZE}; for (int y = 0; y < MAP_HEIGHT; ++y) { for (int x = 0; x < MAP_WIDTH; ++x) { // Tiled pone los tiles vacios del mapa como cero y empieza a contar de 1 a n. @@ -145,7 +145,7 @@ void TilemapRenderer::fillMapTexture(const CollisionMap* collision_map) { } // Localiza todos los tiles animados -void TilemapRenderer::setAnimatedTiles(const CollisionMap* collision_map) { +void TilemapRenderer::setAnimatedTiles(const CollisionMap* collision_map) { // NOLINT(readability-convert-member-functions-to-static) // Recorre la habitación entera por filas buscando tiles de tipo t_animated for (int i = 0; i < (int)tile_map_.size(); ++i) { const auto TILE_TYPE = collision_map->getTile(i); @@ -168,7 +168,7 @@ void TilemapRenderer::setAnimatedTiles(const CollisionMap* collision_map) { } // Actualiza tiles animados -void TilemapRenderer::updateAnimatedTiles() { +void TilemapRenderer::updateAnimatedTiles() { // NOLINT(readability-make-member-function-const) const int NUM_FRAMES = 4; // Calcular frame actual basado en tiempo diff --git a/source/game/options.cpp b/source/game/options.cpp index 7799278a..f4f5942d 100644 --- a/source/game/options.cpp +++ b/source/game/options.cpp @@ -308,6 +308,17 @@ namespace Options { } } + // Helper: carga el campo palette con validación extra + void loadPaletteFromYaml(const fkyaml::node& vid) { + if (!vid.contains("palette")) { return; } + try { + auto palette_str = vid["palette"].get_value(); + video.palette = isValidPalette(palette_str) ? palette_str : Defaults::Video::PALETTE_NAME; + } catch (...) { + video.palette = Defaults::Video::PALETTE_NAME; + } + } + // Carga los campos básicos de configuración de video void loadBasicVideoFieldsFromYaml(const fkyaml::node& vid) { // fullscreen (antes era "mode") @@ -377,18 +388,7 @@ namespace Options { } } - if (vid.contains("palette")) { - try { - auto palette_str = vid["palette"].get_value(); - if (isValidPalette(palette_str)) { - video.palette = palette_str; - } else { - video.palette = Defaults::Video::PALETTE_NAME; - } - } catch (...) { - video.palette = Defaults::Video::PALETTE_NAME; - } - } + loadPaletteFromYaml(vid); } // Carga configuración de video desde YAML @@ -745,7 +745,9 @@ namespace Options { // Preservar el índice cargado desde config.yaml; clampar al rango válido. if (!postfx_presets.empty()) { current_postfx_preset = std::clamp( - current_postfx_preset, 0, static_cast(postfx_presets.size()) - 1); + current_postfx_preset, + 0, + static_cast(postfx_presets.size()) - 1); } else { current_postfx_preset = 0; } @@ -854,12 +856,12 @@ namespace Options { // Cargar los presets recién creados postfx_presets.clear(); - postfx_presets.push_back({"CRT", 0.6F, 0.7F, 0.3F, 0.6F, 0.8F, 0.0F, 0.0F, 0.0F}); - postfx_presets.push_back({"NTSC", 0.4F, 0.5F, 0.2F, 0.4F, 0.5F, 0.0F, 0.6F, 0.0F}); - postfx_presets.push_back({"CURVED", 0.5F, 0.6F, 0.1F, 0.5F, 0.7F, 0.8F, 0.0F, 0.0F}); - postfx_presets.push_back({"SCANLINES",0.0F, 0.8F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F}); - postfx_presets.push_back({"SUBTLE", 0.3F, 0.4F, 0.05F, 0.0F, 0.3F, 0.0F, 0.0F, 0.0F}); - postfx_presets.push_back({"CRT LIVE", 0.5F, 0.6F, 0.3F, 0.3F, 0.4F, 0.3F, 0.4F, 0.8F}); + postfx_presets.push_back({"CRT", 0.6F, 0.7F, 0.3F, 0.6F, 0.8F, 0.0F, 0.0F, 0.0F}); + postfx_presets.push_back({"NTSC", 0.4F, 0.5F, 0.2F, 0.4F, 0.5F, 0.0F, 0.6F, 0.0F}); + postfx_presets.push_back({"CURVED", 0.5F, 0.6F, 0.1F, 0.5F, 0.7F, 0.8F, 0.0F, 0.0F}); + postfx_presets.push_back({"SCANLINES", 0.0F, 0.8F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F}); + postfx_presets.push_back({"SUBTLE", 0.3F, 0.4F, 0.05F, 0.0F, 0.3F, 0.0F, 0.0F, 0.0F}); + postfx_presets.push_back({"CRT LIVE", 0.5F, 0.6F, 0.3F, 0.3F, 0.4F, 0.3F, 0.4F, 0.8F}); current_postfx_preset = 0; return true; diff --git a/source/game/options.hpp b/source/game/options.hpp index f692a461..ce6a48e7 100644 --- a/source/game/options.hpp +++ b/source/game/options.hpp @@ -117,15 +117,15 @@ namespace Options { // Estructura para un preset de PostFX struct PostFXPreset { - std::string name; // Nombre del preset - float vignette{0.6F}; // Intensidad de la viñeta (0.0 = ninguna, 1.0 = máxima) - float scanlines{0.7F}; // Intensidad de las scanlines (0.0 = desactivadas, 1.0 = máximas) - float chroma{0.15F}; // Intensidad de la aberración cromática (0.0 = ninguna, 1.0 = máxima) - float mask{0.0F}; // Intensidad de la máscara de fósforo RGB (0.0 = desactivada, 1.0 = máxima) - float gamma{0.0F}; // Corrección gamma input 2.4 / output 2.2 (0.0 = off, 1.0 = plena) - float curvature{0.0F}; // Distorsión barrel CRT (0.0 = plana, 1.0 = máxima curvatura) - float bleeding{0.0F}; // Sangrado de color NTSC horizontal Y/C (0.0 = off, 1.0 = máximo) - float flicker{0.0F}; // Parpadeo de fósforo CRT ~50 Hz (0.0 = off, 1.0 = máximo) + std::string name; // Nombre del preset + float vignette{0.6F}; // Intensidad de la viñeta (0.0 = ninguna, 1.0 = máxima) + float scanlines{0.7F}; // Intensidad de las scanlines (0.0 = desactivadas, 1.0 = máximas) + float chroma{0.15F}; // Intensidad de la aberración cromática (0.0 = ninguna, 1.0 = máxima) + float mask{0.0F}; // Intensidad de la máscara de fósforo RGB (0.0 = desactivada, 1.0 = máxima) + float gamma{0.0F}; // Corrección gamma input 2.4 / output 2.2 (0.0 = off, 1.0 = plena) + float curvature{0.0F}; // Distorsión barrel CRT (0.0 = plana, 1.0 = máxima curvatura) + float bleeding{0.0F}; // Sangrado de color NTSC horizontal Y/C (0.0 = off, 1.0 = máximo) + float flicker{0.0F}; // Parpadeo de fósforo CRT ~50 Hz (0.0 = off, 1.0 = máximo) }; // --- Variables globales --- diff --git a/source/game/scenes/credits.cpp b/source/game/scenes/credits.cpp index b4b24f55..e0717cb9 100644 --- a/source/game/scenes/credits.cpp +++ b/source/game/scenes/credits.cpp @@ -30,7 +30,7 @@ Credits::Credits() // Configura la escena SceneManager::current = SceneManager::Scene::CREDITS; SceneManager::options = SceneManager::Options::NONE; - shining_sprite_->setPos({194, 174, 8, 8}); + shining_sprite_->setPos({.x = 194, .y = 174, .w = 8, .h = 8}); Screen::get()->setBorderColor(static_cast(PaletteColor::BLACK)); // Cambia el color del borde fillTexture(); // Escribe el texto en la textura @@ -52,37 +52,37 @@ void Credits::handleInput() { } // Inicializa los textos -void Credits::iniTexts() { +void Credits::iniTexts() { // NOLINT(readability-convert-member-functions-to-static) auto* loc = Locale::get(); texts_.clear(); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.instructions"), static_cast(PaletteColor::YELLOW)}); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.l0"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.l1"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.l2"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.instructions"), .color = static_cast(PaletteColor::YELLOW)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.l0"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.l1"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.l2"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.keys"), static_cast(PaletteColor::YELLOW)}); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.keys_move"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.f8"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.f11"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.f1f2"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.f3"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.f9"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.keys"), .color = static_cast(PaletteColor::YELLOW)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.keys_move"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.f8"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.f11"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.f1f2"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.f3"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.f9"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.author"), static_cast(PaletteColor::YELLOW)}); - texts_.push_back({loc->get("credits.date"), static_cast(PaletteColor::YELLOW)}); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.author"), .color = static_cast(PaletteColor::YELLOW)}); + texts_.push_back({.label = loc->get("credits.date"), .color = static_cast(PaletteColor::YELLOW)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); - texts_.push_back({loc->get("credits.love"), static_cast(PaletteColor::WHITE)}); - texts_.push_back({"", static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = loc->get("credits.love"), .color = static_cast(PaletteColor::WHITE)}); + texts_.push_back({.label = "", .color = static_cast(PaletteColor::WHITE)}); } // Escribe el texto en la textura diff --git a/source/game/scenes/credits.hpp b/source/game/scenes/credits.hpp index dff79661..04549730 100644 --- a/source/game/scenes/credits.hpp +++ b/source/game/scenes/credits.hpp @@ -14,7 +14,7 @@ class Credits { public: // --- Constructor y Destructor --- Credits(); - ~Credits(); + ~Credits(); // NOLINT(modernize-use-equals-default, performance-trivially-destructible) -- defined in .cpp for unique_ptr with forward declarations // --- Bucle principal --- void run(); diff --git a/source/game/scenes/ending.cpp b/source/game/scenes/ending.cpp index 9b64beee..04e2b323 100644 --- a/source/game/scenes/ending.cpp +++ b/source/game/scenes/ending.cpp @@ -18,6 +18,9 @@ #include "utils/delta_timer.hpp" // Para DeltaTimer #include "utils/utils.hpp" // Para PaletteColor +// Destructor +Ending::~Ending() = default; + // Constructor Ending::Ending() : delta_timer_(std::make_unique()) { @@ -31,9 +34,6 @@ Ending::Ending() Screen::get()->setBorderColor(static_cast(PaletteColor::BLACK)); // Cambia el color del borde } -// Destructor -Ending::~Ending() = default; - // Actualiza el objeto void Ending::update() { const float DELTA_TIME = delta_timer_->tick(); @@ -170,39 +170,39 @@ void Ending::updateState(float delta_time) { } // Inicializa los textos -void Ending::iniTexts() { +void Ending::iniTexts() { // NOLINT(readability-convert-member-functions-to-static) // Vector con los textos (traducidos según el idioma activo) std::vector texts; auto* loc = Locale::get(); // Escena #0 - texts.push_back({loc->get("ending.t0"), 32}); - texts.push_back({loc->get("ending.t1"), 42}); - texts.push_back({loc->get("ending.t2"), 142}); - texts.push_back({loc->get("ending.t3"), 152}); + texts.push_back({.caption = loc->get("ending.t0"), .pos = 32}); + texts.push_back({.caption = loc->get("ending.t1"), .pos = 42}); + texts.push_back({.caption = loc->get("ending.t2"), .pos = 142}); + texts.push_back({.caption = loc->get("ending.t3"), .pos = 152}); // Escena #1 - texts.push_back({loc->get("ending.t4"), 1}); - texts.push_back({loc->get("ending.t5"), 11}); - texts.push_back({loc->get("ending.t6"), 21}); + texts.push_back({.caption = loc->get("ending.t4"), .pos = 1}); + texts.push_back({.caption = loc->get("ending.t5"), .pos = 11}); + texts.push_back({.caption = loc->get("ending.t6"), .pos = 21}); - texts.push_back({loc->get("ending.t7"), 161}); - texts.push_back({loc->get("ending.t8"), 171}); + texts.push_back({.caption = loc->get("ending.t7"), .pos = 161}); + texts.push_back({.caption = loc->get("ending.t8"), .pos = 171}); - texts.push_back({loc->get("ending.t9"), 181}); + texts.push_back({.caption = loc->get("ending.t9"), .pos = 181}); // Escena #2 - texts.push_back({loc->get("ending.t10"), 19}); - texts.push_back({loc->get("ending.t11"), 29}); + texts.push_back({.caption = loc->get("ending.t10"), .pos = 19}); + texts.push_back({.caption = loc->get("ending.t11"), .pos = 29}); // Escena #3 - texts.push_back({loc->get("ending.t12"), 36}); - texts.push_back({loc->get("ending.t13"), 46}); + texts.push_back({.caption = loc->get("ending.t12"), .pos = 36}); + texts.push_back({.caption = loc->get("ending.t13"), .pos = 46}); // Escena #4 - texts.push_back({loc->get("ending.t14"), 36}); - texts.push_back({loc->get("ending.t15"), 46}); - texts.push_back({loc->get("ending.t16"), 158}); + texts.push_back({.caption = loc->get("ending.t14"), .pos = 36}); + texts.push_back({.caption = loc->get("ending.t15"), .pos = 46}); + texts.push_back({.caption = loc->get("ending.t16"), .pos = 158}); // Crea los sprites sprite_texts_.clear(); @@ -242,11 +242,11 @@ void Ending::iniPics() { // Vector con las rutas y la posición std::vector pics; - pics.push_back({"ending1.gif", 48}); - pics.push_back({"ending2.gif", 26}); - pics.push_back({"ending3.gif", 29}); - pics.push_back({"ending4.gif", 63}); - pics.push_back({"ending5.gif", 53}); + pics.push_back({.caption = "ending1.gif", .pos = 48}); + pics.push_back({.caption = "ending2.gif", .pos = 26}); + pics.push_back({.caption = "ending3.gif", .pos = 29}); + pics.push_back({.caption = "ending4.gif", .pos = 63}); + pics.push_back({.caption = "ending5.gif", .pos = 53}); // Crea los sprites sprite_pics_.clear(); @@ -274,7 +274,7 @@ void Ending::iniPics() { } // Inicializa las escenas -void Ending::iniScenes() { +void Ending::iniScenes() { // NOLINT(readability-convert-member-functions-to-static) // Variable para los tiempos int trigger; constexpr int LAPSE = 80; @@ -291,13 +291,13 @@ void Ending::iniScenes() { sc.text_index.clear(); trigger = 85 * 2; trigger += LAPSE; - sc.text_index.push_back({0, trigger}); + sc.text_index.push_back({.index = 0, .trigger = trigger}); trigger += LAPSE; - sc.text_index.push_back({1, trigger}); + sc.text_index.push_back({.index = 1, .trigger = trigger}); trigger += LAPSE * 3; - sc.text_index.push_back({2, trigger}); + sc.text_index.push_back({.index = 2, .trigger = trigger}); trigger += LAPSE; - sc.text_index.push_back({3, trigger}); + sc.text_index.push_back({.index = 3, .trigger = trigger}); scenes_.push_back(sc); // Crea la escena #1 @@ -306,17 +306,17 @@ void Ending::iniScenes() { sc.text_index.clear(); trigger = 140 * 2; trigger += LAPSE; - sc.text_index.push_back({4, trigger}); + sc.text_index.push_back({.index = 4, .trigger = trigger}); trigger += LAPSE; - sc.text_index.push_back({5, trigger}); + sc.text_index.push_back({.index = 5, .trigger = trigger}); trigger += LAPSE; - sc.text_index.push_back({6, trigger}); + sc.text_index.push_back({.index = 6, .trigger = trigger}); trigger += LAPSE * 3; - sc.text_index.push_back({7, trigger}); + sc.text_index.push_back({.index = 7, .trigger = trigger}); trigger += LAPSE; - sc.text_index.push_back({8, trigger}); + sc.text_index.push_back({.index = 8, .trigger = trigger}); trigger += LAPSE * 3; - sc.text_index.push_back({9, trigger}); + sc.text_index.push_back({.index = 9, .trigger = trigger}); scenes_.push_back(sc); // Crea la escena #2 @@ -325,9 +325,9 @@ void Ending::iniScenes() { sc.text_index.clear(); trigger = 148 / 2; trigger += LAPSE; - sc.text_index.push_back({10, trigger}); + sc.text_index.push_back({.index = 10, .trigger = trigger}); trigger += LAPSE; - sc.text_index.push_back({11, trigger}); + sc.text_index.push_back({.index = 11, .trigger = trigger}); scenes_.push_back(sc); // Crea la escena #3 @@ -336,9 +336,9 @@ void Ending::iniScenes() { sc.text_index.clear(); trigger = 87 / 2; trigger += LAPSE; - sc.text_index.push_back({12, trigger}); + sc.text_index.push_back({.index = 12, .trigger = trigger}); trigger += LAPSE / 2; - sc.text_index.push_back({13, trigger}); + sc.text_index.push_back({.index = 13, .trigger = trigger}); scenes_.push_back(sc); // Crea la escena #4 @@ -347,11 +347,11 @@ void Ending::iniScenes() { sc.text_index.clear(); trigger = 91 * 2; trigger += LAPSE; - sc.text_index.push_back({14, trigger}); + sc.text_index.push_back({.index = 14, .trigger = trigger}); trigger += LAPSE * 2; - sc.text_index.push_back({15, trigger}); + sc.text_index.push_back({.index = 15, .trigger = trigger}); trigger += LAPSE * 3; - sc.text_index.push_back({16, trigger}); + sc.text_index.push_back({.index = 16, .trigger = trigger}); scenes_.push_back(sc); } diff --git a/source/game/scenes/ending.hpp b/source/game/scenes/ending.hpp index 823f300f..6da430fb 100644 --- a/source/game/scenes/ending.hpp +++ b/source/game/scenes/ending.hpp @@ -14,7 +14,7 @@ class Ending { public: // --- Constructor y Destructor --- Ending(); - ~Ending(); + ~Ending(); // NOLINT(modernize-use-equals-default, performance-trivially-destructible) -- defined in .cpp for unique_ptr with forward declarations // --- Bucle principal --- void run(); diff --git a/source/game/scenes/ending2.cpp b/source/game/scenes/ending2.cpp index 0a48d0ec..e1f1ad92 100644 --- a/source/game/scenes/ending2.cpp +++ b/source/game/scenes/ending2.cpp @@ -374,7 +374,7 @@ void Ending2::renderTexts() { } // Coloca los sprites en su sito -void Ending2::placeSprites() { +void Ending2::placeSprites() const { for (int i = 0; i < static_cast(sprites_.size()); ++i) { const float X = i % 2 == 0 ? FIRST_COL : SECOND_COL; const float Y = ((i / 1) * (sprite_max_height_ + DIST_SPRITE_TEXT + Resource::Cache::get()->getText("smb2")->getCharacterSize() + DIST_SPRITE_SPRITE)) + Options::game.height + INITIAL_Y_OFFSET; @@ -383,7 +383,7 @@ void Ending2::placeSprites() { const float DX = -(W / 2); const float DY = sprite_max_height_ - H; - sprites_.at(i)->setPos({X + DX, Y + DY, W, H}); + sprites_.at(i)->setPos({.x = X + DX, .y = Y + DY, .w = W, .h = H}); sprites_.at(i)->setVelY(SPRITE_DESP_SPEED); } @@ -395,7 +395,7 @@ void Ending2::placeSprites() { } // Crea los sprites con las texturas con los textos -void Ending2::createSpriteTexts() { +void Ending2::createSpriteTexts() { // NOLINT(readability-convert-member-functions-to-static) // Crea los sprites de texto a partir de la lista for (size_t i = 0; i < sprite_list_.size(); ++i) { auto text = Resource::Cache::get()->getText("smb2"); @@ -404,7 +404,7 @@ void Ending2::createSpriteTexts() { std::string txt = sprite_list_[i]; std::ranges::replace(txt, '_', ' '); // Reemplaza '_' por ' ' if (txt == "player") { - txt = Locale::get()->get("ending2.jaildoctor"); // Reemplaza "player" por nombre localizado + txt = Locale::get()->get("ending2.jaildoctor"); // NOLINT(readability-static-accessed-through-instance) Reemplaza "player" por nombre localizado } // Calcula las dimensiones del texto @@ -426,7 +426,7 @@ void Ending2::createSpriteTexts() { text->write(0, 0, txt); // Crea el sprite - SDL_FRect pos = {X, Y, W, H}; + SDL_FRect pos = {.x = X, .y = Y, .w = W, .h = H}; sprite_texts_.emplace_back(std::make_shared(surface, pos)); sprite_texts_.back()->setColorReplace(1, static_cast(PaletteColor::WHITE)); sprite_texts_.back()->setProgress(1.0F); // comença invisible @@ -436,7 +436,7 @@ void Ending2::createSpriteTexts() { } // Crea los sprites con las texturas con los textos del final -void Ending2::createTexts() { +void Ending2::createTexts() { // NOLINT(readability-convert-member-functions-to-static) // Crea los primeros textos std::vector list; list.emplace_back(Locale::get()->get("ending2.starring")); @@ -459,7 +459,7 @@ void Ending2::createTexts() { text->write(0, 0, list[i]); // Crea el sprite - SDL_FRect pos = {X + DX, Y, W, H}; + SDL_FRect pos = {.x = X + DX, .y = Y, .w = W, .h = H}; texts_.emplace_back(std::make_shared(surface, pos)); texts_.back()->setProgress(1.0F); // comença invisible texts_.back()->setVelY(SPRITE_DESP_SPEED); @@ -489,7 +489,7 @@ void Ending2::createTexts() { text->write(0, 0, list[i]); // Crea el sprite - SDL_FRect pos = {X + DX, Y, W, H}; + SDL_FRect pos = {.x = X + DX, .y = Y, .w = W, .h = H}; texts_.emplace_back(std::make_shared(surface, pos)); texts_.back()->setProgress(1.0F); // comença invisible texts_.back()->setVelY(SPRITE_DESP_SPEED); diff --git a/source/game/scenes/ending2.hpp b/source/game/scenes/ending2.hpp index b1388eb8..fe2dc93a 100644 --- a/source/game/scenes/ending2.hpp +++ b/source/game/scenes/ending2.hpp @@ -70,7 +70,7 @@ class Ending2 { void renderSprites(); // Dibuja los sprites void renderSpriteTexts(); // Dibuja los sprites con el texto void renderTexts(); // Dibuja los sprites con el texto del final - void placeSprites(); // Coloca los sprites en su sitio + void placeSprites() const; // Coloca los sprites en su sitio void createSpriteTexts(); // Crea los sprites con las texturas con los textos void createTexts(); // Crea los sprites con las texturas con los textos del final void updateFinalFade(); // Actualiza el fade final diff --git a/source/game/scenes/game.cpp b/source/game/scenes/game.cpp index 79ea620a..cfb4a5ea 100644 --- a/source/game/scenes/game.cpp +++ b/source/game/scenes/game.cpp @@ -94,9 +94,9 @@ void Game::handleInput() { } // Input de pausa solo en estado PLAYING - if (Input::get()->checkAction(InputAction::PAUSE, Input::DO_NOT_ALLOW_REPEAT)) { + if (Input::get()->checkAction(InputAction::PAUSE, Input::DO_NOT_ALLOW_REPEAT)) { // NOLINT(readability-static-accessed-through-instance) togglePause(); - Notifier::get()->show({paused_ ? Locale::get()->get("game.paused") : Locale::get()->get("game.running")}); + Notifier::get()->show({paused_ ? Locale::get()->get("game.paused") : Locale::get()->get("game.running")}); // NOLINT(readability-static-accessed-through-instance) } GlobalInputs::handle(); @@ -371,7 +371,7 @@ void Game::renderPostFadeEnding() { static void toggleCheat(Options::Cheat::State& cheat, const std::string& label) { cheat = (cheat == Options::Cheat::State::ENABLED) ? Options::Cheat::State::DISABLED : Options::Cheat::State::ENABLED; const bool ENABLED = (cheat == Options::Cheat::State::ENABLED); - Notifier::get()->show({label + (ENABLED ? Locale::get()->get("game.enabled") : Locale::get()->get("game.disabled"))}, Notifier::Style::DEFAULT, -1, true); + Notifier::get()->show({label + (ENABLED ? Locale::get()->get("game.enabled") : Locale::get()->get("game.disabled"))}, Notifier::Style::DEFAULT, -1, true); // NOLINT(readability-static-accessed-through-instance) } // Pasa la información de debug @@ -390,7 +390,7 @@ void Game::renderDebugInfo() { auto surface = Screen::get()->getRendererSurface(); // Borra el marcador - SDL_FRect rect = {0, 18 * Tile::SIZE, PlayArea::WIDTH, GameCanvas::HEIGHT - PlayArea::HEIGHT}; + SDL_FRect rect = {.x = 0, .y = 18 * Tile::SIZE, .w = PlayArea::WIDTH, .h = GameCanvas::HEIGHT - PlayArea::HEIGHT}; surface->fillRect(&rect, static_cast(PaletteColor::BLACK)); // Pinta la rejilla @@ -406,12 +406,12 @@ void Game::renderDebugInfo() { }*/ // Pinta el texto - Debug::get()->setPos({1, 18 * 8}); + Debug::get()->setPos({.x = 1, .y = 18 * 8}); Debug::get()->render(); } // Comprueba los eventos -void Game::handleDebugEvents(const SDL_Event& event) { +void Game::handleDebugEvents(const SDL_Event& event) { // NOLINT(readability-convert-member-functions-to-static) if (event.type == SDL_EVENT_KEY_DOWN && static_cast(event.key.repeat) == 0) { switch (event.key.key) { case SDLK_R: @@ -435,26 +435,26 @@ void Game::handleDebugEvents(const SDL_Event& event) { break; case SDLK_1: - toggleCheat(Options::cheats.infinite_lives, Locale::get()->get("game.cheat_infinite_lives")); + toggleCheat(Options::cheats.infinite_lives, Locale::get()->get("game.cheat_infinite_lives")); // NOLINT(readability-static-accessed-through-instance) player_->setColor(); break; case SDLK_2: - toggleCheat(Options::cheats.invincible, Locale::get()->get("game.cheat_invincible")); + toggleCheat(Options::cheats.invincible, Locale::get()->get("game.cheat_invincible")); // NOLINT(readability-static-accessed-through-instance) player_->setColor(); break; case SDLK_3: - toggleCheat(Options::cheats.jail_is_open, Locale::get()->get("game.cheat_jail_open")); + toggleCheat(Options::cheats.jail_is_open, Locale::get()->get("game.cheat_jail_open")); // NOLINT(readability-static-accessed-through-instance) break; case SDLK_7: - Notifier::get()->show({Locale::get()->get("achievements.header"), Locale::get()->get("achievements.c11")}, Notifier::Style::CHEEVO, -1, false, "F7"); + Notifier::get()->show({Locale::get()->get("achievements.header"), Locale::get()->get("achievements.c11")}, Notifier::Style::CHEEVO, -1, false, "F7"); // NOLINT(readability-static-accessed-through-instance) break; case SDLK_0: Debug::get()->toggleEnabled(); - Notifier::get()->show({Debug::get()->isEnabled() ? Locale::get()->get("game.debug_enabled") : Locale::get()->get("game.debug_disabled")}); + Notifier::get()->show({Debug::get()->isEnabled() ? Locale::get()->get("game.debug_enabled") : Locale::get()->get("game.debug_disabled")}); // NOLINT(readability-static-accessed-through-instance) room_->redrawMap(); Options::cheats.invincible = static_cast(Debug::get()->isEnabled()); player_->setColor(); @@ -556,7 +556,7 @@ auto Game::changeRoom(const std::string& room_path) -> bool { } // Verifica que exista el fichero que se va a cargar - if (!Resource::List::get()->get(room_path).empty()) { + if (!Resource::List::get()->get(room_path).empty()) { // NOLINT(readability-static-accessed-through-instance) // Crea un objeto habitación nuevo a partir del fichero room_ = std::make_shared(room_path, scoreboard_data_); @@ -655,7 +655,7 @@ void Game::killPlayer() { } // Pone el color del marcador en función del color del borde de la habitación -void Game::setScoreBoardColor() { +void Game::setScoreBoardColor() { // NOLINT(readability-convert-member-functions-to-static) // Obtiene el color del borde const Uint8 BORDER_COLOR = room_->getBorderColor(); @@ -734,7 +734,7 @@ void Game::checkRestoringJail(float delta_time) { } // Inicializa el diccionario de las estadísticas -void Game::initStats() { +void Game::initStats() { // NOLINT(readability-convert-member-functions-to-static) auto list = Resource::Cache::get()->getRooms(); for (const auto& room : list) { @@ -745,7 +745,7 @@ void Game::initStats() { } // Crea la textura con el nombre de la habitación -void Game::fillRoomNameTexture() { +void Game::fillRoomNameTexture() { // NOLINT(readability-convert-member-functions-to-static) // Pone la textura como destino de renderizado auto previuos_renderer = Screen::get()->getRendererSurface(); Screen::get()->setRendererSurface(room_name_surface_); @@ -762,7 +762,7 @@ void Game::fillRoomNameTexture() { } // Comprueba algunos logros -void Game::checkSomeCheevos() { +void Game::checkSomeCheevos() { // NOLINT(readability-convert-member-functions-to-static) auto* cheevos = Cheevos::get(); // Logros sobre la cantidad de items @@ -796,7 +796,7 @@ void Game::checkSomeCheevos() { } // Comprueba los logros de completar el juego -void Game::checkEndGameCheevos() { +void Game::checkEndGameCheevos() { // NOLINT(readability-convert-member-functions-to-static) auto* cheevos = Cheevos::get(); // "Complete the game" @@ -820,7 +820,7 @@ void Game::checkEndGameCheevos() { } // Inicializa al jugador -void Game::initPlayer(const Player::SpawnData& spawn_point, std::shared_ptr room) { +void Game::initPlayer(const Player::SpawnData& spawn_point, std::shared_ptr room) { // NOLINT(readability-convert-member-functions-to-static) std::string player_animations = Options::cheats.alternate_skin == Options::Cheat::State::ENABLED ? "player2.yaml" : "player.yaml"; const Player::Data PLAYER{.spawn_data = spawn_point, .animations_path = player_animations, .room = std::move(room)}; player_ = std::make_shared(PLAYER); diff --git a/source/game/scenes/game_over.cpp b/source/game/scenes/game_over.cpp index b329b65d..fb32842e 100644 --- a/source/game/scenes/game_over.cpp +++ b/source/game/scenes/game_over.cpp @@ -70,7 +70,7 @@ void GameOver::render() { // Escribe el texto de GAME OVER auto* loc = Locale::get(); - text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, TEXT_Y, loc->get("game_over.title"), 1, color_); + text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, TEXT_Y, loc->get("game_over.title"), 1, color_); // NOLINT(readability-static-accessed-through-instance) // Dibuja los sprites (ya posicionados en el constructor, solo ajustamos Y) player_sprite_->setPosY(TEXT_Y + SPRITE_Y_OFFSET); @@ -80,11 +80,11 @@ void GameOver::render() { // Escribe el texto con las habitaciones y los items const std::string ITEMS_TEXT = std::to_string(Options::stats.items / 100) + std::to_string((Options::stats.items % 100) / 10) + std::to_string(Options::stats.items % 10); const std::string ROOMS_TEXT = std::to_string(Options::stats.rooms / 100) + std::to_string((Options::stats.rooms % 100) / 10) + std::to_string(Options::stats.rooms % 10); - text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, TEXT_Y + ITEMS_Y_OFFSET, loc->get("game_over.items") + ITEMS_TEXT, 1, color_); - text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, TEXT_Y + ROOMS_Y_OFFSET, loc->get("game_over.rooms") + ROOMS_TEXT, 1, color_); + text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, TEXT_Y + ITEMS_Y_OFFSET, loc->get("game_over.items") + ITEMS_TEXT, 1, color_); // NOLINT(readability-static-accessed-through-instance) + text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, TEXT_Y + ROOMS_Y_OFFSET, loc->get("game_over.rooms") + ROOMS_TEXT, 1, color_); // NOLINT(readability-static-accessed-through-instance) // Escribe el texto con "Tu peor pesadilla" - text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, TEXT_Y + NIGHTMARE_TITLE_Y_OFFSET, loc->get("game_over.worst_nightmare"), 1, color_); + text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, TEXT_Y + NIGHTMARE_TITLE_Y_OFFSET, loc->get("game_over.worst_nightmare"), 1, color_); // NOLINT(readability-static-accessed-through-instance) text->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, GameCanvas::CENTER_X, TEXT_Y + NIGHTMARE_TEXT_Y_OFFSET, Options::stats.worst_nightmare, 1, color_); // Vuelca el contenido del renderizador en pantalla diff --git a/source/game/scenes/loading_screen.cpp b/source/game/scenes/loading_screen.cpp index 0f48fe99..e13906a6 100644 --- a/source/game/scenes/loading_screen.cpp +++ b/source/game/scenes/loading_screen.cpp @@ -63,7 +63,7 @@ void LoadingScreen::handleInput() { } // Inicializa el array de índices de líneas (imita el direccionamiento de memoria del Spectrum) -void LoadingScreen::initLineIndexArray() { +void LoadingScreen::initLineIndexArray() { // NOLINT(readability-convert-member-functions-to-static) for (int i = 0; i < MONO_TOTAL_LINES; ++i) { if (i < 64) { // Primer bloque de 2K line_index_[i] = ((i % 8) * 8) + (i / 8); @@ -449,7 +449,7 @@ void LoadingScreen::renderBorder() { } // Escribe el nombre del programa -void LoadingScreen::printProgramName() { +void LoadingScreen::printProgramName() { // NOLINT(readability-convert-member-functions-to-static) auto previous_renderer = Screen::get()->getRendererSurface(); Screen::get()->setRendererSurface(screen_surface_); program_sprite_->render(); @@ -463,7 +463,7 @@ void LoadingScreen::updateCarrier(float delta_time) { // Oscilación compuesta: mezcla de dos frecuencias para evitar patrón predecible const float MODULATION = std::sin(carrier_.total_time * 1.2F) * std::sin((carrier_.total_time * 0.35F) + 1.0F); - const float SPEED = CARRIER_BASE_SPEED * (0.5F + 0.5F * MODULATION); // rango [-200, 0] + const float SPEED = CARRIER_BASE_SPEED * (0.5F + (0.5F * MODULATION)); // rango [-200, 0] carrier_.offset += SPEED * delta_time; diff --git a/source/game/scenes/loading_screen.hpp b/source/game/scenes/loading_screen.hpp index 49b26047..56719b0b 100644 --- a/source/game/scenes/loading_screen.hpp +++ b/source/game/scenes/loading_screen.hpp @@ -113,7 +113,7 @@ class LoadingScreen { // Arrays y estructuras auxiliares std::array line_index_; // El orden en el que se procesan las 192 líneas de la pantalla de carga - SDL_FRect load_rect_{0.0F, 0.0F, 0.0F, 1.0F}; // Rectángulo para dibujar la pantalla de carga + SDL_FRect load_rect_{.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 1.0F}; // Rectángulo para dibujar la pantalla de carga Carrier carrier_; // Estructura para los efectos de la carga de cabeceras Noise noise_; // Variaciones de ruido durante los silencios diff --git a/source/game/scenes/logo.cpp b/source/game/scenes/logo.cpp index fe61ee62..2ea21ad1 100644 --- a/source/game/scenes/logo.cpp +++ b/source/game/scenes/logo.cpp @@ -40,8 +40,8 @@ Logo::Logo() // Seleccionar función de easing aleatoria para la animación del logo // Usamos lambdas para funciones con parámetros opcionales static const std::array EASING_OPTIONS = { - [](float t) { return Easing::backOut(t); }, // Overshoot retro - [](float t) { return Easing::elasticOut(t); }, // Rebote múltiple con oscilación + [](float t) -> float { return Easing::backOut(t); }, // Overshoot retro + [](float t) -> float { return Easing::elasticOut(t); }, // Rebote múltiple con oscilación Easing::bounceOut, // Rebote físico decreciente Easing::cubicOut // Suavizado sin overshoot (para variedad) }; @@ -94,7 +94,7 @@ void Logo::updateJAILGAMES(float delta_time) { } // Calcula el índice de color según el progreso (0.0-1.0) -auto Logo::getColorIndex(float progress) const -> int { +auto Logo::getColorIndex(float progress) const -> int { // NOLINT(readability-convert-member-functions-to-static) // Asegurar que progress esté en el rango [0.0, 1.0] progress = std::clamp(progress, 0.0F, 1.0F); @@ -207,7 +207,7 @@ void Logo::update() { } // Dibuja en pantalla -void Logo::render() { +void Logo::render() { // NOLINT(readability-convert-member-functions-to-static) // Prepara para empezar a dibujar en la textura de juego Screen::get()->start(); Screen::get()->clearSurface(static_cast(PaletteColor::BLACK)); @@ -248,7 +248,7 @@ void Logo::endSection() { } // Inicializa el vector de colores -void Logo::initColors() { +void Logo::initColors() { // NOLINT(readability-convert-member-functions-to-static) // Inicializa el vector de colores const std::vector COLORS = { static_cast(PaletteColor::BLACK), @@ -265,7 +265,7 @@ void Logo::initColors() { } // Crea los sprites de cada linea -void Logo::initSprites() { +void Logo::initSprites() { // NOLINT(readability-convert-member-functions-to-static) const float WIDTH = jailgames_surface_->getWidth(); jailgames_initial_x_.reserve(jailgames_surface_->getHeight()); diff --git a/source/game/scenes/title.cpp b/source/game/scenes/title.cpp index 68a33f01..96647fec 100644 --- a/source/game/scenes/title.cpp +++ b/source/game/scenes/title.cpp @@ -50,7 +50,7 @@ Title::Title() } // Destructor -Title::~Title() { +Title::~Title() { // NOLINT(modernize-use-equals-default) loading_screen_surface_->resetSubPalette(); title_surface_->resetSubPalette(); } @@ -66,7 +66,7 @@ void Title::initMarquee() { uint32_t cp = Text::nextCodepoint(long_text_, pos); Glyph l; l.codepoint = cp; - l.clip = marquee_text_->getGlyphClip(cp); // Pre-calcular clip rect (evita búsqueda por frame) + l.clip = marquee_text_->getGlyphClip(cp); // Pre-calcular clip rect (evita búsqueda por frame) l.x = MARQUEE_START_X; l.width = static_cast(marquee_text_->glyphWidth(cp, 0)); // Pre-calcular ancho visual del glifo l.enabled = false; @@ -223,7 +223,7 @@ void Title::updateMarquee(float delta_time) { } // Dibuja la marquesina -void Title::renderMarquee() { +void Title::renderMarquee() const { auto* sprite = marquee_text_->getSprite(); sprite->setY(MARQUEE_Y); // Solo renderizar letras activas (optimización: usa cache y rangos) @@ -442,7 +442,7 @@ void Title::run() { } // Crea y rellena la textura para mostrar los logros -void Title::createCheevosTexture() { +void Title::createCheevosTexture() { // NOLINT(readability-convert-member-functions-to-static) // Define la zona central del menu (entre el logo y la marquesina) constexpr int MENU_ZONE_Y = 73; // Top of menu zone constexpr int MENU_ZONE_HEIGHT = 102; // Height of menu zone @@ -466,7 +466,7 @@ void Title::createCheevosTexture() { cheevos_surface_->clear(CHEEVOS_BG_COLOR); // Escribe la lista de logros en la textura - const std::string CHEEVOS_OWNER = Locale::get()->get("title.projects"); + const std::string CHEEVOS_OWNER = Locale::get()->get("title.projects"); // NOLINT(readability-static-accessed-through-instance) const std::string CHEEVOS_LIST_CAPTION = CHEEVOS_OWNER + " (" + std::to_string(Cheevos::get()->getTotalUnlockedAchievements()) + " / " + std::to_string(Cheevos::get()->size()) + ")"; int pos = 2; TEXT->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, cheevos_surface_->getWidth() / 2, pos, CHEEVOS_LIST_CAPTION, 1, stringToColor("bright_green")); @@ -632,7 +632,7 @@ auto Title::isKeyValid(SDL_Scancode scancode) -> bool { } // Verifica si una tecla ya fue usada en pasos anteriores -auto Title::isKeyDuplicate(SDL_Scancode scancode, int current_step) -> bool { +auto Title::isKeyDuplicate(SDL_Scancode scancode, int current_step) -> bool { // NOLINT(readability-convert-member-functions-to-static) for (int i = 0; i < current_step; i++) { if (temp_keys_[i] == scancode) { return true; @@ -642,7 +642,7 @@ auto Title::isKeyDuplicate(SDL_Scancode scancode, int current_step) -> bool { } // Retorna el nombre de la accion para el paso actual -auto Title::getActionName(int step) -> std::string { +auto Title::getActionName(int step) -> std::string { // NOLINT(readability-convert-member-functions-to-static) switch (step) { case 0: return "LEFT"; @@ -656,7 +656,7 @@ auto Title::getActionName(int step) -> std::string { } // Aplica y guarda las teclas redefinidas -void Title::applyKeyboardRemap() { +void Title::applyKeyboardRemap() { // NOLINT(readability-convert-member-functions-to-static) // Guardar las nuevas teclas en Options::controls Options::keyboard_controls.key_left = temp_keys_[0]; Options::keyboard_controls.key_right = temp_keys_[1]; @@ -670,7 +670,7 @@ void Title::applyKeyboardRemap() { } // Dibuja la pantalla de redefinir teclado -void Title::renderKeyboardRemap() { +void Title::renderKeyboardRemap() const { // Zona central del menu (debe coincidir con la textura de cheevos) constexpr int MENU_ZONE_Y = 73; constexpr int MENU_ZONE_HEIGHT = 102; @@ -697,17 +697,17 @@ void Title::renderKeyboardRemap() { const int KEYS_START_Y = START_Y + (2 * LINE_SPACING); if (remap_step_ > 0) { const std::string LEFT_KEY = SDL_GetScancodeName(temp_keys_[0]); - const std::string LEFT_MSG = loc->get("title.keys.label0") + LEFT_KEY; + const std::string LEFT_MSG = loc->get("title.keys.label0") + LEFT_KEY; // NOLINT(readability-static-accessed-through-instance) menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, PlayArea::CENTER_X, KEYS_START_Y, LEFT_MSG, 1, COLOR); } if (remap_step_ > 1) { const std::string RIGHT_KEY = SDL_GetScancodeName(temp_keys_[1]); - const std::string RIGHT_MSG = loc->get("title.keys.label1") + RIGHT_KEY; + const std::string RIGHT_MSG = loc->get("title.keys.label1") + RIGHT_KEY; // NOLINT(readability-static-accessed-through-instance) menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, PlayArea::CENTER_X, KEYS_START_Y + LINE_SPACING, RIGHT_MSG, 1, COLOR); } if (remap_step_ >= 3) { const std::string JUMP_KEY = SDL_GetScancodeName(temp_keys_[2]); - const std::string JUMP_MSG = loc->get("title.keys.label2") + JUMP_KEY; + const std::string JUMP_MSG = loc->get("title.keys.label2") + JUMP_KEY; // NOLINT(readability-static-accessed-through-instance) menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, PlayArea::CENTER_X, KEYS_START_Y + (2 * LINE_SPACING), JUMP_MSG, 1, COLOR); } @@ -718,7 +718,7 @@ void Title::renderKeyboardRemap() { } // Dibuja la pantalla de redefinir joystick -void Title::renderJoystickRemap() { +void Title::renderJoystickRemap() const { // Zona central del menu (debe coincidir con la textura de cheevos) constexpr int MENU_ZONE_Y = 73; constexpr int MENU_ZONE_HEIGHT = 102; @@ -745,17 +745,17 @@ void Title::renderJoystickRemap() { const int BUTTONS_START_Y = START_Y + (2 * LINE_SPACING); if (remap_step_ > 0) { const std::string LEFT_BTN = getButtonName(temp_buttons_[0]); - const std::string LEFT_MSG = loc->get("title.keys.label0") + LEFT_BTN; + const std::string LEFT_MSG = loc->get("title.keys.label0") + LEFT_BTN; // NOLINT(readability-static-accessed-through-instance) menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, PlayArea::CENTER_X, BUTTONS_START_Y, LEFT_MSG, 1, COLOR); } if (remap_step_ > 1) { const std::string RIGHT_BTN = getButtonName(temp_buttons_[1]); - const std::string RIGHT_MSG = loc->get("title.keys.label1") + RIGHT_BTN; + const std::string RIGHT_MSG = loc->get("title.keys.label1") + RIGHT_BTN; // NOLINT(readability-static-accessed-through-instance) menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, PlayArea::CENTER_X, BUTTONS_START_Y + LINE_SPACING, RIGHT_MSG, 1, COLOR); } if (remap_step_ >= 3) { const std::string JUMP_BTN = getButtonName(temp_buttons_[2]); - const std::string JUMP_MSG = loc->get("title.keys.label2") + JUMP_BTN; + const std::string JUMP_MSG = loc->get("title.keys.label2") + JUMP_BTN; // NOLINT(readability-static-accessed-through-instance) menu_text_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG, PlayArea::CENTER_X, BUTTONS_START_Y + (2 * LINE_SPACING), JUMP_MSG, 1, COLOR); } @@ -827,7 +827,7 @@ void Title::handleJoystickRemap(const SDL_Event& event) { } // Valida si un botón está duplicado -auto Title::isButtonDuplicate(int button, int current_step) -> bool { +auto Title::isButtonDuplicate(int button, int current_step) -> bool { // NOLINT(readability-convert-member-functions-to-static) for (int i = 0; i < current_step; ++i) { if (temp_buttons_[i] == button) { return true; @@ -837,7 +837,7 @@ auto Title::isButtonDuplicate(int button, int current_step) -> bool { } // Aplica y guarda los botones del gamepad redefinidos -void Title::applyJoystickRemap() { +void Title::applyJoystickRemap() { // NOLINT(readability-convert-member-functions-to-static) // Guardar los nuevos botones en Options::gamepad_controls Options::gamepad_controls.button_left = temp_buttons_[0]; Options::gamepad_controls.button_right = temp_buttons_[1]; @@ -851,7 +851,7 @@ void Title::applyJoystickRemap() { } // Retorna el nombre amigable del botón del gamepad -auto Title::getButtonName(int button) -> std::string { +auto Title::getButtonName(int button) -> std::string { // NOLINT(readability-convert-member-functions-to-static) // Triggers especiales if (button == Input::TRIGGER_L2_AS_BUTTON) { return "L2"; diff --git a/source/game/scenes/title.hpp b/source/game/scenes/title.hpp index 64a799ca..98d8403f 100644 --- a/source/game/scenes/title.hpp +++ b/source/game/scenes/title.hpp @@ -74,12 +74,12 @@ class Title { void updatePostFadeMenu(float delta_time); // Actualiza POST_FADE_MENU void initMarquee(); // Inicializa la marquesina void updateMarquee(float delta_time); // Actualiza la marquesina (time-based) - void renderMarquee(); // Dibuja la marquesina + void renderMarquee() const; // Dibuja la marquesina void renderGameLogo(); // Dibuja el logo con el titulo del juego void renderMainMenu(); // Dibuja el menu principal void renderCheevosMenu(); // Dibuja el menu de logros - void renderKeyboardRemap(); // Dibuja la pantalla de redefinir teclado - void renderJoystickRemap(); // Dibuja la pantalla de redefinir joystick + void renderKeyboardRemap() const; // Dibuja la pantalla de redefinir teclado + void renderJoystickRemap() const; // Dibuja la pantalla de redefinir joystick void handleKeyboardRemap(const SDL_Event& event); // Maneja la captura de teclas void handleJoystickRemap(const SDL_Event& event); // Maneja la captura de botones del gamepad static auto isKeyValid(SDL_Scancode scancode) -> bool; // Valida si una tecla es permitida diff --git a/source/game/ui/notifier.cpp b/source/game/ui/notifier.cpp index a3c4025d..b564a460 100644 --- a/source/game/ui/notifier.cpp +++ b/source/game/ui/notifier.cpp @@ -43,7 +43,7 @@ const Notifier::Style Notifier::Style::CHEEVO = { .play_sound = true}; // [SINGLETON] Crearemos el objeto con esta función estática -void Notifier::init(const std::string& icon_file, const std::string& text) { +void Notifier::init(const std::string& icon_file, const std::string& text) { // NOLINT(readability-convert-member-functions-to-static) Notifier::notifier = new Notifier(icon_file, text); } @@ -128,8 +128,8 @@ void Notifier::update(float delta_time) { } // Elimina las notificaciones finalizadas -void Notifier::clearFinishedNotifications() { - auto result = std::ranges::remove_if(notifications_, [](const Notification& notification) { +void Notifier::clearFinishedNotifications() { // NOLINT(readability-convert-member-functions-to-static) + auto result = std::ranges::remove_if(notifications_, [](const Notification& notification) -> bool { return notification.state == Status::FINISHED; }); notifications_.erase(result.begin(), result.end()); @@ -147,7 +147,7 @@ void Notifier::show(std::vector texts, const Style& style, int icon } // Elimina las cadenas vacías - auto result = std::ranges::remove_if(texts, [](const std::string& s) { return s.empty(); }); + auto result = std::ranges::remove_if(texts, [](const std::string& s) -> bool { return s.empty(); }); texts.erase(result.begin(), result.end()); // Encuentra la cadena más larga @@ -219,15 +219,15 @@ void Notifier::show(std::vector texts, const Style& style, int icon else if (SHAPE == Shape::SQUARED) { n.surface->clear(style.bg_color); - SDL_FRect squared_rect = {0, 0, n.surface->getWidth(), n.surface->getHeight()}; + SDL_FRect squared_rect = {.x = 0, .y = 0, .w = n.surface->getWidth(), .h = n.surface->getHeight()}; n.surface->drawRectBorder(&squared_rect, style.border_color); } // Dibuja el icono de la notificación if (has_icons_ && icon >= 0 && texts.size() >= 2) { - auto sp = std::make_unique(icon_surface_, (SDL_FRect){0, 0, ICON_SIZE, ICON_SIZE}); - sp->setPosition({PADDING_IN_H, PADDING_IN_V, ICON_SIZE, ICON_SIZE}); - sp->setClip((SDL_FRect){ICON_SIZE * (icon % 10), ICON_SIZE * (icon / 10), ICON_SIZE, ICON_SIZE}); + auto sp = std::make_unique(icon_surface_, SDL_FRect{.x = 0, .y = 0, .w = ICON_SIZE, .h = ICON_SIZE}); + sp->setPosition({.x = PADDING_IN_H, .y = PADDING_IN_V, .w = ICON_SIZE, .h = ICON_SIZE}); + sp->setClip(SDL_FRect{.x = ICON_SIZE * (icon % 10), .y = ICON_SIZE * (icon / 10), .w = ICON_SIZE, .h = ICON_SIZE}); sp->render(); } diff --git a/source/game/ui/notifier.hpp b/source/game/ui/notifier.hpp index 04e53932..0210feba 100644 --- a/source/game/ui/notifier.hpp +++ b/source/game/ui/notifier.hpp @@ -74,7 +74,7 @@ class Notifier { std::vector texts; Status state{Status::RISING}; Shape shape{Shape::SQUARED}; - SDL_FRect rect{0.0F, 0.0F, 0.0F, 0.0F}; + SDL_FRect rect{.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F}; int y{0}; int travel_dist{0}; std::string code; diff --git a/source/utils/easing_functions.hpp b/source/utils/easing_functions.hpp index be7890b6..5fbf6d76 100644 --- a/source/utils/easing_functions.hpp +++ b/source/utils/easing_functions.hpp @@ -40,7 +40,7 @@ namespace Easing { if (t < 0.5F) { return 2.0F * t * t; } - return -1.0F + ((4.0F - 2.0F * t) * t); + return -1.0F + ((4.0F - (2.0F * t)) * t); } // CUBIC (Cúbica: t^3) @@ -156,12 +156,12 @@ namespace Easing { // BACK (Overshoot - retrocede antes de avanzar) inline auto backIn(float t, float overshoot = 1.70158F) -> float { - return t * t * ((overshoot + 1.0F) * t - overshoot); + return t * t * (((overshoot + 1.0F) * t) - overshoot); } inline auto backOut(float t, float overshoot = 1.70158F) -> float { const float F = t - 1.0F; - return (F * F * ((overshoot + 1.0F) * F + overshoot)) + 1.0F; + return (F * F * (((overshoot + 1.0F) * F) + overshoot)) + 1.0F; } inline auto backInOut(float t, float overshoot = 1.70158F) -> float { @@ -169,11 +169,11 @@ namespace Easing { if (t < 0.5F) { const float F = 2.0F * t; - return 0.5F * (F * F * ((S + 1.0F) * F - S)); + return 0.5F * (F * F * (((S + 1.0F) * F) - S)); } const float F = (2.0F * t) - 2.0F; - return 0.5F * (F * F * ((S + 1.0F) * F + S) + 2.0F); + return 0.5F * ((F * F * (((S + 1.0F) * F) + S)) + 2.0F); } // ELASTIC (Oscilación elástica - efecto de resorte) diff --git a/source/utils/utils.cpp b/source/utils/utils.cpp index c6861a86..f9ff02d7 100644 --- a/source/utils/utils.cpp +++ b/source/utils/utils.cpp @@ -226,8 +226,8 @@ auto checkCollision(const Line& l1, const Line& l2) -> SDL_Point { const float Y4 = l2.y2; // calculate the direction of the lines - float u_a = ((X4 - X3) * (Y1 - Y3) - (Y4 - Y3) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1)); - float u_b = ((X2 - X1) * (Y1 - Y3) - (Y2 - Y1) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1)); + float u_a = (((X4 - X3) * (Y1 - Y3)) - ((Y4 - Y3) * (X1 - X3))) / (((Y4 - Y3) * (X2 - X1)) - ((X4 - X3) * (Y2 - Y1))); + float u_b = (((X2 - X1) * (Y1 - Y3)) - ((Y2 - Y1) * (X1 - X3))) / (((Y4 - Y3) * (X2 - X1)) - ((X4 - X3) * (Y2 - Y1))); // if uA and uB are between 0-1, lines are colliding if (u_a >= 0 && u_a <= 1 && u_b >= 0 && u_b <= 1) { @@ -235,9 +235,9 @@ auto checkCollision(const Line& l1, const Line& l2) -> SDL_Point { const float X = X1 + (u_a * (X2 - X1)); const float Y = Y1 + (u_a * (Y2 - Y1)); - return {static_cast(std::round(X)), static_cast(std::round(Y))}; + return {.x = static_cast(std::round(X)), .y = static_cast(std::round(Y))}; } - return {-1, -1}; + return {.x = -1, .y = -1}; } // Detector de colisiones entre dos lineas @@ -253,8 +253,8 @@ auto checkCollision(const LineDiagonal& l1, const LineVertical& l2) -> SDL_Point const float Y4 = l2.y2; // calculate the direction of the lines - float u_a = ((X4 - X3) * (Y1 - Y3) - (Y4 - Y3) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1)); - float u_b = ((X2 - X1) * (Y1 - Y3) - (Y2 - Y1) * (X1 - X3)) / ((Y4 - Y3) * (X2 - X1) - (X4 - X3) * (Y2 - Y1)); + float u_a = (((X4 - X3) * (Y1 - Y3)) - ((Y4 - Y3) * (X1 - X3))) / (((Y4 - Y3) * (X2 - X1)) - ((X4 - X3) * (Y2 - Y1))); + float u_b = (((X2 - X1) * (Y1 - Y3)) - ((Y2 - Y1) * (X1 - X3))) / (((Y4 - Y3) * (X2 - X1)) - ((X4 - X3) * (Y2 - Y1))); // if uA and uB are between 0-1, lines are colliding if (u_a >= 0 && u_a <= 1 && u_b >= 0 && u_b <= 1) { @@ -262,9 +262,9 @@ auto checkCollision(const LineDiagonal& l1, const LineVertical& l2) -> SDL_Point const float X = X1 + (u_a * (X2 - X1)); const float Y = Y1 + (u_a * (Y2 - Y1)); - return {static_cast(X), static_cast(Y)}; + return {.x = static_cast(X), .y = static_cast(Y)}; } - return {-1, -1}; + return {.x = -1, .y = -1}; } // Normaliza una linea diagonal