clang-tidy

This commit is contained in:
2025-08-10 14:13:11 +02:00
parent 0204a8896a
commit c727cb6541
21 changed files with 255 additions and 209 deletions

View File

@@ -199,15 +199,33 @@ auto Asset::checkFile(const std::string &path) -> bool {
// Parsea string a Type // Parsea string a Type
auto Asset::parseAssetType(const std::string &type_str) -> Type { auto Asset::parseAssetType(const std::string &type_str) -> Type {
if (type_str == "BITMAP") return Type::BITMAP; if (type_str == "BITMAP") {
if (type_str == "MUSIC") return Type::MUSIC; return Type::BITMAP;
if (type_str == "SOUND") return Type::SOUND; }
if (type_str == "FONT") return Type::FONT; if (type_str == "MUSIC") {
if (type_str == "LANG") return Type::LANG; return Type::MUSIC;
if (type_str == "DATA") return Type::DATA; }
if (type_str == "DEMODATA") return Type::DEMODATA; if (type_str == "SOUND") {
if (type_str == "ANIMATION") return Type::ANIMATION; return Type::SOUND;
if (type_str == "PALETTE") return Type::PALETTE; }
if (type_str == "FONT") {
return Type::FONT;
}
if (type_str == "LANG") {
return Type::LANG;
}
if (type_str == "DATA") {
return Type::DATA;
}
if (type_str == "DEMODATA") {
return Type::DEMODATA;
}
if (type_str == "ANIMATION") {
return Type::ANIMATION;
}
if (type_str == "PALETTE") {
return Type::PALETTE;
}
throw std::runtime_error("Unknown asset type: " + type_str); throw std::runtime_error("Unknown asset type: " + type_str);
} }
@@ -264,7 +282,9 @@ auto Asset::replaceVariables(const std::string &path, const std::string &prefix,
// Parsea las opciones de una línea de configuración // Parsea las opciones de una línea de configuración
auto Asset::parseOptions(const std::string &options, bool &required, bool &absolute) -> void { auto Asset::parseOptions(const std::string &options, bool &required, bool &absolute) -> void {
if (options.empty()) return; if (options.empty()) {
return;
}
std::istringstream iss(options); std::istringstream iss(options);
std::string option; std::string option;

View File

@@ -187,7 +187,7 @@ void DefineButtons::checkEnd() {
} }
} }
bool DefineButtons::isReadyToClose() const { auto DefineButtons::isReadyToClose() const -> bool {
// Solo está listo para cerrar si: // Solo está listo para cerrar si:
// 1. Terminó // 1. Terminó
// 2. Ya mostró el mensaje // 2. Ya mostró el mensaje
@@ -198,7 +198,7 @@ bool DefineButtons::isReadyToClose() const {
} }
void DefineButtons::updateWindowMessage() { void DefineButtons::updateWindowMessage() {
if (!window_message_ || !options_gamepad_) { if (!window_message_ || (options_gamepad_ == nullptr)) {
return; return;
} }

View File

@@ -34,7 +34,7 @@ class DefineButtons {
void handleEvents(const SDL_Event &event); void handleEvents(const SDL_Event &event);
auto enable(Options::Gamepad *options_gamepad) -> bool; auto enable(Options::Gamepad *options_gamepad) -> bool;
void disable(); void disable();
bool isReadyToClose() const; [[nodiscard]] auto isReadyToClose() const -> bool;
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; } [[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
[[nodiscard]] auto isFinished() const -> bool { return finished_; } [[nodiscard]] auto isFinished() const -> bool { return finished_; }

View File

@@ -157,7 +157,7 @@ void Director::loadAssets() {
#ifdef MACOS_BUNDLE #ifdef MACOS_BUNDLE
const std::string prefix = "/../Resources"; const std::string prefix = "/../Resources";
#else #else
const std::string prefix = ""; const std::string prefix;
#endif #endif
// Cargar la configuración de assets (también aplicar el prefijo al archivo de configuración) // Cargar la configuración de assets (también aplicar el prefijo al archivo de configuración)

View File

@@ -17,7 +17,9 @@ void handleInputEvents(const SDL_Event &event) {
static auto *input_ = Input::get(); static auto *input_ = Input::get();
auto message = input_->handleEvent(event); auto message = input_->handleEvent(event);
if (message.empty()) return; if (message.empty()) {
return;
}
// Reemplazo de palabras clave por texto localizado // Reemplazo de palabras clave por texto localizado
size_t pos; size_t pos;

View File

@@ -158,7 +158,7 @@ auto checkServiceButton() -> bool {
auto checkSystemInputs() -> bool { auto checkSystemInputs() -> bool {
using Action = Input::Action; using Action = Input::Action;
static const std::vector<std::pair<Action, std::function<void()>>> actions = { static const std::vector<std::pair<Action, std::function<void()>>> ACTIONS = {
{Action::WINDOW_FULLSCREEN, toggleFullscreen}, {Action::WINDOW_FULLSCREEN, toggleFullscreen},
{Action::WINDOW_DEC_SIZE, decWindowSize}, {Action::WINDOW_DEC_SIZE, decWindowSize},
{Action::WINDOW_INC_SIZE, incWindowSize}, {Action::WINDOW_INC_SIZE, incWindowSize},
@@ -175,7 +175,7 @@ auto checkSystemInputs() -> bool {
#endif #endif
}; };
for (const auto& [action, func] : actions) { for (const auto& [action, func] : ACTIONS) {
if (Input::get()->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) { if (Input::get()->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
func(); func();
return true; return true;

View File

@@ -315,14 +315,14 @@ auto Input::handleEvent(const SDL_Event &event) -> std::string {
case SDL_EVENT_GAMEPAD_REMOVED: case SDL_EVENT_GAMEPAD_REMOVED:
return removeGamepad(event.gdevice.which); return removeGamepad(event.gdevice.which);
} }
return std::string(); return {};
} }
auto Input::addGamepad(int device_index) -> std::string { auto Input::addGamepad(int device_index) -> std::string {
SDL_Gamepad *pad = SDL_OpenGamepad(device_index); SDL_Gamepad *pad = SDL_OpenGamepad(device_index);
if (pad == nullptr) { if (pad == nullptr) {
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << std::endl; std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << std::endl;
return std::string(); return {};
} }
auto gamepad = std::make_shared<Gamepad>(pad); auto gamepad = std::make_shared<Gamepad>(pad);
@@ -344,10 +344,9 @@ auto Input::removeGamepad(SDL_JoystickID id) -> std::string {
std::cout << "Gamepad disconnected (" << name << ")" << std::endl; std::cout << "Gamepad disconnected (" << name << ")" << std::endl;
gamepads_.erase(it); gamepads_.erase(it);
return name + " DISCONNECTED"; return name + " DISCONNECTED";
} else { }
std::cerr << "No se encontró el gamepad con ID " << id << std::endl; std::cerr << "No se encontró el gamepad con ID " << id << std::endl;
return {}; return {};
}
} }
void Input::printConnectedGamepads() const { void Input::printConnectedGamepads() const {

View File

@@ -421,7 +421,8 @@ auto playerIdToString(Player::Id player_id) -> std::string {
auto stringToPlayerId(std::string name) -> Player::Id { auto stringToPlayerId(std::string name) -> Player::Id {
if (name == Lang::getText("[SERVICE_MENU] PLAYER1")) { if (name == Lang::getText("[SERVICE_MENU] PLAYER1")) {
return Player::Id::PLAYER1; return Player::Id::PLAYER1;
} else if (name == Lang::getText("[SERVICE_MENU] PLAYER2")) { }
if (name == Lang::getText("[SERVICE_MENU] PLAYER2")) {
return Player::Id::PLAYER2; return Player::Id::PLAYER2;
} else { } else {
return Player::Id::NO_PLAYER; return Player::Id::NO_PLAYER;

View File

@@ -161,7 +161,7 @@ class GamepadManager {
} }
void resyncGamepadsWithPlayers() { void resyncGamepadsWithPlayers() {
for (auto player : players) { for (auto player : players_) {
switch (player->getId()) { switch (player->getId()) {
case Player::Id::PLAYER1: case Player::Id::PLAYER1:
player->setGamepad(gamepads_[0].instance); player->setGamepad(gamepads_[0].instance);
@@ -226,8 +226,8 @@ class GamepadManager {
return false; return false;
} }
void addPlayer(std::shared_ptr<Player> player) { players.push_back(player); } // Añade un jugador a la lista void addPlayer(std::shared_ptr<Player> player) { players_.push_back(player); } // Añade un jugador a la lista
void clearPlayers() { players.clear(); } // Limpia la lista de jugadores void clearPlayers() { players_.clear(); } // Limpia la lista de jugadores
// Asigna el mando a un jugador // Asigna el mando a un jugador
void assignTo(Input::Gamepad gamepad, Player::Id player_id) { void assignTo(Input::Gamepad gamepad, Player::Id player_id) {
@@ -248,7 +248,7 @@ class GamepadManager {
static constexpr std::string_view UNASSIGNED_TEXT = "---"; static constexpr std::string_view UNASSIGNED_TEXT = "---";
static constexpr size_t MAX_PLAYERS = 2; static constexpr size_t MAX_PLAYERS = 2;
std::array<Gamepad, MAX_PLAYERS> gamepads_; // Punteros a las estructuras de mandos de Options std::array<Gamepad, MAX_PLAYERS> gamepads_; // Punteros a las estructuras de mandos de Options
std::vector<std::shared_ptr<Player>> players; // Punteros a los jugadores std::vector<std::shared_ptr<Player>> players_; // Punteros a los jugadores
// Convierte Player::Id a índice del array // Convierte Player::Id a índice del array
[[nodiscard]] static auto playerIdToIndex(Player::Id player_id) -> size_t { [[nodiscard]] static auto playerIdToIndex(Player::Id player_id) -> size_t {

View File

@@ -3,6 +3,7 @@
#include <cstdint> #include <cstdint>
#include <functional> #include <functional>
#include <string> #include <string>
#include <utility>
// Clase dedicada para manejar el sistema de pausa // Clase dedicada para manejar el sistema de pausa
class PauseManager { class PauseManager {
@@ -16,48 +17,48 @@ class PauseManager {
}; };
// Operadores para trabajar con las banderas (funciones friend) // Operadores para trabajar con las banderas (funciones friend)
friend Source operator|(Source a, Source b) { friend auto operator|(Source a, Source b) -> Source {
return static_cast<Source>(static_cast<uint8_t>(a) | static_cast<uint8_t>(b)); return static_cast<Source>(static_cast<uint8_t>(a) | static_cast<uint8_t>(b));
} }
friend Source operator&(Source a, Source b) { friend auto operator&(Source a, Source b) -> Source {
return static_cast<Source>(static_cast<uint8_t>(a) & static_cast<uint8_t>(b)); return static_cast<Source>(static_cast<uint8_t>(a) & static_cast<uint8_t>(b));
} }
friend Source operator~(Source a) { friend auto operator~(Source a) -> Source {
return static_cast<Source>(~static_cast<uint8_t>(a)); return static_cast<Source>(~static_cast<uint8_t>(a));
} }
friend Source& operator|=(Source& a, Source b) { friend auto operator|=(Source& a, Source b) -> Source& {
return a = a | b; return a = a | b;
} }
friend Source& operator&=(Source& a, Source b) { friend auto operator&=(Source& a, Source b) -> Source& {
return a = a & b; return a = a & b;
} }
private: private:
Source flags_ = Source::NONE; Source flags_ = Source::NONE;
std::function<void(bool)> onPauseChangedCallback_; std::function<void(bool)> on_pause_changed_callback_;
bool hasFlag(Source flag) const { [[nodiscard]] auto hasFlag(Source flag) const -> bool {
return (flags_ & flag) != Source::NONE; return (flags_ & flag) != Source::NONE;
} }
void notifyPauseChanged() { void notifyPauseChanged() {
if (onPauseChangedCallback_) { if (on_pause_changed_callback_) {
onPauseChangedCallback_(isPaused()); on_pause_changed_callback_(isPaused());
} }
} }
public: public:
// Constructor con callback opcional // Constructor con callback opcional
explicit PauseManager(std::function<void(bool)> callback = nullptr) explicit PauseManager(std::function<void(bool)> callback = nullptr)
: onPauseChangedCallback_(callback) {} : on_pause_changed_callback_(std::move(callback)) {}
// Establece/quita una fuente de pausa específica // Establece/quita una fuente de pausa específica
void setFlag(Source source, bool enable) { void setFlag(Source source, bool enable) {
bool wasPaused = isPaused(); bool was_paused = isPaused();
if (enable) { if (enable) {
flags_ |= source; flags_ |= source;
@@ -66,7 +67,7 @@ class PauseManager {
} }
// Solo notifica si cambió el estado general de pausa // Solo notifica si cambió el estado general de pausa
if (wasPaused != isPaused()) { if (was_paused != isPaused()) {
notifyPauseChanged(); notifyPauseChanged();
} }
} }
@@ -80,13 +81,13 @@ class PauseManager {
void togglePlayerPause() { setPlayerPause(!isPlayerPaused()); } void togglePlayerPause() { setPlayerPause(!isPlayerPaused()); }
// Getters // Getters
bool isPaused() const { return flags_ != Source::NONE; } [[nodiscard]] auto isPaused() const -> bool { return flags_ != Source::NONE; }
bool isPlayerPaused() const { return hasFlag(Source::PLAYER); } [[nodiscard]] auto isPlayerPaused() const -> bool { return hasFlag(Source::PLAYER); }
bool isServiceMenuPaused() const { return hasFlag(Source::SERVICE_MENU); } [[nodiscard]] auto isServiceMenuPaused() const -> bool { return hasFlag(Source::SERVICE_MENU); }
bool isFocusLossPaused() const { return hasFlag(Source::FOCUS_LOST); } [[nodiscard]] auto isFocusLossPaused() const -> bool { return hasFlag(Source::FOCUS_LOST); }
// Obtiene las banderas actuales // Obtiene las banderas actuales
Source getFlags() const { return flags_; } [[nodiscard]] auto getFlags() const -> Source { return flags_; }
// Limpia todas las pausas (útil para reset) // Limpia todas las pausas (útil para reset)
void clearAll() { void clearAll() {
@@ -97,24 +98,32 @@ class PauseManager {
} }
// Método para debug // Método para debug
std::string getStatusString() const { [[nodiscard]] auto getStatusString() const -> std::string {
if (flags_ == Source::NONE) return "Active"; if (flags_ == Source::NONE) {
return "Active";
}
std::string result = "Paused by: "; std::string result = "Paused by: ";
bool first = true; bool first = true;
if (hasFlag(Source::PLAYER)) { if (hasFlag(Source::PLAYER)) {
if (!first) result += ", "; if (!first) {
result += ", ";
}
result += "Player"; result += "Player";
first = false; first = false;
} }
if (hasFlag(Source::SERVICE_MENU)) { if (hasFlag(Source::SERVICE_MENU)) {
if (!first) result += ", "; if (!first) {
result += ", ";
}
result += "ServiceMenu"; result += "ServiceMenu";
first = false; first = false;
} }
if (hasFlag(Source::FOCUS_LOST)) { if (hasFlag(Source::FOCUS_LOST)) {
if (!first) result += ", "; if (!first) {
result += ", ";
}
result += "FocusLoss"; result += "FocusLoss";
first = false; first = false;
} }
@@ -124,6 +133,6 @@ class PauseManager {
// Permite cambiar el callback en runtime // Permite cambiar el callback en runtime
void setCallback(std::function<void(bool)> callback) { void setCallback(std::function<void(bool)> callback) {
onPauseChangedCallback_ = callback; on_pause_changed_callback_ = callback;
} }
}; };

View File

@@ -51,7 +51,7 @@ Game::Game(Player::Id player_id, int current_stage, bool demo)
input_(Input::get()), input_(Input::get()),
background_(std::make_unique<Background>()), background_(std::make_unique<Background>()),
canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h)), canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h)),
pause_manager_(std::make_unique<PauseManager>([this](bool isPaused) { onPauseStateChanged(isPaused); })), pause_manager_(std::make_unique<PauseManager>([this](bool is_paused) { onPauseStateChanged(is_paused); })),
fade_in_(std::make_unique<Fade>()), fade_in_(std::make_unique<Fade>()),
fade_out_(std::make_unique<Fade>()), fade_out_(std::make_unique<Fade>()),
balloon_manager_(std::make_unique<BalloonManager>()), balloon_manager_(std::make_unique<BalloonManager>()),
@@ -99,10 +99,10 @@ Game::Game(Player::Id player_id, int current_stage, bool demo)
setTotalPower(); setTotalPower();
// Registra callbacks // Registra callbacks
ServiceMenu::get()->setStateChangeCallback([this](bool isActive) { ServiceMenu::get()->setStateChangeCallback([this](bool is_active) {
// Solo aplicar pausa si NO estamos en modo demo // Solo aplicar pausa si NO estamos en modo demo
if (!demo_.enabled) { if (!demo_.enabled) {
pause_manager_->setServiceMenuPause(isActive); pause_manager_->setServiceMenuPause(is_active);
} }
}); });
@@ -1877,9 +1877,9 @@ void Game::sendPlayerToTheFront(const std::shared_ptr<Player> &player) {
players_to_put_at_front_.push_back(player); players_to_put_at_front_.push_back(player);
} }
void Game::onPauseStateChanged(bool isPaused) { void Game::onPauseStateChanged(bool is_paused) {
screen_->attenuate(isPaused); screen_->attenuate(is_paused);
tabe_->pauseTimer(isPaused); tabe_->pauseTimer(is_paused);
} }
#ifdef _DEBUG #ifdef _DEBUG

View File

@@ -291,7 +291,7 @@ class Game {
void sendPlayerToTheBack(const std::shared_ptr<Player> &player); // Mueve el jugador para pintarlo al fondo de la lista de jugadores void sendPlayerToTheBack(const std::shared_ptr<Player> &player); // Mueve el jugador para pintarlo al fondo de la lista de jugadores
void sendPlayerToTheFront(const std::shared_ptr<Player> &player); // Mueve el jugador para pintarlo el primero de la lista de jugadores void sendPlayerToTheFront(const std::shared_ptr<Player> &player); // Mueve el jugador para pintarlo el primero de la lista de jugadores
void onPauseStateChanged(bool isPaused); void onPauseStateChanged(bool is_paused);
// SISTEMA DE GRABACIÓN (CONDICIONAL) // SISTEMA DE GRABACIÓN (CONDICIONAL)
#ifdef RECORDING #ifdef RECORDING

View File

@@ -55,17 +55,17 @@ Text::Text(std::shared_ptr<Texture> texture, std::shared_ptr<Text::File> text_fi
// Escribe texto en pantalla // Escribe texto en pantalla
void Text::write(int x, int y, const std::string &text, int kerning, int length) { void Text::write(int x, int y, const std::string &text, int kerning, int length) {
int shift = 0; int shift = 0;
const std::string_view visible_text = (length == -1) ? std::string_view(text) : std::string_view(text).substr(0, length); const std::string_view VISIBLE_TEXT = (length == -1) ? std::string_view(text) : std::string_view(text).substr(0, length);
sprite_->setY(y); sprite_->setY(y);
for (const auto ch : visible_text) { for (const auto CH : VISIBLE_TEXT) {
const auto index = static_cast<unsigned char>(ch); const auto INDEX = static_cast<unsigned char>(CH);
if (index < offset_.size()) { if (INDEX < offset_.size()) {
sprite_->setSpriteClip(offset_[index].x, offset_[index].y, box_width_, box_height_); sprite_->setSpriteClip(offset_[INDEX].x, offset_[INDEX].y, box_width_, box_height_);
sprite_->setX(x + shift); sprite_->setX(x + shift);
sprite_->render(); sprite_->render();
shift += offset_[index].w + kerning; shift += offset_[INDEX].w + kerning;
} }
} }
} }
@@ -73,20 +73,20 @@ void Text::write(int x, int y, const std::string &text, int kerning, int length)
// Escribe el texto al doble de tamaño // Escribe el texto al doble de tamaño
void Text::write2X(int x, int y, const std::string &text, int kerning, int length) { void Text::write2X(int x, int y, const std::string &text, int kerning, int length) {
int shift = 0; int shift = 0;
const std::string_view visible_text = (length == -1) ? std::string_view(text) : std::string_view(text).substr(0, length); const std::string_view VISIBLE_TEXT = (length == -1) ? std::string_view(text) : std::string_view(text).substr(0, length);
for (const auto ch : visible_text) { for (const auto CH : VISIBLE_TEXT) {
const auto index = static_cast<unsigned char>(ch); const auto INDEX = static_cast<unsigned char>(CH);
if (index < offset_.size()) { if (INDEX < offset_.size()) {
SDL_FRect rect = { SDL_FRect rect = {
static_cast<float>(offset_[index].x), static_cast<float>(offset_[INDEX].x),
static_cast<float>(offset_[index].y), static_cast<float>(offset_[INDEX].y),
static_cast<float>(box_width_), static_cast<float>(box_width_),
static_cast<float>(box_height_)}; static_cast<float>(box_height_)};
sprite_->getTexture()->render(x + shift, y, &rect, 2.0F, 2.0F); sprite_->getTexture()->render(x + shift, y, &rect, 2.0F, 2.0F);
shift += (offset_[index].w + kerning) * 2; shift += (offset_[INDEX].w + kerning) * 2;
} }
} }
} }
@@ -190,11 +190,11 @@ auto Text::length(const std::string &text, int kerning) const -> int {
int shift = 0; int shift = 0;
for (const auto &ch : text) { for (const auto &ch : text) {
// Convertimos a unsigned char para obtener el valor ASCII correcto (0-255) // Convertimos a unsigned char para obtener el valor ASCII correcto (0-255)
const auto index = static_cast<unsigned char>(ch); const auto INDEX = static_cast<unsigned char>(ch);
// Verificamos si el carácter está dentro de los límites del array // Verificamos si el carácter está dentro de los límites del array
if (index < offset_.size()) { if (INDEX < offset_.size()) {
shift += (offset_[index].w + kerning); shift += (offset_[INDEX].w + kerning);
} }
} }

View File

@@ -63,8 +63,8 @@ auto ActionListOption::findCurrentIndex() const -> size_t {
return 0; return 0;
} }
const std::string current_value = value_getter_(); const std::string CURRENT_VALUE = value_getter_();
auto it = std::find(options_.begin(), options_.end(), current_value); auto it = std::find(options_.begin(), options_.end(), CURRENT_VALUE);
if (it != options_.end()) { if (it != options_.end()) {
return static_cast<size_t>(std::distance(options_.begin(), it)); return static_cast<size_t>(std::distance(options_.begin(), it));

View File

@@ -183,7 +183,7 @@ class ActionListOption : public MenuOption {
using ActionExecutor = std::function<void()>; using ActionExecutor = std::function<void()>;
ActionListOption(const std::string &caption, ServiceMenu::SettingsGroup group, std::vector<std::string> options, ValueGetter getter, ValueSetter setter, ActionExecutor action_executor, bool hidden = false) ActionListOption(const std::string &caption, ServiceMenu::SettingsGroup group, std::vector<std::string> options, ValueGetter getter, ValueSetter setter, ActionExecutor action_executor, bool hidden = false)
: MenuOption(caption, group, hidden), options_(std::move(options)), value_getter_(std::move(getter)), value_setter_(std::move(setter)), action_executor_(std::move(action_executor)), current_index_(0) { : MenuOption(caption, group, hidden), options_(std::move(options)), value_getter_(std::move(getter)), value_setter_(std::move(setter)), action_executor_(std::move(action_executor)) {
updateCurrentIndex(); updateCurrentIndex();
} }
@@ -199,7 +199,7 @@ class ActionListOption : public MenuOption {
ValueGetter value_getter_; ValueGetter value_getter_;
ValueSetter value_setter_; ValueSetter value_setter_;
ActionExecutor action_executor_; ActionExecutor action_executor_;
size_t current_index_; size_t current_index_{0};
void updateCurrentIndex(); void updateCurrentIndex();
[[nodiscard]] auto findCurrentIndex() const -> size_t; [[nodiscard]] auto findCurrentIndex() const -> size_t;

View File

@@ -15,17 +15,25 @@
void MenuRenderer::ResizeAnimation::start(float from_w, float from_h, float to_w, float to_h) { void MenuRenderer::ResizeAnimation::start(float from_w, float from_h, float to_w, float to_h) {
start_width = from_w; start_height = from_h; start_width = from_w; start_height = from_h;
target_width = to_w; target_height = to_h; target_width = to_w; target_height = to_h;
elapsed = 0.0f; active = true; elapsed = 0.0F;
active = true;
}
void MenuRenderer::ResizeAnimation::stop() { active = false;
elapsed = 0.0F;
} }
void MenuRenderer::ResizeAnimation::stop() { active = false; elapsed = 0.0f; }
void MenuRenderer::ShowHideAnimation::startShow(float to_w, float to_h) { void MenuRenderer::ShowHideAnimation::startShow(float to_w, float to_h) {
type = Type::SHOWING; target_width = to_w; target_height = to_h; type = Type::SHOWING; target_width = to_w; target_height = to_h;
elapsed = 0.0f; active = true; elapsed = 0.0F;
active = true;
}
void MenuRenderer::ShowHideAnimation::startHide() { type = Type::HIDING;
elapsed = 0.0F;
active = true;
}
void MenuRenderer::ShowHideAnimation::stop() { type = Type::NONE; active = false;
elapsed = 0.0F;
} }
void MenuRenderer::ShowHideAnimation::startHide() { type = Type::HIDING; elapsed = 0.0f; active = true; }
void MenuRenderer::ShowHideAnimation::stop() { type = Type::NONE; active = false; elapsed = 0.0f; }
MenuRenderer::MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr<Text> element_text, std::shared_ptr<Text> title_text) MenuRenderer::MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr<Text> element_text, std::shared_ptr<Text> title_text)
: element_text_(std::move(element_text)), title_text_(std::move(title_text)) { : element_text_(std::move(element_text)), title_text_(std::move(title_text)) {
@@ -34,7 +42,9 @@ MenuRenderer::MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr<Text>
} }
void MenuRenderer::render(const ServiceMenu *menu_state) { void MenuRenderer::render(const ServiceMenu *menu_state) {
if (!visible_) return; if (!visible_) {
return;
}
// Dibuja la sombra // Dibuja la sombra
if (param.service_menu.drop_shadow) { if (param.service_menu.drop_shadow) {
@@ -57,7 +67,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
if (shouldShowContent()) { if (shouldShowContent()) {
// Dibuja el título // Dibuja el título
float y = rect_.y + title_padding_; float y = rect_.y + title_padding_;
title_text_->writeDX(Text::COLOR | Text::CENTER, rect_.x + rect_.w / 2.0f, y, menu_state->getTitle(), -4, param.service_menu.title_color); title_text_->writeDX(Text::COLOR | Text::CENTER, rect_.x + rect_.w / 2.0F, y, menu_state->getTitle(), -4, param.service_menu.title_color);
// Dibuja la línea separadora // Dibuja la línea separadora
y = rect_.y + upper_height_; y = rect_.y + upper_height_;
@@ -73,15 +83,15 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
const Color &current_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color; const Color &current_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color;
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) { if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
const int available_width = rect_.w - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2) - element_text_->length(option_pairs.at(i).first, -2) - ServiceMenu::MIN_GAP_OPTION_VALUE; const int AVAILABLE_WIDTH = rect_.w - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2) - element_text_->length(option_pairs.at(i).first, -2) - ServiceMenu::MIN_GAP_OPTION_VALUE;
std::string truncated_value = getTruncatedValue(option_pairs.at(i).second, available_width); std::string truncated_value = getTruncatedValue(option_pairs.at(i).second, AVAILABLE_WIDTH);
element_text_->writeColored(rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y, option_pairs.at(i).first, current_color, -2); element_text_->writeColored(rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y, option_pairs.at(i).first, current_color, -2);
const int X = rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING - element_text_->length(truncated_value, -2); const int X = rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING - element_text_->length(truncated_value, -2);
element_text_->writeColored(X, y, truncated_value, current_color, -2); element_text_->writeColored(X, y, truncated_value, current_color, -2);
} else { } else {
const int available_width = rect_.w - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2); const int AVAILABLE_WIDTH = rect_.w - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2);
std::string truncated_caption = getTruncatedValue(option_pairs.at(i).first, available_width); std::string truncated_caption = getTruncatedValue(option_pairs.at(i).first, AVAILABLE_WIDTH);
element_text_->writeDX(Text::CENTER | Text::COLOR, rect_.x + rect_.w / 2.0f, y, truncated_caption, -2, current_color); element_text_->writeDX(Text::CENTER | Text::COLOR, rect_.x + rect_.w / 2.0F, y, truncated_caption, -2, current_color);
} }
y += options_height_ + options_padding_; y += options_height_ + options_padding_;
} }
@@ -89,7 +99,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
} }
void MenuRenderer::update(const ServiceMenu *menu_state) { void MenuRenderer::update(const ServiceMenu *menu_state) {
float delta_time = 1.0f / 60.0f; // Asumiendo 60 FPS float delta_time = 1.0F / 60.0F; // Asumiendo 60 FPS
updateAnimations(delta_time); updateAnimations(delta_time);
if (visible_) { if (visible_) {
@@ -101,7 +111,9 @@ void MenuRenderer::update(const ServiceMenu *menu_state) {
// --- Nuevos métodos de control --- // --- Nuevos métodos de control ---
void MenuRenderer::show(const ServiceMenu* menu_state) { void MenuRenderer::show(const ServiceMenu* menu_state) {
if (visible_) return; if (visible_) {
return;
}
visible_ = true; visible_ = true;
// Calcula el tamaño final y lo usa para la animación // Calcula el tamaño final y lo usa para la animación
@@ -114,13 +126,15 @@ void MenuRenderer::show(const ServiceMenu* menu_state) {
show_hide_animation_.startShow(target_rect.w, target_rect.h); show_hide_animation_.startShow(target_rect.w, target_rect.h);
// El tamaño inicial es cero para la animación // El tamaño inicial es cero para la animación
rect_.w = 0.0f; rect_.w = 0.0F;
rect_.h = 0.0f; rect_.h = 0.0F;
updatePosition(); updatePosition();
} }
void MenuRenderer::hide() { void MenuRenderer::hide() {
if (!visible_ || show_hide_animation_.type == ShowHideAnimation::Type::HIDING) return; if (!visible_ || show_hide_animation_.type == ShowHideAnimation::Type::HIDING) {
return;
}
// Detener animación de resize si la hubiera // Detener animación de resize si la hubiera
resize_animation_.stop(); resize_animation_.stop();
@@ -234,7 +248,9 @@ void MenuRenderer::updateShowHideAnimation(float delta_time) {
rect_.w = show_hide_animation_.target_width; rect_.w = show_hide_animation_.target_width;
rect_.h = show_hide_animation_.target_height; rect_.h = show_hide_animation_.target_height;
} else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) { } else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) {
rect_.w = 0.0f; rect_.h = 0.0f; visible_ = false; rect_.w = 0.0F;
rect_.h = 0.0F;
visible_ = false;
} }
show_hide_animation_.stop(); show_hide_animation_.stop();
updatePosition(); updatePosition();
@@ -244,8 +260,8 @@ void MenuRenderer::updateShowHideAnimation(float delta_time) {
rect_.w = show_hide_animation_.target_width * progress; rect_.w = show_hide_animation_.target_width * progress;
rect_.h = show_hide_animation_.target_height * progress; rect_.h = show_hide_animation_.target_height * progress;
} else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) { } else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) {
rect_.w = show_hide_animation_.target_width * (1.0f - progress); rect_.w = show_hide_animation_.target_width * (1.0F - progress);
rect_.h = show_hide_animation_.target_height * (1.0f - progress); rect_.h = show_hide_animation_.target_height * (1.0F - progress);
} }
updatePosition(); updatePosition();
} }
@@ -274,8 +290,8 @@ void MenuRenderer::updateResizeAnimation(float delta_time) {
void MenuRenderer::updatePosition() { void MenuRenderer::updatePosition() {
switch (position_mode_) { switch (position_mode_) {
case PositionMode::CENTERED: case PositionMode::CENTERED:
rect_.x = anchor_x_ - rect_.w / 2.0f; rect_.x = anchor_x_ - rect_.w / 2.0F;
rect_.y = anchor_y_ - rect_.h / 2.0f; rect_.y = anchor_y_ - rect_.h / 2.0F;
break; break;
case PositionMode::FIXED: case PositionMode::FIXED:
rect_.x = anchor_x_; rect_.x = anchor_x_;
@@ -289,12 +305,17 @@ void MenuRenderer::updatePosition() {
// Resto de métodos (sin cambios significativos) // Resto de métodos (sin cambios significativos)
void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state) { void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state) {
for (int &w : group_menu_widths_) w = ServiceMenu::MIN_WIDTH; for (int &w : group_menu_widths_) {
w = ServiceMenu::MIN_WIDTH;
}
for (int group = 0; group < 5; ++group) { for (int group = 0; group < 5; ++group) {
auto sg = static_cast<ServiceMenu::SettingsGroup>(group); auto sg = static_cast<ServiceMenu::SettingsGroup>(group);
int max_option_width = 0, max_value_width = 0; int max_option_width = 0;
int max_value_width = 0;
for (const auto &option : all_options) { for (const auto &option : all_options) {
if (option->getGroup() != sg) continue; if (option->getGroup() != sg) {
continue;
}
max_option_width = std::max(max_option_width, element_text_->length(option->getCaption(), -2)); max_option_width = std::max(max_option_width, element_text_->length(option->getCaption(), -2));
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) { if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
int max_available_value_width = static_cast<int>(max_menu_width_) - max_option_width - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2) - ServiceMenu::MIN_GAP_OPTION_VALUE; int max_available_value_width = static_cast<int>(max_menu_width_) - max_option_width - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2) - ServiceMenu::MIN_GAP_OPTION_VALUE;
@@ -302,7 +323,9 @@ void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<Menu
} }
} }
size_t total_width = max_option_width + (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2); size_t total_width = max_option_width + (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2);
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) total_width += ServiceMenu::MIN_GAP_OPTION_VALUE + max_value_width; if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
total_width += ServiceMenu::MIN_GAP_OPTION_VALUE + max_value_width;
}
group_menu_widths_[group] = std::min(std::max((int)ServiceMenu::MIN_WIDTH, (int)total_width), static_cast<int>(max_menu_width_)); group_menu_widths_[group] = std::min(std::max((int)ServiceMenu::MIN_WIDTH, (int)total_width), static_cast<int>(max_menu_width_));
} }
} }
@@ -375,5 +398,5 @@ auto MenuRenderer::getTruncatedValue(const std::string &value, int available_wid
return truncated; return truncated;
} }
auto MenuRenderer::easeOut(float t) const -> float { return 1.0f - (1.0f - t) * (1.0f - t); } auto MenuRenderer::easeOut(float t) const -> float { return 1.0F - (1.0F - t) * (1.0F - t); }
auto MenuRenderer::shouldShowContent() const -> bool { return !show_hide_animation_.active; } auto MenuRenderer::shouldShowContent() const -> bool { return !show_hide_animation_.active; }

View File

@@ -68,8 +68,8 @@ class MenuRenderer {
// --- Posicionamiento --- // --- Posicionamiento ---
PositionMode position_mode_ = PositionMode::CENTERED; PositionMode position_mode_ = PositionMode::CENTERED;
float anchor_x_ = 0.0f; float anchor_x_ = 0.0F;
float anchor_y_ = 0.0f; float anchor_y_ = 0.0F;
// --- Límites de tamaño máximo --- // --- Límites de tamaño máximo ---
size_t max_menu_width_ = 0; size_t max_menu_width_ = 0;
@@ -80,8 +80,8 @@ class MenuRenderer {
bool active = false; bool active = false;
float start_width, start_height; float start_width, start_height;
float target_width, target_height; float target_width, target_height;
float elapsed = 0.0f; float elapsed = 0.0F;
float duration = 0.2f; float duration = 0.2F;
void start(float from_w, float from_h, float to_w, float to_h); void start(float from_w, float from_h, float to_w, float to_h);
void stop(); void stop();
@@ -92,8 +92,8 @@ class MenuRenderer {
Type type = Type::NONE; Type type = Type::NONE;
bool active = false; bool active = false;
float target_width, target_height; float target_width, target_height;
float elapsed = 0.0f; float elapsed = 0.0F;
float duration = 0.25f; float duration = 0.25F;
void startShow(float to_w, float to_h); void startShow(float to_w, float to_h);
void startHide(); void startHide();

View File

@@ -41,8 +41,12 @@ ServiceMenu::ServiceMenu()
} }
void ServiceMenu::toggle() { void ServiceMenu::toggle() {
if (define_buttons_ && define_buttons_->isEnabled()) return; if (define_buttons_ && define_buttons_->isEnabled()) {
if (isAnimating() && !define_buttons_->isEnabled()) return; return;
}
if (isAnimating() && !define_buttons_->isEnabled()) {
return;
}
playBackSound(); playBackSound();
@@ -83,7 +87,9 @@ void ServiceMenu::update() {
// El renderer siempre se actualiza para manejar sus animaciones // El renderer siempre se actualiza para manejar sus animaciones
renderer_->update(this); renderer_->update(this);
if (!enabled_) return; if (!enabled_) {
return;
}
// Lógica de actualización del mensaje de reinicio y botones // Lógica de actualización del mensaje de reinicio y botones
bool now_pending = Options::pending_changes.has_pending_changes; bool now_pending = Options::pending_changes.has_pending_changes;
@@ -294,7 +300,7 @@ void ServiceMenu::initializeOptions() {
[this]() { [this]() {
// Acción: configurar botones del mando del jugador 1 // Acción: configurar botones del mando del jugador 1
auto *gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER1); auto *gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER1);
if (gamepad && gamepad->instance) { if ((gamepad != nullptr) && gamepad->instance) {
define_buttons_->enable(gamepad); define_buttons_->enable(gamepad);
} }
})); }));
@@ -312,7 +318,7 @@ void ServiceMenu::initializeOptions() {
[this]() { [this]() {
// Acción: configurar botones del mando del jugador 2 // Acción: configurar botones del mando del jugador 2
auto *gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER2); auto *gamepad = &Options::gamepad_manager.getGamepad(Player::Id::PLAYER2);
if (gamepad && gamepad->instance) { if ((gamepad != nullptr) && gamepad->instance) {
define_buttons_->enable(gamepad); define_buttons_->enable(gamepad);
} }
})); }));
@@ -565,17 +571,17 @@ void ServiceMenu::handleEvent(const SDL_Event &event) {
} }
} }
bool ServiceMenu::checkInput() { auto ServiceMenu::checkInput() -> bool {
// --- Guardas --- // --- Guardas ---
// No procesar input si el menú no está habilitado, si se está animando o si se definen botones // No procesar input si el menú no está habilitado, si se está animando o si se definen botones
if (!enabled_ || isAnimating() || (define_buttons_ && define_buttons_->isEnabled())) { if (!enabled_ || isAnimating() || (define_buttons_ && define_buttons_->isEnabled())) {
return false; return false;
} }
static auto input = Input::get(); static auto *input_ = Input::get();
using Action = Input::Action; using Action = Input::Action;
const std::vector<std::pair<Action, std::function<void()>>> actions = { const std::vector<std::pair<Action, std::function<void()>>> ACTIONS = {
{Action::UP, [this]() { setSelectorUp(); }}, {Action::UP, [this]() { setSelectorUp(); }},
{Action::DOWN, [this]() { setSelectorDown(); }}, {Action::DOWN, [this]() { setSelectorDown(); }},
{Action::RIGHT, [this]() { adjustOption(true); }}, {Action::RIGHT, [this]() { adjustOption(true); }},
@@ -585,17 +591,17 @@ bool ServiceMenu::checkInput() {
}; };
// Teclado // Teclado
for (const auto &[action, func] : actions) { for (const auto &[action, func] : ACTIONS) {
if (input->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) { if (input_->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::CHECK_KEYBOARD)) {
func(); func();
return true; return true;
} }
} }
// Mandos // Mandos
for (auto gamepad : input->getGamepads()) { for (auto gamepad : input_->getGamepads()) {
for (const auto &[action, func] : actions) { for (const auto &[action, func] : ACTIONS) {
if (input->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) { if (input_->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) {
func(); func();
return true; return true;
} }

View File

@@ -33,7 +33,7 @@ class ServiceMenu {
static constexpr size_t MIN_GAP_OPTION_VALUE = 30; static constexpr size_t MIN_GAP_OPTION_VALUE = 30;
static constexpr size_t SETTINGS_GROUP_SIZE = 6; static constexpr size_t SETTINGS_GROUP_SIZE = 6;
using StateChangeCallback = std::function<void(bool isActive)>; using StateChangeCallback = std::function<void(bool is_active)>;
// --- Métodos de singleton --- // --- Métodos de singleton ---
static void init(); static void init();
@@ -57,7 +57,7 @@ class ServiceMenu {
// --- Método para manejar eventos --- // --- Método para manejar eventos ---
void handleEvent(const SDL_Event &event); void handleEvent(const SDL_Event &event);
bool checkInput(); auto checkInput() -> bool;
// --- Método principal para refresco externo --- // --- Método principal para refresco externo ---
void refresh(); // Refresca los valores y el layout del menú bajo demanda void refresh(); // Refresca los valores y el layout del menú bajo demanda

View File

@@ -9,11 +9,11 @@
WindowMessage::WindowMessage( WindowMessage::WindowMessage(
std::shared_ptr<Text> text_renderer, std::shared_ptr<Text> text_renderer,
const std::string& title, std::string title,
const Config& config) const Config& config)
: text_renderer_(std::move(text_renderer)), : text_renderer_(std::move(text_renderer)),
config_(config), config_(config),
title_(title), title_(std::move(title)),
title_style_(Text::CENTER | Text::COLOR, config_.title_color, config_.title_color, 0, -2), title_style_(Text::CENTER | Text::COLOR, config_.title_color, config_.title_color, 0, -2),
text_style_(Text::CENTER | Text::COLOR, config_.text_color, config_.text_color, 0, -2) { text_style_(Text::CENTER | Text::COLOR, config_.text_color, config_.text_color, 0, -2) {
} }
@@ -45,7 +45,7 @@ void WindowMessage::render() {
std::string visible_title = getTruncatedText(title_, available_width); std::string visible_title = getTruncatedText(title_, available_width);
if (!visible_title.empty()) { if (!visible_title.empty()) {
text_renderer_->writeStyle( text_renderer_->writeStyle(
rect_.x + rect_.w / 2.0f, rect_.x + rect_.w / 2.0F,
current_y, current_y,
visible_title, visible_title,
title_style_); title_style_);
@@ -58,9 +58,9 @@ void WindowMessage::render() {
config_.border_color.b, config_.border_color.a); config_.border_color.b, config_.border_color.a);
SDL_RenderLine(renderer, SDL_RenderLine(renderer,
rect_.x + config_.padding, rect_.x + config_.padding,
current_y - config_.title_separator_spacing / 2.0f, current_y - config_.title_separator_spacing / 2.0F,
rect_.x + rect_.w - config_.padding, rect_.x + rect_.w - config_.padding,
current_y - config_.title_separator_spacing / 2.0f); current_y - config_.title_separator_spacing / 2.0F);
} }
} }
@@ -69,7 +69,7 @@ void WindowMessage::render() {
std::string visible_text = getTruncatedText(text, available_width); std::string visible_text = getTruncatedText(text, available_width);
if (!visible_text.empty()) { if (!visible_text.empty()) {
text_renderer_->writeStyle( text_renderer_->writeStyle(
rect_.x + rect_.w / 2.0f, rect_.x + rect_.w / 2.0F,
current_y, current_y,
visible_text, visible_text,
text_style_); text_style_);
@@ -84,7 +84,7 @@ void WindowMessage::update() {
if (show_hide_animation_.active || resize_animation_.active) { if (show_hide_animation_.active || resize_animation_.active) {
// Aquí necesitarías el delta_time del game loop // Aquí necesitarías el delta_time del game loop
// Por ahora usamos un valor fijo, pero idealmente se pasaría como parámetro // Por ahora usamos un valor fijo, pero idealmente se pasaría como parámetro
float delta_time = 1.0f / 60.0f; // Asumiendo 60 FPS float delta_time = 1.0F / 60.0F; // Asumiendo 60 FPS
updateAnimation(delta_time); updateAnimation(delta_time);
} }
} }
@@ -102,8 +102,8 @@ void WindowMessage::show() {
// Iniciar animación de mostrar desde tamaño 0 // Iniciar animación de mostrar desde tamaño 0
show_hide_animation_.startShow(rect_.w, rect_.h); show_hide_animation_.startShow(rect_.w, rect_.h);
rect_.w = 0.0f; rect_.w = 0.0F;
rect_.h = 0.0f; rect_.h = 0.0F;
updatePosition(); // Reposicionar con tamaño 0 updatePosition(); // Reposicionar con tamaño 0
} }
@@ -150,8 +150,7 @@ void WindowMessage::clearTexts() {
} }
void WindowMessage::setPosition(float x, float y, PositionMode mode) { void WindowMessage::setPosition(float x, float y, PositionMode mode) {
anchor_x_ = x; anchor_ = {x, y};
anchor_y_ = y;
position_mode_ = mode; position_mode_ = mode;
updatePosition(); updatePosition();
} }
@@ -163,7 +162,7 @@ void WindowMessage::setSize(float width, float height) {
} }
void WindowMessage::centerOnScreen() { void WindowMessage::centerOnScreen() {
setPosition(getScreenWidth() / 2.0f, getScreenHeight() / 2.0f, PositionMode::CENTERED); setPosition(getScreenWidth() / 2.0F, getScreenHeight() / 2.0F, PositionMode::CENTERED);
} }
void WindowMessage::autoSize() { void WindowMessage::autoSize() {
@@ -201,18 +200,18 @@ void WindowMessage::updateStyles() {
void WindowMessage::updatePosition() { void WindowMessage::updatePosition() {
switch (position_mode_) { switch (position_mode_) {
case PositionMode::CENTERED: case PositionMode::CENTERED:
rect_.x = anchor_x_ - rect_.w / 2.0f; rect_.x = anchor_.x- rect_.w / 2.0F;
rect_.y = anchor_y_ - rect_.h / 2.0f; rect_.y = anchor_.y - rect_.h / 2.0F;
break; break;
case PositionMode::FIXED: case PositionMode::FIXED:
rect_.x = anchor_x_; rect_.x = anchor_.x;
rect_.y = anchor_y_; rect_.y = anchor_.y;
break; break;
} }
// Asegurar que la ventana esté dentro de los límites de la pantalla // Asegurar que la ventana esté dentro de los límites de la pantalla
rect_.x = std::max(0.0f, std::min(rect_.x, getScreenWidth() - rect_.w)); rect_.x = std::max(0.0F, std::min(rect_.x, getScreenWidth() - rect_.w));
rect_.y = std::max(0.0f, std::min(rect_.y, getScreenHeight() - rect_.h)); rect_.y = std::max(0.0F, std::min(rect_.y, getScreenHeight() - rect_.h));
} }
void WindowMessage::ensureTextFits() { void WindowMessage::ensureTextFits() {
@@ -282,12 +281,12 @@ auto WindowMessage::calculateContentWidth() const -> float {
return max_width; return max_width;
} }
auto WindowMessage::getScreenWidth() const -> float { auto WindowMessage::getScreenWidth() -> float {
return static_cast<float>(param.game.width); return param.game.width;
} }
auto WindowMessage::getScreenHeight() const -> float { auto WindowMessage::getScreenHeight() -> float {
return static_cast<float>(param.game.height); return param.game.height;
} }
void WindowMessage::triggerAutoResize() { void WindowMessage::triggerAutoResize() {
@@ -321,8 +320,8 @@ void WindowMessage::updateShowHideAnimation(float delta_time) {
rect_.h = show_hide_animation_.target_height; rect_.h = show_hide_animation_.target_height;
} else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) { } else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) {
// Ocultar completado // Ocultar completado
rect_.w = 0.0f; rect_.w = 0.0F;
rect_.h = 0.0f; rect_.h = 0.0F;
visible_ = false; visible_ = false;
} }
@@ -338,8 +337,8 @@ void WindowMessage::updateShowHideAnimation(float delta_time) {
rect_.h = show_hide_animation_.target_height * progress; rect_.h = show_hide_animation_.target_height * progress;
} else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) { } else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) {
// Decrecer desde el tamaño actual hasta 0 // Decrecer desde el tamaño actual hasta 0
rect_.w = show_hide_animation_.target_width * (1.0f - progress); rect_.w = show_hide_animation_.target_width * (1.0F - progress);
rect_.h = show_hide_animation_.target_height * (1.0f - progress); rect_.h = show_hide_animation_.target_height * (1.0F - progress);
} }
updatePosition(); // Mantener la posición centrada durante la animación updatePosition(); // Mantener la posición centrada durante la animación
@@ -377,14 +376,14 @@ auto WindowMessage::shouldShowContent() const -> bool {
return !show_hide_animation_.active; return !show_hide_animation_.active;
} }
auto WindowMessage::easeOut(float t) const -> float { auto WindowMessage::easeOut(float t) -> float {
// Función de suavizado ease-out cuadrática // Función de suavizado ease-out cuadrática
return 1.0f - (1.0f - t) * (1.0f - t); return 1.0F - (1.0F - t) * (1.0F - t);
} }
auto WindowMessage::getAvailableTextWidth() const -> float { auto WindowMessage::getAvailableTextWidth() const -> float {
// Ancho disponible = ancho total - padding en ambos lados // Ancho disponible = ancho total - padding en ambos lados
return rect_.w - (config_.padding * 2.0f); return rect_.w - (config_.padding * 2.0F);
} }
auto WindowMessage::getTruncatedText(const std::string& text, float available_width) const -> std::string { auto WindowMessage::getTruncatedText(const std::string& text, float available_width) const -> std::string {
@@ -399,7 +398,7 @@ auto WindowMessage::getTruncatedText(const std::string& text, float available_wi
} }
// Si no hay espacio suficiente, devolver string vacío // Si no hay espacio suficiente, devolver string vacío
if (available_width < 10.0f) { // Mínimo espacio para al menos un carácter if (available_width < 10.0F) { // Mínimo espacio para al menos un carácter
return ""; return "";
} }

View File

@@ -24,45 +24,33 @@ class WindowMessage {
Color text_color; Color text_color;
// Espaciado y dimensiones // Espaciado y dimensiones
float padding; float padding{15.0f};
float line_spacing; float line_spacing{5.0f};
float title_separator_spacing; // Espacio extra para separador del título float title_separator_spacing{10.0f}; // Espacio extra para separador del título
// Límites de tamaño // Límites de tamaño
float min_width; float min_width{200.0f};
float min_height; float min_height{100.0f};
float max_width_ratio; // % máximo de ancho de pantalla float max_width_ratio{0.8f}; // % máximo de ancho de pantalla
float max_height_ratio; // % máximo de alto de pantalla float max_height_ratio{0.8f}; // % máximo de alto de pantalla
// Margen de seguridad para texto // Margen de seguridad para texto
float text_safety_margin; // Margen extra para evitar texto cortado float text_safety_margin{20.0f}; // Margen extra para evitar texto cortado
// Animaciones // Animaciones
float animation_duration; // Duración en segundos para todas las animaciones float animation_duration{0.3f}; // Duración en segundos para todas las animaciones
// Constructor con valores por defecto // Constructor con valores por defecto
Config() Config()
: bg_color{40, 40, 60, 220} : bg_color{40, 40, 60, 220}, border_color{100, 100, 120, 255}, title_color{255, 255, 255, 255}, text_color{200, 200, 200, 255}
, border_color{100, 100, 120, 255}
, title_color{255, 255, 255, 255}
, text_color{200, 200, 200, 255}
, padding{15.0f}
, line_spacing{5.0f}
, title_separator_spacing{10.0f}
, min_width{200.0f}
, min_height{100.0f}
, max_width_ratio{0.8f}
, max_height_ratio{0.8f}
, text_safety_margin{20.0f}
, animation_duration{0.3f}
{} {}
}; };
WindowMessage( WindowMessage(
std::shared_ptr<Text> text_renderer, std::shared_ptr<Text> text_renderer,
const std::string& title = "", std::string title = "",
const Config& config = Config{} const Config& config = Config{});
);
// Métodos principales // Métodos principales
void render(); void render();
@@ -109,7 +97,7 @@ class WindowMessage {
// Getters // Getters
[[nodiscard]] auto getRect() const -> const SDL_FRect& { return rect_; } [[nodiscard]] auto getRect() const -> const SDL_FRect& { return rect_; }
[[nodiscard]] auto getPositionMode() const -> PositionMode { return position_mode_; } [[nodiscard]] auto getPositionMode() const -> PositionMode { return position_mode_; }
[[nodiscard]] auto getAnchorPoint() const -> std::pair<float, float> { return {anchor_x_, anchor_y_}; } [[nodiscard]] auto getAnchorPoint() const -> SDL_FPoint { return anchor_; }
private: private:
std::shared_ptr<Text> text_renderer_; std::shared_ptr<Text> text_renderer_;
@@ -126,28 +114,27 @@ class WindowMessage {
// Posición y tamaño // Posición y tamaño
SDL_FRect rect_{0, 0, 300, 200}; SDL_FRect rect_{0, 0, 300, 200};
PositionMode position_mode_ = PositionMode::CENTERED; PositionMode position_mode_ = PositionMode::CENTERED;
float anchor_x_ = 0.0f; SDL_FPoint anchor_{0.0f, 0.0f};
float anchor_y_ = 0.0f;
// Animación de redimensionado // Animación de redimensionado
struct ResizeAnimation { struct ResizeAnimation {
bool active = false; bool active = false;
float start_width, start_height; float start_width, start_height;
float target_width, target_height; float target_width, target_height;
float elapsed = 0.0f; float elapsed = 0.0F;
void start(float from_w, float from_h, float to_w, float to_h) { void start(float from_w, float from_h, float to_w, float to_h) {
start_width = from_w; start_width = from_w;
start_height = from_h; start_height = from_h;
target_width = to_w; target_width = to_w;
target_height = to_h; target_height = to_h;
elapsed = 0.0f; elapsed = 0.0F;
active = true; active = true;
} }
void stop() { void stop() {
active = false; active = false;
elapsed = 0.0f; elapsed = 0.0F;
} }
[[nodiscard]] auto isFinished(float duration) const -> bool { [[nodiscard]] auto isFinished(float duration) const -> bool {
@@ -155,7 +142,7 @@ class WindowMessage {
} }
[[nodiscard]] auto getProgress(float duration) const -> float { [[nodiscard]] auto getProgress(float duration) const -> float {
return std::min(elapsed / duration, 1.0f); return std::min(elapsed / duration, 1.0F);
} }
} resize_animation_; } resize_animation_;
@@ -166,26 +153,26 @@ class WindowMessage {
Type type = Type::NONE; Type type = Type::NONE;
bool active = false; bool active = false;
float target_width, target_height; // Tamaño final al mostrar float target_width, target_height; // Tamaño final al mostrar
float elapsed = 0.0f; float elapsed = 0.0F;
void startShow(float to_w, float to_h) { void startShow(float to_w, float to_h) {
type = Type::SHOWING; type = Type::SHOWING;
target_width = to_w; target_width = to_w;
target_height = to_h; target_height = to_h;
elapsed = 0.0f; elapsed = 0.0F;
active = true; active = true;
} }
void startHide() { void startHide() {
type = Type::HIDING; type = Type::HIDING;
elapsed = 0.0f; elapsed = 0.0F;
active = true; active = true;
} }
void stop() { void stop() {
type = Type::NONE; type = Type::NONE;
active = false; active = false;
elapsed = 0.0f; elapsed = 0.0F;
} }
[[nodiscard]] auto isFinished(float duration) const -> bool { [[nodiscard]] auto isFinished(float duration) const -> bool {
@@ -193,7 +180,7 @@ class WindowMessage {
} }
[[nodiscard]] auto getProgress(float duration) const -> float { [[nodiscard]] auto getProgress(float duration) const -> float {
return std::min(elapsed / duration, 1.0f); return std::min(elapsed / duration, 1.0F);
} }
} show_hide_animation_; } show_hide_animation_;
@@ -212,7 +199,7 @@ class WindowMessage {
void updateResizeAnimation(float delta_time); // Actualiza la animación de redimensionado void updateResizeAnimation(float delta_time); // Actualiza la animación de redimensionado
// Función de suavizado (ease-out) // Función de suavizado (ease-out)
[[nodiscard]] auto easeOut(float t) const -> float; [[nodiscard]] static auto easeOut(float t) -> float;
// Métodos para manejo de texto durante animación // Métodos para manejo de texto durante animación
[[nodiscard]] auto getTruncatedText(const std::string& text, float available_width) const -> std::string; [[nodiscard]] auto getTruncatedText(const std::string& text, float available_width) const -> std::string;
@@ -221,6 +208,6 @@ class WindowMessage {
[[nodiscard]] auto calculateContentHeight() const -> float; [[nodiscard]] auto calculateContentHeight() const -> float;
[[nodiscard]] auto calculateContentWidth() const -> float; [[nodiscard]] auto calculateContentWidth() const -> float;
[[nodiscard]] auto getScreenWidth() const -> float; [[nodiscard]] static auto getScreenWidth() -> float;
[[nodiscard]] auto getScreenHeight() const -> float; [[nodiscard]] static auto getScreenHeight() -> float;
}; };