diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp index 5cb1b3a..e8d4784 100644 --- a/source/animated_sprite.cpp +++ b/source/animated_sprite.cpp @@ -1,11 +1,10 @@ #include "animated_sprite.h" -#include // Para size_t -#include // Para basic_ostream, basic_istream, operator<<, basic... -#include // Para cout, cerr -#include // Para basic_stringstream -#include // Para runtime_error -#include "texture.h" // Para Texture -#include "utils.h" // Para printWithDots +#include // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError +#include // Para size_t +#include // Para basic_istream, basic_ifstream, basic_ios +#include // Para basic_stringstream +#include // Para runtime_error +#include "texture.h" // Para Texture // Carga las animaciones en un vector(Animations) desde un fichero AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path) @@ -13,11 +12,11 @@ AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path) std::ifstream file(file_path); if (!file) { - std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str()); throw std::runtime_error("Fichero no encontrado: " + file_path); } - printWithDots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]"); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Animation file loaded: %s", file_path.c_str()); std::vector buffer; std::string line; @@ -52,7 +51,7 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr texture, const Animation } } -// Obtiene el indice de la animación a partir del nombre +// Obtiene el índice de la animación a partir del nombre int AnimatedSprite::getIndex(const std::string &name) { auto index = -1; @@ -65,7 +64,7 @@ int AnimatedSprite::getIndex(const std::string &name) return index; } } - std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl; + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "** Warning: could not find \"%s\" animation", name.c_str()); return -1; } @@ -169,7 +168,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so // Parsea el fichero para buscar variables y valores if (line != "[animation]") { - // Encuentra la posición del caracter '=' + // Encuentra la posición del carácter '=' size_t pos = line.find("="); // Procesa las dos subcadenas @@ -182,7 +181,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so else if (key == "frame_height") frame_height = value; else - std::cout << "Warning: unknown parameter " << key << std::endl; + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: unknown parameter %s", key.c_str()); frames_per_row = texture_->getWidth() / frame_width; const int w = texture_->getWidth() / frame_width; @@ -191,7 +190,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so } } - // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación + // Si la línea contiene el texto [animation] se realiza el proceso de carga de una animación if (line == "[animation]") { Animation animation; @@ -220,7 +219,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so SDL_FRect rect = {0, 0, frame_width, frame_height}; while (getline(ss, tmp, ',')) { - // Comprueba que el tile no sea mayor que el maximo indice permitido + // Comprueba que el tile no sea mayor que el máximo índice permitido const int num_tile = std::stoi(tmp); if (num_tile <= max_tiles) { @@ -230,9 +229,8 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so } } } - else - std::cout << "Warning: unknown parameter " << key << std::endl; + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: unknown parameter %s", key.c_str()); } } while (line != "[/animation]"); @@ -240,7 +238,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so animations_.emplace_back(animation); } - // Una vez procesada la linea, aumenta el indice para pasar a la siguiente + // Una vez procesada la línea, aumenta el índice para pasar a la siguiente index++; } diff --git a/source/asset.cpp b/source/asset.cpp index 68704bc..dc2780b 100644 --- a/source/asset.cpp +++ b/source/asset.cpp @@ -1,9 +1,9 @@ #include "asset.h" -#include // Para find_if, max -#include // Para basic_ostream, operator<<, basic_ifstream, endl -#include // Para cout -#include // Para allocator, char_traits, string, operator+, oper... -#include "utils.h" // Para getFileName, printWithDots +#include // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError +#include // Para find_if, max +#include // Para basic_ifstream, ifstream +#include // Para allocator, string, char_traits, operator+ +#include "utils.h" // Para getFileName // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado Asset *Asset::asset_ = nullptr; @@ -48,7 +48,7 @@ std::string Asset::get(const std::string &text) const } else { - std::cout << "Warning: file " << text << " not found" << std::endl; + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s not found", text.c_str()); return ""; } } @@ -58,12 +58,9 @@ bool Asset::check() const { bool success = true; - std::cout << "\n** CHECKING FILES" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES"); - // std::cout << "Executable path is: " << executable_path_ << std::endl; - // std::cout << "Sample filepath: " << file_list_.back().file << std::endl; - - // Comprueba la lista de ficheros clasificandolos por tipo + // Comprueba la lista de ficheros clasificándolos por tipo for (int type = 0; type < static_cast(AssetType::MAX_ASSET_TYPE); ++type) { // Comprueba si hay ficheros de ese tipo @@ -80,7 +77,7 @@ bool Asset::check() const // Si hay ficheros de ese tipo, comprueba si existen if (any) { - std::cout << "\n>> " << getTypeName(static_cast(type)).c_str() << " FILES" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> %s FILES", getTypeName(static_cast(type)).c_str()); for (const auto &f : file_list_) { @@ -90,12 +87,19 @@ bool Asset::check() const } } if (success) - std::cout << " All files are OK." << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, " All files are OK."); } } // Resultado - std::cout << (success ? "\n** CHECKING FILES COMPLETED.\n" : "\n** CHECKING FILES FAILED.\n") << std::endl; + if (success) + { + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES COMPLETED.\n"); + } + else + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "\n** CHECKING FILES FAILED.\n"); + } return success; } @@ -108,7 +112,9 @@ bool Asset::checkFile(const std::string &path) const file.close(); if (!success) - printWithDots("Checking file : ", getFileName(path), "[ ERROR ]"); + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Checking file: %s [ ERROR ]", getFileName(path).c_str()); + } return success; } @@ -120,43 +126,24 @@ std::string Asset::getTypeName(AssetType type) const { case AssetType::BITMAP: return "BITMAP"; - break; - case AssetType::MUSIC: return "MUSIC"; - break; - case AssetType::SOUND: return "SOUND"; - break; - case AssetType::FONT: return "FONT"; - break; - case AssetType::LANG: return "LANG"; - break; - case AssetType::DATA: return "DATA"; - break; - case AssetType::ANIMATION: return "ANIMATION"; - break; - case AssetType::PALETTE: return "PALETTE"; - break; - case AssetType::ITEM: return "ITEM"; - break; - default: return "ERROR"; - break; } } diff --git a/source/balloon_manager.cpp b/source/balloon_manager.cpp index 3bd67d9..43642d1 100644 --- a/source/balloon_manager.cpp +++ b/source/balloon_manager.cpp @@ -321,7 +321,7 @@ int BalloonManager::destroyAllBalloons() balloon_deploy_counter_ = 300; JA_PlaySound(Resource::get()->getSound("power_ball_explosion.wav")); - Screen::get()->flash(flash_color, 3); + Screen::get()->flash(FLASH_COLOR, 3); Screen::get()->shake(); return score; diff --git a/source/credits.cpp b/source/credits.cpp index 07fac24..b488033 100644 --- a/source/credits.cpp +++ b/source/credits.cpp @@ -46,7 +46,7 @@ Credits::Credits() section::name = section::Name::CREDITS; balloon_manager_->setPlayArea(play_area_); - fade_in_->setColor(fade_color.r, fade_color.g, fade_color.b); + fade_in_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b); fade_in_->setType(FadeType::FULLSCREEN); fade_in_->setPostDuration(50); fade_in_->setMode(FadeMode::IN); @@ -185,46 +185,46 @@ void Credits::fillTextTexture() int y = (param.game.height - TEXTS_HEIGHT) / 2; y = 0; text->setPalette(1); - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); text->setPalette(0); y += SPACE_POST_TITLE; - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); y += SPACE_PRE_TITLE; text->setPalette(1); - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(1), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(1), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); text->setPalette(0); y += SPACE_POST_TITLE; - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); y += SPACE_PRE_TITLE; text->setPalette(1); - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(2), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(2), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); text->setPalette(0); y += SPACE_POST_TITLE; - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(5), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(5), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); y += SPACE_POST_TITLE; - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(6), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(6), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); y += SPACE_PRE_TITLE; text->setPalette(1); - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(3), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(3), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); text->setPalette(0); y += SPACE_POST_TITLE; - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(7), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(7), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); y += SPACE_POST_TITLE; - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(8), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(8), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); y += SPACE_POST_TITLE; - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(9), 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(9), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); // Mini logo y += SPACE_PRE_TITLE; mini_logo_rect_src_.y = y; auto mini_logo_sprite = std::make_unique(Resource::get()->getTexture("logo_jailgames_mini.png")); mini_logo_sprite->setPosition(1 + param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, 1 + y); - Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(shdw_txt_color.r, shdw_txt_color.g, shdw_txt_color.b); + Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(SHADOW_TEXT_COLOR.r, SHADOW_TEXT_COLOR.g, SHADOW_TEXT_COLOR.b); mini_logo_sprite->render(); mini_logo_sprite->setPosition(param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, y); @@ -233,7 +233,7 @@ void Credits::fillTextTexture() // Texto con el copyright y += mini_logo_sprite->getHeight() + 3; - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXT_COPYRIGHT, 1, no_color, 1, shdw_txt_color); + text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXT_COPYRIGHT, 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); // Resetea el renderizador SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr); diff --git a/source/director.cpp b/source/director.cpp index 70d77a6..f165f7a 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -1,15 +1,11 @@ // IWYU pragma: no_include #include "director.h" #include // Para SDL_AudioFormat -#include // Para SDL_BLENDMODE_BLEND #include // Para SDL_GetError #include // Para SDL_GamepadButton -#include // Para SDL_SetHint, SDL_HINT_RENDER_DRIVER -#include // Para SDL_Init, SDL_Quit, SDL_INIT_VIDEO -#include // Para SDL_Log -#include // Para SDL_HideCursor +#include // Para SDL_Init, SDL_Quit, SDL_INIT_AUDIO +#include // Para SDL_Log, SDL_LogCategory, SDL_LogE... #include // Para SDL_Scancode -#include // Para SDL_free, SDL_PRIu32, Uint32 #include // Para errno, EEXIST, EACCES, ENAMETOOLONG #include // Para printf, perror #include // Para mkdir, stat, S_IRWXU @@ -17,10 +13,9 @@ #include // Para min #include // Para exit, EXIT_FAILURE, size_t, srand #include // Para time -#include // Para basic_ostream, operator<<, cout, endl #include // Para make_unique, unique_ptr #include // Para runtime_error -#include // Para operator+, char_traits, allocator +#include // Para operator+, allocator, char_traits #include // Para vector #include "asset.h" // Para Asset, AssetType #include "credits.h" // Para Credits @@ -35,8 +30,8 @@ #include "manage_hiscore_table.h" // Para ManageHiScoreTable #include "notifier.h" // Para Notifier #include "on_screen_help.h" // Para OnScreenHelp -#include "options.h" // Para Options, options, GamepadOptions -#include "param.h" // Para Param, ParamGame, param, loadParam... +#include "options.h" // Para GamepadOptions, Options, options +#include "param.h" // Para loadParamsFromFile #include "resource.h" // Para Resource #include "screen.h" // Para Screen #include "section.h" // Para Name, Options, name, options @@ -61,13 +56,7 @@ Director::Director(int argc, const char *argv[]) section::attract_mode = section::AttractMode::TITLE_TO_DEMO; #endif -#ifndef VERBOSE - // Deshabilita todos los std::cout - std::ostream null_stream(nullptr); - orig_buf = std::cout.rdbuf(null_stream.rdbuf()); -#endif - - std::cout << "Game start" << std::endl; + SDL_Log("Game start"); // Inicia la semilla aleatoria usando el tiempo actual en segundos std::srand(static_cast(std::time(nullptr))); @@ -85,7 +74,7 @@ Director::Director(int argc, const char *argv[]) Director::~Director() { close(); - std::cout << "\nBye!" << std::endl; + SDL_Log("\nBye!"); } // Inicializa todo @@ -694,12 +683,7 @@ int Director::run() break; } - std::cout << "\nGame end " << return_code << std::endl; - -#ifndef VERBOSE - // Habilita de nuevo los std::cout - std::cout.rdbuf(orig_buf); -#endif + SDL_Log("\nGame end %s", return_code.c_str()); return (section::options == section::Options::QUIT_WITH_CONTROLLER) ? 1 : 0; } diff --git a/source/director.h b/source/director.h index d4f39ab..3b9cbfa 100644 --- a/source/director.h +++ b/source/director.h @@ -1,25 +1,14 @@ #pragma once -#include // Para SDL_Renderer -#include // Para SDL_Window -#include // Para string +#include // Para string namespace lang { enum class Code : int; -} // lines 9-9 - -// Textos -constexpr char WINDOW_CAPTION[] = "Coffee Crisis Arcade Edition"; +} // lines 8-8 class Director { private: - // Objetos y punteros - -#ifndef VERBOSE - std::streambuf *orig_buf; // Puntero al buffer de flujo original para restaurar std::cout -#endif - // Variables std::string executable_path_; // Path del ejecutable std::string system_folder_; // Carpeta del sistema donde guardar datos diff --git a/source/game.cpp b/source/game.cpp index 7674d68..d74b95f 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -64,14 +64,14 @@ Game::Game(int player_id, int current_stage, bool demo) Scoreboard::init(); scoreboard_ = Scoreboard::get(); - fade_in_->setColor(fade_color.r, fade_color.g, fade_color.b); + fade_in_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b); fade_in_->setPreDuration(demo_.enabled ? 80 : 0); fade_in_->setPostDuration(0); fade_in_->setType(FadeType::RANDOM_SQUARE); fade_in_->setMode(FadeMode::IN); fade_in_->activate(); - fade_out_->setColor(fade_color.r, fade_color.g, fade_color.b); + fade_out_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b); fade_out_->setPostDuration(param.fade.post_duration); fade_out_->setType(FadeType::VENETIAN); @@ -263,7 +263,7 @@ void Game::updateStage() ++Stage::number; JA_PlaySound(Resource::get()->getSound("stage_change.wav")); balloon_manager_->resetBalloonSpeed(); - screen_->flash(flash_color, 3); + screen_->flash(FLASH_COLOR, 3); screen_->shake(); // Escribe el texto por pantalla @@ -1691,7 +1691,7 @@ void Game::initDifficultyVars() { balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[0]); difficulty_score_multiplier_ = 0.5f; - scoreboard_->setColor(scoreboard_easy_color); + scoreboard_->setColor(SCOREBOARD_EASY_COLOR); break; } @@ -1699,7 +1699,7 @@ void Game::initDifficultyVars() { balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[0]); difficulty_score_multiplier_ = 1.0f; - scoreboard_->setColor(scoreboard_normal_color); + scoreboard_->setColor(SCOREBOARD_NORMAL_COLOR); break; } @@ -1707,7 +1707,7 @@ void Game::initDifficultyVars() { balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[4]); difficulty_score_multiplier_ = 1.5f; - scoreboard_->setColor(scoreboard_hard_color); + scoreboard_->setColor(SCOREBOARD_HARD_COLOR); break; } diff --git a/source/gif.cpp b/source/gif.cpp index 606683d..3637a19 100644 --- a/source/gif.cpp +++ b/source/gif.cpp @@ -1,14 +1,11 @@ #include "gif.h" -#include // Para std::cout -#include // Para memcpy, size_t -#include // Para runtime_error -#include // Para allocator, char_traits, operator==, basic_string +#include // Para SDL_LogError, SDL_LogCategory, SDL_LogInfo +#include // Para memcpy, size_t +#include // Para runtime_error +#include // Para char_traits, operator==, basic_string, string namespace GIF { - - // Función inline para reemplazar el macro READ. - // Actualiza el puntero 'buffer' tras copiar 'size' bytes a 'dst'. inline void readBytes(const uint8_t *&buffer, void *dst, size_t size) { std::memcpy(dst, buffer, size); @@ -17,9 +14,9 @@ namespace GIF void Gif::decompress(int code_length, const uint8_t *input, int input_length, uint8_t *out) { - // Verifica que el code_length tenga un rango razonable. if (code_length < 2 || code_length > 12) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Invalid LZW code length: %d", code_length); throw std::runtime_error("Invalid LZW code length"); } @@ -33,7 +30,6 @@ namespace GIF int stop_code = clear_code + 1; int match_len = 0; - // Inicializamos el diccionario con el tamaño correspondiente. dictionary.resize(1 << (code_length + 1)); for (dictionary_ind = 0; dictionary_ind < (1 << code_length); dictionary_ind++) { @@ -41,17 +37,16 @@ namespace GIF dictionary[dictionary_ind].prev = -1; dictionary[dictionary_ind].len = 1; } - dictionary_ind += 2; // Reservamos espacio para clear y stop codes + dictionary_ind += 2; - // Bucle principal: procesar el stream comprimido. while (input_length > 0) { int code = 0; - // Lee (code_length + 1) bits para formar el código. for (i = 0; i < (code_length + 1); i++) { if (input_length <= 0) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unexpected end of input in decompress"); throw std::runtime_error("Unexpected end of input in decompress"); } bit = ((*input & mask) != 0) ? 1 : 0; @@ -67,7 +62,6 @@ namespace GIF if (code == clear_code) { - // Reinicia el diccionario. code_length = reset_code_length; dictionary.resize(1 << (code_length + 1)); for (dictionary_ind = 0; dictionary_ind < (1 << code_length); dictionary_ind++) @@ -89,8 +83,7 @@ namespace GIF { if (code > dictionary_ind) { - std::cerr << "code = " << std::hex << code - << ", but dictionary_ind = " << dictionary_ind << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "LZW error: code (%d) exceeds dictionary_ind (%d)", code, dictionary_ind); throw std::runtime_error("LZW error: code exceeds dictionary_ind."); } @@ -122,23 +115,20 @@ namespace GIF prev = code; - // Verifica que 'code' sea un índice válido antes de usarlo. if (code < 0 || static_cast(code) >= dictionary.size()) { - std::cerr << "Invalid LZW code " << code - << ", dictionary size " << dictionary.size() << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Invalid LZW code %d, dictionary size %lu", code, static_cast(dictionary.size())); throw std::runtime_error("LZW error: invalid code encountered"); } - int curCode = code; // Variable temporal para recorrer la cadena. + int curCode = code; match_len = dictionary[curCode].len; while (curCode != -1) { - // Se asume que dictionary[curCode].len > 0. out[dictionary[curCode].len - 1] = dictionary[curCode].byte; if (dictionary[curCode].prev == curCode) { - std::cerr << "Internal error; self-reference detected." << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Internal error; self-reference detected."); throw std::runtime_error("Internal error in decompress: self-reference"); } curCode = dictionary[curCode].prev; @@ -165,7 +155,6 @@ namespace GIF std::vector Gif::processImageDescriptor(const uint8_t *&buffer, const std::vector &gct, int resolution_bits) { ImageDescriptor image_descriptor; - // Lee 9 bytes para el image descriptor. readBytes(buffer, &image_descriptor, sizeof(ImageDescriptor)); uint8_t lzw_code_size; @@ -208,26 +197,27 @@ namespace GIF std::vector Gif::processGifStream(const uint8_t *buffer, uint16_t &w, uint16_t &h) { - // Leer la cabecera de 6 bytes ("GIF87a" o "GIF89a") uint8_t header[6]; std::memcpy(header, buffer, 6); buffer += 6; - // Opcional: Validar header std::string headerStr(reinterpret_cast(header), 6); if (headerStr != "GIF87a" && headerStr != "GIF89a") { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Formato de archivo GIF inválido: %s", headerStr.c_str()); throw std::runtime_error("Formato de archivo GIF inválido."); } - // Leer el Screen Descriptor (7 bytes, empaquetado sin padding) + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Procesando GIF con cabecera: %s", headerStr.c_str()); + ScreenDescriptor screen_descriptor; readBytes(buffer, &screen_descriptor, sizeof(ScreenDescriptor)); - // Asigna ancho y alto w = screen_descriptor.width; h = screen_descriptor.height; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Resolución del GIF: %dx%d", w, h); + int color_resolution_bits = ((screen_descriptor.fields & 0x70) >> 4) + 1; std::vector global_color_table; if (screen_descriptor.fields & 0x80) @@ -238,22 +228,18 @@ namespace GIF buffer += 3 * global_color_table_size; } - // Supongamos que 'buffer' es el puntero actual y TRAILER es 0x3B uint8_t block_type = *buffer++; while (block_type != TRAILER) { - if (block_type == EXTENSION_INTRODUCER) // 0x21 + if (block_type == EXTENSION_INTRODUCER) { - // Se lee la etiqueta de extensión, la cual indica el tipo de extensión. uint8_t extension_label = *buffer++; switch (extension_label) { - case GRAPHIC_CONTROL: // 0xF9 + case GRAPHIC_CONTROL: { - // Procesar Graphic Control Extension: - uint8_t blockSize = *buffer++; // Normalmente, blockSize == 4 - buffer += blockSize; // Saltamos los 4 bytes del bloque fijo - // Saltar los sub-bloques + uint8_t blockSize = *buffer++; + buffer += blockSize; uint8_t subBlockSize = *buffer++; while (subBlockSize != 0) { @@ -262,11 +248,10 @@ namespace GIF } break; } - case APPLICATION_EXTENSION: // 0xFF - case COMMENT_EXTENSION: // 0xFE - case PLAINTEXT_EXTENSION: // 0x01 + case APPLICATION_EXTENSION: + case COMMENT_EXTENSION: + case PLAINTEXT_EXTENSION: { - // Para estas extensiones, saltamos el bloque fijo y los sub-bloques. uint8_t blockSize = *buffer++; buffer += blockSize; uint8_t subBlockSize = *buffer++; @@ -279,7 +264,6 @@ namespace GIF } default: { - // Si la etiqueta de extensión es desconocida, saltarla también: uint8_t blockSize = *buffer++; buffer += blockSize; uint8_t subBlockSize = *buffer++; @@ -294,17 +278,18 @@ namespace GIF } else if (block_type == IMAGE_DESCRIPTOR) { - // Procesar el Image Descriptor y retornar los datos de imagen + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Procesando Image Descriptor..."); return processImageDescriptor(buffer, global_color_table, color_resolution_bits); } else { - std::cerr << "Unrecognized block type " << std::hex << static_cast(block_type) << std::endl; + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Unrecognized block type: 0x%X", block_type); return std::vector{}; } block_type = *buffer++; } + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "GIF procesado correctamente."); return std::vector{}; } diff --git a/source/global_events.cpp b/source/global_events.cpp index 4b737a2..4a20fd0 100644 --- a/source/global_events.cpp +++ b/source/global_events.cpp @@ -1,7 +1,7 @@ #include "global_events.h" -#include // Para char_traits, basic_ostream, operator<<, cout, endl -#include "mouse.h" // Para handleEvent -#include "section.h" // Para Name, Options, name, options +#include // Para SDL_LogInfo, SDL_LogCategory +#include "mouse.h" // Para handleEvent +#include "section.h" // Para Name, Options, name, options namespace globalEvents { @@ -14,16 +14,20 @@ namespace globalEvents section::name = section::Name::QUIT; section::options = section::Options::QUIT_FROM_EVENT; return; + case SDL_EVENT_RENDER_DEVICE_RESET: case SDL_EVENT_RENDER_TARGETS_RESET: - std::cout << "SDL_RENDER_TARGETS_RESET" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "SDL_RENDER_TARGETS_RESET"); break; + case SDL_EVENT_WINDOW_RESIZED: - std::cout << "SDL_WINDOWEVENT_SIZE_CHANGED" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "SDL_WINDOWEVENT_SIZE_CHANGED"); break; + default: break; } + Mouse::handleEvent(event); } } \ No newline at end of file diff --git a/source/hiscore_table.cpp b/source/hiscore_table.cpp index c1c5778..38d8d83 100644 --- a/source/hiscore_table.cpp +++ b/source/hiscore_table.cpp @@ -117,7 +117,7 @@ void HiScoreTable::render() Screen::get()->start(); // Limpia la pantalla - Screen::get()->clean(bg_color); + Screen::get()->clean(BG_COLOR); // Pinta el fondo background_->render(); @@ -233,7 +233,7 @@ void HiScoreTable::createSprites() // Crea los sprites para las entradas en la tabla de puntuaciones const int animation = rand() % 4; const std::string sample_line(ENTRY_LENGHT + 3, ' '); - auto sample_entry = std::make_unique(entry_text->writeDXToTexture(TEXT_SHADOW, sample_line, 1, orange_color, 1, shdw_txt_color)); + auto sample_entry = std::make_unique(entry_text->writeDXToTexture(TEXT_SHADOW, sample_line, 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR)); const auto entry_width = sample_entry->getWidth(); for (int i = 0; i < MAX_NAMES; ++i) { @@ -248,7 +248,7 @@ void HiScoreTable::createSprites() } const auto line = table_position + options.game.hi_score_table.at(i).name + dots + score + one_cc; - entry_names_.emplace_back(std::make_shared(entry_text->writeDXToTexture(TEXT_SHADOW, line, 1, orange_color, 1, shdw_txt_color))); + entry_names_.emplace_back(std::make_shared(entry_text->writeDXToTexture(TEXT_SHADOW, line, 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR))); const int default_pos_x = (backbuffer_width - entry_width) / 2; const int pos_x = (i < 9) ? default_pos_x : default_pos_x - entry_text->getCharacterSize(); const int pos_y = (i * space_between_lines) + first_line + space_between_header; @@ -324,7 +324,7 @@ void HiScoreTable::updateSprites() // Inicializa el fade void HiScoreTable::initFade() { - fade_->setColor(fade_color.r, fade_color.g, fade_color.b); + fade_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b); fade_->setType(FadeType::RANDOM_SQUARE); fade_->setPostDuration(param.fade.post_duration); fade_->setMode(fade_mode_); @@ -346,7 +346,7 @@ void HiScoreTable::initBackground() background_->setTransition(0.0f); background_->setSunProgression(1.0f); background_->setMoonProgression(0.0f); - background_fade_color_ = green_sky_color; + background_fade_color_ = GREEN_SKY_COLOR; break; } @@ -356,7 +356,7 @@ void HiScoreTable::initBackground() background_->setTransition(0.0f); background_->setSunProgression(0.65f); background_->setMoonProgression(0.0f); - background_fade_color_ = pink_sky_color; + background_fade_color_ = PINK_SKY_COLOR; break; } @@ -366,7 +366,7 @@ void HiScoreTable::initBackground() background_->setTransition(0.0f); background_->setSunProgression(0.0f); background_->setMoonProgression(0.0f); - background_fade_color_ = blue_sky_color; + background_fade_color_ = BLUE_SKY_COLOR; break; } diff --git a/source/input.cpp b/source/input.cpp index 337f75f..88c0fa7 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -1,9 +1,9 @@ #include "input.h" -#include // Para SDL_GetError +#include // Para SDL_GetError #include // Para SDL_INIT_GAMEPAD, SDL_InitSubSystem #include // Para SDL_GetKeyboardState +#include // Para SDL_LogInfo, SDL_LogCategory, SDL_Log... #include // Para find -#include // Para basic_ostream, operator<<, basic_ostr... #include // Para distance #include // Para unordered_map, operator==, _Node_cons... #include // Para pair @@ -226,7 +226,7 @@ bool Input::discoverGameControllers() if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) { - std::cout << "Error, could not load " << game_controller_db_path_.c_str() << " file: " << SDL_GetError() << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: could not load %s file: %s", game_controller_db_path_.c_str(), SDL_GetError()); } SDL_GetJoysticks(&num_joysticks_); @@ -244,15 +244,15 @@ bool Input::discoverGameControllers() } } - std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** LOOKING FOR GAME CONTROLLERS"); if (num_joysticks_ != num_gamepads_) { - std::cout << "Joysticks found: " << num_joysticks_ << std::endl; - std::cout << "Gamepads found : " << num_gamepads_ << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Joysticks found: %d", num_joysticks_); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Gamepads found : %d", num_gamepads_); } else { - std::cout << "Gamepads found: " << num_gamepads_ << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Gamepads found: %d", num_gamepads_); } if (num_gamepads_ > 0) @@ -267,19 +267,19 @@ bool Input::discoverGameControllers() { connected_controllers_.push_back(pad); const std::string name = SDL_GetGamepadNameForID(i); - std::cout << "#" << i << ": " << name << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "#%d: %s", i, name.c_str()); controller_names_.push_back(name); } else { - std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GetError() = %s", SDL_GetError()); } } SDL_SetGamepadEventsEnabled(true); } - std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** FINISHED LOOKING FOR GAME CONTROLLERS"); return found; } @@ -321,12 +321,12 @@ void Input::printBindings(InputDeviceToUse device, int controller_index) const } // Muestra el nombre del mando - std::cout << "\n" + controller_names_.at(controller_index) << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n%s", controller_names_.at(controller_index).c_str()); // Muestra los botones asignados for (auto bi : button_inputs_) { - std::cout << to_string(bi) << " : " << controller_bindings_.at(controller_index).at(static_cast(bi)).button << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s : %d", to_string(bi).c_str(), controller_bindings_.at(controller_index).at(static_cast(bi)).button); } } } diff --git a/source/instructions.cpp b/source/instructions.cpp index e150475..e524787 100644 --- a/source/instructions.cpp +++ b/source/instructions.cpp @@ -38,7 +38,7 @@ Instructions::Instructions() view_ = param.game.game_area.rect; // Inicializa objetos - fade_->setColor(fade_color.r, fade_color.g, fade_color.b); + fade_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b); fade_->setType(FadeType::FULLSCREEN); fade_->setPostDuration(param.fade.post_duration); fade_->setMode(FadeMode::IN); @@ -147,24 +147,24 @@ void Instructions::fillTexture() const int anchor_item = (param.game.width - (lenght + desp_x)) / 2; // Escribe el texto de las instrucciones - text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, first_line, lang::getText(11), 1, orange_color, 1, shdw_txt_color); + text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, first_line, lang::getText(11), 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR); const int anchor1 = first_line + space_post_header; - text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 0, lang::getText(12), 1, no_color, 1, shdw_txt_color); - text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 1, lang::getText(13), 1, no_color, 1, shdw_txt_color); - text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 2, lang::getText(14), 1, no_color, 1, shdw_txt_color); - text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 3, lang::getText(15), 1, no_color, 1, shdw_txt_color); + text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 0, lang::getText(12), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); + text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_between_lines * 1, lang::getText(13), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); + text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 2, lang::getText(14), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); + text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor1 + space_new_paragraph + space_between_lines * 3, lang::getText(15), 1, NO_COLOR, 1, SHADOW_TEXT_COLOR); // Escribe el texto de los objetos y sus puntos const int anchor2 = anchor1 + space_pre_header + space_new_paragraph + space_between_lines * 3; - text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor2, lang::getText(16), 1, orange_color, 1, shdw_txt_color); + text_->writeDX(TEXT_CENTER | TEXT_COLOR | TEXT_SHADOW, param.game.game_area.center_x, anchor2, lang::getText(16), 1, ORANGE_COLOR, 1, SHADOW_TEXT_COLOR); const int anchor3 = anchor2 + space_post_header; - text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 0, lang::getText(17), shdw_txt_color); - text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 1, lang::getText(18), shdw_txt_color); - text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 2, lang::getText(19), shdw_txt_color); - text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 3, lang::getText(20), shdw_txt_color); - text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 4, lang::getText(21), shdw_txt_color); + text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 0, lang::getText(17), SHADOW_TEXT_COLOR); + text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 1, lang::getText(18), SHADOW_TEXT_COLOR); + text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 2, lang::getText(19), SHADOW_TEXT_COLOR); + text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 3, lang::getText(20), SHADOW_TEXT_COLOR); + text_->writeShadowed(anchor_item + desp_x, anchor3 + space_between_item_lines * 4, lang::getText(21), SHADOW_TEXT_COLOR); // Deja el renderizador como estaba SDL_SetRenderTarget(renderer_, temp); @@ -242,7 +242,7 @@ void Instructions::render() Screen::get()->start(); // Limpia la pantalla - Screen::get()->clean(bg_color); + Screen::get()->clean(BG_COLOR); // Dibuja el mosacico de fondo tiled_bg_->render(); diff --git a/source/intro.cpp b/source/intro.cpp index 1199caf..3c50a64 100644 --- a/source/intro.cpp +++ b/source/intro.cpp @@ -260,7 +260,7 @@ void Intro::render() Screen::get()->start(); // Limpia la pantalla - Screen::get()->clean(bg_color); + Screen::get()->clean(BG_COLOR); // Dibuja el fondo tiled_bg_->render(); diff --git a/source/jail_audio.cpp b/source/jail_audio.cpp index 23c3ffe..bc4b894 100644 --- a/source/jail_audio.cpp +++ b/source/jail_audio.cpp @@ -1,49 +1,53 @@ #ifndef JA_USESDLMIXER #include "jail_audio.h" -#include "stb_vorbis.c" -#include -#include +#include // Para SDL_IOFromMem +#include // Para SDL_Log, SDL_SetLogPriority, SDL_LogC... +#include // Para SDL_GetTicks, SDL_AddTimer, SDL_Remov... +#include // Para uint32_t, uint8_t +#include // Para NULL, fseek, printf, fclose, fopen +#include // Para free, malloc +#include "stb_vorbis.c" // Para stb_vorbis_decode_memory -#define JA_MAX_SIMULTANEOUS_CHANNELS 5 +#define JA_MAX_SIMULTANEOUS_CHANNELS 20 struct JA_Sound_t { - SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 }; - Uint32 length { 0 }; - Uint8 *buffer { NULL }; + SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000}; + Uint32 length{0}; + Uint8 *buffer{NULL}; }; struct JA_Channel_t { - JA_Sound_t *sound { nullptr }; - int pos { 0 }; - int times { 0 }; - SDL_AudioStream *stream { nullptr }; - JA_Channel_state state { JA_CHANNEL_FREE }; + JA_Sound_t *sound{nullptr}; + int pos{0}; + int times{0}; + SDL_AudioStream *stream{nullptr}; + JA_Channel_state state{JA_CHANNEL_FREE}; }; struct JA_Music_t { - SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 }; - Uint32 length { 0 }; - Uint8 *buffer { nullptr }; + SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000}; + Uint32 length{0}; + Uint8 *buffer{nullptr}; - int pos { 0 }; - int times { 0 }; - SDL_AudioStream *stream { nullptr }; - JA_Music_state state { JA_MUSIC_INVALID }; + int pos{0}; + int times{0}; + SDL_AudioStream *stream{nullptr}; + JA_Music_state state{JA_MUSIC_INVALID}; }; -JA_Music_t *current_music { nullptr }; -JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS]; +JA_Music_t *current_music{nullptr}; +JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS]; -SDL_AudioSpec JA_audioSpec { SDL_AUDIO_S16, 2, 48000 }; -float JA_musicVolume { 1.0f }; -float JA_soundVolume { 0.5f }; -bool JA_musicEnabled { true }; -bool JA_soundEnabled { true }; -SDL_AudioDeviceID sdlAudioDevice { 0 }; -SDL_TimerID JA_timerID { 0 }; +SDL_AudioSpec JA_audioSpec{SDL_AUDIO_S16, 2, 48000}; +float JA_musicVolume{1.0f}; +float JA_soundVolume{0.5f}; +bool JA_musicEnabled{true}; +bool JA_soundEnabled{true}; +SDL_AudioDeviceID sdlAudioDevice{0}; +SDL_TimerID JA_timerID{0}; bool fading = false; int fade_start_time; @@ -92,13 +96,17 @@ Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval) { if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING) { - if (fading) { + if (fading) + { int time = SDL_GetTicks(); - if (time > (fade_start_time+fade_duration)) { + if (time > (fade_start_time + fade_duration)) + { fading = false; JA_StopMusic(); return 30; - } else { + } + else + { const int time_passed = time - fade_start_time; const float percent = (float)time_passed / (float)fade_duration; SDL_SetAudioStreamGain(current_music->stream, 1.0 - percent); @@ -107,34 +115,38 @@ Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval) if (current_music->times != 0) { - if (SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length/2)) { + if (SDL_GetAudioStreamAvailable(current_music->stream) < static_cast(current_music->length / 2)) + { SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length); } - if (current_music->times>0) current_music->times--; + if (current_music->times > 0) + current_music->times--; } else { - if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) JA_StopMusic(); + if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) + JA_StopMusic(); } } if (JA_soundEnabled) { - for (int i=0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) + for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) if (channels[i].state == JA_CHANNEL_PLAYING) { if (channels[i].times != 0) { - if (SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length/2)) + if (SDL_GetAudioStreamAvailable(channels[i].stream) < static_cast(channels[i].sound->length / 2)) SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length); - if (channels[i].times>0) channels[i].times--; + if (channels[i].times > 0) + channels[i].times--; } } else { - if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) JA_StopChannel(i); + if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) + JA_StopChannel(i); } - } return 30; @@ -142,28 +154,31 @@ Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval) void JA_Init(const int freq, const SDL_AudioFormat format, const int channels) { - #ifdef DEBUG +#ifdef DEBUG SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG); - #endif - +#endif + SDL_Log("Iniciant JailAudio..."); - JA_audioSpec = {format, channels, freq }; - if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); + JA_audioSpec = {format, channels, freq}; + if (!sdlAudioDevice) + SDL_CloseAudioDevice(sdlAudioDevice); sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec); - SDL_Log( (sdlAudioDevice==0) ? "Failed to initialize SDL audio!\n" : "OK!\n"); - //SDL_PauseAudioDevice(sdlAudioDevice); + SDL_Log((sdlAudioDevice == 0) ? "Failed to initialize SDL audio!\n" : "OK!\n"); + // SDL_PauseAudioDevice(sdlAudioDevice); JA_timerID = SDL_AddTimer(30, JA_UpdateCallback, nullptr); } void JA_Quit() { - if (JA_timerID) SDL_RemoveTimer(JA_timerID); + if (JA_timerID) + SDL_RemoveTimer(JA_timerID); - if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); + if (!sdlAudioDevice) + SDL_CloseAudioDevice(sdlAudioDevice); sdlAudioDevice = 0; } -JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length) +JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length) { JA_Music_t *music = new JA_Music_t(); @@ -174,7 +189,7 @@ JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length) music->spec.channels = chan; music->spec.freq = samplerate; music->spec.format = SDL_AUDIO_S16; - music->buffer = (Uint8*)SDL_malloc(music->length); + music->buffer = (Uint8 *)SDL_malloc(music->length); SDL_memcpy(music->buffer, output, music->length); free(output); music->pos = 0; @@ -183,15 +198,16 @@ JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length) return music; } -JA_Music_t *JA_LoadMusic(const char* filename) +JA_Music_t *JA_LoadMusic(const char *filename) { // [RZC 28/08/22] Carreguem primer el arxiu en memòria i després el descomprimim. Es algo més rapid. FILE *f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); - Uint8 *buffer = (Uint8*)malloc(fsize + 1); - if (fread(buffer, fsize, 1, f)!=1) return NULL; + Uint8 *buffer = (Uint8 *)malloc(fsize + 1); + if (fread(buffer, fsize, 1, f) != 1) + return NULL; fclose(f); JA_Music_t *music = JA_LoadMusic(buffer, fsize); @@ -203,7 +219,8 @@ JA_Music_t *JA_LoadMusic(const char* filename) void JA_PlayMusic(JA_Music_t *music, const int loop) { - if (!JA_musicEnabled) return; + if (!JA_musicEnabled) + return; JA_StopMusic(); @@ -213,48 +230,58 @@ void JA_PlayMusic(JA_Music_t *music, const int loop) current_music->times = loop; current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &JA_audioSpec); - if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) printf("[ERROR] SDL_PutAudioStreamData failed!\n"); + if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) + printf("[ERROR] SDL_PutAudioStreamData failed!\n"); SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); - if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) printf("[ERROR] SDL_BindAudioStream failed!\n"); - //SDL_ResumeAudioStreamDevice(current_music->stream); + if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) + printf("[ERROR] SDL_BindAudioStream failed!\n"); + // SDL_ResumeAudioStreamDevice(current_music->stream); } void JA_PauseMusic() { - if (!JA_musicEnabled) return; - if (!current_music || current_music->state == JA_MUSIC_INVALID) return; + if (!JA_musicEnabled) + return; + if (!current_music || current_music->state == JA_MUSIC_INVALID) + return; current_music->state = JA_MUSIC_PAUSED; - //SDL_PauseAudioStreamDevice(current_music->stream); + // SDL_PauseAudioStreamDevice(current_music->stream); SDL_UnbindAudioStream(current_music->stream); } void JA_ResumeMusic() { - if (!JA_musicEnabled) return; - if (!current_music || current_music->state == JA_MUSIC_INVALID) return; + if (!JA_musicEnabled) + return; + if (!current_music || current_music->state == JA_MUSIC_INVALID) + return; current_music->state = JA_MUSIC_PLAYING; - //SDL_ResumeAudioStreamDevice(current_music->stream); + // SDL_ResumeAudioStreamDevice(current_music->stream); SDL_BindAudioStream(sdlAudioDevice, current_music->stream); } void JA_StopMusic() { - if (!JA_musicEnabled) return; - if (!current_music || current_music->state == JA_MUSIC_INVALID) return; + if (!JA_musicEnabled) + return; + if (!current_music || current_music->state == JA_MUSIC_INVALID) + return; current_music->pos = 0; current_music->state = JA_MUSIC_STOPPED; - //SDL_PauseAudioStreamDevice(current_music->stream); + // SDL_PauseAudioStreamDevice(current_music->stream); SDL_DestroyAudioStream(current_music->stream); current_music->stream = nullptr; } void JA_FadeOutMusic(const int milliseconds) { - if (!JA_musicEnabled) return; - if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) return; + if (!JA_musicEnabled) + return; + if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) + return; fading = true; fade_start_time = SDL_GetTicks(); @@ -264,51 +291,55 @@ void JA_FadeOutMusic(const int milliseconds) JA_Music_state JA_GetMusicState() { - if (!JA_musicEnabled) return JA_MUSIC_DISABLED; - if (!current_music) return JA_MUSIC_INVALID; + if (!JA_musicEnabled) + return JA_MUSIC_DISABLED; + if (!current_music) + return JA_MUSIC_INVALID; return current_music->state; } void JA_DeleteMusic(JA_Music_t *music) { - if (current_music == music) current_music = nullptr; + if (current_music == music) + current_music = nullptr; SDL_free(music->buffer); - if (music->stream) SDL_DestroyAudioStream(music->stream); + if (music->stream) + SDL_DestroyAudioStream(music->stream); delete music; } float JA_SetMusicVolume(float volume) { - JA_musicVolume = SDL_clamp( volume, 0.0f, 1.0f ); - if (current_music) SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); + JA_musicVolume = SDL_clamp(volume, 0.0f, 1.0f); + if (current_music) + SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); return JA_musicVolume; } void JA_SetMusicPosition(float value) { - if (!current_music) return; + if (!current_music) + return; current_music->pos = value * current_music->spec.freq; } float JA_GetMusicPosition() { - if (!current_music) return 0; - return float(current_music->pos)/float(current_music->spec.freq); + if (!current_music) + return 0; + return float(current_music->pos) / float(current_music->spec.freq); } void JA_EnableMusic(const bool value) { - if ( !value && current_music && (current_music->state==JA_MUSIC_PLAYING) ) JA_StopMusic(); + if (!value && current_music && (current_music->state == JA_MUSIC_PLAYING)) + JA_StopMusic(); JA_musicEnabled = value; } - - - - -JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length) +JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length) { JA_Sound_t *sound = new JA_Sound_t(); sound->buffer = buffer; @@ -316,15 +347,15 @@ JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length) return sound; } -JA_Sound_t *JA_LoadSound(uint8_t* buffer, uint32_t size) +JA_Sound_t *JA_LoadSound(uint8_t *buffer, uint32_t size) { JA_Sound_t *sound = new JA_Sound_t(); - SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size),1, &sound->spec, &sound->buffer, &sound->length); + SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length); return sound; } -JA_Sound_t *JA_LoadSound(const char* filename) +JA_Sound_t *JA_LoadSound(const char *filename) { JA_Sound_t *sound = new JA_Sound_t(); SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length); @@ -334,11 +365,16 @@ JA_Sound_t *JA_LoadSound(const char* filename) int JA_PlaySound(JA_Sound_t *sound, const int loop) { - if (!JA_soundEnabled) return -1; + if (!JA_soundEnabled) + return -1; int channel = 0; - while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { channel++; } - if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) channel = 0; + while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) + { + channel++; + } + if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) + channel = 0; JA_StopChannel(channel); channels[channel].sound = sound; @@ -355,9 +391,11 @@ int JA_PlaySound(JA_Sound_t *sound, const int loop) int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop) { - if (!JA_soundEnabled) return -1; + if (!JA_soundEnabled) + return -1; - if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return -1; + if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) + return -1; JA_StopChannel(channel); channels[channel].sound = sound; @@ -374,8 +412,10 @@ int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop) void JA_DeleteSound(JA_Sound_t *sound) { - for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { - if (channels[i].sound == sound) JA_StopChannel(i); + for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) + { + if (channels[i].sound == sound) + JA_StopChannel(i); } SDL_free(sound->buffer); delete sound; @@ -383,7 +423,8 @@ void JA_DeleteSound(JA_Sound_t *sound) void JA_PauseChannel(const int channel) { - if (!JA_soundEnabled) return; + if (!JA_soundEnabled) + return; if (channel == -1) { @@ -391,7 +432,7 @@ void JA_PauseChannel(const int channel) if (channels[i].state == JA_CHANNEL_PLAYING) { channels[i].state = JA_CHANNEL_PAUSED; - //SDL_PauseAudioStreamDevice(channels[i].stream); + // SDL_PauseAudioStreamDevice(channels[i].stream); SDL_UnbindAudioStream(channels[i].stream); } } @@ -400,7 +441,7 @@ void JA_PauseChannel(const int channel) if (channels[channel].state == JA_CHANNEL_PLAYING) { channels[channel].state = JA_CHANNEL_PAUSED; - //SDL_PauseAudioStreamDevice(channels[channel].stream); + // SDL_PauseAudioStreamDevice(channels[channel].stream); SDL_UnbindAudioStream(channels[channel].stream); } } @@ -408,7 +449,8 @@ void JA_PauseChannel(const int channel) void JA_ResumeChannel(const int channel) { - if (!JA_soundEnabled) return; + if (!JA_soundEnabled) + return; if (channel == -1) { @@ -416,7 +458,7 @@ void JA_ResumeChannel(const int channel) if (channels[i].state == JA_CHANNEL_PAUSED) { channels[i].state = JA_CHANNEL_PLAYING; - //SDL_ResumeAudioStreamDevice(channels[i].stream); + // SDL_ResumeAudioStreamDevice(channels[i].stream); SDL_BindAudioStream(sdlAudioDevice, channels[i].stream); } } @@ -425,7 +467,7 @@ void JA_ResumeChannel(const int channel) if (channels[channel].state == JA_CHANNEL_PAUSED) { channels[channel].state = JA_CHANNEL_PLAYING; - //SDL_ResumeAudioStreamDevice(channels[channel].stream); + // SDL_ResumeAudioStreamDevice(channels[channel].stream); SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream); } } @@ -433,12 +475,15 @@ void JA_ResumeChannel(const int channel) void JA_StopChannel(const int channel) { - if (!JA_soundEnabled) return; + if (!JA_soundEnabled) + return; if (channel == -1) { - for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { - if (channels[i].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[i].stream); + for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) + { + if (channels[i].state != JA_CHANNEL_FREE) + SDL_DestroyAudioStream(channels[i].stream); channels[channel].stream = nullptr; channels[i].state = JA_CHANNEL_FREE; channels[i].pos = 0; @@ -447,7 +492,8 @@ void JA_StopChannel(const int channel) } else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) { - if (channels[channel].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[channel].stream); + if (channels[channel].state != JA_CHANNEL_FREE) + SDL_DestroyAudioStream(channels[channel].stream); channels[channel].stream = nullptr; channels[channel].state = JA_CHANNEL_FREE; channels[channel].pos = 0; @@ -457,19 +503,21 @@ void JA_StopChannel(const int channel) JA_Channel_state JA_GetChannelState(const int channel) { - if (!JA_soundEnabled) return JA_SOUND_DISABLED; + if (!JA_soundEnabled) + return JA_SOUND_DISABLED; - if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return JA_CHANNEL_INVALID; + if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) + return JA_CHANNEL_INVALID; return channels[channel].state; } float JA_SetSoundVolume(float volume) { - JA_soundVolume = SDL_clamp( volume, 0.0f, 1.0f ); + JA_soundVolume = SDL_clamp(volume, 0.0f, 1.0f); for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) - if ( (channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED) ) + if ((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume); return JA_soundVolume; @@ -479,7 +527,8 @@ void JA_EnableSound(const bool value) { for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { - if (channels[i].state == JA_CHANNEL_PLAYING) JA_StopChannel(i); + if (channels[i].state == JA_CHANNEL_PLAYING) + JA_StopChannel(i); } JA_soundEnabled = value; } diff --git a/source/jail_audio.h b/source/jail_audio.h index 53e1a0f..635d901 100644 --- a/source/jail_audio.h +++ b/source/jail_audio.h @@ -1,8 +1,26 @@ #pragma once -#include -enum JA_Channel_state { JA_CHANNEL_INVALID, JA_CHANNEL_FREE, JA_CHANNEL_PLAYING, JA_CHANNEL_PAUSED, JA_SOUND_DISABLED }; -enum JA_Music_state { JA_MUSIC_INVALID, JA_MUSIC_PLAYING, JA_MUSIC_PAUSED, JA_MUSIC_STOPPED, JA_MUSIC_DISABLED }; +#include // Para SDL_AudioFormat +#include // Para Uint32, Uint8 +struct JA_Music_t; // lines 8-8 +struct JA_Sound_t; // lines 7-7 + +enum JA_Channel_state +{ + JA_CHANNEL_INVALID, + JA_CHANNEL_FREE, + JA_CHANNEL_PLAYING, + JA_CHANNEL_PAUSED, + JA_SOUND_DISABLED +}; +enum JA_Music_state +{ + JA_MUSIC_INVALID, + JA_MUSIC_PLAYING, + JA_MUSIC_PAUSED, + JA_MUSIC_STOPPED, + JA_MUSIC_DISABLED +}; struct JA_Sound_t; struct JA_Music_t; @@ -10,8 +28,8 @@ struct JA_Music_t; void JA_Init(const int freq, const SDL_AudioFormat format, const int channels); void JA_Quit(); -JA_Music_t *JA_LoadMusic(const char* filename); -JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length); +JA_Music_t *JA_LoadMusic(const char *filename); +JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length); void JA_PlayMusic(JA_Music_t *music, const int loop = -1); void JA_PauseMusic(); void JA_ResumeMusic(); @@ -24,9 +42,9 @@ void JA_SetMusicPosition(float value); float JA_GetMusicPosition(); void JA_EnableMusic(const bool value); -JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length); -JA_Sound_t *JA_LoadSound(Uint8* buffer, Uint32 length); -JA_Sound_t *JA_LoadSound(const char* filename); +JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length); +JA_Sound_t *JA_LoadSound(Uint8 *buffer, Uint32 length); +JA_Sound_t *JA_LoadSound(const char *filename); int JA_PlaySound(JA_Sound_t *sound, const int loop = 0); int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop = 0); void JA_PauseChannel(const int channel); diff --git a/source/jail_shader.cpp b/source/jail_shader.cpp index 7051296..8f35ed2 100644 --- a/source/jail_shader.cpp +++ b/source/jail_shader.cpp @@ -1,7 +1,7 @@ #include "jail_shader.h" +#include // Para SDL_LogCategory, SDL_LogError, SDL_LogWarn #include // Para SDL_FPoint, SDL_Point #include // Para strncmp -#include // Para basic_ostream, operator<<, endl, cout #include // Para runtime_error #include // Para vector @@ -71,6 +71,7 @@ namespace shader { if (source.empty()) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "ERROR FATAL: El código fuente del shader está vacío."); throw std::runtime_error("ERROR FATAL: El código fuente del shader está vacío."); } @@ -95,14 +96,14 @@ namespace shader glGetShaderiv(resultado, GL_COMPILE_STATUS, &compiladoCorrectamente); if (compiladoCorrectamente != GL_TRUE) { - std::cout << "Error en la compilación del shader (" << resultado << ")!" << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error en la compilación del shader (%d)!", resultado); GLint longitudLog; glGetShaderiv(resultado, GL_INFO_LOG_LENGTH, &longitudLog); if (longitudLog > 0) { std::vector log(longitudLog); glGetShaderInfoLog(resultado, longitudLog, &longitudLog, log.data()); - std::cout << "Registro de compilación del shader: " << log.data() << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Registro de compilación del shader: %s", log.data()); } glDeleteShader(resultado); resultado = 0; @@ -134,8 +135,7 @@ namespace shader { std::vector log(longitudLog); glGetProgramInfoLog(idPrograma, longitudLog, &longitudLog, log.data()); - std::cout << "Registro de información del programa:" << std::endl - << log.data() << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Registro de información del programa:\n%s", log.data()); } } if (idShaderVertice) @@ -156,13 +156,7 @@ namespace shader shader::backBuffer = texturaBackBuffer; SDL_GetWindowSize(ventana, &win_size.x, &win_size.y); - // int acceso; SDL_GetTextureSize(texturaBackBuffer, &tex_size.x, &tex_size.y); - // SDL_QueryTexture(texturaBackBuffer, nullptr, &acceso, &tex_size.x, &tex_size.y); - /*if (acceso != SDL_TEXTUREACCESS_TARGET) - { - throw std::runtime_error("ERROR FATAL: La textura debe tener definido SDL_TEXTUREACCESS_TARGET."); - }*/ const auto RENDER_NAME = SDL_GetRendererName(renderer); @@ -172,7 +166,7 @@ namespace shader #ifndef __APPLE__ if (!initGLExtensions()) { - std::cout << "ADVERTENCIA: No se han podido inicializar las extensiones de OpenGL." << std::endl; + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "ADVERTENCIA: No se han podido inicializar las extensiones de OpenGL."); usingOpenGL = false; return false; } @@ -182,7 +176,7 @@ namespace shader } else { - std::cout << "ADVERTENCIA: El driver del renderer no es OpenGL." << std::endl; + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "ADVERTENCIA: El driver del renderer no es OpenGL."); usingOpenGL = false; return false; } diff --git a/source/manage_hiscore_table.cpp b/source/manage_hiscore_table.cpp index e80f6cf..d7499d4 100644 --- a/source/manage_hiscore_table.cpp +++ b/source/manage_hiscore_table.cpp @@ -1,8 +1,8 @@ #include "manage_hiscore_table.h" #include // Para SDL_GetError #include // Para SDL_ReadIO, SDL_WriteIO, SDL_CloseIO +#include // Para SDL_LogCategory, SDL_LogError, SDL_Lo... #include // Para find_if, sort -#include // Para basic_ostream, operator<<, cout, endl #include // Para distance #include "utils.h" // Para getFileName @@ -116,12 +116,12 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path) table_.push_back(entry); } - std::cout << "Reading file: " << getFileName(file_path) << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Reading file: %s", getFileName(file_path).c_str()); SDL_CloseIO(file); } else { - std::cout << "Error: Unable to load " << getFileName(file_path) << " file! " << SDL_GetError() << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unable to load %s file! %s", getFileName(file_path).c_str(), SDL_GetError()); success = false; } return success; @@ -157,12 +157,12 @@ bool ManageHiScoreTable::saveToFile(const std::string &file_path) SDL_WriteIO(file, &occ_value, sizeof(int)); } - std::cout << "Writing file: " << getFileName(file_path) << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Writing file: %s", getFileName(file_path).c_str()); SDL_CloseIO(file); } else { - std::cout << "Error: Unable to save " << getFileName(file_path) << " file! " << SDL_GetError() << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unable to save %s file! %s", getFileName(file_path).c_str(), SDL_GetError()); success = false; } return success; diff --git a/source/options.cpp b/source/options.cpp index a993304..b4cf35e 100644 --- a/source/options.cpp +++ b/source/options.cpp @@ -1,13 +1,13 @@ #include "options.h" -#include // Para clamp -#include // Para basic_ostream, operator<<, basic_ostream::opera... -#include // Para cout -#include // Para swap -#include // Para vector -#include "input.h" // Para InputDeviceToUse -#include "lang.h" // Para Code -#include "screen.h" // Para ScreenFilter -#include "utils.h" // Para boolToString, stringToBool, getFileName +#include // Para SDL_LogCategory, SDL_LogInfo, SDL_LogWarn +#include // Para clamp +#include // Para basic_ostream, operator<<, basic_ostream::... +#include // Para swap +#include // Para vector +#include "input.h" // Para InputDeviceToUse +#include "lang.h" // Para Code +#include "screen.h" // Para ScreenFilter +#include "utils.h" // Para boolToString, stringToBool, getFileName // Variables Options options; @@ -65,31 +65,30 @@ bool loadOptionsFile(std::string file_path) // Si el fichero se puede abrir if (file.good()) { - // Procesa el fichero linea a linea - std::cout << "Reading file: " << getFileName(file_path) << std::endl; + // Procesa el fichero línea a línea + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Reading file: %s", getFileName(file_path).c_str()); std::string line; while (std::getline(file, line)) { - // Comprueba que la linea no sea un comentario + // Comprueba que la línea no sea un comentario if (line.substr(0, 1) != "#") { - // Encuentra la posición del caracter '=' + // Encuentra la posición del carácter '=' int pos = line.find("="); // Procesa las dos subcadenas if (!setOptions(line.substr(0, pos), line.substr(pos + 1, line.length()))) { - std::cout << "Warning: file " << getFileName(file_path) << std::endl; - std::cout << "Unknown parameter " << line.substr(0, pos).c_str() << std::endl; + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Warning: file %s", getFileName(file_path).c_str()); + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Unknown parameter: %s", line.substr(0, pos).c_str()); success = false; } } } file.close(); } - // El fichero no existe else - { + { // Crea el fichero con los valores por defecto saveOptionsFile(file_path); } @@ -112,11 +111,11 @@ bool saveOptionsFile(std::string file_path) if (!file.good()) { - std::cout << getFileName(file_path) << " can't be opened" << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s can't be opened", getFileName(file_path).c_str()); return false; } - std::cout << "Writing file: " << getFileName(file_path) << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Writing file: %s", getFileName(file_path).c_str()); // Opciones de video file << "## VIDEO\n"; diff --git a/source/param.cpp b/source/param.cpp index efdafd6..69bf30d 100644 --- a/source/param.cpp +++ b/source/param.cpp @@ -1,18 +1,88 @@ #include "param.h" -#include // Para char_traits, basic_ostream, basic_ifstream, basi... -#include // Para cout -#include -#include -#include -#include "utils.h" // Para Param, ParamGame, Zone, ParamBalloon +#include // Para SDL_LogCategory, SDL_LogError, SDL_LogInfo +#include // Para basic_istream, basic_ifstream, ifstream +#include // Para basic_istringstream +#include // Para runtime_error +#include // Para operator==, stoi, char_traits, string, ope... +#include "utils.h" // Para Zone, Color, NotifyPosition, getFileName Param param; -// Asigna variables a partir de dos cadenas -bool setParams(const std::string &var, const std::string &value); - // Calcula variables a partir de otras variables -void precalculateZones(); +void precalculateZones() +{ + // playArea + param.game.play_area.center_x = param.game.play_area.rect.w / 2; + param.game.play_area.first_quarter_x = param.game.play_area.rect.w / 4; + param.game.play_area.third_quarter_x = param.game.play_area.rect.w / 4 * 3; + param.game.play_area.center_y = param.game.play_area.rect.h / 2; + param.game.play_area.first_quarter_y = param.game.play_area.rect.h / 4; + param.game.play_area.third_quarter_y = param.game.play_area.rect.h / 4 * 3; + + // gameArea + param.game.game_area.rect = {0, 0, static_cast(param.game.width), static_cast(param.game.height)}; + param.game.game_area.center_x = param.game.game_area.rect.w / 2; + param.game.game_area.first_quarter_x = param.game.game_area.rect.w / 4; + param.game.game_area.third_quarter_x = param.game.game_area.rect.w / 4 * 3; + param.game.game_area.center_y = param.game.game_area.rect.h / 2; + param.game.game_area.first_quarter_y = param.game.game_area.rect.h / 4; + param.game.game_area.third_quarter_y = param.game.game_area.rect.h / 4 * 3; +} + +// Asigna variables a partir de dos cadenas +bool setParams(const std::string &var, const std::string &value) +{ + // Indicador de éxito en la asignación + auto success = true; + + // GAME + if (var == "game.width") + { + param.game.width = std::stoi(value); + } + else if (var == "game.height") + { + param.game.height = std::stoi(value); + } + else if (var == "game.item_size") + { + param.game.item_size = std::stoi(value); + } + else if (var == "game.coffee_machine_w") + { + param.game.coffee_machine_w = std::stoi(value); + } + else if (var == "game.coffee_machine_h") + { + param.game.coffee_machine_h = std::stoi(value); + } + else if (var == "game.play_area.rect.x") + { + param.game.play_area.rect.x = std::stoi(value); + } + else if (var == "game.play_area.rect.y") + { + param.game.play_area.rect.y = std::stoi(value); + } + else if (var == "game.play_area.rect.w") + { + param.game.play_area.rect.w = std::stoi(value); + } + else if (var == "game.play_area.rect.h") + { + param.game.play_area.rect.h = std::stoi(value); + } + else if (var == "game.enter_name_seconds") + { + param.game.enter_name_seconds = std::stoi(value); + } + else + { + success = false; + } + + return success; +} // Establece valores por defecto a las variables void initParam() @@ -65,6 +135,7 @@ void initParam() param.notification.color.b = 48; } +// Carga los parámetros desde un archivo void loadParamsFromFile(const std::string &file_path) { // Inicializa los parámetros con valores por defecto @@ -74,11 +145,11 @@ void loadParamsFromFile(const std::string &file_path) std::ifstream file(file_path); if (!file.is_open()) { - std::cerr << "Error: No se pudo abrir el archivo " << file_path << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo abrir el archivo %s", file_path.c_str()); throw std::runtime_error("No se pudo abrir el archivo: " + file_path); } - std::cout << "Reading file: " << getFileName(file_path) << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Leyendo archivo: %s", getFileName(file_path).c_str()); std::string line, param1, param2; while (std::getline(file, line)) @@ -94,7 +165,10 @@ void loadParamsFromFile(const std::string &file_path) std::istringstream iss(line); if (iss >> param1 >> param2) { - setParams(param1, param2); + if (!setParams(param1, param2)) + { + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Parámetro desconocido: %s", param1.c_str()); + } } } @@ -104,267 +178,3 @@ void loadParamsFromFile(const std::string &file_path) // Realiza cálculos adicionales después de cargar los parámetros precalculateZones(); } - -// Asigna variables a partir de dos cadenas -bool setParams(const std::string &var, const std::string &value) -{ - // Indicador de éxito en la asignación - auto success = true; - - // GAME - if (var == "game.width") - { - param.game.width = std::stoi(value); - } - - else if (var == "game.height") - { - param.game.height = std::stoi(value); - } - - else if (var == "game.item_size") - { - param.game.item_size = std::stoi(value); - } - - else if (var == "game.coffee_machine_w") - { - param.game.coffee_machine_w = std::stoi(value); - } - - else if (var == "game.coffee_machine_h") - { - param.game.coffee_machine_h = std::stoi(value); - } - - else if (var == "game.play_area.rect.x") - { - param.game.play_area.rect.x = std::stoi(value); - } - - else if (var == "game.play_area.rect.y") - { - param.game.play_area.rect.y = std::stoi(value); - } - - else if (var == "game.play_area.rect.w") - { - param.game.play_area.rect.w = std::stoi(value); - } - - else if (var == "game.play_area.rect.h") - { - param.game.play_area.rect.h = std::stoi(value); - } - - else if (var == "game.enter_name_seconds") - { - param.game.enter_name_seconds = std::stoi(value); - } - - // FADE - else if (var == "fade.num_squares_width") - { - param.fade.num_squares_width = std::stoi(value); - } - - else if (var == "fade.num_squares_height") - { - param.fade.num_squares_height = std::stoi(value); - } - - else if (var == "fade.random_squares_delay") - { - param.fade.random_squares_delay = std::stoi(value); - } - - else if (var == "fade.random_squares_mult") - { - param.fade.random_squares_mult = std::stoi(value); - } - - else if (var == "fade.post_duration") - { - param.fade.post_duration = std::stoi(value); - } - - else if (var == "fade.venetian_size") - { - param.fade.venetian_size = std::stoi(value); - } - - // SCOREBOARD - else if (var == "scoreboard.x") - { - param.scoreboard.x = std::stoi(value); - } - - else if (var == "scoreboard.y") - { - param.scoreboard.y = std::stoi(value); - } - - else if (var == "scoreboard.w") - { - param.scoreboard.w = std::stoi(value); - } - - else if (var == "scoreboard.h") - { - param.scoreboard.h = std::stoi(value); - } - - // TITLE - else if (var == "title.press_start_position") - { - param.title.press_start_position = std::stoi(value); - } - - else if (var == "title.title_duration") - { - param.title.title_duration = std::stoi(value); - } - - else if (var == "title.arcade_edition_position") - { - param.title.arcade_edition_position = std::stoi(value); - } - - else if (var == "title.title_c_c_position") - { - param.title.title_c_c_position = std::stoi(value); - } - - // BACKGROUND - else if (var == "background.attenuate_color.r") - { - param.background.attenuate_color.r = std::stoi(value); - } - - else if (var == "background.attenuate_color.g") - { - param.background.attenuate_color.g = std::stoi(value); - } - - else if (var == "background.attenuate_color.b") - { - param.background.attenuate_color.b = std::stoi(value); - } - - else if (var == "background.attenuate_alpha") - { - param.background.attenuate_alpha = std::stoi(value); - } - - // BALLOON - else if (var == "balloon_1.vel") - { - param.balloon.at(0).vel = std::stof(value); - } - - else if (var == "balloon_1.grav") - { - param.balloon.at(0).grav = std::stof(value); - } - - else if (var == "balloon_2.vel") - { - param.balloon.at(1).vel = std::stof(value); - } - - else if (var == "balloon_2.grav") - { - param.balloon.at(1).grav = std::stof(value); - } - - else if (var == "balloon_3.vel") - { - param.balloon.at(2).vel = std::stof(value); - } - - else if (var == "balloon_3.grav") - { - param.balloon.at(2).grav = std::stof(value); - } - - else if (var == "balloon_4.vel") - { - param.balloon.at(3).vel = std::stof(value); - } - - else if (var == "balloon_4.grav") - { - param.balloon.at(3).grav = std::stof(value); - } - - // NOTIFICACIONES - else if (var == "notification.pos_h") - { - if (value == "LEFT") - { - param.notification.pos_h = NotifyPosition::LEFT; - } - else if (value == "MIDDLE") - { - param.notification.pos_h = NotifyPosition::MIDDLE; - } - else - { - param.notification.pos_h = NotifyPosition::RIGHT; - } - } - - else if (var == "notification.pos_v") - { - param.notification.pos_v = value == "TOP" ? NotifyPosition::TOP : NotifyPosition::BOTTOM; - } - - else if (var == "notification.sound") - { - param.notification.sound = stringToBool(value); - } - - else if (var == "notification.color.r") - { - param.notification.color.r = std::stoi(value); - } - - else if (var == "notification.color.g") - { - param.notification.color.g = std::stoi(value); - } - - else if (var == "notification.color.b") - { - param.notification.color.b = std::stoi(value); - } - - // RESTO - else - { - success = false; - } - - return success; -} - -// Calcula variables a partir de otras variables -void precalculateZones() -{ - // playArea - param.game.play_area.center_x = param.game.play_area.rect.w / 2; - param.game.play_area.first_quarter_x = param.game.play_area.rect.w / 4; - param.game.play_area.third_quarter_x = param.game.play_area.rect.w / 4 * 3; - param.game.play_area.center_y = param.game.play_area.rect.h / 2; - param.game.play_area.first_quarter_y = param.game.play_area.rect.h / 4; - param.game.play_area.third_quarter_y = param.game.play_area.rect.h / 4 * 3; - - // gameArea - param.game.game_area.rect = {0, 0, static_cast(param.game.width), static_cast(param.game.height)}; - param.game.game_area.center_x = param.game.game_area.rect.w / 2; - param.game.game_area.first_quarter_x = param.game.game_area.rect.w / 4; - param.game.game_area.third_quarter_x = param.game.game_area.rect.w / 4 * 3; - param.game.game_area.center_y = param.game.game_area.rect.h / 2; - param.game.game_area.first_quarter_y = param.game.game_area.rect.h / 4; - param.game.game_area.third_quarter_y = param.game.game_area.rect.h / 4 * 3; -} \ No newline at end of file diff --git a/source/resource.cpp b/source/resource.cpp index b65df46..6390c74 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -1,14 +1,14 @@ #include "resource.h" -#include // Para find_if -#include // Para basic_ostream, operator<<, endl, cout, cerr -#include // Para runtime_error -#include "asset.h" // Para Asset, AssetType -#include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic -#include "lang.h" // Para getText -#include "screen.h" // Para Screen -#include "text.h" // Para Text, loadTextFile -struct JA_Music_t; // lines 11-11 -struct JA_Sound_t; // lines 12-12 +#include // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError +#include // Para find_if +#include // Para runtime_error +#include "asset.h" // Para Asset, AssetType +#include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic +#include "lang.h" // Para getText +#include "screen.h" // Para Screen +#include "text.h" // Para Text, loadTextFile +struct JA_Music_t; // lines 11-11 +struct JA_Sound_t; // lines 12-12 // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado Resource *Resource::resource_ = nullptr; @@ -52,7 +52,7 @@ void Resource::clear() // Carga todos los recursos void Resource::load() { - std::cout << "** LOADING RESOURCES" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "** LOADING RESOURCES"); loadSounds(); loadMusics(); loadTextures(); @@ -62,7 +62,7 @@ void Resource::load() addPalettes(); createText(); createTextures(); - std::cout << "\n** RESOURCES LOADED" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "** RESOURCES LOADED"); } // Recarga todos los recursos @@ -91,7 +91,7 @@ JA_Sound_t *Resource::getSound(const std::string &name) return it->sound; } - std::cerr << "Error: Sonido no encontrado " << name << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Sonido no encontrado %s", name.c_str()); throw std::runtime_error("Sonido no encontrado: " + name); } @@ -106,7 +106,7 @@ JA_Music_t *Resource::getMusic(const std::string &name) return it->music; } - std::cerr << "Error: Música no encontrada " << name << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Música no encontrada %s", name.c_str()); throw std::runtime_error("Música no encontrada: " + name); } @@ -121,7 +121,7 @@ std::shared_ptr Resource::getTexture(const std::string &name) return it->texture; } - std::cerr << "Error: Imagen no encontrada " << name << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Imagen no encontrada %s", name.c_str()); throw std::runtime_error("Imagen no encontrada: " + name); } @@ -136,7 +136,7 @@ std::shared_ptr Resource::getTextFile(const std::string &name) return it->text_file; } - std::cerr << "Error: TextFile no encontrado " << name << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: TextFile no encontrado %s", name.c_str()); throw std::runtime_error("TextFile no encontrado: " + name); } @@ -151,7 +151,7 @@ std::shared_ptr Resource::getText(const std::string &name) return it->text; } - std::cerr << "Error: Text no encontrado " << name << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Text no encontrado %s", name.c_str()); throw std::runtime_error("Text no encontrado: " + name); } @@ -166,7 +166,7 @@ AnimationsFileBuffer &Resource::getAnimation(const std::string &name) return it->animation; } - std::cerr << "Error: Animación no encontrada " << name << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Animación no encontrada %s", name.c_str()); throw std::runtime_error("Animación no encontrada: " + name); } @@ -179,7 +179,7 @@ DemoData &Resource::getDemoData(int index) // Carga los sonidos void Resource::loadSounds() { - std::cout << "\n>> SOUND FILES" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> SOUND FILES"); auto list = Asset::get()->getListByType(AssetType::SOUND); sounds_.clear(); @@ -187,14 +187,14 @@ void Resource::loadSounds() { auto name = getFileName(l); sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str()))); - printWithDots("Sound : ", name, "[ LOADED ]"); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Sound : %s [ LOADED ]", name.c_str()); } } -// Carga las musicas +// Carga las músicas void Resource::loadMusics() { - std::cout << "\n>> MUSIC FILES" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> MUSIC FILES"); auto list = Asset::get()->getListByType(AssetType::MUSIC); musics_.clear(); @@ -202,14 +202,14 @@ void Resource::loadMusics() { auto name = getFileName(l); musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str()))); - printWithDots("Music : ", name, "[ LOADED ]"); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Music : %s [ LOADED ]", name.c_str()); } } // Carga las texturas void Resource::loadTextures() { - std::cout << "\n>> TEXTURES" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> TEXTURES"); auto list = Asset::get()->getListByType(AssetType::BITMAP); textures_.clear(); @@ -217,13 +217,14 @@ void Resource::loadTextures() { auto name = getFileName(l); textures_.emplace_back(ResourceTexture(name, std::make_shared(Screen::get()->getRenderer(), l))); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Texture : %s [ LOADED ]", name.c_str()); } } // Carga los ficheros de texto void Resource::loadTextFiles() { - std::cout << "\n>> TEXT FILES" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> TEXT FILES"); auto list = Asset::get()->getListByType(AssetType::FONT); text_files_.clear(); @@ -231,13 +232,14 @@ void Resource::loadTextFiles() { auto name = getFileName(l); text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l))); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "TextFile : %s [ LOADED ]", name.c_str()); } } // Carga las animaciones void Resource::loadAnimations() { - std::cout << "\n>> ANIMATIONS" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> ANIMATIONS"); auto list = Asset::get()->getListByType(AssetType::ANIMATION); animations_.clear(); @@ -245,22 +247,25 @@ void Resource::loadAnimations() { auto name = getFileName(l); animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l))); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Animation : %s [ LOADED ]", name.c_str()); } } // Carga los datos para el modo demostración void Resource::loadDemoData() { - std::cout << "\n>> DEMO_FILES" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> DEMO FILES"); demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo1.bin"))); demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo2.bin"))); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Demo data loaded."); } // Añade paletas a las texturas void Resource::addPalettes() { + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> PALETTES"); + // Jugador 1 - std::cout << "\n>> PALETTES" << std::endl; getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_1_coffee_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_2_coffee_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_invencible_palette.gif")); @@ -282,43 +287,42 @@ void Resource::createTextures() std::string name; std::string text; - // Constructor NameAndText(const std::string &name_init, const std::string &text_init) : name(name_init), text(text_init) {} }; - std::cout << "\n>> CREATING TEXTURES" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> CREATING TEXTURES"); // Tamaño normal std::vector strings = { - NameAndText("game_text_1000_points", "1.000"), - NameAndText("game_text_2500_points", "2.500"), - NameAndText("game_text_5000_points", "5.000"), - NameAndText("game_text_powerup", lang::getText(117)), - NameAndText("game_text_one_hit", lang::getText(118)), - NameAndText("game_text_stop", lang::getText(119)), - NameAndText("game_text_1000000_points", lang::getText(76))}; + {"game_text_1000_points", "1.000"}, + {"game_text_2500_points", "2.500"}, + {"game_text_5000_points", "5.000"}, + {"game_text_powerup", lang::getText(117)}, + {"game_text_one_hit", lang::getText(118)}, + {"game_text_stop", lang::getText(119)}, + {"game_text_1000000_points", lang::getText(76)}}; auto text = getText("04b_25"); for (const auto &s : strings) { textures_.emplace_back(ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2))); - printWithDots("Texture : ", s.name, "[ DONE ]"); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Texture : %s [ DONE ]", s.name.c_str()); } // Tamaño doble std::vector strings2X = { - NameAndText("game_text_100000_points", "100.000"), - NameAndText("game_text_get_ready", lang::getText(75)), - NameAndText("game_text_last_stage", lang::getText(79)), - NameAndText("game_text_congratulations", lang::getText(50)), - NameAndText("game_text_game_over", "Game Over")}; + {"game_text_100000_points", "100.000"}, + {"game_text_get_ready", lang::getText(75)}, + {"game_text_last_stage", lang::getText(79)}, + {"game_text_congratulations", lang::getText(50)}, + {"game_text_game_over", "Game Over"}}; auto text2 = getText("04b_25_2x"); for (const auto &s : strings2X) { textures_.emplace_back(ResourceTexture(s.name, text2->writeToTexture(s.text, 1, -4))); - printWithDots("Texture : ", s.name, "[ DONE ]"); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Texture : %s [ DONE ]", s.name.c_str()); } } @@ -326,16 +330,15 @@ void Resource::createText() { struct ResourceInfo { - std::string key; // Identificador del recurso - std::string textureFile; // Nombre del archivo de textura - std::string textFile; // Nombre del archivo de texto + std::string key; + std::string textureFile; + std::string textFile; - // Constructor para facilitar la creación de objetos ResourceInfo ResourceInfo(const std::string &k, const std::string &tFile, const std::string &txtFile) : key(k), textureFile(tFile), textFile(txtFile) {} }; - std::cout << "\n>> CREATING TEXT_OBJECTS" << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, ">> CREATING TEXT OBJECTS"); std::vector resources = { {"04b_25", "04b_25.png", "04b_25.txt"}, @@ -350,14 +353,13 @@ void Resource::createText() texts_.emplace_back(ResourceText(resource.key, std::make_shared( getTexture(resource.textureFile), getTextFile(resource.textFile)))); - printWithDots("Text : ", resource.key, "[ DONE ]"); + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Text : %s [ DONE ]", resource.key.c_str()); } } // Vacía el vector de sonidos void Resource::clearSounds() { - // Itera sobre el vector y libera los recursos asociados a cada JA_Sound_t for (auto &sound : sounds_) { if (sound.sound) @@ -366,13 +368,12 @@ void Resource::clearSounds() sound.sound = nullptr; } } - sounds_.clear(); // Limpia el vector después de liberar todos los recursos + sounds_.clear(); } -// Vacía el vector de musicas +// Vacía el vector de músicas void Resource::clearMusics() { - // Itera sobre el vector y libera los recursos asociados a cada JA_Music_t for (auto &music : musics_) { if (music.music) @@ -381,5 +382,5 @@ void Resource::clearMusics() music.music = nullptr; } } - musics_.clear(); // Limpia el vector después de liberar todos los recursos + musics_.clear(); } \ No newline at end of file diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 41de8ff..a9f0f1d 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -269,7 +269,7 @@ void Scoreboard::fillPanelTextures() for (size_t j = 0; j < MAX_NAME_LENGHT; ++j) { // Selecciona el color - const Color color = j < selector_pos_[i] ? orange_soft_color.lighten() : Color(0xFF, 0xFF, 0xEB); + const Color color = j < selector_pos_[i] ? ORANGE_SOFT_COLOR.lighten() : Color(0xFF, 0xFF, 0xEB); if (j != selector_pos_[i] || time_counter_ % 3 == 0) { @@ -439,14 +439,14 @@ void Scoreboard::createPanelTextures() void Scoreboard::renderSeparator() { // Dibuja la linea que separa el marcador de la zona de juego - SDL_SetRenderDrawColor(renderer_, separator_color.r, separator_color.g, separator_color.b, 255); + SDL_SetRenderDrawColor(renderer_, SEPARATOR_COLOR.r, SEPARATOR_COLOR.g, SEPARATOR_COLOR.b, 255); SDL_RenderLine(renderer_, 0, 0, rect_.w, 0); } // Inicializa el vector de colores para el nombre void Scoreboard::iniNameColors() { - Color color = green_color; + Color color = GREEN_COLOR; name_colors_.clear(); name_colors_.emplace_back(color.lighten(50)); diff --git a/source/screen.cpp b/source/screen.cpp index 6364b64..56f0b79 100644 --- a/source/screen.cpp +++ b/source/screen.cpp @@ -1,21 +1,25 @@ #include "screen.h" -#include // Para SDL_PixelFormat -#include // Para SDL_PixelFormat -#include // Para SDL_GetTicks -#include // Para SDL_Init, SDL_INIT_VIDEO -#include // Para max, min -#include // Para basic_ifstream, ifstream -#include // Para istreambuf_iterator, operator== -#include // Para __shared_ptr_access, shared_ptr -#include // Para string, operator+, to_string -#include "asset.h" // Para Asset -#include "jail_shader.h" // Para init, render -#include "mouse.h" // Para updateCursorVisibility -#include "notifier.h" // Para Notifier -#include "on_screen_help.h" // Para OnScreenHelp -#include "options.h" // Para Options, VideoOptions, options, WindowO... -#include "resource.h" // Para Resource -#include "text.h" // Para Text +#include // Para SDL_BLENDMODE_BLEND +#include // Para SDL_GetError +#include // Para SDL_SetHint, SDL_HINT_RENDER_DRIVER +#include // Para SDL_Init, SDL_INIT_VIDEO +#include // Para SDL_LogCategory, SDL_LogError, SDL_L... +#include // Para SDL_PixelFormat +#include // Para SDL_ScaleMode +#include // Para SDL_GetTicks +#include // Para min, max +#include // Para basic_ifstream, ifstream +#include // Para istreambuf_iterator, operator== +#include // Para __shared_ptr_access, shared_ptr +#include // Para allocator, char_traits, operator+ +#include "asset.h" // Para Asset +#include "jail_shader.h" // Para init, render +#include "mouse.h" // Para updateCursorVisibility +#include "notifier.h" // Para Notifier +#include "on_screen_help.h" // Para OnScreenHelp +#include "options.h" // Para Options, options, WindowOptions, Vid... +#include "resource.h" // Para Resource +#include "text.h" // Para Text // [SINGLETON] Screen *Screen::screen_ = nullptr; @@ -220,10 +224,10 @@ void Screen::renderInfo() // FPS const std::string FPS_TEXT = std::to_string(fps_.lastValue) + " FPS"; - text->writeColored(param.game.width - text->lenght(FPS_TEXT), 0, FPS_TEXT, orange_soft_color); + text->writeColored(param.game.width - text->lenght(FPS_TEXT), 0, FPS_TEXT, ORANGE_SOFT_COLOR); // Resolution - text->writeColored(0, 0, options.video.info, orange_soft_color); + text->writeColored(0, 0, options.video.info, ORANGE_SOFT_COLOR); } } diff --git a/source/text.cpp b/source/text.cpp index 0768bce..d4169c8 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -1,8 +1,8 @@ #include "text.h" #include // Para SDL_BLENDMODE_BLEND -#include // Para SDL_PIXELFORMAT_RGBA8888 +#include // Para SDL_PixelFormat #include // Para SDL_FRect -#include // Para SDL_TEXTUREACCESS_TARGET +#include // Para SDL_SetRenderTarget, SDL_GetRenderTa... #include // Para size_t #include // Para basic_ifstream, basic_istream, basic... #include // Para cerr diff --git a/source/texture.cpp b/source/texture.cpp index 63973af..2ce3c4c 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -1,14 +1,15 @@ #include "texture.h" #include // Para SDL_GetError -#include // Para SDL_CreateRGBSurfaceWithFormatFrom +#include // Para SDL_LogError, SDL_LogCategory, SDL_Log... +#include // Para SDL_CreateSurfaceFrom, SDL_DestroySurface #include // Para uint32_t #include // Para memcpy, size_t -#include // Para basic_ostream, operator<<, basic_ifstream -#include // Para cerr, cout +#include // Para basic_ifstream, basic_ios, ios, operator| #include // Para runtime_error -#include // Para char_traits, operator<<, operator+ +#include // Para operator+, char_traits, string, operat... #include // Para vector #include "gif.h" // Para Gif +#include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_a... #include "utils.h" // Para getFileName, Color, printWithDots #define STB_IMAGE_IMPLEMENTATION @@ -67,7 +68,7 @@ bool Texture::loadFromFile(const std::string &file_path) unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format); if (!data) { - std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", getFileName(file_path).c_str()); throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); } else @@ -89,11 +90,10 @@ bool Texture::loadFromFile(const std::string &file_path) SDL_Texture *new_texture = nullptr; // Carga la imagen desde una ruta específica - /*auto loaded_surface = SDL_CreateRGBSurfaceWithFormatFrom(static_cast(data), width, height, depth, pitch, pixel_format);*/ auto loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast(data), pitch); if (loaded_surface == nullptr) { - std::cout << "Unable to load image " << file_path << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load image %s", file_path.c_str()); } else { @@ -101,7 +101,7 @@ bool Texture::loadFromFile(const std::string &file_path) new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface); if (new_texture == nullptr) { - std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create texture from %s! SDL Error: %s", file_path.c_str(), SDL_GetError()); } else { @@ -127,7 +127,7 @@ bool Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_Tex texture_ = SDL_CreateTexture(renderer_, format, access, width, height); if (!texture_) { - std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create blank texture! SDL Error: %s", SDL_GetError()); } else { @@ -249,7 +249,7 @@ std::shared_ptr Texture::loadSurface(const std::string &file_path) std::ifstream file(file_path, std::ios::binary | std::ios::ate); if (!file) { - std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str()); throw std::runtime_error("Fichero no encontrado: " + file_path); } @@ -261,7 +261,7 @@ std::shared_ptr Texture::loadSurface(const std::string &file_path) std::vector buffer(size); if (!file.read(reinterpret_cast(buffer.data()), size)) { - std::cerr << "Error al leer el fichero " << file_path << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al leer el fichero %s", file_path.c_str()); throw std::runtime_error("Error al leer el fichero: " + file_path); } @@ -271,11 +271,11 @@ std::shared_ptr Texture::loadSurface(const std::string &file_path) std::vector rawPixels = gif.loadGif(buffer.data(), w, h); if (rawPixels.empty()) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo cargar el GIF %s", file_path.c_str()); return nullptr; } - // Si el constructor de Surface espera un std::shared_ptr, - // reservamos un bloque dinámico y copiamos los datos del vector. + // Si el constructor de Surface espera un std::shared_ptr: size_t pixelCount = rawPixels.size(); auto pixels = std::shared_ptr(new Uint8[pixelCount], std::default_delete()); std::memcpy(pixels.get(), rawPixels.data(), pixelCount); @@ -286,6 +286,7 @@ std::shared_ptr Texture::loadSurface(const std::string &file_path) width_ = w; height_ = h; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "GIF %s cargado correctamente.", file_path.c_str()); return surface; } @@ -325,8 +326,8 @@ std::vector Texture::loadPaletteFromFile(const std::string &file_path) std::ifstream file(file_path, std::ios::binary | std::ios::ate); if (!file) { - std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; - throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str()); + throw std::runtime_error("Fichero no encontrado: " + file_path); } else { @@ -340,8 +341,8 @@ std::vector Texture::loadPaletteFromFile(const std::string &file_path) std::vector buffer(size); if (!file.read(reinterpret_cast(buffer.data()), size)) { - std::cerr << "Error: No se pudo leer completamente el fichero " << getFileName(file_path) << std::endl; - throw std::runtime_error("Error al leer el fichero: " + getFileName(file_path)); + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo leer completamente el fichero %s", file_path.c_str()); + throw std::runtime_error("Error al leer el fichero: " + file_path); } // Usar la nueva función loadPalette, que devuelve un vector @@ -349,6 +350,7 @@ std::vector Texture::loadPaletteFromFile(const std::string &file_path) std::vector pal = gif.loadPalette(buffer.data()); if (pal.empty()) { + SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Advertencia: No se encontró paleta en el archivo %s", file_path.c_str()); return palette; // Devuelve un vector vacío si no hay paleta } @@ -358,6 +360,7 @@ std::vector Texture::loadPaletteFromFile(const std::string &file_path) palette.push_back((color << 8) | 0xFF); // Resultado: 0xRRGGBBAA } + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Paleta cargada correctamente desde %s", file_path.c_str()); return palette; } diff --git a/source/title.cpp b/source/title.cpp index 348e114..08ec5f9 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -39,7 +39,7 @@ Title::Title() // Configura objetos game_logo_->enable(); mini_logo_sprite_->setX(param.game.game_area.center_x - mini_logo_sprite_->getWidth() / 2); - fade_->setColor(fade_color.r, fade_color.g, fade_color.b); + fade_->setColor(FADE_COLOR.r, FADE_COLOR.g, FADE_COLOR.b); fade_->setType(FadeType::RANDOM_SQUARE); fade_->setPostDuration(param.fade.post_duration); Resource::get()->getTexture("smb2.gif")->setPalette(1); @@ -87,7 +87,7 @@ void Title::render() Screen::get()->start(); // Limpia la pantalla - Screen::get()->clean(bg_color); + Screen::get()->clean(BG_COLOR); // Dibuja el mosacico de fondo tiled_bg_->render(); @@ -106,7 +106,7 @@ void Title::render() mini_logo_sprite_->render(); // Texto con el copyright - text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, pos2, TEXT_COPYRIGHT, 1, no_color, 1, shadow); + text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, pos2, TEXT_COPYRIGHT, 1, NO_COLOR, 1, shadow); } if (state_ == TitleState::LOGO_FINISHED) @@ -114,7 +114,7 @@ void Title::render() // 'PRESS TO PLAY' if (counter_ % 50 > 14 && !define_buttons_->isEnabled()) { - text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, lang::getText(23), 1, no_color, 1, shadow); + text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, lang::getText(23), 1, NO_COLOR, 1, shadow); } } @@ -123,7 +123,7 @@ void Title::render() // 'PRESS TO PLAY' if (counter_ % 10 > 4 && !define_buttons_->isEnabled()) { - text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, lang::getText(23), 1, no_color, 1, shadow); + text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, param.title.press_start_position, lang::getText(23), 1, NO_COLOR, 1, shadow); } } diff --git a/source/utils.cpp b/source/utils.cpp index 5d06cdd..9e99c26 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -1,36 +1,36 @@ #define _USE_MATH_DEFINES #include "utils.h" #include // Para SDL_CloseIO, SDL_IOFromFile, SDL_ReadIO +#include // Para SDL_LogCategory, SDL_LogError, SDL_Lo... #include // Para size_t #include // Para min, clamp, find_if_not, find, transform #include // Para tolower, isspace #include // Para pow, sin, M_PI, cos #include // Para operator< #include // Para path -#include // Para basic_ostream, cout, basic_ios, endl #include // Para runtime_error -#include // Para basic_string, string, char_traits +#include // Para basic_string, string, operator==, ope... #include "lang.h" // Para getText // Variables Overrides overrides = Overrides(); // Colores -const Color bg_color = Color(0X27, 0X27, 0X36); -const Color no_color = Color(0XFF, 0XFF, 0XFF); -const Color shdw_txt_color = Color(0X43, 0X43, 0X4F); -const Color separator_color = Color(0X0D, 0X1A, 0X2B); -const Color scoreboard_easy_color = Color(0X4B, 0X69, 0X2F); -const Color scoreboard_normal_color = Color(0X2E, 0X3F, 0X47); -const Color scoreboard_hard_color = Color(0X76, 0X42, 0X8A); -const Color flash_color = Color(0XFF, 0XFF, 0XFF); -const Color fade_color = Color(0X27, 0X27, 0X36); -const Color orange_color = Color(0XFF, 0X7A, 0X00); -const Color orange_soft_color = Color(0XFF, 0XA0, 0X33); -const Color green_color = Color(0X5B, 0XEC, 0X95); -const Color blue_sky_color = Color(0X02, 0X88, 0XD1); -const Color pink_sky_color = Color(0XFF, 0X6B, 0X97); -const Color green_sky_color = Color(0X00, 0X79, 0X6B); +const Color BG_COLOR = Color(0X27, 0X27, 0X36); +const Color NO_COLOR = Color(0XFF, 0XFF, 0XFF); +const Color SHADOW_TEXT_COLOR = Color(0X43, 0X43, 0X4F); +const Color SEPARATOR_COLOR = Color(0X0D, 0X1A, 0X2B); +const Color SCOREBOARD_EASY_COLOR = Color(0X4B, 0X69, 0X2F); +const Color SCOREBOARD_NORMAL_COLOR = Color(0X2E, 0X3F, 0X47); +const Color SCOREBOARD_HARD_COLOR = Color(0X76, 0X42, 0X8A); +const Color FLASH_COLOR = Color(0XFF, 0XFF, 0XFF); +const Color FADE_COLOR = Color(0X27, 0X27, 0X36); +const Color ORANGE_COLOR = Color(0XFF, 0X7A, 0X00); +const Color ORANGE_SOFT_COLOR = Color(0XFF, 0XA0, 0X33); +const Color GREEN_COLOR = Color(0X5B, 0XEC, 0X95); +const Color BLUE_SKY_COLOR = Color(0X02, 0X88, 0XD1); +const Color PINK_SKY_COLOR = Color(0XFF, 0X6B, 0X97); +const Color GREEN_SKY_COLOR = Color(0X00, 0X79, 0X6B); // Obtiene un color del vector de colores imitando al Coche Fantástico Color getColorLikeKnightRider(const std::vector &colors, int counter_) @@ -299,17 +299,16 @@ bool stringInVector(const std::vector &vec, const std::string &str) return std::find(vec.begin(), vec.end(), str) != vec.end(); } -// Imprime por pantalla una linea de texto de tamaño fijo rellena con puntos +// Imprime por pantalla una línea de texto de tamaño fijo rellena con puntos void printWithDots(const std::string &text1, const std::string &text2, const std::string &text3) { - std::cout.setf(std::ios::left, std::ios::adjustfield); - std::cout << text1; + std::string output = text1; + size_t dots_count = 50 - text1.length() - text3.length(); + output.append(dots_count, '.'); + output.append(text2); + output.append(text3); - std::cout.width(50 - text1.length() - text3.length()); - std::cout.fill('.'); - std::cout << text2; - - std::cout << text3 << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%s", output.c_str()); } // Carga el fichero de datos para la demo @@ -321,7 +320,7 @@ DemoData loadDemoDataFromFile(const std::string &file_path) auto file = SDL_IOFromFile(file_path.c_str(), "r+b"); if (!file) { - std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str()); throw std::runtime_error("Fichero no encontrado: " + file_path); } else @@ -357,21 +356,21 @@ bool saveDemoFile(const std::string &file_path, const DemoData &dd) { if (SDL_RWwrite(file, &data, sizeof(DemoKeys), 1) != 1) { - std::cerr << "Error al escribir el fichero " << getFileName(file_path) << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error al escribir el fichero %s", getFileName(file_path).c_str()); success = false; break; } } if (success) { - std::cout << "Writing file " << getFileName(file_path).c_str() << std::endl; + SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Writing file %s", getFileName(file_path).c_str()); } // Cierra el fichero SDL_CloseIO(file); } else { - std::cout << "Error: Unable to save " << getFileName(file_path).c_str() << " file! " << SDL_GetError() << std::endl; + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Unable to save %s file! %s", getFileName(file_path).c_str(), SDL_GetError()); success = false; } diff --git a/source/utils.h b/source/utils.h index 8ee36c9..ac4ced6 100644 --- a/source/utils.h +++ b/source/utils.h @@ -201,18 +201,18 @@ std::string getFileName(const std::string &path); std::string getPath(const std::string &full_path); // Colores -extern const Color bg_color; -extern const Color no_color; -extern const Color shdw_txt_color; -extern const Color separator_color; -extern const Color scoreboard_easy_color; -extern const Color scoreboard_normal_color; -extern const Color scoreboard_hard_color; -extern const Color flash_color; -extern const Color fade_color; -extern const Color orange_color; -extern const Color orange_soft_color; -extern const Color green_color; -extern const Color blue_sky_color; -extern const Color pink_sky_color; -extern const Color green_sky_color; \ No newline at end of file +extern const Color BG_COLOR; +extern const Color NO_COLOR; +extern const Color SHADOW_TEXT_COLOR; +extern const Color SEPARATOR_COLOR; +extern const Color SCOREBOARD_EASY_COLOR; +extern const Color SCOREBOARD_NORMAL_COLOR; +extern const Color SCOREBOARD_HARD_COLOR; +extern const Color FLASH_COLOR; +extern const Color FADE_COLOR; +extern const Color ORANGE_COLOR; +extern const Color ORANGE_SOFT_COLOR; +extern const Color GREEN_COLOR; +extern const Color BLUE_SKY_COLOR; +extern const Color PINK_SKY_COLOR; +extern const Color GREEN_SKY_COLOR; \ No newline at end of file