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
auto Asset::parseAssetType(const std::string &type_str) -> Type {
if (type_str == "BITMAP") return Type::BITMAP;
if (type_str == "MUSIC") return Type::MUSIC;
if (type_str == "SOUND") return Type::SOUND;
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;
if (type_str == "BITMAP") {
return Type::BITMAP;
}
if (type_str == "MUSIC") {
return Type::MUSIC;
}
if (type_str == "SOUND") {
return Type::SOUND;
}
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);
}
@@ -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
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::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:
// 1. Terminó
// 2. Ya mostró el mensaje
@@ -198,7 +198,7 @@ bool DefineButtons::isReadyToClose() const {
}
void DefineButtons::updateWindowMessage() {
if (!window_message_ || !options_gamepad_) {
if (!window_message_ || (options_gamepad_ == nullptr)) {
return;
}

View File

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

View File

@@ -157,7 +157,7 @@ void Director::loadAssets() {
#ifdef MACOS_BUNDLE
const std::string prefix = "/../Resources";
#else
const std::string prefix = "";
const std::string prefix;
#endif
// 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();
auto message = input_->handleEvent(event);
if (message.empty()) return;
if (message.empty()) {
return;
}
// Reemplazo de palabras clave por texto localizado
size_t pos;

View File

@@ -158,7 +158,7 @@ auto checkServiceButton() -> bool {
auto checkSystemInputs() -> bool {
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_DEC_SIZE, decWindowSize},
{Action::WINDOW_INC_SIZE, incWindowSize},
@@ -175,7 +175,7 @@ auto checkSystemInputs() -> bool {
#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)) {
func();
return true;

View File

@@ -315,14 +315,14 @@ auto Input::handleEvent(const SDL_Event &event) -> std::string {
case SDL_EVENT_GAMEPAD_REMOVED:
return removeGamepad(event.gdevice.which);
}
return std::string();
return {};
}
auto Input::addGamepad(int device_index) -> std::string {
SDL_Gamepad *pad = SDL_OpenGamepad(device_index);
if (pad == nullptr) {
std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << std::endl;
return std::string();
return {};
}
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;
gamepads_.erase(it);
return name + " DISCONNECTED";
} else {
}
std::cerr << "No se encontró el gamepad con ID " << id << std::endl;
return {};
}
}
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 {
if (name == Lang::getText("[SERVICE_MENU] PLAYER1")) {
return Player::Id::PLAYER1;
} else if (name == Lang::getText("[SERVICE_MENU] PLAYER2")) {
}
if (name == Lang::getText("[SERVICE_MENU] PLAYER2")) {
return Player::Id::PLAYER2;
} else {
return Player::Id::NO_PLAYER;

View File

@@ -161,7 +161,7 @@ class GamepadManager {
}
void resyncGamepadsWithPlayers() {
for (auto player : players) {
for (auto player : players_) {
switch (player->getId()) {
case Player::Id::PLAYER1:
player->setGamepad(gamepads_[0].instance);
@@ -226,8 +226,8 @@ class GamepadManager {
return false;
}
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 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
// Asigna el mando a un jugador
void assignTo(Input::Gamepad gamepad, Player::Id player_id) {
@@ -248,7 +248,7 @@ class GamepadManager {
static constexpr std::string_view UNASSIGNED_TEXT = "---";
static constexpr size_t MAX_PLAYERS = 2;
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
[[nodiscard]] static auto playerIdToIndex(Player::Id player_id) -> size_t {

View File

@@ -3,6 +3,7 @@
#include <cstdint>
#include <functional>
#include <string>
#include <utility>
// Clase dedicada para manejar el sistema de pausa
class PauseManager {
@@ -16,48 +17,48 @@ class PauseManager {
};
// 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));
}
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));
}
friend Source operator~(Source a) {
friend auto operator~(Source a) -> Source {
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;
}
friend Source& operator&=(Source& a, Source b) {
friend auto operator&=(Source& a, Source b) -> Source& {
return a = a & b;
}
private:
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;
}
void notifyPauseChanged() {
if (onPauseChangedCallback_) {
onPauseChangedCallback_(isPaused());
if (on_pause_changed_callback_) {
on_pause_changed_callback_(isPaused());
}
}
public:
// Constructor con callback opcional
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
void setFlag(Source source, bool enable) {
bool wasPaused = isPaused();
bool was_paused = isPaused();
if (enable) {
flags_ |= source;
@@ -66,7 +67,7 @@ class PauseManager {
}
// Solo notifica si cambió el estado general de pausa
if (wasPaused != isPaused()) {
if (was_paused != isPaused()) {
notifyPauseChanged();
}
}
@@ -80,13 +81,13 @@ class PauseManager {
void togglePlayerPause() { setPlayerPause(!isPlayerPaused()); }
// Getters
bool isPaused() const { return flags_ != Source::NONE; }
bool isPlayerPaused() const { return hasFlag(Source::PLAYER); }
bool isServiceMenuPaused() const { return hasFlag(Source::SERVICE_MENU); }
bool isFocusLossPaused() const { return hasFlag(Source::FOCUS_LOST); }
[[nodiscard]] auto isPaused() const -> bool { return flags_ != Source::NONE; }
[[nodiscard]] auto isPlayerPaused() const -> bool { return hasFlag(Source::PLAYER); }
[[nodiscard]] auto isServiceMenuPaused() const -> bool { return hasFlag(Source::SERVICE_MENU); }
[[nodiscard]] auto isFocusLossPaused() const -> bool { return hasFlag(Source::FOCUS_LOST); }
// Obtiene las banderas actuales
Source getFlags() const { return flags_; }
[[nodiscard]] auto getFlags() const -> Source { return flags_; }
// Limpia todas las pausas (útil para reset)
void clearAll() {
@@ -97,24 +98,32 @@ class PauseManager {
}
// Método para debug
std::string getStatusString() const {
if (flags_ == Source::NONE) return "Active";
[[nodiscard]] auto getStatusString() const -> std::string {
if (flags_ == Source::NONE) {
return "Active";
}
std::string result = "Paused by: ";
bool first = true;
if (hasFlag(Source::PLAYER)) {
if (!first) result += ", ";
if (!first) {
result += ", ";
}
result += "Player";
first = false;
}
if (hasFlag(Source::SERVICE_MENU)) {
if (!first) result += ", ";
if (!first) {
result += ", ";
}
result += "ServiceMenu";
first = false;
}
if (hasFlag(Source::FOCUS_LOST)) {
if (!first) result += ", ";
if (!first) {
result += ", ";
}
result += "FocusLoss";
first = false;
}
@@ -124,6 +133,6 @@ class PauseManager {
// Permite cambiar el callback en runtime
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()),
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)),
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_out_(std::make_unique<Fade>()),
balloon_manager_(std::make_unique<BalloonManager>()),
@@ -99,10 +99,10 @@ Game::Game(Player::Id player_id, int current_stage, bool demo)
setTotalPower();
// Registra callbacks
ServiceMenu::get()->setStateChangeCallback([this](bool isActive) {
ServiceMenu::get()->setStateChangeCallback([this](bool is_active) {
// Solo aplicar pausa si NO estamos en modo demo
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);
}
void Game::onPauseStateChanged(bool isPaused) {
screen_->attenuate(isPaused);
tabe_->pauseTimer(isPaused);
void Game::onPauseStateChanged(bool is_paused) {
screen_->attenuate(is_paused);
tabe_->pauseTimer(is_paused);
}
#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 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)
#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
void Text::write(int x, int y, const std::string &text, int kerning, int length) {
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);
for (const auto ch : visible_text) {
const auto index = static_cast<unsigned char>(ch);
for (const auto CH : VISIBLE_TEXT) {
const auto INDEX = static_cast<unsigned char>(CH);
if (index < offset_.size()) {
sprite_->setSpriteClip(offset_[index].x, offset_[index].y, box_width_, box_height_);
if (INDEX < offset_.size()) {
sprite_->setSpriteClip(offset_[INDEX].x, offset_[INDEX].y, box_width_, box_height_);
sprite_->setX(x + shift);
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
void Text::write2X(int x, int y, const std::string &text, int kerning, int length) {
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) {
const auto index = static_cast<unsigned char>(ch);
for (const auto CH : VISIBLE_TEXT) {
const auto INDEX = static_cast<unsigned char>(CH);
if (index < offset_.size()) {
if (INDEX < offset_.size()) {
SDL_FRect rect = {
static_cast<float>(offset_[index].x),
static_cast<float>(offset_[index].y),
static_cast<float>(offset_[INDEX].x),
static_cast<float>(offset_[INDEX].y),
static_cast<float>(box_width_),
static_cast<float>(box_height_)};
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;
for (const auto &ch : text) {
// 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
if (index < offset_.size()) {
shift += (offset_[index].w + kerning);
if (INDEX < offset_.size()) {
shift += (offset_[INDEX].w + kerning);
}
}

View File

@@ -63,8 +63,8 @@ auto ActionListOption::findCurrentIndex() const -> size_t {
return 0;
}
const std::string current_value = value_getter_();
auto it = std::find(options_.begin(), options_.end(), current_value);
const std::string CURRENT_VALUE = value_getter_();
auto it = std::find(options_.begin(), options_.end(), CURRENT_VALUE);
if (it != options_.end()) {
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()>;
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();
}
@@ -199,7 +199,7 @@ class ActionListOption : public MenuOption {
ValueGetter value_getter_;
ValueSetter value_setter_;
ActionExecutor action_executor_;
size_t current_index_;
size_t current_index_{0};
void updateCurrentIndex();
[[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) {
start_width = from_w; start_height = from_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) {
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)
: 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) {
if (!visible_) return;
if (!visible_) {
return;
}
// Dibuja la sombra
if (param.service_menu.drop_shadow) {
@@ -57,7 +67,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
if (shouldShowContent()) {
// Dibuja el título
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
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;
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;
std::string truncated_value = getTruncatedValue(option_pairs.at(i).second, available_width);
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);
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);
element_text_->writeColored(X, y, truncated_value, current_color, -2);
} else {
const int available_width = rect_.w - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2);
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);
const int AVAILABLE_WIDTH = rect_.w - (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2);
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);
}
y += options_height_ + options_padding_;
}
@@ -89,7 +99,7 @@ void MenuRenderer::render(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);
if (visible_) {
@@ -101,7 +111,9 @@ void MenuRenderer::update(const ServiceMenu *menu_state) {
// --- Nuevos métodos de control ---
void MenuRenderer::show(const ServiceMenu* menu_state) {
if (visible_) return;
if (visible_) {
return;
}
visible_ = true;
// 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);
// El tamaño inicial es cero para la animación
rect_.w = 0.0f;
rect_.h = 0.0f;
rect_.w = 0.0F;
rect_.h = 0.0F;
updatePosition();
}
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
resize_animation_.stop();
@@ -234,7 +248,9 @@ void MenuRenderer::updateShowHideAnimation(float delta_time) {
rect_.w = show_hide_animation_.target_width;
rect_.h = show_hide_animation_.target_height;
} 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();
updatePosition();
@@ -244,8 +260,8 @@ void MenuRenderer::updateShowHideAnimation(float delta_time) {
rect_.w = show_hide_animation_.target_width * progress;
rect_.h = show_hide_animation_.target_height * progress;
} else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) {
rect_.w = show_hide_animation_.target_width * (1.0f - progress);
rect_.h = show_hide_animation_.target_height * (1.0f - progress);
rect_.w = show_hide_animation_.target_width * (1.0F - progress);
rect_.h = show_hide_animation_.target_height * (1.0F - progress);
}
updatePosition();
}
@@ -274,8 +290,8 @@ void MenuRenderer::updateResizeAnimation(float delta_time) {
void MenuRenderer::updatePosition() {
switch (position_mode_) {
case PositionMode::CENTERED:
rect_.x = anchor_x_ - rect_.w / 2.0f;
rect_.y = anchor_y_ - rect_.h / 2.0f;
rect_.x = anchor_x_ - rect_.w / 2.0F;
rect_.y = anchor_y_ - rect_.h / 2.0F;
break;
case PositionMode::FIXED:
rect_.x = anchor_x_;
@@ -289,12 +305,17 @@ void MenuRenderer::updatePosition() {
// Resto de métodos (sin cambios significativos)
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) {
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) {
if (option->getGroup() != sg) continue;
if (option->getGroup() != sg) {
continue;
}
max_option_width = std::max(max_option_width, element_text_->length(option->getCaption(), -2));
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;
@@ -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);
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_));
}
}
@@ -375,5 +398,5 @@ auto MenuRenderer::getTruncatedValue(const std::string &value, int available_wid
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; }

View File

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

View File

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

View File

@@ -33,7 +33,7 @@ class ServiceMenu {
static constexpr size_t MIN_GAP_OPTION_VALUE = 30;
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 ---
static void init();
@@ -57,7 +57,7 @@ class ServiceMenu {
// --- Método para manejar eventos ---
void handleEvent(const SDL_Event &event);
bool checkInput();
auto checkInput() -> bool;
// --- Método principal para refresco externo ---
void refresh(); // Refresca los valores y el layout del menú bajo demanda

View File

@@ -9,11 +9,11 @@
WindowMessage::WindowMessage(
std::shared_ptr<Text> text_renderer,
const std::string& title,
std::string title,
const Config& config)
: text_renderer_(std::move(text_renderer)),
config_(config),
title_(title),
title_(std::move(title)),
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) {
}
@@ -45,7 +45,7 @@ void WindowMessage::render() {
std::string visible_title = getTruncatedText(title_, available_width);
if (!visible_title.empty()) {
text_renderer_->writeStyle(
rect_.x + rect_.w / 2.0f,
rect_.x + rect_.w / 2.0F,
current_y,
visible_title,
title_style_);
@@ -58,9 +58,9 @@ void WindowMessage::render() {
config_.border_color.b, config_.border_color.a);
SDL_RenderLine(renderer,
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,
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);
if (!visible_text.empty()) {
text_renderer_->writeStyle(
rect_.x + rect_.w / 2.0f,
rect_.x + rect_.w / 2.0F,
current_y,
visible_text,
text_style_);
@@ -84,7 +84,7 @@ void WindowMessage::update() {
if (show_hide_animation_.active || resize_animation_.active) {
// Aquí necesitarías el delta_time del game loop
// 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);
}
}
@@ -102,8 +102,8 @@ void WindowMessage::show() {
// Iniciar animación de mostrar desde tamaño 0
show_hide_animation_.startShow(rect_.w, rect_.h);
rect_.w = 0.0f;
rect_.h = 0.0f;
rect_.w = 0.0F;
rect_.h = 0.0F;
updatePosition(); // Reposicionar con tamaño 0
}
@@ -150,8 +150,7 @@ void WindowMessage::clearTexts() {
}
void WindowMessage::setPosition(float x, float y, PositionMode mode) {
anchor_x_ = x;
anchor_y_ = y;
anchor_ = {x, y};
position_mode_ = mode;
updatePosition();
}
@@ -163,7 +162,7 @@ void WindowMessage::setSize(float width, float height) {
}
void WindowMessage::centerOnScreen() {
setPosition(getScreenWidth() / 2.0f, getScreenHeight() / 2.0f, PositionMode::CENTERED);
setPosition(getScreenWidth() / 2.0F, getScreenHeight() / 2.0F, PositionMode::CENTERED);
}
void WindowMessage::autoSize() {
@@ -201,18 +200,18 @@ void WindowMessage::updateStyles() {
void WindowMessage::updatePosition() {
switch (position_mode_) {
case PositionMode::CENTERED:
rect_.x = anchor_x_ - rect_.w / 2.0f;
rect_.y = anchor_y_ - rect_.h / 2.0f;
rect_.x = anchor_.x- rect_.w / 2.0F;
rect_.y = anchor_.y - rect_.h / 2.0F;
break;
case PositionMode::FIXED:
rect_.x = anchor_x_;
rect_.y = anchor_y_;
rect_.x = anchor_.x;
rect_.y = anchor_.y;
break;
}
// 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_.y = std::max(0.0f, std::min(rect_.y, getScreenHeight() - rect_.h));
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));
}
void WindowMessage::ensureTextFits() {
@@ -282,12 +281,12 @@ auto WindowMessage::calculateContentWidth() const -> float {
return max_width;
}
auto WindowMessage::getScreenWidth() const -> float {
return static_cast<float>(param.game.width);
auto WindowMessage::getScreenWidth() -> float {
return param.game.width;
}
auto WindowMessage::getScreenHeight() const -> float {
return static_cast<float>(param.game.height);
auto WindowMessage::getScreenHeight() -> float {
return param.game.height;
}
void WindowMessage::triggerAutoResize() {
@@ -321,8 +320,8 @@ void WindowMessage::updateShowHideAnimation(float delta_time) {
rect_.h = show_hide_animation_.target_height;
} else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) {
// Ocultar completado
rect_.w = 0.0f;
rect_.h = 0.0f;
rect_.w = 0.0F;
rect_.h = 0.0F;
visible_ = false;
}
@@ -338,8 +337,8 @@ void WindowMessage::updateShowHideAnimation(float delta_time) {
rect_.h = show_hide_animation_.target_height * progress;
} else if (show_hide_animation_.type == ShowHideAnimation::Type::HIDING) {
// Decrecer desde el tamaño actual hasta 0
rect_.w = show_hide_animation_.target_width * (1.0f - progress);
rect_.h = show_hide_animation_.target_height * (1.0f - progress);
rect_.w = show_hide_animation_.target_width * (1.0F - progress);
rect_.h = show_hide_animation_.target_height * (1.0F - progress);
}
updatePosition(); // Mantener la posición centrada durante la animación
@@ -377,14 +376,14 @@ auto WindowMessage::shouldShowContent() const -> bool {
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
return 1.0f - (1.0f - t) * (1.0f - t);
return 1.0F - (1.0F - t) * (1.0F - t);
}
auto WindowMessage::getAvailableTextWidth() const -> float {
// 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 {
@@ -399,7 +398,7 @@ auto WindowMessage::getTruncatedText(const std::string& text, float available_wi
}
// 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 "";
}

View File

@@ -24,45 +24,33 @@ class WindowMessage {
Color text_color;
// Espaciado y dimensiones
float padding;
float line_spacing;
float title_separator_spacing; // Espacio extra para separador del título
float padding{15.0f};
float line_spacing{5.0f};
float title_separator_spacing{10.0f}; // Espacio extra para separador del título
// Límites de tamaño
float min_width;
float min_height;
float max_width_ratio; // % máximo de ancho de pantalla
float max_height_ratio; // % máximo de alto de pantalla
float min_width{200.0f};
float min_height{100.0f};
float max_width_ratio{0.8f}; // % máximo de ancho de pantalla
float max_height_ratio{0.8f}; // % máximo de alto de pantalla
// 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
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
Config()
: bg_color{40, 40, 60, 220}
, 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}
: bg_color{40, 40, 60, 220}, border_color{100, 100, 120, 255}, title_color{255, 255, 255, 255}, text_color{200, 200, 200, 255}
{}
};
WindowMessage(
std::shared_ptr<Text> text_renderer,
const std::string& title = "",
const Config& config = Config{}
);
std::string title = "",
const Config& config = Config{});
// Métodos principales
void render();
@@ -109,7 +97,7 @@ class WindowMessage {
// Getters
[[nodiscard]] auto getRect() const -> const SDL_FRect& { return rect_; }
[[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:
std::shared_ptr<Text> text_renderer_;
@@ -126,28 +114,27 @@ class WindowMessage {
// Posición y tamaño
SDL_FRect rect_{0, 0, 300, 200};
PositionMode position_mode_ = PositionMode::CENTERED;
float anchor_x_ = 0.0f;
float anchor_y_ = 0.0f;
SDL_FPoint anchor_{0.0f, 0.0f};
// Animación de redimensionado
struct ResizeAnimation {
bool active = false;
float start_width, start_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) {
start_width = from_w;
start_height = from_h;
target_width = to_w;
target_height = to_h;
elapsed = 0.0f;
elapsed = 0.0F;
active = true;
}
void stop() {
active = false;
elapsed = 0.0f;
elapsed = 0.0F;
}
[[nodiscard]] auto isFinished(float duration) const -> bool {
@@ -155,7 +142,7 @@ class WindowMessage {
}
[[nodiscard]] auto getProgress(float duration) const -> float {
return std::min(elapsed / duration, 1.0f);
return std::min(elapsed / duration, 1.0F);
}
} resize_animation_;
@@ -166,26 +153,26 @@ class WindowMessage {
Type type = Type::NONE;
bool active = false;
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) {
type = Type::SHOWING;
target_width = to_w;
target_height = to_h;
elapsed = 0.0f;
elapsed = 0.0F;
active = true;
}
void startHide() {
type = Type::HIDING;
elapsed = 0.0f;
elapsed = 0.0F;
active = true;
}
void stop() {
type = Type::NONE;
active = false;
elapsed = 0.0f;
elapsed = 0.0F;
}
[[nodiscard]] auto isFinished(float duration) const -> bool {
@@ -193,7 +180,7 @@ class WindowMessage {
}
[[nodiscard]] auto getProgress(float duration) const -> float {
return std::min(elapsed / duration, 1.0f);
return std::min(elapsed / duration, 1.0F);
}
} show_hide_animation_;
@@ -212,7 +199,7 @@ class WindowMessage {
void updateResizeAnimation(float delta_time); // Actualiza la animación de redimensionado
// 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
[[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 calculateContentWidth() const -> float;
[[nodiscard]] auto getScreenWidth() const -> float;
[[nodiscard]] auto getScreenHeight() const -> float;
[[nodiscard]] static auto getScreenWidth() -> float;
[[nodiscard]] static auto getScreenHeight() -> float;
};