From 848d61b5c06c60d20d1451970617050f8e8da39c Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Sun, 20 Oct 2024 15:36:04 +0200 Subject: [PATCH] =?UTF-8?q?He=20fet=20un=20"manolete"=20i=20he=20pasat=20a?= =?UTF-8?q?=20c++=20i=20smartpointers=20la=20c=C3=A1rrega=20de=20surfaces?= =?UTF-8?q?=20desde=20gif.=20Sembla=20que=20no=20ha=20petat=20res=20Prec?= =?UTF-8?q?=C3=A1rrega=20i=20asignaci=C3=B3=20de=20paletes=20a=20les=20tex?= =?UTF-8?q?tures=20Ara=20si=20alg=C3=BA=20toca=20una=20paleta,=20que=20sig?= =?UTF-8?q?a=20conscient=20que=20la=20textura=20es=20compartida=20durant?= =?UTF-8?q?=20tot=20el=20joc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../font/{smb2_pal1.gif => smb2_palette1.pal} | Bin ...pal3.gif => player1_all_white_palette.pal} | Bin ...al1.gif => player1_one_coffee_palette.pal} | Bin data/gfx/player/player1_power.gif | Bin 772 -> 0 bytes ...al2.gif => player1_two_coffee_palette.pal} | Bin ...pal3.gif => player2_all_white_palette.pal} | Bin ...al1.gif => player2_one_coffee_palette.pal} | Bin data/gfx/player/player2_power.gif | Bin 772 -> 0 bytes ...al2.gif => player2_two_coffee_palette.pal} | Bin ..._pal.gif => player_power_blue_palette.pal} | Bin source/director.cpp | 16 +-- source/game.cpp | 15 +- source/player.cpp | 16 +-- source/player.h | 12 +- source/resource.cpp | 28 ++++ source/resource.h | 3 + source/text.cpp | 38 ----- source/text.h | 8 -- source/texture.cpp | 132 +++++++++--------- source/texture.h | 56 ++++---- source/tiled_bg.cpp | 2 +- source/tiled_bg.h | 8 +- source/title.cpp | 60 ++++---- source/title.h | 21 ++- 24 files changed, 187 insertions(+), 228 deletions(-) rename data/font/{smb2_pal1.gif => smb2_palette1.pal} (100%) rename data/gfx/player/{player1_pal3.gif => player1_all_white_palette.pal} (100%) rename data/gfx/player/{player1_pal1.gif => player1_one_coffee_palette.pal} (100%) delete mode 100644 data/gfx/player/player1_power.gif rename data/gfx/player/{player1_pal2.gif => player1_two_coffee_palette.pal} (100%) rename data/gfx/player/{player2_pal3.gif => player2_all_white_palette.pal} (100%) rename data/gfx/player/{player2_pal1.gif => player2_one_coffee_palette.pal} (100%) delete mode 100644 data/gfx/player/player2_power.gif rename data/gfx/player/{player2_pal2.gif => player2_two_coffee_palette.pal} (100%) rename data/gfx/player/{player_power_pal.gif => player_power_blue_palette.pal} (100%) diff --git a/data/font/smb2_pal1.gif b/data/font/smb2_palette1.pal similarity index 100% rename from data/font/smb2_pal1.gif rename to data/font/smb2_palette1.pal diff --git a/data/gfx/player/player1_pal3.gif b/data/gfx/player/player1_all_white_palette.pal similarity index 100% rename from data/gfx/player/player1_pal3.gif rename to data/gfx/player/player1_all_white_palette.pal diff --git a/data/gfx/player/player1_pal1.gif b/data/gfx/player/player1_one_coffee_palette.pal similarity index 100% rename from data/gfx/player/player1_pal1.gif rename to data/gfx/player/player1_one_coffee_palette.pal diff --git a/data/gfx/player/player1_power.gif b/data/gfx/player/player1_power.gif deleted file mode 100644 index 969fd24d62696f6e9c7e2313fe1b47e2f7d5138e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 772 zcmV+f1N;0(Nk%v~VT=GM0HOc@00030vjG2~0RN8w|8D>Q0000000000A^!_bMO0Hm zK~P09E-(WD0000X`2-0H0000i00000i~uMA00aLBx*PnExk#(MIBOW@^I9N)jYV!i zN2(oqoo>^O3fOKUEx|QkvAW*KhhoJdGeOW6#N<}Z-OH0xGNUnIbd|{s209TH`xAi2 zWbw3NUOrv6YCHaMn!n3D89A@@KUOATcQi?RKWJZgD_nvD1ZNV1kw{FDB8xkJ6l$0R zkRwW$ETkNTn2(>7DQXgqs(KEndpCZIX0Q`pt9-J!uwS5ZN<$}|zqvwNM4q`bw~wo1 zmY}K5cfw_b$dI4FibI@p+}E2aht1w#qQJ>LetD_Z>g?_{l4s=J>h^qi^ZV9iQsyI_ zx?ue5-FRbbpF>FVcv%7i@L|A1=b~9W=*<5M7GD)NUeq;dTS$@F{NU?`(jhNXCq=Hi z^Rk7(mh?!Hyri$?s3tdYrW6-bCPIlOg+4sP@LW=*IRmYPI+Q3?i%3CUrMC%FsG=w- zZs{4;O|6VuM*`BC7NRslV13pkyOEM1YHh1J4SE%+#=LsbQe`S?Y+RWi+Z^_37;wLa zeMP+#oK~8x#f+g~Mht_m+{u);+TH0mC!o!B)6mWAFE3Bhr6+qH3>0!?9M28mIvjD+5HG)i`P|{V=hXtqJovm0m$N65SEo*na61X zCXOU3=%SWK*7syBXqxFHl~X>sVwPAcdFOtu`I#r4b^2CDZ=el&BRW>f2Btj;0029& C++nu> diff --git a/data/gfx/player/player1_pal2.gif b/data/gfx/player/player1_two_coffee_palette.pal similarity index 100% rename from data/gfx/player/player1_pal2.gif rename to data/gfx/player/player1_two_coffee_palette.pal diff --git a/data/gfx/player/player2_pal3.gif b/data/gfx/player/player2_all_white_palette.pal similarity index 100% rename from data/gfx/player/player2_pal3.gif rename to data/gfx/player/player2_all_white_palette.pal diff --git a/data/gfx/player/player2_pal1.gif b/data/gfx/player/player2_one_coffee_palette.pal similarity index 100% rename from data/gfx/player/player2_pal1.gif rename to data/gfx/player/player2_one_coffee_palette.pal diff --git a/data/gfx/player/player2_power.gif b/data/gfx/player/player2_power.gif deleted file mode 100644 index 53b139c0c30789e90aa778a4b7d2e835e89c36cc..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 772 zcmV+f1N;0(Nk%v~VT=GM0HOc@00000-~RyA{{YDU0H*%{0000000000A^!_bMO0Hm zK~P09E-(WD0000X`2-0H0000i00000i~uMA00aLBx*PnExk#(MIBOW@^I9N)jYV!i zN2(oqoo>^O3fOKUEx|QkvAW*KhhoJdGeOW6#N<}Z-OH0xGNUnIbd|{s209TH`xAi2 zWbw3NUOrv6YCHaMn!n3D89A@@KUOATcQi?RKWJZgD_nvD1ZNV1kw{FDB8xkJ6l$0R zkRwW$ETkNTn2(>7DQXgqs(KEndpCZIX0Q`pt9-J!uwS5ZN<$}|zqvwNM4q`bw~wo1 zmY}K5cfw_b$dI4FibI@p+}E2aht1w#qQJ>LetD_Z>g?_{l4s=J>h^qi^ZV9iQsyI_ zx?ue5-FRbbpF>FVcv%7i@L|A1=b~9W=*<5M7GD)NUeq;dTS$@F{NU?`(jhNXCq=Hi z^Rk7(mh?!Hyri$?s3tdYrW6-bCPIlOg+4sP@LW=*IRmYPI+Q3?i%3CUrMC%FsG=w- zZs{4;O|6VuM*`BC7NRslV13pkyOEM1YHh1J4SE%+#=LsbQe`S?Y+RWi+Z^_37;wLa zeMP+#oK~8x#f+g~Mht_m+{u);+TH0mC!o!B)6mWAFE3Bhr6+qH3>0!?9M28mIvjD+5HG)i`P|{V=hXtqJovm0m$N65SEo*na61X zCXOU3=%SWK*7syBXqxFHl~X>sVwPAcdFOtu`I#r4b^2CDZ=el&BRW>f2Btj;0027+ Cpkjvr diff --git a/data/gfx/player/player2_pal2.gif b/data/gfx/player/player2_two_coffee_palette.pal similarity index 100% rename from data/gfx/player/player2_pal2.gif rename to data/gfx/player/player2_two_coffee_palette.pal diff --git a/data/gfx/player/player_power_pal.gif b/data/gfx/player/player_power_blue_palette.pal similarity index 100% rename from data/gfx/player/player_power_pal.gif rename to data/gfx/player/player_power_blue_palette.pal diff --git a/source/director.cpp b/source/director.cpp index 4f935b5..57bb455 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -436,19 +436,19 @@ void Director::setFileList() Asset::get()->add(prefix + "/data/gfx/title/title_dust.ani", AssetType::ANIMATION); Asset::get()->add(prefix + "/data/gfx/player/player1.gif", AssetType::BITMAP); - Asset::get()->add(prefix + "/data/gfx/player/player1_pal1.gif", AssetType::PALETTE); - Asset::get()->add(prefix + "/data/gfx/player/player1_pal2.gif", AssetType::PALETTE); - Asset::get()->add(prefix + "/data/gfx/player/player1_pal3.gif", AssetType::PALETTE); + Asset::get()->add(prefix + "/data/gfx/player/player1_one_coffee_palette.pal", AssetType::PALETTE); + Asset::get()->add(prefix + "/data/gfx/player/player1_two_coffee_palette.pal", AssetType::PALETTE); + Asset::get()->add(prefix + "/data/gfx/player/player1_all_white_palette.pal", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player2.gif", AssetType::BITMAP); - Asset::get()->add(prefix + "/data/gfx/player/player2_pal1.gif", AssetType::PALETTE); - Asset::get()->add(prefix + "/data/gfx/player/player2_pal2.gif", AssetType::PALETTE); - Asset::get()->add(prefix + "/data/gfx/player/player2_pal3.gif", AssetType::PALETTE); + Asset::get()->add(prefix + "/data/gfx/player/player2_one_coffee_palette.pal", AssetType::PALETTE); + Asset::get()->add(prefix + "/data/gfx/player/player2_two_coffee_palette.pal", AssetType::PALETTE); + Asset::get()->add(prefix + "/data/gfx/player/player2_all_white_palette.pal", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player.ani", AssetType::ANIMATION); Asset::get()->add(prefix + "/data/gfx/player/player_power.gif", AssetType::BITMAP); - Asset::get()->add(prefix + "/data/gfx/player/player_power_pal.gif", AssetType::PALETTE); + Asset::get()->add(prefix + "/data/gfx/player/player_power_blue_palette.pal", AssetType::PALETTE); Asset::get()->add(prefix + "/data/gfx/player/player_power.ani", AssetType::ANIMATION); // Fuentes de texto @@ -463,7 +463,7 @@ void Director::setFileList() Asset::get()->add(prefix + "/data/font/smb2_big.png", AssetType::BITMAP); Asset::get()->add(prefix + "/data/font/smb2_big.txt", AssetType::FONT); Asset::get()->add(prefix + "/data/font/smb2.gif", AssetType::BITMAP); - Asset::get()->add(prefix + "/data/font/smb2_pal1.gif", AssetType::PALETTE); + Asset::get()->add(prefix + "/data/font/smb2_palette1.pal", AssetType::PALETTE); Asset::get()->add(prefix + "/data/font/smb2.txt", AssetType::FONT); // Textos diff --git a/source/game.cpp b/source/game.cpp index 7ab7273..b053e0b 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -347,13 +347,7 @@ void Game::loadMedia() { std::vector> player_texture; player_texture.emplace_back(Resource::get()->getTexture("player1.gif")); - player_texture.back()->addPalette(asset_->get("player1_pal1.gif")); - player_texture.back()->addPalette(asset_->get("player1_pal2.gif")); - player_texture.back()->addPalette(asset_->get("player1_pal3.gif")); - player_texture.emplace_back(Resource::get()->getTexture("player_power.gif")); - player_texture.back()->addPalette(asset_->get("player_power_pal.gif")); - player_textures_.push_back(player_texture); } @@ -361,14 +355,7 @@ void Game::loadMedia() { std::vector> player_texture; player_texture.emplace_back(Resource::get()->getTexture("player2.gif")); - player_texture.back()->addPalette(asset_->get("player2_pal1.gif")); - player_texture.back()->addPalette(asset_->get("player2_pal2.gif")); - player_texture.back()->addPalette(asset_->get("player2_pal3.gif")); - player_texture.emplace_back(Resource::get()->getTexture("player_power.gif")); - player_texture.back()->addPalette(asset_->get("player_power_pal.gif")); - player_texture.back()->setPalette(1); - player_textures_.push_back(player_texture); } @@ -1205,6 +1192,8 @@ void Game::renderItems() // Devuelve un item al azar y luego segun sus probabilidades ItemType Game::dropItem() { + return ItemType::COFFEE_MACHINE; + const auto lucky_number = rand() % 100; const auto item = rand() % 6; diff --git a/source/player.cpp b/source/player.cpp index d0391e3..450c331 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -347,7 +347,7 @@ void Player::update() setAnimation(); shiftColliders(); updateCooldown(); - updatePowerUpCounter(); + updatePowerUp(); updateInvulnerable(); updateContinueCounter(); updateEnterNameCounter(); @@ -578,7 +578,7 @@ void Player::updateInvulnerable() { if (invulnerable_counter_ > 0) { - invulnerable_counter_--; + --invulnerable_counter_; invulnerable_counter_ % 8 > 3 ? player_sprite_->getTexture()->setPalette(coffees_) : player_sprite_->getTexture()->setPalette(3); } else @@ -615,15 +615,13 @@ void Player::setPowerUpCounter(int value) } // Actualiza el valor de la variable -void Player::updatePowerUpCounter() +void Player::updatePowerUp() { - if ((power_up_counter_ > 0) && (power_up_)) + if (power_up_) { - power_up_counter_--; - } - else - { - power_up_ = false; + --power_up_counter_; + power_up_ = power_up_counter_ > 0; + power_sprite_->getTexture()->setPalette(id_ - 1); } } diff --git a/source/player.h b/source/player.h index e0483a5..8e128bc 100644 --- a/source/player.h +++ b/source/player.h @@ -43,13 +43,13 @@ class Player { private: // Objetos y punteros - std::unique_ptr player_sprite_; // Sprite para dibujar el jugador - std::unique_ptr power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope - std::unique_ptr enter_name_; // Clase utilizada para introducir el nombre - SDL_Rect *play_area_; // Rectangulo con la zona de juego + std::unique_ptr player_sprite_; // Sprite para dibujar el jugador + std::unique_ptr power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope + std::unique_ptr enter_name_; // Clase utilizada para introducir el nombre + SDL_Rect *play_area_; // Rectangulo con la zona de juego // Variables - int id_; // Numero de identificación para el jugador + int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2 float pos_x_; // Posicion en el eje X int pos_y_; // Posicion en el eje Y float default_pos_x_; // Posición inicial para el jugador @@ -245,7 +245,7 @@ public: void setPowerUpCounter(int value); // Actualiza el valor de la variable - void updatePowerUpCounter(); + void updatePowerUp(); // Obtiene el valor de la variable bool hasExtraHit() const; diff --git a/source/resource.cpp b/source/resource.cpp index c477042..ba5b7d9 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -34,6 +34,10 @@ Resource::Resource() loadTextFiles(); loadAnimations(); std::cout << "\n** RESOURCES LOADED" << std::endl; + + std::cout << "\n** ADD PALETTES" << std::endl; + addPalettes(); + std::cout << "\n** PALETTES ADDED" << std::endl; } // Destructor @@ -219,4 +223,28 @@ void Resource::loadAnimations() animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l))); } +} + +// Añade paletas a las texturas +void Resource::addPalettes() +{ + // Jugador 1 + std::cout << "\n>> PLAYER1" << std::endl; + getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_one_coffee_palette.pal")); + getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_two_coffee_palette.pal")); + getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_all_white_palette.pal")); + + // Jugador 2 + std::cout << "\n>> PLAYER2" << std::endl; + getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_one_coffee_palette.pal")); + getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_two_coffee_palette.pal")); + getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_all_white_palette.pal")); + + // Player_power + std::cout << "\n>> PLAYER_POWER" << std::endl; + getTexture("player_power.gif")->addPaletteFromFile(Asset::get()->get("player_power_blue_palette.pal")); + + // Fuentes + std::cout << "\n>> FONTS" << std::endl; + getTexture("smb2.gif")->addPaletteFromFile(Asset::get()->get("smb2_palette1.pal")); } \ No newline at end of file diff --git a/source/resource.h b/source/resource.h index ca021a2..0110761 100644 --- a/source/resource.h +++ b/source/resource.h @@ -91,6 +91,9 @@ private: // Carga las animaciones void loadAnimations(); + // Añade paletas a las texturas + void addPalettes(); + // [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera // Constructor diff --git a/source/text.cpp b/source/text.cpp index 55c2130..47f0998 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -77,33 +77,8 @@ std::shared_ptr loadTextFile(const std::string &file_path) return tf; } -// Constructor -Text::Text(const std::string &bitmap_file, const std::string &text_file, SDL_Renderer *renderer) -{ - // Carga los offsets desde el fichero - auto tf = loadTextFile(text_file); - - // Inicializa variables desde la estructura - box_height_ = tf->box_height; - box_width_ = tf->box_width; - for (int i = 0; i < 128; ++i) - { - offset_[i].x = tf->offset[i].x; - offset_[i].y = tf->offset[i].y; - offset_[i].w = tf->offset[i].w; - } - - // Crea los objetos - texture_ = std::make_shared(renderer, bitmap_file); - sprite_ = std::make_unique(texture_, (SDL_Rect){0, 0, box_width_, box_height_}); - - // Inicializa variables - fixed_width_ = false; -} - // Constructor Text::Text(std::shared_ptr texture, const std::string &text_file) - : texture_(texture) { // Carga los offsets desde el fichero auto tf = loadTextFile(text_file); @@ -127,7 +102,6 @@ Text::Text(std::shared_ptr texture, const std::string &text_file) // Constructor Text::Text(std::shared_ptr texture, std::shared_ptr text_file) - : texture_(texture) { // Inicializa variables desde la estructura box_height_ = text_file->box_height; @@ -265,16 +239,4 @@ void Text::reLoadTexture() void Text::setFixedWidth(bool value) { fixed_width_ = value; -} - -// Carga una paleta de colores para el texto -void Text::addPalette(const std::string &path) -{ - texture_->addPalette(path); -} - -// Establece una paleta de colores para el texto -void Text::setPalette(int index) -{ - texture_->setPalette(index); } \ No newline at end of file diff --git a/source/text.h b/source/text.h index 8241219..4c218a4 100644 --- a/source/text.h +++ b/source/text.h @@ -34,7 +34,6 @@ class Text private: // Objetos y punteros std::unique_ptr sprite_; // Objeto con los graficos para el texto - std::shared_ptr texture_; // Textura con los bitmaps del texto // Variables int box_width_; // Anchura de la caja de cada caracter en el png @@ -44,7 +43,6 @@ private: public: // Constructor - Text(const std::string &bitmap_file, const std::string &text_file, SDL_Renderer *renderer); Text(std::shared_ptr texture, const std::string &text_file); Text(std::shared_ptr texture, std::shared_ptr text_file); @@ -77,10 +75,4 @@ public: // Establece si se usa un tamaño fijo de letra void setFixedWidth(bool value); - - // Carga una paleta de colores para el texto - void addPalette(const std::string &path); - - // Establece una paleta de colores para el texto - void setPalette(int index); }; \ No newline at end of file diff --git a/source/texture.cpp b/source/texture.cpp index 859308a..116f225 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -7,22 +7,22 @@ #include // for fseek, fclose, fopen, fread, ftell, NULL #include // for malloc, free, exit #include // for basic_ostream, operator<<, cout, endl -#include "gif.c" // for LoadGif, LoadPalette +#include +#include +#include "gif.c" // for LoadGif, LoadPalette #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" // for stbi_failure_reason, stbi_image_free // Constructor Texture::Texture(SDL_Renderer *renderer, const std::string &path) - : renderer_(renderer), path_(path) + : texture_(nullptr), + renderer_(renderer), + surface_(nullptr), + width_(0), + height_(0), + path_(path), + current_palette_(0) { - // Inicializa - surface_ = nullptr; - texture_ = nullptr; - width_ = 0; - height_ = 0; - paletteIndex_ = 0; - palettes_.clear(); - // Carga el fichero en la textura if (!path_.empty()) { @@ -39,7 +39,7 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path) else if (extension == "gif") { surface_ = loadSurface(path_); - addPalette(path_); + addPaletteFromFile(path_); setPaletteColor(0, 0, 0x00000000); createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING); SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND); @@ -51,7 +51,9 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path) // Destructor Texture::~Texture() { - unload(); + unloadTexture(); + unloadSurface(); + palettes_.clear(); } // Carga una imagen desde un fichero @@ -87,7 +89,7 @@ bool Texture::loadFromFile(const std::string &file_path) } // Limpia - unload(); + unloadTexture(); // La textura final SDL_Texture *newTexture = nullptr; @@ -142,7 +144,7 @@ bool Texture::createBlank(int width, int height, SDL_PixelFormatEnum format, SDL } // Libera la memoria de la textura -void Texture::unload() +void Texture::unloadTexture() { // Libera la textura if (texture_) @@ -152,13 +154,6 @@ void Texture::unload() width_ = 0; height_ = 0; } - - // Libera la surface - if (surface_) - { - deleteSurface(surface_); - surface_ = nullptr; - } } // Establece el color para la modulacion @@ -229,61 +224,56 @@ SDL_Texture *Texture::getSDLTexture() return texture_; } -// Crea una nueva surface -/*Surface Texture::newSurface(int w, int h) +// Desencadenar la superficie actual +void Texture::unloadSurface() { - Surface surf = static_cast(malloc(sizeof(surface_s))); - surf->w = w; - surf->h = h; - surf->data = static_cast(malloc(w * h)); - return surf; -}*/ - -// Elimina una surface -void Texture::deleteSurface(Surface surface) -{ - if (surface == nullptr) - { - return; - } - - if (surface->data != nullptr) - { - free(surface->data); - } - - free(surface); + surface_.reset(); // Resetea el shared_ptr + width_ = 0; + height_ = 0; } // Crea una surface desde un fichero .gif -Surface Texture::loadSurface(const std::string &file_name) +std::shared_ptr Texture::loadSurface(const std::string &file_path) { - FILE *f = fopen(file_name.c_str(), "rb"); - if (!f) + // Desencadenar la superficie actual + unloadSurface(); + + // Abrir el archivo usando std::ifstream para manejo automático del recurso + std::ifstream file(file_path, std::ios::binary | std::ios::ate); + if (!file) { - return nullptr; + std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; + throw std::runtime_error("Fichero no encontrado: " + file_path); } - fseek(f, 0, SEEK_END); - long size = ftell(f); - fseek(f, 0, SEEK_SET); - Uint8 *buffer = static_cast(malloc(size)); - fread(buffer, size, 1, f); - fclose(f); + // Obtener el tamaño del archivo + std::streamsize size = file.tellg(); + file.seekg(0, std::ios::beg); + // Leer el contenido del archivo en un buffer + std::vector buffer(size); + if (!file.read(reinterpret_cast(buffer.data()), size)) + { + std::cerr << "Error al leer el fichero " << file_path << std::endl; + throw std::runtime_error("Error al leer el fichero: " + file_path); + } + + // Cerrar el archivo (automáticamente manejado por std::ifstream) + file.close(); + + // Llamar a la función LoadGif Uint16 w, h; - Uint8 *pixels = LoadGif(buffer, &w, &h); - if (pixels == nullptr) + Uint8 *rawPixels = LoadGif(buffer.data(), &w, &h); + if (!rawPixels) { return nullptr; } - Surface surface = static_cast(malloc(sizeof(surface_s))); - surface->w = w; - surface->h = h; - surface->data = pixels; - free(buffer); + // Crear un std::shared_ptr con std::make_shared para pixels + auto pixels = std::shared_ptr(rawPixels, std::default_delete()); + auto surface = std::make_shared(w, h, pixels); + // Actualizar la anchura y altura width_ = w; height_ = h; @@ -306,7 +296,7 @@ void Texture::flipSurface() SDL_LockTexture(texture_, nullptr, reinterpret_cast(&pixels), &pitch); for (int i = 0; i < width_ * height_; ++i) { - pixels[i] = palettes_[paletteIndex_][surface_->data[i]]; + pixels[i] = palettes_[current_palette_][surface_->data[i]]; } SDL_UnlockTexture(texture_); } @@ -318,14 +308,20 @@ void Texture::setPaletteColor(int palette, int index, Uint32 color) } // Carga una paleta desde un fichero -std::vector Texture::loadPal(const std::string &file_name) +std::vector Texture::loadPaletteFromFile(const std::string &file_path) { std::vector palette; - FILE *f = fopen(file_name.c_str(), "rb"); + FILE *f = fopen(file_path.c_str(), "rb"); if (!f) { - return palette; + std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; + throw std::runtime_error("Fichero no encontrado: " + file_path); + } + else + { + const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); + printWithDots("Image : ", file_name, "[ LOADED ]"); } fseek(f, 0, SEEK_END); @@ -352,9 +348,9 @@ std::vector Texture::loadPal(const std::string &file_name) } // Añade una paleta a la lista -void Texture::addPalette(const std::string &path) +void Texture::addPaletteFromFile(const std::string &path) { - palettes_.push_back(loadPal(path)); + palettes_.emplace_back(loadPaletteFromFile(path)); setPaletteColor((int)palettes_.size() - 1, 0, 0x00000000); } @@ -363,7 +359,7 @@ void Texture::setPalette(int palette) { if (palette < (int)palettes_.size()) { - paletteIndex_ = palette; + current_palette_ = palette; flipSurface(); } } diff --git a/source/texture.h b/source/texture.h index 03e5b5d..e3783a1 100644 --- a/source/texture.h +++ b/source/texture.h @@ -1,51 +1,54 @@ #pragma once -#include // for SDL_BlendMode -#include // for SDL_PIXELFORMAT_RGBA8888, SDL_PixelF... -#include // for SDL_Point, SDL_Rect -#include // for SDL_Renderer, SDL_FLIP_NONE, SDL_TEX... -#include // for Uint8, Uint32, Uint16 -#include // for string, basic_string -#include // for vector +#include // for SDL_BlendMode +#include // for SDL_PIXELFORMAT_RGBA8888, SDL_PixelF... +#include // for SDL_Point, SDL_Rect +#include // for SDL_Renderer, SDL_FLIP_NONE, SDL_TEX... +#include // for Uint8, Uint32, Uint16 +#include // for string, basic_string +#include // for vector +#include // Definiciones de tipos -struct surface_s +struct Surface { - Uint8 *data; + std::shared_ptr data; Uint16 w, h; -}; -typedef struct surface_s *Surface; + // Constructor + Surface(Uint16 width, Uint16 height, std::shared_ptr pixels) + : data(pixels), w(width), h(height) {} +}; class Texture { private: // Objetos y punteros - SDL_Texture *texture_; // La textura - SDL_Renderer *renderer_; // Renderizador donde dibujar la textura - Surface surface_; // Surface para usar imagenes en formato gif con paleta + SDL_Texture *texture_; // La textura + SDL_Renderer *renderer_; // Renderizador donde dibujar la textura + std::shared_ptr surface_; // Surface para usar imagenes en formato gif con paleta // Variables int width_; // Ancho de la imagen int height_; // Alto de la imagen std::string path_; // Ruta de la imagen de la textura std::vector> palettes_; // Vector con las diferentes paletas - int paletteIndex_; // Indice de la paleta en uso - - // Crea una nueva surface - //Surface newSurface(int w, int h); - - // Elimina una surface - void deleteSurface(Surface surface); + int current_palette_; // Indice de la paleta en uso // Crea una surface desde un fichero .gif - Surface loadSurface(const std::string &file_name); + std::shared_ptr loadSurface(const std::string &file_name); // Vuelca la surface en la textura - void flipSurface(); + void flipSurface(); // Carga una paleta desde un fichero - std::vector loadPal(const std::string &file_name); + std::vector loadPaletteFromFile(const std::string &file_name); + + // Libera la memoria de la textura + void unloadTexture(); + + // Desencadenar la superficie actual + void unloadSurface(); public: // Constructor @@ -60,9 +63,6 @@ public: // Crea una textura en blanco bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING); - // Libera la memoria de la textura - void unload(); - // Establece el color para la modulacion void setColor(Uint8 red, Uint8 green, Uint8 blue); @@ -91,7 +91,7 @@ public: SDL_Texture *getSDLTexture(); // Añade una paleta a la lista - void addPalette(const std::string &path); + void addPaletteFromFile(const std::string &path); // Establece un color de la paleta void setPaletteColor(int palette, int index, Uint32 color); diff --git a/source/tiled_bg.cpp b/source/tiled_bg.cpp index 10dd1ab..077aede 100644 --- a/source/tiled_bg.cpp +++ b/source/tiled_bg.cpp @@ -28,7 +28,7 @@ TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode) // Inicializa los valores del vector con los valores del seno for (int i = 0; i < 360; ++i) { - sin_[i] = std::sinf(i * 3.14159f / 180.0f); // Convierte grados a radianes y calcula el seno + sin_[i] = std::sin(i * 3.14159 / 180.0); // Convierte grados a radianes y calcula el seno } } diff --git a/source/tiled_bg.h b/source/tiled_bg.h index 578e2de..3adbff5 100644 --- a/source/tiled_bg.h +++ b/source/tiled_bg.h @@ -33,10 +33,10 @@ private: SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles // Variables - SDL_Rect pos_; // Posición y tamaño del mosaico - int counter_; // Contador - TiledBGMode mode_; // Tipo de movimiento del mosaico - float sin_[360]; // Vector con los valores del seno precalculados + SDL_Rect pos_; // Posición y tamaño del mosaico + int counter_; // Contador + TiledBGMode mode_; // Tipo de movimiento del mosaico + double sin_[360]; // Vector con los valores del seno precalculados // Rellena la textura con el contenido void fillTexture(); diff --git a/source/title.cpp b/source/title.cpp index 357f526..f948ff2 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -24,51 +24,43 @@ struct JA_Music_t; // lines 17-17 // Constructor Title::Title() + : text1_(std::make_unique(Resource::get()->getTexture("smb2.gif"), Resource::get()->getTextFile("smb2.txt"))), + text2_(std::make_unique(Resource::get()->getTexture("8bithud.png"), Resource::get()->getTextFile("8bithud.txt"))), + fade_(std::make_unique()), + tiled_bg_(std::make_unique((SDL_Rect){0, 0, param.game.width, param.game.height}, TiledBGMode::RANDOM)), + game_logo_(std::make_unique(param.game.game_area.center_x, param.title.title_c_c_position)), + mini_logo_texture_(Resource::get()->getTexture("logo_jailgames_mini.png")), + mini_logo_sprite_(std::make_unique(mini_logo_texture_, param.game.game_area.center_x - mini_logo_texture_->getWidth() / 2, 0, mini_logo_texture_->getWidth(), mini_logo_texture_->getHeight())), + define_buttons_(std::make_unique(std::move(text2_))), + counter_(0), + ticks_(0), + demo_(true), + next_section_(section::Name::GAME), + post_fade_(0), + num_controllers_(Input::get()->getNumControllers()) { - // Reserva memoria y crea los objetos - fade_ = std::make_unique(); - - text1_ = std::make_unique(Resource::get()->getTexture("smb2.gif"), Resource::get()->getTextFile("smb2.txt")); - text1_->addPalette(Asset::get()->get("smb2_pal1.gif")); - text1_->setPalette(1); - text2_ = std::make_unique(Resource::get()->getTexture("8bithud.png"), Resource::get()->getTextFile("8bithud.txt")); - - mini_logo_texture_ = Resource::get()->getTexture("logo_jailgames_mini.png"); - mini_logo_sprite_ = std::make_unique(mini_logo_texture_, param.game.game_area.center_x - mini_logo_texture_->getWidth() / 2, 0, mini_logo_texture_->getWidth(), mini_logo_texture_->getHeight()); - - tiled_bg_ = std::make_unique((SDL_Rect){0, 0, param.game.width, param.game.height}, TiledBGMode::RANDOM); - - game_logo_ = std::make_unique(param.game.game_area.center_x, param.title.title_c_c_position); + // Configura objetos game_logo_->enable(); - - define_buttons_ = std::make_unique(std::move(text2_)); - - // Inicializa los valores - init(); -} - -// Inicializa los valores de las variables -void Title::init() -{ - // Inicializa variables - section::options = section::Options::TITLE_1; - counter_ = 0; - next_section_ = section::Name::GAME; - post_fade_ = 0; - ticks_ = 0; - ticks_speed_ = 15; fade_->setColor(fade_color.r, fade_color.g, fade_color.b); fade_->setType(FadeType::RANDOM_SQUARE); fade_->setPost(param.fade.post_duration); - demo_ = true; - num_controllers_ = Input::get()->getNumControllers(); + Resource::get()->getTexture("smb2.gif")->setPalette(1); + + // Asigna valores a otras variables + section::options = section::Options::TITLE_1; +} + +// Destructor +Title::~Title() +{ + Resource::get()->getTexture("smb2.gif")->setPalette(0); } // Actualiza las variables del objeto void Title::update() { // Calcula la lógica de los objetos - if (SDL_GetTicks() - ticks_ > ticks_speed_) + if (SDL_GetTicks() - ticks_ > TICKS_SPEED_) { // Actualiza el contador de ticks_ ticks_ = SDL_GetTicks(); diff --git a/source/title.h b/source/title.h index a7feb83..4e23067 100644 --- a/source/title.h +++ b/source/title.h @@ -42,29 +42,28 @@ constexpr bool ALLOW_TITLE_ANIMATION_SKIP = true; class Title { private: - // Objetos y punteros - std::unique_ptr tiled_bg_; // Objeto para dibujar el mosaico animado de fondo - std::unique_ptr game_logo_; // Objeto para dibujar el logo con el título del juego - std::unique_ptr define_buttons_; // Objeto para definir los botones del joystic - std::shared_ptr mini_logo_texture_; // Textura con el logo de JailGames mini - std::unique_ptr mini_logo_sprite_; // Sprite con el logo de JailGames mini + // Constantes + static constexpr Uint32 TICKS_SPEED_ = 15; // Velocidad a la que se repiten los bucles del programa + // Objetos y punteros std::unique_ptr text1_; // Objeto de texto para poder escribir textos en pantalla std::unique_ptr text2_; // Objeto de texto para poder escribir textos en pantalla std::unique_ptr fade_; // Objeto para realizar fundidos en pantalla + std::unique_ptr tiled_bg_; // Objeto para dibujar el mosaico animado de fondo + std::unique_ptr game_logo_; // Objeto para dibujar el logo con el título del juego + std::shared_ptr mini_logo_texture_; // Textura con el logo de JailGames mini + std::unique_ptr mini_logo_sprite_; // Sprite con el logo de JailGames mini + std::unique_ptr define_buttons_; // Objeto para definir los botones del joystic + // Variable int counter_; // Temporizador para la pantalla de titulo Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticks_speed_; // Velocidad a la que se repiten los bucles del programa bool demo_; // Indica si el modo demo estará activo section::Name next_section_; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo int post_fade_; // Opción a realizar cuando termina el fundido int num_controllers_; // Número de mandos conectados - // Inicializa los valores de las variables - void init(); - // Actualiza las variables del objeto void update(); @@ -91,7 +90,7 @@ public: Title(); // Destructor - ~Title() = default; + ~Title(); // Bucle para el titulo del juego void run();