From 7a0bc5c9ae50df6db0bbc296c5df795945d6b48f Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Fri, 21 Feb 2025 19:45:29 +0100 Subject: [PATCH] canvi de pc --- source/credits.cpp | 241 ++++++++++++++--------------- source/credits.h | 38 ++--- source/debug.cpp | 65 ++++---- source/debug.h | 22 +-- source/director.cpp | 213 +++++++++++++------------- source/director.h | 17 +-- source/input.cpp | 120 ++++++++------- source/input.h | 37 +++-- source/loading_screen.cpp | 230 ++++++++++++++-------------- source/loading_screen.h | 48 +++--- source/logo.cpp | 217 +++++++++++++------------- source/logo.h | 40 ++--- source/resource.cpp | 99 ++++++------ source/resource.h | 17 +-- source/screen.cpp | 314 ++++++++++++++++++++------------------ source/screen.h | 65 +++++--- source/title.cpp | 20 +-- source/title.h | 4 +- 18 files changed, 918 insertions(+), 889 deletions(-) diff --git a/source/credits.cpp b/source/credits.cpp index afa6cd98..4398e6f0 100644 --- a/source/credits.cpp +++ b/source/credits.cpp @@ -12,59 +12,54 @@ #include "resource.h" // Para Resource #include "screen.h" // Para Screen #include "text.h" // Para Text, TXT_CENTER, TXT_COLOR +#include "asset.h" class Asset; // Constructor -Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section) -{ - // Copia la dirección de los objetos - this->renderer = renderer; - this->screen = screen; - this->resource = resource; - this->asset = asset; - this->input = input; - this->options = options; - this->section = section; +Credits::Credits(Resource *resource, options_t *options, section_t *section) + : screen_(Screen::get()), + renderer_(Screen::get()->getRenderer()), + resource_(resource), + asset_(Asset::get()), + input_(Input::get()), + options_(options), + section_(section) +{ // Reserva memoria para los punteros - eventHandler = new SDL_Event(); - text = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); - sprite = new AnimatedSprite(renderer, resource->getAnimation("shine.ani")); + event_handler_ = new SDL_Event(); + text_ = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer_); + sprite_ = new AnimatedSprite(renderer_, resource->getAnimation("shine.ani")); // Inicializa variables - counter = 0; - counterEnabled = true; - subCounter = 0; section->name = SECTION_CREDITS; section->subsection = 0; - ticks = 0; - ticksSpeed = 15; - sprite->setRect({194, 174, 8, 8}); + sprite_->setRect({194, 174, 8, 8}); // Cambia el color del borde - screen->setBorderColor(stringToColor(options->palette, "black")); + screen_->setBorderColor(stringToColor(options->palette, "black")); // Crea la textura para el texto que se escribe en pantalla - textTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); - if (textTexture == nullptr) + text_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); + if (text_texture_ == nullptr) { if (options->console) { std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } - SDL_SetTextureBlendMode(textTexture, SDL_BLENDMODE_BLEND); + SDL_SetTextureBlendMode(text_texture_, SDL_BLENDMODE_BLEND); // Crea la textura para cubrir el rexto - coverTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); - if (coverTexture == nullptr) + cover_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); + if (cover_texture_ == nullptr) { if (options->console) { std::cout << "Error: textTexture could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } - SDL_SetTextureBlendMode(coverTexture, SDL_BLENDMODE_BLEND); + SDL_SetTextureBlendMode(cover_texture_, SDL_BLENDMODE_BLEND); // Escribe el texto en la textura fillTexture(); @@ -73,23 +68,23 @@ Credits::Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Ass // Destructor Credits::~Credits() { - delete eventHandler; - delete text; - delete sprite; - SDL_DestroyTexture(textTexture); - SDL_DestroyTexture(coverTexture); + delete event_handler_; + delete text_; + delete sprite_; + SDL_DestroyTexture(text_texture_); + SDL_DestroyTexture(cover_texture_); } // Comprueba el manejador de eventos void Credits::checkEvents() { // Comprueba los eventos que hay en la cola - while (SDL_PollEvent(eventHandler) != 0) + while (SDL_PollEvent(event_handler_) != 0) { // Evento de salida de la aplicación - if (eventHandler->type == SDL_QUIT) + if (event_handler_->type == SDL_QUIT) { - section->name = SECTION_QUIT; + section_->name = SECTION_QUIT; break; } } @@ -99,40 +94,40 @@ void Credits::checkEvents() void Credits::checkInput() { - if (input->checkInput(input_exit, REPEAT_FALSE)) + if (input_->checkInput(input_exit, REPEAT_FALSE)) { - section->name = SECTION_QUIT; + section_->name = SECTION_QUIT; } - else if (input->checkInput(input_toggle_border, REPEAT_FALSE)) + else if (input_->checkInput(input_toggle_border, REPEAT_FALSE)) { - screen->toggleBorder(); + screen_->toggleBorder(); } - else if (input->checkInput(input_toggle_videomode, REPEAT_FALSE)) + else if (input_->checkInput(input_toggle_videomode, REPEAT_FALSE)) { - screen->toggleVideoMode(); + screen_->toggleVideoMode(); } - else if (input->checkInput(input_window_dec_size, REPEAT_FALSE)) + else if (input_->checkInput(input_window_dec_size, REPEAT_FALSE)) { - screen->decWindowSize(); + screen_->decWindowSize(); } - else if (input->checkInput(input_window_inc_size, REPEAT_FALSE)) + else if (input_->checkInput(input_window_inc_size, REPEAT_FALSE)) { - screen->incWindowSize(); + screen_->incWindowSize(); } - else if (input->checkInput(input_toggle_palette, REPEAT_FALSE)) + else if (input_->checkInput(input_toggle_palette, REPEAT_FALSE)) { switchPalette(); } - else if (input->checkInput(input_pause, REPEAT_FALSE) || input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_jump, REPEAT_FALSE)) + else if (input_->checkInput(input_pause, REPEAT_FALSE) || input_->checkInput(input_accept, REPEAT_FALSE) || input_->checkInput(input_jump, REPEAT_FALSE)) { - section->name = SECTION_TITLE; - section->subsection = 0; + section_->name = SECTION_TITLE; + section_->subsection = 0; } } @@ -140,11 +135,11 @@ void Credits::checkInput() void Credits::iniTexts() { std::string keys = ""; - if (options->keys == ctrl_cursor) + if (options_->keys == ctrl_cursor) { keys = "CURSORS"; } - else if (options->keys == ctrl_opqa) + else if (options_->keys == ctrl_opqa) { keys = "O,P AND Q"; } @@ -154,34 +149,34 @@ void Credits::iniTexts() } #ifndef GAME_CONSOLE - texts.clear(); - texts.push_back({"", stringToColor(options->palette, "white")}); - texts.push_back({"INSTRUCTIONS:", stringToColor(options->palette, "yellow")}); - texts.push_back({"", stringToColor(options->palette, "white")}); - texts.push_back({"HELP JAILDOC TO GET BACK ALL", stringToColor(options->palette, "white")}); - texts.push_back({"HIS PROJECTS AND GO TO THE", stringToColor(options->palette, "white")}); - texts.push_back({"JAIL TO FINISH THEM", stringToColor(options->palette, "white")}); - texts.push_back({"", stringToColor(options->palette, "white")}); - texts.push_back({"", stringToColor(options->palette, "white")}); + texts_.clear(); + texts_.push_back({"", stringToColor(options_->palette, "white")}); + texts_.push_back({"INSTRUCTIONS:", stringToColor(options_->palette, "yellow")}); + texts_.push_back({"", stringToColor(options_->palette, "white")}); + texts_.push_back({"HELP JAILDOC TO GET BACK ALL", stringToColor(options_->palette, "white")}); + texts_.push_back({"HIS PROJECTS AND GO TO THE", stringToColor(options_->palette, "white")}); + texts_.push_back({"JAIL TO FINISH THEM", stringToColor(options_->palette, "white")}); + texts_.push_back({"", stringToColor(options_->palette, "white")}); + texts_.push_back({"", stringToColor(options_->palette, "white")}); - texts.push_back({"KEYS:", stringToColor(options->palette, "yellow")}); - texts.push_back({"", stringToColor(options->palette, "white")}); - texts.push_back({keys + " TO MOVE AND JUMP", stringToColor(options->palette, "white")}); - texts.push_back({"M TO SWITCH THE MUSIC", stringToColor(options->palette, "white")}); - texts.push_back({"H TO PAUSE THE GAME", stringToColor(options->palette, "white")}); - texts.push_back({"F1-F2 TO CHANGE WINDOWS SIZE", stringToColor(options->palette, "white")}); - texts.push_back({"F3 TO SWITCH TO FULLSCREEN", stringToColor(options->palette, "white")}); - texts.push_back({"B TO TOOGLE THE BORDER SCREEN", stringToColor(options->palette, "white")}); - texts.push_back({"", stringToColor(options->palette, "white")}); - texts.push_back({"", stringToColor(options->palette, "white")}); + texts_.push_back({"KEYS:", stringToColor(options_->palette, "yellow")}); + texts_.push_back({"", stringToColor(options_->palette, "white")}); + texts_.push_back({keys + " TO MOVE AND JUMP", stringToColor(options_->palette, "white")}); + texts_.push_back({"M TO SWITCH THE MUSIC", stringToColor(options_->palette, "white")}); + texts_.push_back({"H TO PAUSE THE GAME", stringToColor(options_->palette, "white")}); + texts_.push_back({"F1-F2 TO CHANGE WINDOWS SIZE", stringToColor(options_->palette, "white")}); + texts_.push_back({"F3 TO SWITCH TO FULLSCREEN", stringToColor(options_->palette, "white")}); + texts_.push_back({"B TO TOOGLE THE BORDER SCREEN", stringToColor(options_->palette, "white")}); + texts_.push_back({"", stringToColor(options_->palette, "white")}); + texts_.push_back({"", stringToColor(options_->palette, "white")}); - texts.push_back({"A GAME BY JAILDESIGNER", stringToColor(options->palette, "yellow")}); - texts.push_back({"MADE ON SUMMER/FALL 2022", stringToColor(options->palette, "yellow")}); - texts.push_back({"", stringToColor(options->palette, "white")}); - texts.push_back({"", stringToColor(options->palette, "white")}); + texts_.push_back({"A GAME BY JAILDESIGNER", stringToColor(options_->palette, "yellow")}); + texts_.push_back({"MADE ON SUMMER/FALL 2022", stringToColor(options_->palette, "yellow")}); + texts_.push_back({"", stringToColor(options_->palette, "white")}); + texts_.push_back({"", stringToColor(options_->palette, "white")}); - texts.push_back({"I LOVE JAILGAMES! ", stringToColor(options->palette, "white")}); - texts.push_back({"", stringToColor(options->palette, "white")}); + texts_.push_back({"I LOVE JAILGAMES! ", stringToColor(options_->palette, "white")}); + texts_.push_back({"", stringToColor(options_->palette, "white")}); #else texts.clear(); texts.push_back({"", stringToColor(options->palette, "white")}); @@ -221,82 +216,82 @@ void Credits::fillTexture() iniTexts(); // Rellena la textura de texto - SDL_SetRenderTarget(renderer, textTexture); - color_t c = stringToColor(options->palette, "black"); - SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF); - SDL_RenderClear(renderer); + SDL_SetRenderTarget(renderer_, text_texture_); + color_t c = stringToColor(options_->palette, "black"); + SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0xFF); + SDL_RenderClear(renderer_); // Escribe el texto en la textura - const int size = text->getCharacterSize(); + const int size = text_->getCharacterSize(); int i = 0; - for (auto t : texts) + for (auto t : texts_) { - text->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, i * size, t.label, 1, t.color); + text_->writeDX(TXT_CENTER | TXT_COLOR, PLAY_AREA_CENTER_X, i * size, t.label, 1, t.color); i++; } // Escribe el corazón - const int textLenght = text->lenght(texts[22].label, 1) - text->lenght(" ", 1); // Se resta el ultimo caracter que es un espacio + const int textLenght = text_->lenght(texts_[22].label, 1) - text_->lenght(" ", 1); // Se resta el ultimo caracter que es un espacio const int posX = ((PLAY_AREA_WIDTH - textLenght) / 2) + textLenght; - text->writeColored(posX, 176, "}", stringToColor(options->palette, "bright_red")); + text_->writeColored(posX, 176, "}", stringToColor(options_->palette, "bright_red")); // Recoloca el sprite del brillo - sprite->setPosX(posX + 2); + sprite_->setPosX(posX + 2); - SDL_SetRenderTarget(renderer, nullptr); + SDL_SetRenderTarget(renderer_, nullptr); // Rellena la textura que cubre el texto con color transparente - SDL_SetRenderTarget(renderer, coverTexture); - SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0x00); - SDL_RenderClear(renderer); + SDL_SetRenderTarget(renderer_, cover_texture_); + SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0x00); + SDL_RenderClear(renderer_); // Los primeros 8 pixels crea una malla - SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, 0xFF); + SDL_SetRenderDrawColor(renderer_, c.r, c.g, c.b, 0xFF); for (int i = 0; i < 256; i += 2) { - SDL_RenderDrawPoint(renderer, i, 0); - SDL_RenderDrawPoint(renderer, i, 2); - SDL_RenderDrawPoint(renderer, i, 4); - SDL_RenderDrawPoint(renderer, i, 6); + SDL_RenderDrawPoint(renderer_, i, 0); + SDL_RenderDrawPoint(renderer_, i, 2); + SDL_RenderDrawPoint(renderer_, i, 4); + SDL_RenderDrawPoint(renderer_, i, 6); - SDL_RenderDrawPoint(renderer, i + 1, 5); - SDL_RenderDrawPoint(renderer, i + 1, 7); + SDL_RenderDrawPoint(renderer_, i + 1, 5); + SDL_RenderDrawPoint(renderer_, i + 1, 7); } // El resto se rellena de color sólido SDL_Rect rect = {0, 8, 256, 192}; - SDL_RenderFillRect(renderer, &rect); + SDL_RenderFillRect(renderer_, &rect); - SDL_SetRenderTarget(renderer, nullptr); + SDL_SetRenderTarget(renderer_, nullptr); } // Actualiza el contador void Credits::updateCounter() { // Incrementa el contador - if (counterEnabled) + if (counter_enabled_) { - counter++; - if (counter == 224 || counter == 544 || counter == 672) + counter_++; + if (counter_ == 224 || counter_ == 544 || counter_ == 672) { - counterEnabled = false; + counter_enabled_ = false; } } else { - subCounter++; - if (subCounter == 100) + sub_counter_++; + if (sub_counter_ == 100) { - counterEnabled = true; - subCounter = 0; + counter_enabled_ = true; + sub_counter_ = 0; } } // Comprueba si ha terminado la sección - if (counter > 1200) + if (counter_ > 1200) { - section->name = SECTION_DEMO; + section_->name = SECTION_DEMO; } } @@ -304,10 +299,10 @@ void Credits::updateCounter() void Credits::update() { // Comprueba que la diferencia de ticks sea mayor a la velocidad del juego - if (SDL_GetTicks() - ticks > ticksSpeed) + if (SDL_GetTicks() - ticks_ > ticks_speed_) { // Actualiza el contador de ticks - ticks = SDL_GetTicks(); + ticks_ = SDL_GetTicks(); // Comprueba las entradas checkInput(); @@ -316,12 +311,12 @@ void Credits::update() updateCounter(); // Actualiza las notificaciones - screen->updateNotifier(); + screen_->updateNotifier(); // Actualiza el sprite con el brillo - if (counter > 770) + if (counter_ > 770) { - sprite->update(); + sprite_->update(); } } } @@ -330,34 +325,34 @@ void Credits::update() void Credits::render() { // Prepara para empezar a dibujar en la textura de juego - screen->start(); + screen_->start(); // Limpia la pantalla - screen->clean(); + screen_->clean(); - if (counter < 1150) + if (counter_ < 1150) { // Dibuja la textura con el texto en pantalla - SDL_RenderCopy(renderer, textTexture, nullptr, nullptr); + SDL_RenderCopy(renderer_, text_texture_, nullptr, nullptr); // Dibuja la textura que cubre el texto - const int offset = std::min(counter / 8, 192 / 2); + const int offset = std::min(counter_ / 8, 192 / 2); SDL_Rect srcRect = {0, 0, 256, 192 - (offset * 2)}; SDL_Rect dstRect = {0, offset * 2, 256, 192 - (offset * 2)}; - SDL_RenderCopy(renderer, coverTexture, &srcRect, &dstRect); + SDL_RenderCopy(renderer_, cover_texture_, &srcRect, &dstRect); // Dibuja el sprite con el brillo - sprite->render(); + sprite_->render(); } // Vuelca el contenido del renderizador en pantalla - screen->render(); + screen_->render(); } // Bucle para el logo del juego void Credits::run() { - while (section->name == SECTION_CREDITS) + while (section_->name == SECTION_CREDITS) { update(); checkEvents(); @@ -368,6 +363,6 @@ void Credits::run() // Cambia la paleta void Credits::switchPalette() { - options->palette = options->palette == p_zxspectrum ? p_zxarne : p_zxspectrum; + options_->palette = options_->palette == p_zxspectrum ? p_zxarne : p_zxspectrum; fillTexture(); } \ No newline at end of file diff --git a/source/credits.h b/source/credits.h index d6446fe1..45e3a191 100644 --- a/source/credits.h +++ b/source/credits.h @@ -23,26 +23,26 @@ private: }; // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana - Screen *screen; // Objeto encargado de dibujar en pantalla - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto con los ficheros de recursos - Input *input; // Objeto pata gestionar la entrada - SDL_Event *eventHandler; // Manejador de eventos - Text *text; // Objeto para escribir texto en pantalla - SDL_Texture *textTexture; // Textura para dibujar el texto - SDL_Texture *coverTexture; // Textura para cubrir el texto - AnimatedSprite *sprite; // Sprite para el brillo del corazón - options_t *options; // Puntero a las opciones del juego - section_t *section; // Estado del bucle principal para saber si continua o se sale + Screen *screen_; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer_; // El renderizador de la ventana + Resource *resource_; // Objeto con los recursos + Asset *asset_; // Objeto con los ficheros de recursos + Input *input_; // Objeto pata gestionar la entrada + SDL_Event *event_handler_; // Manejador de eventos + Text *text_; // Objeto para escribir texto en pantalla + SDL_Texture *text_texture_; // Textura para dibujar el texto + SDL_Texture *cover_texture_; // Textura para cubrir el texto + AnimatedSprite *sprite_; // Sprite para el brillo del corazón + options_t *options_; // Puntero a las opciones del juego + section_t *section_; // Estado del bucle principal para saber si continua o se sale // Variables - int counter; // Contador - bool counterEnabled; // Indica si esta activo el contador - int subCounter; // Contador secundario - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - std::vector texts; // Vector con los textos + int counter_ = 0; // Contador + bool counter_enabled_ = true; // Indica si esta activo el contador + int sub_counter_ = 0; // Contador secundario + Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticks_speed_ = 15; // Velocidad a la que se repiten los bucles del programa + std::vector texts_; // Vector con los textos // Actualiza las variables void update(); @@ -70,7 +70,7 @@ private: public: // Constructor - Credits(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section); + Credits(Resource *resource, options_t *options, section_t *section); // Destructor ~Credits(); diff --git a/source/debug.cpp b/source/debug.cpp index 64fcbfa7..c9264e6d 100644 --- a/source/debug.cpp +++ b/source/debug.cpp @@ -4,31 +4,26 @@ #include "text.h" // Para Text #include "texture.h" // Para Texture #include "utils.h" -class Screen; +#include "screen.h" +#include "asset.h" // Constructor -Debug::Debug(SDL_Renderer *renderer, Screen *screen, Asset *asset) -{ +Debug::Debug() // Copia la dirección de los objetos - this->renderer = renderer; - this->screen = screen; - this->asset = asset; - + : screen_(Screen::get()), + renderer_(Screen::get()->getRenderer()), + asset_(Asset::get()) +{ // Reserva memoria para los punteros - texture = new Texture(renderer, asset->get("debug.png")); - text = new Text(asset->get("debug.txt"), texture, renderer); - - // Inicializa variables - x = 0; - y = 0; - enabled = false; + texture_ = new Texture(renderer_, asset_->get("debug.png")); + text_ = new Text(asset_->get("debug.txt"), texture_, renderer_); } // Destructor Debug::~Debug() { - delete texture; - delete text; + delete texture_; + delete text_; } // Actualiza las variables @@ -39,74 +34,74 @@ void Debug::update() // Dibuja en pantalla void Debug::render() { - int y = this->y; + int y = y_; int w = 0; - for (auto s : slot) + for (auto s : slot_) { - text->write(x, y, s); + text_->write(x_, y, s); w = (std::max(w, (int)s.length())); - y += text->getCharacterSize() + 1; - if (y > 192 - text->getCharacterSize()) + y += text_->getCharacterSize() + 1; + if (y > 192 - text_->getCharacterSize()) { - y = this->y; - x += w * text->getCharacterSize() + 2; + y = y_; + x_ += w * text_->getCharacterSize() + 2; } } y = 0; - for (auto l : log) + for (auto l : log_) { - text->writeColored(x + 10, y, l, color_t(255, 255, 255)); - y += text->getCharacterSize() + 1; + text_->writeColored(x_ + 10, y, l, color_t(255, 255, 255)); + y += text_->getCharacterSize() + 1; } } // Establece la posición donde se colocará la información de debug void Debug::setPos(SDL_Point p) { - x = p.x; - y = p.y; + x_ = p.x; + y_ = p.y; } // Añade un texto para mostrar void Debug::add(std::string text) { - slot.push_back(text); + slot_.push_back(text); } // Borra la información de debug void Debug::clear() { - slot.clear(); + slot_.clear(); } // Añade un texto para mostrar en el apartado log void Debug::addToLog(std::string text) { - log.push_back(text); + log_.push_back(text); } // Borra la información de debug del apartado log void Debug::clearLog() { - log.clear(); + log_.clear(); } // Establece el valor de la variable void Debug::setEnabled(bool value) { - enabled = value; + enabled_ = value; } // Obtiene el valor de la variable bool Debug::getEnabled() { - return enabled; + return enabled_; } // Cambia el valor de la variable void Debug::switchEnabled() { - enabled = !enabled; + enabled_ = !enabled_; } \ No newline at end of file diff --git a/source/debug.h b/source/debug.h index 0e5f1d5d..3bc98f5c 100644 --- a/source/debug.h +++ b/source/debug.h @@ -14,22 +14,22 @@ class Debug { private: // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana - Screen *screen; // Objeto encargado de dibujar en pantalla - Asset *asset; // Objeto con los ficheros de recursos - Text *text; // Objeto encargado de escribir texto en pantalla - Texture *texture; // Textura para el texto + Screen *screen_; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer_; // El renderizador de la ventana + Asset *asset_; // Objeto con los ficheros de recursos + Text *text_; // Objeto encargado de escribir texto en pantalla + Texture *texture_; // Textura para el texto // Variables - std::vector slot; // Vector con los textos a escribir - std::vector log; // Vector con los textos a escribir - int x; // Posicion donde escribir el texto de debug - int y; // Posición donde escribir el texto de debug - bool enabled; // Indica si esta activo el modo debug + std::vector slot_; // Vector con los textos a escribir + std::vector log_; // Vector con los textos a escribir + int x_ = 0; // Posicion donde escribir el texto de debug + int y_ = 0; // Posición donde escribir el texto de debug + bool enabled_ = false; // Indica si esta activo el modo debug public: // Constructor - Debug(SDL_Renderer *renderer, Screen *screen, Asset *asset); + Debug(); // Destructor ~Debug(); diff --git a/source/director.cpp b/source/director.cpp index db153f9a..45f8515c 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -53,6 +53,7 @@ Director::Director(int argc, const char *argv[]) #ifdef DEBUG section->name = SECTION_TITLE; #endif + Asset::init(argv[0]); // Crea el objeto que controla los ficheros de recursos // Crea e inicializa las opciones del programa @@ -88,13 +89,13 @@ Director::Director(int argc, const char *argv[]) initJailAudio(); // Crea los objetos - resource = new Resource(renderer, Asset::get(), options); - input = new Input(Asset::get()->get("gamecontrollerdb.txt")); + Screen::init(window_, renderer_); + Screen::get()->setBorderColor(borderColor); + resource_ = new Resource(options); + Input::init(Asset::get()->get("gamecontrollerdb.txt")); initInput(); - screen = new Screen(window, renderer, Asset::get(), options); - screen->setBorderColor(borderColor); - debug = new Debug(renderer, screen, Asset::get()); - music = JA_LoadMusic(Asset::get()->get("title.ogg").c_str()); + debug_ = new Debug(); + title_music_ = JA_LoadMusic(Asset::get()->get("title.ogg").c_str()); } Director::~Director() @@ -105,14 +106,12 @@ Director::~Director() // Libera la memoria delete section; delete options; - delete input; - delete screen; - delete debug; - delete resource; - JA_DeleteMusic(music); + delete debug_; + delete resource_; + JA_DeleteMusic(title_music_); - SDL_DestroyRenderer(renderer); - SDL_DestroyWindow(window); + SDL_DestroyRenderer(renderer_); + SDL_DestroyWindow(window_); SDL_Quit(); std::cout << "\nBye!" << std::endl; @@ -172,7 +171,7 @@ void Director::initOptions() void Director::checkProgramArguments(int argc, const char *argv[]) { // Establece la ruta del programa - executablePath = argv[0]; + executable_path_ = argv[0]; // Comprueba el resto de parametros for (int i = 1; i < argc; ++i) @@ -413,7 +412,7 @@ bool Director::saveConfig() void Director::createSystemFolder(const std::string &folder) { #ifdef _WIN32 - systemFolder = std::string(getenv("APPDATA")) + "/" + folder; + system_folder_ = std::string(getenv("APPDATA")) + "/" + folder; #elif __APPLE__ struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; @@ -436,11 +435,11 @@ void Director::createSystemFolder(const std::string &folder) #endif struct stat st = {0}; - if (stat(systemFolder.c_str(), &st) == -1) + if (stat(system_folder_.c_str(), &st) == -1) { errno = 0; #ifdef _WIN32 - int ret = mkdir(systemFolder.c_str()); + int ret = mkdir(system_folder_.c_str()); #else int ret = mkdir(systemFolder.c_str(), S_IRWXU); #endif @@ -483,7 +482,7 @@ void Director::loadResources(section_t *section) textureList.push_back("jailgames.png"); textureList.push_back("since_1998.png"); - resource->loadTextures(textureList); + resource_->loadTextures(textureList); } else if (section->name == SECTION_LOADING_SCREEN) @@ -494,7 +493,7 @@ void Director::loadResources(section_t *section) textureList.push_back("loading_screen_bn_zxarne.png"); textureList.push_back("loading_screen_color_zxarne.png"); - resource->loadTextures(textureList); + resource_->loadTextures(textureList); } else if (section->name == SECTION_TITLE) @@ -507,14 +506,14 @@ void Director::loadResources(section_t *section) textureList.push_back("notify.png"); textureList.push_back("title_logo.png"); - resource->loadTextures(textureList); + resource_->loadTextures(textureList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); offsetsList.push_back("subatomic.txt"); - resource->loadOffsets(offsetsList); + resource_->loadOffsets(offsetsList); } else if (section->name == SECTION_CREDITS) @@ -524,19 +523,19 @@ void Director::loadResources(section_t *section) textureList.push_back("shine.png"); textureList.push_back("smb2.png"); - resource->loadTextures(textureList); + resource_->loadTextures(textureList); // Animaciones std::vector animationList; animationList.push_back("shine.ani"); - resource->loadAnimations(animationList); + resource_->loadAnimations(animationList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); - resource->loadOffsets(offsetsList); + resource_->loadOffsets(offsetsList); } else if (section->name == SECTION_ENDING) @@ -555,13 +554,13 @@ void Director::loadResources(section_t *section) textureList.push_back("ending5_zxarne.png"); textureList.push_back("smb2.png"); - resource->loadTextures(textureList); + resource_->loadTextures(textureList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); - resource->loadOffsets(offsetsList); + resource_->loadOffsets(offsetsList); } else if (section->name == SECTION_ENDING2) @@ -630,7 +629,7 @@ void Director::loadResources(section_t *section) // Player textureList.push_back("player.png"); - resource->loadTextures(textureList); + resource_->loadTextures(textureList); // Animaciones std::vector animationList; @@ -693,13 +692,13 @@ void Director::loadResources(section_t *section) // Player animationList.push_back("player.ani"); - resource->loadAnimations(animationList); + resource_->loadAnimations(animationList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); - resource->loadOffsets(offsetsList); + resource_->loadOffsets(offsetsList); } else if (section->name == SECTION_GAME_OVER) @@ -710,20 +709,20 @@ void Director::loadResources(section_t *section) textureList.push_back("player_game_over.png"); textureList.push_back("tv.png"); - resource->loadTextures(textureList); + resource_->loadTextures(textureList); // Animaciones std::vector animationList; animationList.push_back("player_game_over.ani"); animationList.push_back("tv.ani"); - resource->loadAnimations(animationList); + resource_->loadAnimations(animationList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); - resource->loadOffsets(offsetsList); + resource_->loadOffsets(offsetsList); } else if (section->name == SECTION_GAME || section->name == SECTION_DEMO) @@ -811,7 +810,7 @@ void Director::loadResources(section_t *section) textureList.push_back("smb2.png"); textureList.push_back("debug.png"); - resource->loadTextures(textureList); + resource_->loadTextures(textureList); // Animaciones std::vector animationList; @@ -885,14 +884,14 @@ void Director::loadResources(section_t *section) animationList.push_back("wave.ani"); animationList.push_back("z80.ani"); - resource->loadAnimations(animationList); + resource_->loadAnimations(animationList); // Offsets std::vector offsetsList; offsetsList.push_back("smb2.txt"); offsetsList.push_back("debug.txt"); - resource->loadOffsets(offsetsList); + resource_->loadOffsets(offsetsList); // TileMaps std::vector tileMapList; @@ -957,7 +956,7 @@ void Director::loadResources(section_t *section) tileMapList.push_back("59.tmx"); tileMapList.push_back("60.tmx"); - resource->loadTileMaps(tileMapList); + resource_->loadTileMaps(tileMapList); // Habitaciones std::vector roomList; @@ -1022,7 +1021,7 @@ void Director::loadResources(section_t *section) roomList.push_back("59.room"); roomList.push_back("60.room"); - resource->loadRooms(roomList); + resource_->loadRooms(roomList); } if (options->console) @@ -1194,68 +1193,68 @@ bool Director::setOptions(options_t *options, std::string var, std::string value void Director::initInput() { // Establece si ha de mostrar mensajes - input->setVerbose(options->console); + Input::get()->setVerbose(options->console); // Busca si hay un mando conectado - input->discoverGameController(); + Input::get()->discoverGameController(); // Teclado - Movimiento if (options->keys == ctrl_cursor) { - input->bindKey(input_jump, SDL_SCANCODE_UP); - input->bindKey(input_left, SDL_SCANCODE_LEFT); - input->bindKey(input_right, SDL_SCANCODE_RIGHT); - input->bindKey(input_up, SDL_SCANCODE_UP); - input->bindKey(input_down, SDL_SCANCODE_DOWN); + Input::get()->bindKey(input_jump, SDL_SCANCODE_UP); + Input::get()->bindKey(input_left, SDL_SCANCODE_LEFT); + Input::get()->bindKey(input_right, SDL_SCANCODE_RIGHT); + Input::get()->bindKey(input_up, SDL_SCANCODE_UP); + Input::get()->bindKey(input_down, SDL_SCANCODE_DOWN); } else if (options->keys == ctrl_opqa) { - input->bindKey(input_jump, SDL_SCANCODE_Q); - input->bindKey(input_left, SDL_SCANCODE_O); - input->bindKey(input_right, SDL_SCANCODE_P); - input->bindKey(input_up, SDL_SCANCODE_Q); - input->bindKey(input_down, SDL_SCANCODE_A); + Input::get()->bindKey(input_jump, SDL_SCANCODE_Q); + Input::get()->bindKey(input_left, SDL_SCANCODE_O); + Input::get()->bindKey(input_right, SDL_SCANCODE_P); + Input::get()->bindKey(input_up, SDL_SCANCODE_Q); + Input::get()->bindKey(input_down, SDL_SCANCODE_A); } else if (options->keys == ctrl_wasd) { - input->bindKey(input_jump, SDL_SCANCODE_W); - input->bindKey(input_left, SDL_SCANCODE_A); - input->bindKey(input_right, SDL_SCANCODE_D); - input->bindKey(input_up, SDL_SCANCODE_W); - input->bindKey(input_down, SDL_SCANCODE_S); + Input::get()->bindKey(input_jump, SDL_SCANCODE_W); + Input::get()->bindKey(input_left, SDL_SCANCODE_A); + Input::get()->bindKey(input_right, SDL_SCANCODE_D); + Input::get()->bindKey(input_up, SDL_SCANCODE_W); + Input::get()->bindKey(input_down, SDL_SCANCODE_S); } // Teclado - Otros - input->bindKey(input_accept, SDL_SCANCODE_RETURN); - input->bindKey(input_cancel, SDL_SCANCODE_ESCAPE); - input->bindKey(input_pause, SDL_SCANCODE_H); - input->bindKey(input_exit, SDL_SCANCODE_ESCAPE); - input->bindKey(input_window_dec_size, SDL_SCANCODE_F1); - input->bindKey(input_window_inc_size, SDL_SCANCODE_F2); - input->bindKey(input_toggle_videomode, SDL_SCANCODE_F3); - input->bindKey(input_toggle_shaders, SDL_SCANCODE_F4); - input->bindKey(input_toggle_palette, SDL_SCANCODE_F5); - input->bindKey(input_toggle_music, SDL_SCANCODE_M); - input->bindKey(input_toggle_border, SDL_SCANCODE_B); + Input::get()->bindKey(input_accept, SDL_SCANCODE_RETURN); + Input::get()->bindKey(input_cancel, SDL_SCANCODE_ESCAPE); + Input::get()->bindKey(input_pause, SDL_SCANCODE_H); + Input::get()->bindKey(input_exit, SDL_SCANCODE_ESCAPE); + Input::get()->bindKey(input_window_dec_size, SDL_SCANCODE_F1); + Input::get()->bindKey(input_window_inc_size, SDL_SCANCODE_F2); + Input::get()->bindKey(input_toggle_videomode, SDL_SCANCODE_F3); + Input::get()->bindKey(input_toggle_shaders, SDL_SCANCODE_F4); + Input::get()->bindKey(input_toggle_palette, SDL_SCANCODE_F5); + Input::get()->bindKey(input_toggle_music, SDL_SCANCODE_M); + Input::get()->bindKey(input_toggle_border, SDL_SCANCODE_B); // Mando - Movimiento - input->bindGameControllerButton(input_jump, SDL_CONTROLLER_BUTTON_B); - input->bindGameControllerButton(input_left, SDL_CONTROLLER_BUTTON_DPAD_LEFT); - input->bindGameControllerButton(input_right, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); + Input::get()->bindGameControllerButton(input_jump, SDL_CONTROLLER_BUTTON_B); + Input::get()->bindGameControllerButton(input_left, SDL_CONTROLLER_BUTTON_DPAD_LEFT); + Input::get()->bindGameControllerButton(input_right, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); // Mando - Otros - input->bindGameControllerButton(input_accept, SDL_CONTROLLER_BUTTON_B); - input->bindGameControllerButton(input_cancel, SDL_CONTROLLER_BUTTON_A); + Input::get()->bindGameControllerButton(input_accept, SDL_CONTROLLER_BUTTON_B); + Input::get()->bindGameControllerButton(input_cancel, SDL_CONTROLLER_BUTTON_A); #ifdef GAME_CONSOLE - input->bindGameControllerButton(input_pause, SDL_CONTROLLER_BUTTON_BACK); - input->bindGameControllerButton(input_exit, SDL_CONTROLLER_BUTTON_START); + Input::get()->bindGameControllerButton(input_pause, SDL_CONTROLLER_BUTTON_BACK); + Input::get()->bindGameControllerButton(input_exit, SDL_CONTROLLER_BUTTON_START); #else - input->bindGameControllerButton(input_pause, SDL_CONTROLLER_BUTTON_START); - input->bindGameControllerButton(input_exit, SDL_CONTROLLER_BUTTON_BACK); + Input::get()->bindGameControllerButton(input_pause, SDL_CONTROLLER_BUTTON_START); + Input::get()->bindGameControllerButton(input_exit, SDL_CONTROLLER_BUTTON_BACK); #endif - input->bindGameControllerButton(input_toggle_palette, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); - input->bindGameControllerButton(input_toggle_music, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); - input->bindGameControllerButton(input_toggle_border, SDL_CONTROLLER_BUTTON_X); + Input::get()->bindGameControllerButton(input_toggle_palette, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); + Input::get()->bindGameControllerButton(input_toggle_music, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); + Input::get()->bindGameControllerButton(input_toggle_border, SDL_CONTROLLER_BUTTON_X); } // Inicializa JailAudio @@ -1308,8 +1307,8 @@ bool Director::initSDL() incH = options->borderHeight * 2; } - window = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (options->gameWidth + incW) * options->windowSize, (options->gameHeight + incH) * options->windowSize, SDL_WINDOW_HIDDEN); - if (window == nullptr) + window_ = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, (options->gameWidth + incW) * options->windowSize, (options->gameHeight + incH) * options->windowSize, SDL_WINDOW_HIDDEN); + if (window_ == nullptr) { if (options->console) { @@ -1325,9 +1324,9 @@ bool Director::initSDL() { flags = flags | SDL_RENDERER_PRESENTVSYNC; } - renderer = SDL_CreateRenderer(window, -1, flags); + renderer_ = SDL_CreateRenderer(window_, -1, flags); - if (renderer == nullptr) + if (renderer_ == nullptr) { if (options->console) { @@ -1338,13 +1337,13 @@ bool Director::initSDL() else { // Inicializa el color de renderizado - SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF); + SDL_SetRenderDrawColor(renderer_, 0x00, 0x00, 0x00, 0xFF); // Establece el tamaño del buffer de renderizado - SDL_RenderSetLogicalSize(renderer, options->gameWidth, options->gameHeight); + SDL_RenderSetLogicalSize(renderer_, options->gameWidth, options->gameHeight); // Establece el modo de mezcla - SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); + SDL_SetRenderDrawBlendMode(renderer_, SDL_BLENDMODE_BLEND); } } } @@ -1383,10 +1382,10 @@ bool Director::setFileList() Asset::get()->add(prefix + "/data/input/gamecontrollerdb.txt", t_data); // Ficheros de sistema - Asset::get()->add(systemFolder + "/config.txt", t_data, false, true); - Asset::get()->add(systemFolder + "/stats_buffer.csv", t_data, false, true); - Asset::get()->add(systemFolder + "/stats.csv", t_data, false, true); - Asset::get()->add(systemFolder + "/cheevos.bin", t_data, false, true); + Asset::get()->add(system_folder_ + "/config.txt", t_data, false, true); + Asset::get()->add(system_folder_ + "/stats_buffer.csv", t_data, false, true); + Asset::get()->add(system_folder_ + "/stats.csv", t_data, false, true); + Asset::get()->add(system_folder_ + "/cheevos.bin", t_data, false, true); // Notificaciones Asset::get()->add(prefix + "/data/notifications/notify.png", t_bitmap); @@ -1724,9 +1723,9 @@ void Director::runLogo() std::cout << "\n* SECTION: LOGO" << std::endl; } loadResources(section); - auto logo = std::make_unique(renderer, screen, resource, Asset::get(), input, options, section); + auto logo = std::make_unique(resource_, options, section); logo->run(); - resource->free(); + resource_->free(); } // Ejecuta la seccion de juego de la pantalla de carga @@ -1737,9 +1736,9 @@ void Director::runLoadingScreen() std::cout << "\n* SECTION: INTRO" << std::endl; } loadResources(section); - auto loadingScreen = std::make_unique(renderer, screen, resource, Asset::get(), input, options, section); + auto loadingScreen = std::make_unique(resource_, options, section); loadingScreen->run(); - resource->free(); + resource_->free(); } // Ejecuta la seccion de juego con el titulo y los menus @@ -1751,12 +1750,12 @@ void Director::runTitle() } if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED)) { - JA_PlayMusic(music); + JA_PlayMusic(title_music_); } loadResources(section); - auto title = std::make_unique(renderer, screen, resource, input, options, section); + auto title = std::make_unique<Title>(resource_, options, section); title->run(); - resource->free(); + resource_->free(); } // Ejecuta la seccion de los creditos del juego @@ -1767,9 +1766,9 @@ void Director::runCredits() std::cout << "\n* SECTION: CREDITS" << std::endl; } loadResources(section); - auto credits = std::make_unique<Credits>(renderer, screen, resource, Asset::get(), input, options, section); + auto credits = std::make_unique<Credits>(resource_, options, section); credits->run(); - resource->free(); + resource_->free(); } // Ejecuta la seccion de la demo, donde se ven pantallas del juego @@ -1780,9 +1779,9 @@ void Director::runDemo() std::cout << "\n* SECTION: DEMO" << std::endl; } loadResources(section); - auto demo = std::make_unique<Demo>(renderer, screen, resource, Asset::get(), input, options, section, debug); + auto demo = std::make_unique<Demo>(resource_, options, section, debug_); demo->run(); - resource->free(); + resource_->free(); } // Ejecuta la seccion del final del juego @@ -1793,9 +1792,9 @@ void Director::runEnding() std::cout << "\n* SECTION: ENDING" << std::endl; } loadResources(section); - auto ending = std::make_unique<Ending>(renderer, screen, resource, Asset::get(), input, options, section); + auto ending = std::make_unique<Ending>(resource_, options, section); ending->run(); - resource->free(); + resource_->free(); } // Ejecuta la seccion del final del juego @@ -1806,9 +1805,9 @@ void Director::runEnding2() std::cout << "\n* SECTION: ENDING2" << std::endl; } loadResources(section); - auto ending2 = std::make_unique<Ending2>(renderer, screen, resource, Asset::get(), input, options, section); + auto ending2 = std::make_unique<Ending2>(resource_, options, section); ending2->run(); - resource->free(); + resource_->free(); } // Ejecuta la seccion del final de la partida @@ -1819,9 +1818,9 @@ void Director::runGameOver() std::cout << "\n* SECTION: GAME OVER" << std::endl; } loadResources(section); - auto gameOver = std::make_unique<GameOver>(renderer, screen, resource, Asset::get(), input, options, section); + auto gameOver = std::make_unique<GameOver>(resource_, options, section); gameOver->run(); - resource->free(); + resource_->free(); } // Ejecuta la seccion de juego donde se juega @@ -1833,9 +1832,9 @@ void Director::runGame() } JA_StopMusic(); loadResources(section); - auto game = std::make_unique<Game>(renderer, screen, resource, Asset::get(), options, input, section, debug); + auto game = std::make_unique<Game>(resource_, options, section, debug_); game->run(); - resource->free(); + resource_->free(); } int Director::run() diff --git a/source/director.h b/source/director.h index e5aece09..05eadc2f 100644 --- a/source/director.h +++ b/source/director.h @@ -16,19 +16,18 @@ class Director { private: // Objetos y punteros - SDL_Window *window; // La ventana donde dibujamos - SDL_Renderer *renderer; // El renderizador de la ventana - Screen *screen; // Objeto encargado de dibujar en pantalla - Resource *resource; // Objeto con los recursos - Input *input; // Objeto Input para gestionar las entradas - Debug *debug; // Objeto para getsionar la información de debug + SDL_Window *window_; // La ventana donde dibujamos + SDL_Renderer *renderer_; // El renderizador de la ventana + + Resource *resource_; // Objeto con los recursos + Debug *debug_; // Objeto para gestionar la información de debug struct options_t *options; // Variable con todas las opciones del programa section_t *section; // Sección y subsección actual del programa; // Variables - JA_Music_t *music; // Musica del titulo - std::string executablePath; // Path del ejecutable - std::string systemFolder; // Carpeta del sistema donde guardar datos + JA_Music_t *title_music_; // Musica del titulo + std::string executable_path_; // Path del ejecutable + std::string system_folder_; // Carpeta del sistema donde guardar datos // Crea e inicializa las opciones del programa void initOptions(); diff --git a/source/input.cpp b/source/input.cpp index b0b63ba5..99aa7e3d 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -6,31 +6,47 @@ #include <SDL2/SDL_keyboard.h> // Para SDL_GetKeyboardState #include <iostream> // Para basic_ostream, operator<<, cout, basi... -// Constructor -Input::Input(std::string file) -{ - // Fichero gamecontrollerdb.txt - dbPath = file; +// [SINGLETON] +Input *Input::input_ = nullptr; +// [SINGLETON] Crearemos el objeto con esta función estática +void Input::init(const std::string &game_controller_db_path) +{ + Input::input_ = new Input(game_controller_db_path); +} + +// [SINGLETON] Destruiremos el objeto con esta función estática +void Input::destroy() +{ + delete Input::input_; +} + +// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él +Input *Input::get() +{ + return Input::input_; +} + +// Constructor +Input::Input(const std::string &game_controller_db_path) + : db_path_(game_controller_db_path) +{ // Inicializa las variables keyBindings_t kb; kb.scancode = 0; kb.active = false; - keyBindings.resize(input_number_of_inputs, kb); + key_bindings_.resize(input_number_of_inputs, kb); GameControllerBindings_t gcb; gcb.button = SDL_CONTROLLER_BUTTON_INVALID; gcb.active = false; - gameControllerBindings.resize(input_number_of_inputs, gcb); - - verbose = true; - enabled = true; + game_controller_bindings_.resize(input_number_of_inputs, gcb); } // Actualiza el estado del objeto void Input::update() { - if (disabledUntil == d_keyPressed && !checkAnyInput()) + if (disabled_until_ == d_keyPressed && !checkAnyInput()) { enable(); } @@ -39,19 +55,19 @@ void Input::update() // Asigna inputs a teclas void Input::bindKey(Uint8 input, SDL_Scancode code) { - keyBindings[input].scancode = code; + key_bindings_[input].scancode = code; } // Asigna inputs a botones del mando void Input::bindGameControllerButton(Uint8 input, SDL_GameControllerButton button) { - gameControllerBindings[input].button = button; + game_controller_bindings_[input].button = button; } // Comprueba si un input esta activo bool Input::checkInput(Uint8 input, bool repeat, int device, int index) { - if (!enabled) + if (!enabled_) { return false; } @@ -70,7 +86,7 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index) if (repeat) { - if (keyStates[keyBindings[input].scancode] != 0) + if (keyStates[key_bindings_[input].scancode] != 0) { successKeyboard = true; } @@ -81,11 +97,11 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index) } else { - if (!keyBindings[input].active) + if (!key_bindings_[input].active) { - if (keyStates[keyBindings[input].scancode] != 0) + if (keyStates[key_bindings_[input].scancode] != 0) { - keyBindings[input].active = true; + key_bindings_[input].active = true; successKeyboard = true; } else @@ -95,9 +111,9 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index) } else { - if (keyStates[keyBindings[input].scancode] == 0) + if (keyStates[key_bindings_[input].scancode] == 0) { - keyBindings[input].active = false; + key_bindings_[input].active = false; successKeyboard = false; } else @@ -113,7 +129,7 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index) { if (repeat) { - if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[input].button) != 0) + if (SDL_GameControllerGetButton(connected_controllers_[index], game_controller_bindings_[input].button) != 0) { successGameController = true; } @@ -124,11 +140,11 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index) } else { - if (!gameControllerBindings[input].active) + if (!game_controller_bindings_[input].active) { - if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[input].button) != 0) + if (SDL_GameControllerGetButton(connected_controllers_[index], game_controller_bindings_[input].button) != 0) { - gameControllerBindings[input].active = true; + game_controller_bindings_[input].active = true; successGameController = true; } else @@ -138,9 +154,9 @@ bool Input::checkInput(Uint8 input, bool repeat, int device, int index) } else { - if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[input].button) == 0) + if (SDL_GameControllerGetButton(connected_controllers_[index], game_controller_bindings_[input].button) == 0) { - gameControllerBindings[input].active = false; + game_controller_bindings_[input].active = false; successGameController = false; } else @@ -166,9 +182,9 @@ bool Input::checkAnyInput(int device, int index) { const Uint8 *mKeystates = SDL_GetKeyboardState(nullptr); - for (int i = 0; i < (int)keyBindings.size(); ++i) + for (int i = 0; i < (int)key_bindings_.size(); ++i) { - if (mKeystates[keyBindings[i].scancode] != 0) + if (mKeystates[key_bindings_[i].scancode] != 0) { return true; } @@ -179,9 +195,9 @@ bool Input::checkAnyInput(int device, int index) { if (device == INPUT_USE_GAMECONTROLLER || device == INPUT_USE_ANY) { - for (int i = 0; i < (int)gameControllerBindings.size(); ++i) + for (int i = 0; i < (int)game_controller_bindings_.size(); ++i) { - if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[i].button) != 0) + if (SDL_GameControllerGetButton(connected_controllers_[index], game_controller_bindings_[i].button) != 0) { return true; } @@ -202,56 +218,56 @@ bool Input::discoverGameController() SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER); } - if (SDL_GameControllerAddMappingsFromFile(dbPath.c_str()) < 0) + if (SDL_GameControllerAddMappingsFromFile(db_path_.c_str()) < 0) { - if (verbose) + if (verbose_) { - std::cout << "Error, could not load " << dbPath.c_str() << " file: " << SDL_GetError() << std::endl; + std::cout << "Error, could not load " << db_path_.c_str() << " file: " << SDL_GetError() << std::endl; } } const int nJoysticks = SDL_NumJoysticks(); - numGamepads = 0; + num_gamepads_ = 0; // Cuenta el numero de mandos for (int i = 0; i < nJoysticks; ++i) { if (SDL_IsGameController(i)) { - numGamepads++; + num_gamepads_++; } } - if (verbose) + if (verbose_) { std::cout << "\nChecking for game controllers...\n"; - std::cout << nJoysticks << " joysticks found, " << numGamepads << " are gamepads\n"; + std::cout << nJoysticks << " joysticks found, " << num_gamepads_ << " are gamepads\n"; } - if (numGamepads > 0) + if (num_gamepads_ > 0) { found = true; - for (int i = 0; i < numGamepads; i++) + for (int i = 0; i < num_gamepads_; i++) { // Abre el mando y lo añade a la lista SDL_GameController *pad = SDL_GameControllerOpen(i); if (SDL_GameControllerGetAttached(pad) == 1) { - connectedControllers.push_back(pad); + connected_controllers_.push_back(pad); const std::string separator(" #"); std::string name = SDL_GameControllerNameForIndex(i); name.resize(25); name = name + separator + std::to_string(i); - if (verbose) + if (verbose_) { std::cout << name << std::endl; } - controllerNames.push_back(name); + controller_names_.push_back(name); } else { - if (verbose) + if (verbose_) { std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl; } @@ -267,7 +283,7 @@ bool Input::discoverGameController() // Comprueba si hay algun mando conectado bool Input::gameControllerFound() { - if (numGamepads > 0) + if (num_gamepads_ > 0) { return true; } @@ -280,9 +296,9 @@ bool Input::gameControllerFound() // Obten el nombre de un mando de juego std::string Input::getControllerName(int index) { - if (numGamepads > 0) + if (num_gamepads_ > 0) { - return controllerNames[index]; + return controller_names_[index]; } else { @@ -293,25 +309,25 @@ std::string Input::getControllerName(int index) // Obten el numero de mandos conectados int Input::getNumControllers() { - return numGamepads; + return num_gamepads_; } // Establece si ha de mostrar mensajes void Input::setVerbose(bool value) { - verbose = value; + verbose_ = value; } // Deshabilita las entradas durante un periodo de tiempo void Input::disableUntil(i_disable_e value) { - disabledUntil = value; - enabled = false; + disabled_until_ = value; + enabled_ = false; } // Hablita las entradas void Input::enable() { - enabled = true; - disabledUntil = d_notDisabled; + enabled_ = true; + disabled_until_ = d_notDisabled; } \ No newline at end of file diff --git a/source/input.h b/source/input.h index dc2f47b1..23c42ce0 100644 --- a/source/input.h +++ b/source/input.h @@ -52,6 +52,9 @@ enum i_disable_e class Input { private: + // [SINGLETON] Objeto privado + static Input *input_; + struct keyBindings_t { Uint8 scancode; // Scancode asociado @@ -65,21 +68,33 @@ private: }; // Objetos y punteros - std::vector<SDL_GameController *> connectedControllers; // Vector con todos los mandos conectados + std::vector<SDL_GameController *> connected_controllers_; // Vector con todos los mandos conectados // Variables - std::vector<keyBindings_t> keyBindings; // Vector con las teclas asociadas a los inputs predefinidos - std::vector<GameControllerBindings_t> gameControllerBindings; // Vector con las teclas asociadas a los inputs predefinidos - std::vector<std::string> controllerNames; // Vector con los nombres de los mandos - int numGamepads; // Numero de mandos conectados - std::string dbPath; // Ruta al archivo gamecontrollerdb.txt - bool verbose; // Indica si ha de mostrar mensajes - i_disable_e disabledUntil; // Tiempo que esta deshabilitado - bool enabled; // Indica si está habilitado + std::vector<keyBindings_t> key_bindings_; // Vector con las teclas asociadas a los inputs predefinidos + std::vector<GameControllerBindings_t> game_controller_bindings_; // Vector con las teclas asociadas a los inputs predefinidos + std::vector<std::string> controller_names_; // Vector con los nombres de los mandos + int num_gamepads_; // Numero de mandos conectados + std::string db_path_; // Ruta al archivo gamecontrollerdb.txt + bool verbose_ = true; // Indica si ha de mostrar mensajes + i_disable_e disabled_until_; // Tiempo que esta deshabilitado + bool enabled_ = true; // Indica si está habilitado + + // Constructor + explicit Input(const std::string &game_controller_db_path); + + // Destructor + ~Input() = default; public: - // Constructor - Input(std::string file); + // [SINGLETON] Crearemos el objeto con esta función estática + static void init(const std::string &game_controller_db_path); + + // [SINGLETON] Destruiremos el objeto con esta función estática + static void destroy(); + + // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él + static Input *get(); // Actualiza el estado del objeto void update(); diff --git a/source/loading_screen.cpp b/source/loading_screen.cpp index d170ea14..a37064d7 100644 --- a/source/loading_screen.cpp +++ b/source/loading_screen.cpp @@ -12,78 +12,70 @@ #include "utils.h" // for options_t, section_t, color_t, stringToC... // Constructor -LoadingScreen::LoadingScreen(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section) -{ - // Copia la dirección de los objetos - this->resource = resource; - this->renderer = renderer; - this->screen = screen; - this->asset = asset; - this->input = input; - this->options = options; - this->section = section; +LoadingScreen::LoadingScreen(Resource *resource, options_t *options, section_t *section) + : resource_(resource), + screen_(Screen::get()), + renderer_(Screen::get()->getRenderer()), + asset_(Asset::get()), + input_(Input::get()), + options_(options), + section_(section) +{ // Reserva memoria para los punteros eventHandler = new SDL_Event(); if (options->palette == p_zxspectrum) { - loadingScreenTexture1 = resource->getTexture("loading_screen_bn.png"); - loadingScreenTexture2 = resource->getTexture("loading_screen_color.png"); + mono_loading_screen_texture_ = resource->getTexture("loading_screen_bn.png"); + color_loading_screen_texture_ = resource->getTexture("loading_screen_color.png"); } else if (options->palette == p_zxarne) { - loadingScreenTexture1 = resource->getTexture("loading_screen_bn_zxarne.png"); - loadingScreenTexture2 = resource->getTexture("loading_screen_color_zxarne.png"); + mono_loading_screen_texture_ = resource->getTexture("loading_screen_bn_zxarne.png"); + color_loading_screen_texture_ = resource->getTexture("loading_screen_color_zxarne.png"); } - sprite1 = new Sprite(0, 0, loadingScreenTexture1->getWidth(), loadingScreenTexture1->getHeight(), loadingScreenTexture1, renderer); - sprite2 = new Sprite(0, 0, loadingScreenTexture2->getWidth(), loadingScreenTexture2->getHeight(), loadingScreenTexture2, renderer); - loadingSound1 = JA_LoadMusic(asset->get("loading_sound1.ogg").c_str()); - loadingSound2 = JA_LoadMusic(asset->get("loading_sound2.ogg").c_str()); - loadingSound3 = JA_LoadMusic(asset->get("loading_sound3.ogg").c_str()); + mono_loading_screen_sprite_ = new Sprite(0, 0, mono_loading_screen_texture_->getWidth(), mono_loading_screen_texture_->getHeight(), mono_loading_screen_texture_, renderer_); + color_loading_screen_sprite_ = new Sprite(0, 0, color_loading_screen_texture_->getWidth(), color_loading_screen_texture_->getHeight(), color_loading_screen_texture_, renderer_); + loading_sound1_ = JA_LoadMusic(asset_->get("loading_sound1.ogg").c_str()); + loading_sound2_ = JA_LoadMusic(asset_->get("loading_sound2.ogg").c_str()); + loading_sound3_ = JA_LoadMusic(asset_->get("loading_sound3.ogg").c_str()); // Inicializa variables - preCounter = 0; - counter = 0; section->name = SECTION_LOADING_SCREEN; section->subsection = 0; - ticks = 0; - ticksSpeed = 15; - loadCounter = 0; - loadingFirstPart = true; - loadRect = {0, 0, 51, 1}; // Establece el orden de las lineas para imitar el direccionamiento de memoria del spectrum for (int i = 0; i < 192; ++i) { if (i < 64) { // Primer bloque de 2K - lineIndex[i] = ((i % 8) * 8) + (i / 8); + line_index_[i] = ((i % 8) * 8) + (i / 8); } else if (i >= 64 && i < 128) { // Segundo bloque de 2K - lineIndex[i] = 64 + ((i % 8) * 8) + ((i - 64) / 8); + line_index_[i] = 64 + ((i % 8) * 8) + ((i - 64) / 8); } else if (i >= 128 && i < 192) { // tercer bloque de 2K - lineIndex[i] = 128 + ((i % 8) * 8) + ((i - 128) / 8); + line_index_[i] = 128 + ((i % 8) * 8) + ((i - 128) / 8); } } // Cambia el color del borde - screen->setBorderColor(stringToColor(options->palette, "black")); + screen_->setBorderColor(stringToColor(options->palette, "black")); } // Destructor LoadingScreen::~LoadingScreen() { - delete sprite1; - delete sprite2; + delete mono_loading_screen_sprite_; + delete color_loading_screen_sprite_; delete eventHandler; - JA_DeleteMusic(loadingSound1); - JA_DeleteMusic(loadingSound2); - JA_DeleteMusic(loadingSound3); + JA_DeleteMusic(loading_sound1_); + JA_DeleteMusic(loading_sound2_); + JA_DeleteMusic(loading_sound3_); } // Comprueba el manejador de eventos @@ -95,7 +87,7 @@ void LoadingScreen::checkEvents() // Evento de salida de la aplicación if (eventHandler->type == SDL_QUIT) { - section->name = SECTION_QUIT; + section_->name = SECTION_QUIT; break; } } @@ -105,40 +97,40 @@ void LoadingScreen::checkEvents() void LoadingScreen::checkInput() { - if (input->checkInput(input_exit, REPEAT_FALSE)) + if (input_->checkInput(input_exit, REPEAT_FALSE)) { - section->name = SECTION_QUIT; + section_->name = SECTION_QUIT; } - else if (input->checkInput(input_toggle_border, REPEAT_FALSE)) + else if (input_->checkInput(input_toggle_border, REPEAT_FALSE)) { - screen->toggleBorder(); + screen_->toggleBorder(); } - else if (input->checkInput(input_toggle_videomode, REPEAT_FALSE)) + else if (input_->checkInput(input_toggle_videomode, REPEAT_FALSE)) { - screen->toggleVideoMode(); + screen_->toggleVideoMode(); } - else if (input->checkInput(input_window_dec_size, REPEAT_FALSE)) + else if (input_->checkInput(input_window_dec_size, REPEAT_FALSE)) { - screen->decWindowSize(); + screen_->decWindowSize(); } - else if (input->checkInput(input_window_inc_size, REPEAT_FALSE)) + else if (input_->checkInput(input_window_inc_size, REPEAT_FALSE)) { - screen->incWindowSize(); + screen_->incWindowSize(); } - else if (input->checkInput(input_toggle_palette, REPEAT_FALSE)) + else if (input_->checkInput(input_toggle_palette, REPEAT_FALSE)) { switchPalette(); } - else if (input->checkInput(input_pause, REPEAT_FALSE) || input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_jump, REPEAT_FALSE)) + else if (input_->checkInput(input_pause, REPEAT_FALSE) || input_->checkInput(input_accept, REPEAT_FALSE) || input_->checkInput(input_jump, REPEAT_FALSE)) { - section->name = SECTION_TITLE; - section->subsection = 0; + section_->name = SECTION_TITLE; + section_->subsection = 0; } } @@ -146,45 +138,45 @@ void LoadingScreen::checkInput() void LoadingScreen::updateLoad() { // Primera parte de la carga, la parte en blanco y negro - if (loadingFirstPart) + if (loading_first_part_) { // Cada 5 pasos el loadCounter se incrementa en uno const int numSteps = 5; const int step = 51; - loadCounter = counter / numSteps; + load_counter_ = counter_ / numSteps; - if (loadCounter < 192) + if (load_counter_ < 192) { - loadRect.x = step * (counter % numSteps); - loadRect.y = lineIndex[loadCounter]; - sprite1->setSpriteClip(loadRect); - sprite1->setRect(loadRect); + load_rect_.x = step * (counter_ % numSteps); + load_rect_.y = line_index_[load_counter_]; + mono_loading_screen_sprite_->setSpriteClip(load_rect_); + mono_loading_screen_sprite_->setRect(load_rect_); } // Una vez actualizadas las 192 lineas, pasa a la segunda fase de la carga - else if (loadCounter == 192) + else if (load_counter_ == 192) { - loadingFirstPart = false; - loadCounter = 0; - loadRect = {0, 0, 16, 8}; - sprite2->setRect(loadRect); - sprite2->setSpriteClip(loadRect); - JA_PlayMusic(loadingSound3); + loading_first_part_ = false; + load_counter_ = 0; + load_rect_ = {0, 0, 16, 8}; + color_loading_screen_sprite_->setRect(load_rect_); + color_loading_screen_sprite_->setSpriteClip(load_rect_); + JA_PlayMusic(loading_sound3_); } } // Segunda parte de la carga, la parte de los bloques en color else { - loadCounter += 2; - loadRect.x = (loadCounter * 8) % 256; - loadRect.y = (loadCounter / 32) * 8; - sprite2->setSpriteClip(loadRect); - sprite2->setRect(loadRect); + load_counter_ += 2; + load_rect_.x = (load_counter_ * 8) % 256; + load_rect_.y = (load_counter_ / 32) * 8; + color_loading_screen_sprite_->setSpriteClip(load_rect_); + color_loading_screen_sprite_->setRect(load_rect_); // Comprueba si ha terminado la intro - if (loadCounter >= 768) + if (load_counter_ >= 768) { - section->name = SECTION_TITLE; - section->subsection = SUBSECTION_TITLE_WITH_LOADING_SCREEN; + section_->name = SECTION_TITLE; + section_->subsection = SUBSECTION_TITLE_WITH_LOADING_SCREEN; JA_StopMusic(); } } @@ -193,33 +185,33 @@ void LoadingScreen::updateLoad() // Gestiona el contador interno void LoadingScreen::updateCounter() { - (preCounter >= 50) ? counter++ : preCounter++; + (pre_counter_ >= 50) ? counter_++ : pre_counter_++; - if (counter == 1) + if (counter_ == 1) { - JA_PlayMusic(loadingSound2); + JA_PlayMusic(loading_sound2_); } } // Dibuja la pantalla de carga void LoadingScreen::renderLoad() { - loadingFirstPart ? sprite1->render() : sprite2->render(); + loading_first_part_ ? mono_loading_screen_sprite_->render() : color_loading_screen_sprite_->render(); } // Dibuja el efecto de carga en el borde void LoadingScreen::renderBorder() { // Pinta el borde de colro azul - color_t color = stringToColor(options->palette, "blue"); - SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF); - SDL_RenderClear(renderer); + color_t color = stringToColor(options_->palette, "blue"); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); + SDL_RenderClear(renderer_); // Añade lineas amarillas - color = stringToColor(options->palette, "yellow"); - SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF); - const int width = GAMECANVAS_WIDTH + (options->borderWidth * 2); - const int height = GAMECANVAS_HEIGHT + (options->borderHeight * 2); + color = stringToColor(options_->palette, "yellow"); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); + const int width = GAMECANVAS_WIDTH + (options_->borderWidth * 2); + const int height = GAMECANVAS_HEIGHT + (options_->borderHeight * 2); bool drawEnabled = rand() % 2 == 0 ? true : false; // Para (int i = 0; i < height; ++i) //{ @@ -236,7 +228,7 @@ void LoadingScreen::renderBorder() if (drawEnabled) for (int i = row; i < row + rowSize; ++i) { - SDL_RenderDrawLine(renderer, 0, i, width, i); + SDL_RenderDrawLine(renderer_, 0, i, width, i); } row += rowSize; drawEnabled = !drawEnabled; @@ -247,10 +239,10 @@ void LoadingScreen::renderBorder() void LoadingScreen::update() { // Comprueba que la diferencia de ticks sea mayor a la velocidad del juego - if (SDL_GetTicks() - ticks > ticksSpeed) + if (SDL_GetTicks() - ticks_ > ticks_speed_) { // Actualiza el contador de ticks - ticks = SDL_GetTicks(); + ticks_ = SDL_GetTicks(); // Comprueba las entradas checkInput(); @@ -262,30 +254,30 @@ void LoadingScreen::update() updateLoad(); // Actualiza las notificaciones - screen->updateNotifier(); + screen_->updateNotifier(); } } // Dibuja en pantalla void LoadingScreen::render() { - if (options->borderEnabled) + if (options_->borderEnabled) { // Prepara para empezar a dibujar en la textura del borde - screen->startDrawOnBorder(); + screen_->startDrawOnBorder(); // Dibuja el efecto de carga en el borde renderBorder(); } // Prepara para empezar a dibujar en la textura de juego - screen->start(); + screen_->start(); // Dibuja la pantalla de carga renderLoad(); // Vuelca el contenido del renderizador en pantalla - screen->render(); + screen_->render(); } // Bucle para el logo del juego @@ -293,14 +285,14 @@ void LoadingScreen::run() { // Inicia el sonido de carga JA_SetVolume(64); - JA_PlayMusic(loadingSound1); + JA_PlayMusic(loading_sound1_); // Limpia la pantalla - screen->start(); - screen->clean(); - screen->render(); + screen_->start(); + screen_->clean(); + screen_->render(); - while (section->name == SECTION_LOADING_SCREEN) + while (section_->name == SECTION_LOADING_SCREEN) { update(); checkEvents(); @@ -313,17 +305,17 @@ void LoadingScreen::run() // Cambia la paleta void LoadingScreen::switchPalette() { - if (options->palette == p_zxspectrum) + if (options_->palette == p_zxspectrum) { - options->palette = p_zxarne; - sprite1->setTexture(resource->getTexture("loading_screen_bn_zxarne.png")); - sprite2->setTexture(resource->getTexture("loading_screen_color_zxarne.png")); + options_->palette = p_zxarne; + mono_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_bn_zxarne.png")); + color_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_color_zxarne.png")); } else { - options->palette = p_zxspectrum; - sprite1->setTexture(resource->getTexture("loading_screen_bn.png")); - sprite2->setTexture(resource->getTexture("loading_screen_color.png")); + options_->palette = p_zxspectrum; + mono_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_bn.png")); + color_loading_screen_sprite_->setTexture(resource_->getTexture("loading_screen_color.png")); } recreateLoadingScreen(); @@ -333,37 +325,37 @@ void LoadingScreen::switchPalette() void LoadingScreen::recreateLoadingScreen() { // Prepara para empezar a dibujar en la textura de juego - screen->start(); + screen_->start(); // Primera parte de la carga, la parte en blanco y negro - if (loadingFirstPart) + if (loading_first_part_) { const int numSteps = 5; const int step = 51; - for (int i = 0; i <= counter; i++) + for (int i = 0; i <= counter_; i++) { - loadCounter = i / numSteps; - loadRect.x = step * (i % numSteps); - loadRect.y = lineIndex[loadCounter]; - sprite1->setSpriteClip(loadRect); - sprite1->setRect(loadRect); - sprite1->render(); + load_counter_ = i / numSteps; + load_rect_.x = step * (i % numSteps); + load_rect_.y = line_index_[load_counter_]; + mono_loading_screen_sprite_->setSpriteClip(load_rect_); + mono_loading_screen_sprite_->setRect(load_rect_); + mono_loading_screen_sprite_->render(); } } // Segunda parte de la carga, la parte de los bloques en color else { - for (int i = 0; i <= loadCounter; i++) + for (int i = 0; i <= load_counter_; i++) { - loadRect.x = (i * 8) % 256; - loadRect.y = (i / 32) * 8; - sprite2->setSpriteClip(loadRect); - sprite2->setRect(loadRect); - sprite2->render(); + load_rect_.x = (i * 8) % 256; + load_rect_.y = (i / 32) * 8; + color_loading_screen_sprite_->setSpriteClip(load_rect_); + color_loading_screen_sprite_->setRect(load_rect_); + color_loading_screen_sprite_->render(); } } // Vuelca el contenido del renderizador en pantalla - screen->render(); + screen_->render(); } \ No newline at end of file diff --git a/source/loading_screen.h b/source/loading_screen.h index 898b860a..69caef1c 100644 --- a/source/loading_screen.h +++ b/source/loading_screen.h @@ -18,31 +18,31 @@ class LoadingScreen { private: // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana - Screen *screen; // Objeto encargado de dibujar en pantalla - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto con los ficheros de recursos - Input *input; // Objeto pata gestionar la entrada - Texture *loadingScreenTexture1; // Textura con la pantalla de carga en blanco y negro - Texture *loadingScreenTexture2; // Textura con la pantalla de carga en color - SDL_Event *eventHandler; // Manejador de eventos - Sprite *sprite1; // Sprite para manejar la textura loadingScreenTexture1 - Sprite *sprite2; // Sprite para manejar la textura loadingScreenTexture2 - options_t *options; // Puntero a las opciones del juego - section_t *section; // Estado del bucle principal para saber si continua o se sale + SDL_Renderer *renderer_; // El renderizador de la ventana + Screen *screen_; // Objeto encargado de dibujar en pantalla + Resource *resource_; // Objeto con los recursos + Asset *asset_; // Objeto con los ficheros de recursos + Input *input_; // Objeto pata gestionar la entrada + Texture *mono_loading_screen_texture_; // Textura con la pantalla de carga en blanco y negro + Texture *color_loading_screen_texture_; // Textura con la pantalla de carga en color + SDL_Event *eventHandler; // Manejador de eventos + Sprite *mono_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture1 + Sprite *color_loading_screen_sprite_; // Sprite para manejar la textura loadingScreenTexture2 + options_t *options_; // Puntero a las opciones del juego + section_t *section_; // Estado del bucle principal para saber si continua o se sale // Variables - int preCounter; // Contador previo para realizar una pausa inicial - int counter; // Contador - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - int loadCounter; // Contador para controlar las cargas - bool loadingFirstPart; // Para saber en que parte de la carga se encuentra - JA_Music_t *loadingSound1; // Sonidos para imitar la carga tipo spectrum - JA_Music_t *loadingSound2; // Sonidos para imitar la carga tipo spectrum - JA_Music_t *loadingSound3; // Sonidos para imitar la carga tipo spectrum - int lineIndex[192]; // El orden en el que se procesan las 192 lineas de la pantalla de carga - SDL_Rect loadRect; // Rectangulo para dibujar la pantalla de carga + int pre_counter_ = 0; // Contador previo para realizar una pausa inicial + int counter_ = 0; // Contador + Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticks_speed_ = 15; // Velocidad a la que se repiten los bucles del programa + int load_counter_ = 0; // Contador para controlar las cargas + bool loading_first_part_ = true; // Para saber en que parte de la carga se encuentra + JA_Music_t *loading_sound1_; // Sonidos para imitar la carga tipo spectrum + JA_Music_t *loading_sound2_; // Sonidos para imitar la carga tipo spectrum + JA_Music_t *loading_sound3_; // Sonidos para imitar la carga tipo spectrum + int line_index_[192]; // El orden en el que se procesan las 192 lineas de la pantalla de carga + SDL_Rect load_rect_ = {0, 0, 51, 1}; // Rectangulo para dibujar la pantalla de carga // Actualiza las variables void update(); @@ -76,7 +76,7 @@ private: public: // Constructor - LoadingScreen(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section); + LoadingScreen(Resource *resource, options_t *options, section_t *section); // Destructor ~LoadingScreen(); diff --git a/source/logo.cpp b/source/logo.cpp index cca04041..77a7eb0a 100644 --- a/source/logo.cpp +++ b/source/logo.cpp @@ -9,86 +9,79 @@ #include "sprite.h" // for Sprite #include "texture.h" // for Texture #include "utils.h" // for color_t, section_t, options_t, stringToC... -class Asset; // lines 11-11 +#include "asset.h" +class Asset; // lines 11-11 // Constructor -Logo::Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section) +Logo::Logo(Resource *resource, options_t *options, section_t *section) + : resource_(resource), + screen_(Screen::get()), + renderer_(Screen::get()->getRenderer()), + asset_(Asset::get()), + input_(Input::get()), + options_(options), + section_(section) { - // Copia la dirección de los objetos - this->resource = resource; - this->renderer = renderer; - this->screen = screen; - this->asset = asset; - this->input = input; - this->options = options; - this->section = section; - // Reserva memoria para los punteros - eventHandler = new SDL_Event(); - texture = resource->getTexture("jailgames.png"); - texture2 = resource->getTexture("since_1998.png"); - sprite2 = new Sprite((256 - texture2->getWidth()) / 2, 83 + texture->getHeight() + 5, texture2->getWidth(), texture2->getHeight(), texture2, renderer); - sprite2->setSpriteClip(0, 0, texture2->getWidth(), texture2->getHeight()); - texture2->setColor(0, 0, 0); + event_handler_ = new SDL_Event(); + jailgames_texture_ = resource->getTexture("jailgames.png"); + since_1998_texture_ = resource->getTexture("since_1998.png"); + since_1998_sprite_ = new Sprite((256 - since_1998_texture_->getWidth()) / 2, 83 + jailgames_texture_->getHeight() + 5, since_1998_texture_->getWidth(), since_1998_texture_->getHeight(), since_1998_texture_, renderer_); + since_1998_sprite_->setSpriteClip(0, 0, since_1998_texture_->getWidth(), since_1998_texture_->getHeight()); + since_1998_texture_->setColor(0, 0, 0); // Crea los sprites de cada linea - for (int i = 0; i < texture->getHeight(); ++i) + for (int i = 0; i < jailgames_texture_->getHeight(); ++i) { - sprite.push_back(new Sprite(0, i, texture->getWidth(), 1, texture, renderer)); - sprite.back()->setSpriteClip(0, i, texture->getWidth(), 1); + jailgames_sprite_.push_back(new Sprite(0, i, jailgames_texture_->getWidth(), 1, jailgames_texture_, renderer_)); + jailgames_sprite_.back()->setSpriteClip(0, i, jailgames_texture_->getWidth(), 1); if (i % 2 == 0) { - sprite[i]->setPosX(256 + (i * 3)); + jailgames_sprite_[i]->setPosX(256 + (i * 3)); } else { - sprite[i]->setPosX(-181 - (i * 3)); + jailgames_sprite_[i]->setPosX(-181 - (i * 3)); } - sprite[i]->setPosY(83 + i); + jailgames_sprite_[i]->setPosY(83 + i); } // Inicializa variables - counter = 0; section->name = SECTION_LOGO; - ticks = 0; - ticksSpeed = 15; - initFade = 300; - endLogo = 400; - postLogo = 20; // Inicializa el vector de colores const std::vector<std::string> vColors = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"}; for (auto v : vColors) { - color.push_back(stringToColor(options->palette, v)); + color_.push_back(stringToColor(options->palette, v)); } // Cambia el color del borde - screen->setBorderColor(stringToColor(options->palette, "black")); + screen_->setBorderColor(stringToColor(options->palette, "black")); } // Destructor Logo::~Logo() { - for (auto s : sprite) + for (auto s : jailgames_sprite_) { delete s; } - delete sprite2; - delete eventHandler; + delete since_1998_sprite_; + delete event_handler_; } // Comprueba el manejador de eventos void Logo::checkEvents() { // Comprueba los eventos que hay en la cola - while (SDL_PollEvent(eventHandler) != 0) + while (SDL_PollEvent(event_handler_) != 0) { // Evento de salida de la aplicación - if (eventHandler->type == SDL_QUIT) + if (event_handler_->type == SDL_QUIT) { - section->name = SECTION_QUIT; + section_->name = SECTION_QUIT; break; } } @@ -97,39 +90,39 @@ void Logo::checkEvents() // Comprueba las entradas void Logo::checkInput() { - if (input->checkInput(input_exit, REPEAT_FALSE)) + if (input_->checkInput(input_exit, REPEAT_FALSE)) { - section->name = SECTION_TITLE; + section_->name = SECTION_TITLE; } - else if (input->checkInput(input_toggle_border, REPEAT_FALSE)) + else if (input_->checkInput(input_toggle_border, REPEAT_FALSE)) { - screen->toggleBorder(); + screen_->toggleBorder(); } - else if (input->checkInput(input_toggle_videomode, REPEAT_FALSE)) + else if (input_->checkInput(input_toggle_videomode, REPEAT_FALSE)) { - screen->toggleVideoMode(); + screen_->toggleVideoMode(); } - else if (input->checkInput(input_window_dec_size, REPEAT_FALSE)) + else if (input_->checkInput(input_window_dec_size, REPEAT_FALSE)) { - screen->decWindowSize(); + screen_->decWindowSize(); } - else if (input->checkInput(input_window_inc_size, REPEAT_FALSE)) + else if (input_->checkInput(input_window_inc_size, REPEAT_FALSE)) { - screen->incWindowSize(); + screen_->incWindowSize(); } - else if (input->checkInput(input_toggle_palette, REPEAT_FALSE)) + else if (input_->checkInput(input_toggle_palette, REPEAT_FALSE)) { switchPalette(); } - else if (input->checkInput(input_pause, REPEAT_FALSE) || input->checkInput(input_accept, REPEAT_FALSE) || input->checkInput(input_jump, REPEAT_FALSE)) + else if (input_->checkInput(input_pause, REPEAT_FALSE) || input_->checkInput(input_accept, REPEAT_FALSE) || input_->checkInput(input_jump, REPEAT_FALSE)) { - section->subsection = SUBSECTION_LOGO_TO_TITLE; + section_->subsection = SUBSECTION_LOGO_TO_TITLE; endSection(); } } @@ -137,28 +130,28 @@ void Logo::checkInput() // Gestiona el logo de JAILGAME void Logo::updateJAILGAMES() { - if (counter > 30) + if (counter_ > 30) { - for (int i = 1; i < (int)sprite.size(); ++i) + for (int i = 1; i < (int)jailgames_sprite_.size(); ++i) { const int speed = 8; const int dest = 37; - if (sprite[i]->getPosX() != 37) + if (jailgames_sprite_[i]->getPosX() != 37) { if (i % 2 == 0) { - sprite[i]->incPosX(-speed); - if (sprite[i]->getPosX() < dest) + jailgames_sprite_[i]->incPosX(-speed); + if (jailgames_sprite_[i]->getPosX() < dest) { - sprite[i]->setPosX(dest); + jailgames_sprite_[i]->setPosX(dest); } } else { - sprite[i]->incPosX(speed); - if (sprite[i]->getPosX() > dest) + jailgames_sprite_[i]->incPosX(speed); + if (jailgames_sprite_[i]->getPosX() > dest) { - sprite[i]->setPosX(dest); + jailgames_sprite_[i]->setPosX(dest); } } } @@ -172,86 +165,86 @@ void Logo::updateTextureColors() const int ini = 70; const int inc = 4; - if (counter == ini + inc * 0) + if (counter_ == ini + inc * 0) { - texture2->setColor(color[0].r, color[0].g, color[0].b); + since_1998_texture_->setColor(color_[0].r, color_[0].g, color_[0].b); } - else if (counter == ini + inc * 1) + else if (counter_ == ini + inc * 1) { - texture2->setColor(color[1].r, color[1].g, color[1].b); + since_1998_texture_->setColor(color_[1].r, color_[1].g, color_[1].b); } - else if (counter == ini + inc * 2) + else if (counter_ == ini + inc * 2) { - texture2->setColor(color[2].r, color[2].g, color[2].b); + since_1998_texture_->setColor(color_[2].r, color_[2].g, color_[2].b); } - else if (counter == ini + inc * 3) + else if (counter_ == ini + inc * 3) { - texture2->setColor(color[3].r, color[3].g, color[3].b); + since_1998_texture_->setColor(color_[3].r, color_[3].g, color_[3].b); } - else if (counter == ini + inc * 4) + else if (counter_ == ini + inc * 4) { - texture2->setColor(color[4].r, color[4].g, color[4].b); + since_1998_texture_->setColor(color_[4].r, color_[4].g, color_[4].b); } - else if (counter == ini + inc * 5) + else if (counter_ == ini + inc * 5) { - texture2->setColor(color[5].r, color[5].g, color[5].b); + since_1998_texture_->setColor(color_[5].r, color_[5].g, color_[5].b); } - else if (counter == ini + inc * 6) + else if (counter_ == ini + inc * 6) { - texture2->setColor(color[6].r, color[6].g, color[6].b); + since_1998_texture_->setColor(color_[6].r, color_[6].g, color_[6].b); } - else if (counter == ini + inc * 7) + else if (counter_ == ini + inc * 7) { - texture2->setColor(color[7].r, color[7].g, color[7].b); + since_1998_texture_->setColor(color_[7].r, color_[7].g, color_[7].b); } - else if (counter == initFade + inc * 0) + else if (counter_ == init_fade_ + inc * 0) { - texture->setColor(color[6].r, color[6].g, color[6].b); - texture2->setColor(color[6].r, color[6].g, color[6].b); + jailgames_texture_->setColor(color_[6].r, color_[6].g, color_[6].b); + since_1998_texture_->setColor(color_[6].r, color_[6].g, color_[6].b); } - else if (counter == initFade + inc * 1) + else if (counter_ == init_fade_ + inc * 1) { - texture->setColor(color[5].r, color[5].g, color[5].b); - texture2->setColor(color[5].r, color[5].g, color[5].b); + jailgames_texture_->setColor(color_[5].r, color_[5].g, color_[5].b); + since_1998_texture_->setColor(color_[5].r, color_[5].g, color_[5].b); } - else if (counter == initFade + inc * 2) + else if (counter_ == init_fade_ + inc * 2) { - texture->setColor(color[4].r, color[4].g, color[4].b); - texture2->setColor(color[4].r, color[4].g, color[4].b); + jailgames_texture_->setColor(color_[4].r, color_[4].g, color_[4].b); + since_1998_texture_->setColor(color_[4].r, color_[4].g, color_[4].b); } - else if (counter == initFade + inc * 3) + else if (counter_ == init_fade_ + inc * 3) { - texture->setColor(color[3].r, color[3].g, color[3].b); - texture2->setColor(color[3].r, color[3].g, color[3].b); + jailgames_texture_->setColor(color_[3].r, color_[3].g, color_[3].b); + since_1998_texture_->setColor(color_[3].r, color_[3].g, color_[3].b); } - else if (counter == initFade + inc * 4) + else if (counter_ == init_fade_ + inc * 4) { - texture->setColor(color[2].r, color[2].g, color[2].b); - texture2->setColor(color[2].r, color[2].g, color[2].b); + jailgames_texture_->setColor(color_[2].r, color_[2].g, color_[2].b); + since_1998_texture_->setColor(color_[2].r, color_[2].g, color_[2].b); } - else if (counter == initFade + inc * 5) + else if (counter_ == init_fade_ + inc * 5) { - texture->setColor(color[1].r, color[1].g, color[1].b); - texture2->setColor(color[1].r, color[1].g, color[1].b); + jailgames_texture_->setColor(color_[1].r, color_[1].g, color_[1].b); + since_1998_texture_->setColor(color_[1].r, color_[1].g, color_[1].b); } - else if (counter == initFade + inc * 6) + else if (counter_ == init_fade_ + inc * 6) { - texture->setColor(color[0].r, color[0].g, color[0].b); - texture2->setColor(color[0].r, color[0].g, color[0].b); + jailgames_texture_->setColor(color_[0].r, color_[0].g, color_[0].b); + since_1998_texture_->setColor(color_[0].r, color_[0].g, color_[0].b); } } @@ -259,16 +252,16 @@ void Logo::updateTextureColors() void Logo::update() { // Comprueba que la diferencia de ticks sea mayor a la velocidad del juego - if (SDL_GetTicks() - ticks > ticksSpeed) + if (SDL_GetTicks() - ticks_ > ticks_speed_) { // Actualiza el contador de ticks - ticks = SDL_GetTicks(); + ticks_ = SDL_GetTicks(); // Comprueba las entradas checkInput(); // Incrementa el contador - counter++; + counter_++; // Gestiona el logo de JAILGAME updateJAILGAMES(); @@ -277,10 +270,10 @@ void Logo::update() updateTextureColors(); // Actualiza las notificaciones - screen->updateNotifier(); + screen_->updateNotifier(); // Comprueba si ha terminado el logo - if (counter == endLogo + postLogo) + if (counter_ == end_logo_ + post_logo_) { endSection(); } @@ -291,20 +284,20 @@ void Logo::update() void Logo::render() { // Prepara para empezar a dibujar en la textura de juego - screen->start(); + screen_->start(); // Limpia la pantalla - screen->clean(); + screen_->clean(); // Dibuja los objetos - for (auto s : sprite) + for (auto s : jailgames_sprite_) { s->render(); } - sprite2->render(); + since_1998_sprite_->render(); // Vuelca el contenido del renderizador en pantalla - screen->render(); + screen_->render(); } // Bucle para el logo del juego @@ -313,7 +306,7 @@ void Logo::run() // Detiene la música JA_StopMusic(); - while (section->name == SECTION_LOGO) + while (section_->name == SECTION_LOGO) { update(); checkEvents(); @@ -324,19 +317,19 @@ void Logo::run() // Cambia la paleta void Logo::switchPalette() { - options->palette = options->palette == p_zxspectrum ? p_zxarne : p_zxspectrum; + options_->palette = options_->palette == p_zxspectrum ? p_zxarne : p_zxspectrum; } // Termina la sección void Logo::endSection() { - if (section->subsection == SUBSECTION_LOGO_TO_TITLE) + if (section_->subsection == SUBSECTION_LOGO_TO_TITLE) { - section->name = SECTION_TITLE; + section_->name = SECTION_TITLE; } - else if (section->subsection == SUBSECTION_LOGO_TO_INTRO) + else if (section_->subsection == SUBSECTION_LOGO_TO_INTRO) { - section->name = SECTION_LOADING_SCREEN; + section_->name = SECTION_LOADING_SCREEN; } } \ No newline at end of file diff --git a/source/logo.h b/source/logo.h index 6975355d..1224f41c 100644 --- a/source/logo.h +++ b/source/logo.h @@ -18,27 +18,27 @@ class Logo { private: // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana - Screen *screen; // Objeto encargado de dibujar en pantalla - Resource *resource; // Objeto con los recursos - Asset *asset; // Objeto con los ficheros de recursos - Input *input; // Objeto pata gestionar la entrada - Texture *texture; // Textura con los graficos "JAILGAMES" - Texture *texture2; // Textura con los graficos "Since 1998" - SDL_Event *eventHandler; // Manejador de eventos - std::vector<Sprite *> sprite; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES - Sprite *sprite2; // Sprite para manejar la textura2 - options_t *options; // Puntero a las opciones del juego - section_t *section; // Estado del bucle principal para saber si continua o se sale + SDL_Renderer *renderer_; // El renderizador de la ventana + Screen *screen_; // Objeto encargado de dibujar en pantalla + Resource *resource_; // Objeto con los recursos + Asset *asset_; // Objeto con los ficheros de recursos + Input *input_; // Objeto pata gestionar la entrada + Texture *jailgames_texture_; // Textura con los graficos "JAILGAMES" + Texture *since_1998_texture_; // Textura con los graficos "Since 1998" + SDL_Event *event_handler_; // Manejador de eventos + std::vector<Sprite *> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES + Sprite *since_1998_sprite_; // Sprite para manejar la textura2 + options_t *options_; // Puntero a las opciones del juego + section_t *section_; // Estado del bucle principal para saber si continua o se sale // Variables - std::vector<color_t> color; // Vector con los colores para el fade - int counter; // Contador - Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa - int initFade; // Tiempo del contador cuando inicia el fade a negro - int endLogo; // Tiempo del contador para terminar el logo - int postLogo; // Tiempo que dura el logo con el fade al maximo + std::vector<color_t> color_; // Vector con los colores para el fade + int counter_ = 0; // Contador + Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa + Uint32 ticks_speed_ = 15; // Velocidad a la que se repiten los bucles del programa + int init_fade_ = 300; // Tiempo del contador cuando inicia el fade a negro + int end_logo_ = 400; // Tiempo del contador para terminar el logo + int post_logo_ = 20; // Tiempo que dura el logo con el fade al maximo // Actualiza las variables void update(); @@ -66,7 +66,7 @@ private: public: // Constructor - Logo(SDL_Renderer *renderer, Screen *screen, Resource *resource, Asset *asset, Input *input, options_t *options, section_t *section); + Logo(Resource *resource, options_t *options, section_t *section); // Destructor ~Logo(); diff --git a/source/resource.cpp b/source/resource.cpp index 9cbabdcc..cfc64c36 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -8,37 +8,30 @@ #include "text.h" // Para textFile_t, LoadTextFile #include "texture.h" // Para Texture #include "utils.h" // Para options_t - -// Constructor -Resource::Resource(SDL_Renderer *renderer, Asset *asset, options_t *options) -{ - this->renderer = renderer; - this->asset = asset; - this->options = options; -} +#include "screen.h" // Carga las texturas de una lista void Resource::loadTextures(std::vector<std::string> list) { for (auto l : list) { - if (options->console) + if (options_->console) { std::cout << "\nLOAD TEXTURE: " << l << std::endl; - std::cout << "png: " << asset->get(l) << std::endl; + std::cout << "png: " << Asset::get()->get(l) << std::endl; } res_texture_t t; t.name = l; - t.texture = new Texture(renderer, asset->get(t.name), options->console); - textures.push_back(t); + t.texture = new Texture(Screen::get()->getRenderer(), Asset::get()->get(t.name), options_->console); + textures_.push_back(t); } } // Vuelve a cargar las texturas void Resource::reLoadTextures() { - for (auto texture : textures) + for (auto texture : textures_) { texture.texture->reLoad(); } @@ -52,17 +45,17 @@ void Resource::loadAnimations(std::vector<std::string> list) // Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura const std::string pngFile = l.substr(0, l.find_last_of(".")) + ".png"; - if (options->console) + if (options_->console) { std::cout << "\nLOAD ANIMATION: " << l << std::endl; - std::cout << "png: " << asset->get(pngFile) << std::endl; - std::cout << "ani: " << asset->get(l) << std::endl; + std::cout << "png: " << Asset::get()->get(pngFile) << std::endl; + std::cout << "ani: " << Asset::get()->get(l) << std::endl; } res_animation_t as; as.name = l; - as.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), asset->get(as.name), options->console)); - animations.push_back(as); + as.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(as.name), options_->console)); + animations_.push_back(as); } } @@ -71,12 +64,12 @@ void Resource::reLoadAnimations() { // reLoadTextures(); - for (auto &a : animations) + for (auto &a : animations_) { // Extrae el nombre del fichero sin la extension para crear el nombre del fichero de la textura const std::string pngFile = a.name.substr(0, a.name.find_last_of(".")) + ".png"; delete a.animation; - a.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), asset->get(a.name), options->console)); + a.animation = new animatedSprite_t(loadAnimationFromFile(getTexture(pngFile), Asset::get()->get(a.name), options_->console)); } } @@ -87,18 +80,18 @@ void Resource::loadOffsets(std::vector<std::string> list) { res_textOffset_t to; to.name = l; - to.textFile = new textFile_t(LoadTextFile(asset->get(l), options->console)); - offsets.push_back(to); + to.textFile = new textFile_t(LoadTextFile(Asset::get()->get(l), options_->console)); + offsets_.push_back(to); } } // Vuelve a cargar los offsets void Resource::reLoadOffsets() { - for (auto &o : offsets) + for (auto &o : offsets_) { delete o.textFile; - o.textFile = new textFile_t(LoadTextFile(asset->get(o.name), options->console)); + o.textFile = new textFile_t(LoadTextFile(Asset::get()->get(o.name), options_->console)); } } @@ -109,18 +102,18 @@ void Resource::loadTileMaps(std::vector<std::string> list) { res_tileMap_t tm; tm.name = l; - tm.tileMap = new std::vector<int>(loadRoomTileFile(asset->get(l), options->console)); - tileMaps.push_back(tm); + tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(l), options_->console)); + tile_maps_.push_back(tm); } } // Vuelve a cargar los mapas de tiles void Resource::reLoadTileMaps() { - for (auto &tm : tileMaps) + for (auto &tm : tile_maps_) { delete tm.tileMap; - tm.tileMap = new std::vector<int>(loadRoomTileFile(asset->get(tm.name), options->console)); + tm.tileMap = new std::vector<int>(loadRoomTileFile(Asset::get()->get(tm.name), options_->console)); } } @@ -131,7 +124,7 @@ void Resource::loadRooms(std::vector<std::string> list) { res_room_t r; r.name = l; - r.room = new room_t(loadRoomFile(asset->get(l), options->console)); + r.room = new room_t(loadRoomFile(Asset::get()->get(l), options_->console)); r.room->tileMap = getTileMap(r.room->tileMapFile); for (auto &e : r.room->enemies) { @@ -143,7 +136,7 @@ void Resource::loadRooms(std::vector<std::string> list) } r.room->textureA = getTexture("standard.png"); r.room->textureB = getTexture("standard_zxarne.png"); - rooms.push_back(r); + rooms_.push_back(r); } } @@ -152,10 +145,10 @@ void Resource::reLoadRooms() { reLoadTileMaps(); - for (auto &r : rooms) + for (auto &r : rooms_) { delete r.room; - r.room = new room_t(loadRoomFile(asset->get(r.name))); + r.room = new room_t(loadRoomFile(Asset::get()->get(r.name))); r.room->tileMap = getTileMap(r.room->tileMapFile); for (auto &e : r.room->enemies) { @@ -181,51 +174,51 @@ void Resource::reLoad() // Libera las texturas void Resource::freeTextures() { - for (auto texture : textures) + for (auto texture : textures_) { delete texture.texture; } - textures.clear(); + textures_.clear(); } // Libera las animaciones void Resource::freeAnimations() { - for (auto a : animations) + for (auto a : animations_) { delete a.animation; } - animations.clear(); + animations_.clear(); } // Libera los offsets void Resource::freeOffsets() { - for (auto o : offsets) + for (auto o : offsets_) { delete o.textFile; } - offsets.clear(); + offsets_.clear(); } // Libera los mapas de tiles void Resource::freeTileMaps() { - for (auto t : tileMaps) + for (auto t : tile_maps_) { delete t.tileMap; } - tileMaps.clear(); + tile_maps_.clear(); } // Libera las habitaciones void Resource::freeRooms() { - for (auto r : rooms) + for (auto r : rooms_) { delete r.room; } - rooms.clear(); + rooms_.clear(); } // Libera todos los recursos @@ -241,7 +234,7 @@ void Resource::free() // Obtiene una textura Texture *Resource::getTexture(std::string name) { - for (auto texture : textures) + for (auto texture : textures_) { // if (texture.name.find(name) != std::string::npos) if (texture.name == name) @@ -253,7 +246,7 @@ Texture *Resource::getTexture(std::string name) } } - if (options->console) + if (options_->console) { std::cout << "NOT FOUND ON CACHE: " << name << std::endl; } @@ -263,7 +256,7 @@ Texture *Resource::getTexture(std::string name) // Obtiene una animación animatedSprite_t *Resource::getAnimation(std::string name) { - for (auto animation : animations) + for (auto animation : animations_) { // if (animation.name.find(name) != std::string::npos) if (animation.name == name) @@ -274,7 +267,7 @@ animatedSprite_t *Resource::getAnimation(std::string name) } } - if (options->console) + if (options_->console) { std::cout << "NOT FOUND ON CACHE: " << name << std::endl; } @@ -284,7 +277,7 @@ animatedSprite_t *Resource::getAnimation(std::string name) // Obtiene un offset textFile_t *Resource::getOffset(std::string name) { - for (auto offset : offsets) + for (auto offset : offsets_) { // if (offset.name.find(name) != std::string::npos) if (offset.name == name) @@ -293,7 +286,7 @@ textFile_t *Resource::getOffset(std::string name) } } - if (options->console) + if (options_->console) { std::cout << "NOT FOUND ON CACHE: " << name << std::endl; } @@ -303,7 +296,7 @@ textFile_t *Resource::getOffset(std::string name) // Obtiene un mapa de tiles std::vector<int> *Resource::getTileMap(std::string name) { - for (auto tileMap : tileMaps) + for (auto tileMap : tile_maps_) { // if (tileMap.name.find(name) != std::string::npos) if (tileMap.name == name) @@ -312,7 +305,7 @@ std::vector<int> *Resource::getTileMap(std::string name) } } - if (options->console) + if (options_->console) { std::cout << "NOT FOUND ON CACHE: " << name << std::endl; } @@ -322,7 +315,7 @@ std::vector<int> *Resource::getTileMap(std::string name) // Obtiene una habitacion room_t *Resource::getRoom(std::string name) { - for (auto room : rooms) + for (auto room : rooms_) { // if (room.name.find(name) != std::string::npos) if (room.name == name) @@ -331,7 +324,7 @@ room_t *Resource::getRoom(std::string name) } } - if (options->console) + if (options_->console) { std::cout << "NOT FOUND ON CACHE: " << name << std::endl; } @@ -341,5 +334,5 @@ room_t *Resource::getRoom(std::string name) // Obtiene todas las habitaciones std::vector<res_room_t> *Resource::getAllRooms() { - return &rooms; + return &rooms_; } \ No newline at end of file diff --git a/source/resource.h b/source/resource.h index eeaa01bf..65d2e718 100644 --- a/source/resource.h +++ b/source/resource.h @@ -45,20 +45,19 @@ class Resource { private: // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana - Asset *asset; // Objeto con la ruta a todos los ficheros de recursos - options_t *options; // Puntero a las opciones del juego + options_t *options_; // Puntero a las opciones del juego // Variables - std::vector<res_texture_t> textures; - std::vector<res_animation_t> animations; - std::vector<res_textOffset_t> offsets; - std::vector<res_tileMap_t> tileMaps; - std::vector<res_room_t> rooms; + std::vector<res_texture_t> textures_; + std::vector<res_animation_t> animations_; + std::vector<res_textOffset_t> offsets_; + std::vector<res_tileMap_t> tile_maps_; + std::vector<res_room_t> rooms_; public: // Constructor - Resource(SDL_Renderer *renderer, Asset *asset, options_t *options); + Resource(options_t *options) + : options_(options) {} // Carga las texturas de una lista void loadTextures(std::vector<std::string> list); diff --git a/source/screen.cpp b/source/screen.cpp index 82665af3..84221919 100644 --- a/source/screen.cpp +++ b/source/screen.cpp @@ -12,55 +12,73 @@ #include "jail_shader.h" // Para init, render #include "notify.h" // Para Notify -// Constructor -Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options_t *options) +// [SINGLETON] +Screen *Screen::screen_ = nullptr; + +// [SINGLETON] Crearemos el objeto con esta función estática +void Screen::init(SDL_Window *window, SDL_Renderer *renderer) { - // Inicializa variables - this->window = window; - this->renderer = renderer; - this->options = options; - this->asset = asset; + Screen::screen_ = new Screen(window, renderer); +} +// [SINGLETON] Destruiremos el objeto con esta función estática +void Screen::destroy() +{ + delete Screen::screen_; +} + +// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él +Screen *Screen::get() +{ + return Screen::screen_; +} + +// Constructor +Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) + : window_(window), + renderer_(renderer), + asset_(Asset::get()) +{ // Crea los objetos - notify = new Notify(renderer, asset->get("notify.png"), asset->get("smb2.png"), asset->get("smb2.txt"), asset->get("notify.wav"), options); + notify_ = new Notify(renderer, asset_->get("notify.png"), asset_->get("smb2.png"), asset_->get("smb2.txt"), asset_->get("notify.wav"), options_); - gameCanvasWidth = options->gameWidth; - gameCanvasHeight = options->gameHeight; - notificationLogicalWidth = gameCanvasWidth; - notificationLogicalHeight = gameCanvasHeight; + game_canvas_width_ = options_->gameWidth; + game_canvas_height_ = options_->gameHeight; + notification_logical_width_ = game_canvas_width_; + notification_logical_height_ = game_canvas_height_; iniFade(); iniSpectrumFade(); // Define el color del borde para el modo de pantalla completa - borderColor = {0x00, 0x00, 0x00}; + border_color_ = {0x00, 0x00, 0x00}; // Crea la textura donde se dibujan los graficos del juego - gameCanvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, gameCanvasWidth, gameCanvasHeight); - if (gameCanvas == nullptr) + game_canvas_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, game_canvas_width_, game_canvas_height_); + if (game_canvas_ == nullptr) { - if (options->console) + if (options_->console) { std::cout << "gameCanvas could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } // Crea la textura donde se dibuja el borde que rodea el area de juego - borderCanvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, gameCanvasWidth + options->borderWidth * 2, gameCanvasHeight + options->borderHeight * 2); - if (borderCanvas == nullptr) + border_canvas_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, game_canvas_width_ + options_->borderWidth * 2, game_canvas_height_ + options_->borderHeight * 2); + if (border_canvas_ == nullptr) { - if (options->console) + if (options_->console) { std::cout << "borderCanvas could not be created!\nSDL Error: " << SDL_GetError() << std::endl; } } - setBorderColor(borderColor); + setBorderColor(border_color_); // Establece el modo de video - setVideoMode(options->videoMode); + setVideoMode(options_->videoMode); // Inicializa variables - notifyActive = false; + notify_active_ = false; // Muestra la ventana SDL_ShowWindow(window); @@ -69,28 +87,28 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options // Destructor Screen::~Screen() { - delete notify; - SDL_DestroyTexture(gameCanvas); - SDL_DestroyTexture(borderCanvas); + delete notify_; + SDL_DestroyTexture(game_canvas_); + SDL_DestroyTexture(border_canvas_); } // Limpia la pantalla void Screen::clean(color_t color) { - SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF); - SDL_RenderClear(renderer); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, 0xFF); + SDL_RenderClear(renderer_); } // Prepara para empezar a dibujar en la textura de juego void Screen::start() { - SDL_SetRenderTarget(renderer, gameCanvas); + SDL_SetRenderTarget(renderer_, game_canvas_); } // Prepara para empezar a dibujar en la textura del borde void Screen::startDrawOnBorder() { - SDL_SetRenderTarget(renderer, borderCanvas); + SDL_SetRenderTarget(renderer_, border_canvas_); } // Vuelca el contenido del renderizador en pantalla @@ -100,7 +118,7 @@ void Screen::render() renderNotifications(); // Si está el borde activo, vuelca gameCanvas sobre borderCanvas - if (options->borderEnabled) + if (options_->borderEnabled) { gameCanvasToBorderCanvas(); } @@ -113,7 +131,7 @@ void Screen::render() void Screen::setVideoMode(int videoMode) { // Aplica el modo de video - SDL_SetWindowFullscreen(window, videoMode); + SDL_SetWindowFullscreen(window_, videoMode); // Modo ventana if (videoMode == 0) @@ -122,23 +140,23 @@ void Screen::setVideoMode(int videoMode) SDL_ShowCursor(SDL_ENABLE); // Modifica el tamaño de la ventana en función del borde - if (options->borderEnabled) + if (options_->borderEnabled) { - windowWidth = gameCanvasWidth + options->borderWidth * 2; - windowHeight = gameCanvasHeight + options->borderHeight * 2; - dest = {options->borderWidth, options->borderHeight, gameCanvasWidth, gameCanvasHeight}; + window_width_ = game_canvas_width_ + options_->borderWidth * 2; + window_height_ = game_canvas_height_ + options_->borderHeight * 2; + dest_ = {options_->borderWidth, options_->borderHeight, game_canvas_width_, game_canvas_height_}; } else { - windowWidth = gameCanvasWidth; - windowHeight = gameCanvasHeight; - dest = {0, 0, gameCanvasWidth, gameCanvasHeight}; + window_width_ = game_canvas_width_; + window_height_ = game_canvas_height_; + dest_ = {0, 0, game_canvas_width_, game_canvas_height_}; } // Modifica el tamaño de la ventana - SDL_SetWindowSize(window, windowWidth * options->windowSize, windowHeight * options->windowSize); - SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); + SDL_SetWindowSize(window_, window_width_ * options_->windowSize, window_height_ * options_->windowSize); + SDL_SetWindowPosition(window_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); } // Si está activo el modo de pantalla completa añade el borde @@ -148,74 +166,74 @@ void Screen::setVideoMode(int videoMode) SDL_ShowCursor(SDL_DISABLE); // Obten el alto y el ancho de la ventana - SDL_GetWindowSize(window, &windowWidth, &windowHeight); + SDL_GetWindowSize(window_, &window_width_, &window_height_); // Aplica el escalado al rectangulo donde se pinta la textura del juego - if (options->integerScale) + if (options_->integerScale) { // Calcula el tamaño de la escala máxima int scale = 0; - while (((gameCanvasWidth * (scale + 1)) <= windowWidth) && ((gameCanvasHeight * (scale + 1)) <= windowHeight)) + while (((game_canvas_width_ * (scale + 1)) <= window_width_) && ((game_canvas_height_ * (scale + 1)) <= window_height_)) { scale++; } - dest.w = gameCanvasWidth * scale; - dest.h = gameCanvasHeight * scale; - dest.x = (windowWidth - dest.w) / 2; - dest.y = (windowHeight - dest.h) / 2; + dest_.w = game_canvas_width_ * scale; + dest_.h = game_canvas_height_ * scale; + dest_.x = (window_width_ - dest_.w) / 2; + dest_.y = (window_height_ - dest_.h) / 2; } - else if (options->keepAspect) + else if (options_->keepAspect) { - float ratio = (float)gameCanvasWidth / (float)gameCanvasHeight; - if ((windowWidth - gameCanvasWidth) >= (windowHeight - gameCanvasHeight)) + float ratio = (float)game_canvas_width_ / (float)game_canvas_height_; + if ((window_width_ - game_canvas_width_) >= (window_height_ - game_canvas_height_)) { - dest.h = windowHeight; - dest.w = (int)((windowHeight * ratio) + 0.5f); - dest.x = (windowWidth - dest.w) / 2; - dest.y = (windowHeight - dest.h) / 2; + dest_.h = window_height_; + dest_.w = (int)((window_height_ * ratio) + 0.5f); + dest_.x = (window_width_ - dest_.w) / 2; + dest_.y = (window_height_ - dest_.h) / 2; } else { - dest.w = windowWidth; - dest.h = (int)((windowWidth / ratio) + 0.5f); - dest.x = (windowWidth - dest.w) / 2; - dest.y = (windowHeight - dest.h) / 2; + dest_.w = window_width_; + dest_.h = (int)((window_width_ / ratio) + 0.5f); + dest_.x = (window_width_ - dest_.w) / 2; + dest_.y = (window_height_ - dest_.h) / 2; } } else { - dest.w = windowWidth; - dest.h = windowHeight; - dest.x = dest.y = 0; + dest_.w = window_width_; + dest_.h = window_height_; + dest_.x = dest_.y = 0; } } // Modifica el tamaño del renderizador - SDL_RenderSetLogicalSize(renderer, windowWidth, windowHeight); + SDL_RenderSetLogicalSize(renderer_, window_width_, window_height_); // Actualiza las opciones - options->videoMode = videoMode; - options->screen.windowWidth = windowWidth; - options->screen.windowHeight = windowHeight; + options_->videoMode = videoMode; + options_->screen.windowWidth = window_width_; + options_->screen.windowHeight = window_height_; // Establece el tamaño de las notificaciones setNotificationSize(); // Reinicia los shaders - if (options->shaders) + if (options_->shaders) { - const std::string glsl_file = options->screen.windowHeight == 192 ? "crtpi_192.glsl" : "crtpi_240.glsl"; - std::ifstream f(asset->get(glsl_file).c_str()); + const std::string glsl_file = options_->screen.windowHeight == 192 ? "crtpi_192.glsl" : "crtpi_240.glsl"; + std::ifstream f(asset_->get(glsl_file).c_str()); std::string source((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); - if (options->borderEnabled) + if (options_->borderEnabled) { - shader::init(window, borderCanvas, source.c_str()); + shader::init(window_, border_canvas_, source.c_str()); } else { - shader::init(window, gameCanvas, source.c_str()); + shader::init(window_, game_canvas_, source.c_str()); } } } @@ -223,85 +241,85 @@ void Screen::setVideoMode(int videoMode) // Camibia entre pantalla completa y ventana void Screen::toggleVideoMode() { - options->videoMode = (options->videoMode == 0) ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0; - setVideoMode(options->videoMode); + options_->videoMode = (options_->videoMode == 0) ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0; + setVideoMode(options_->videoMode); } // Cambia el tamaño de la ventana void Screen::setWindowSize(int size) { - options->windowSize = size; + options_->windowSize = size; setVideoMode(0); } // Reduce el tamaño de la ventana void Screen::decWindowSize() { - --options->windowSize; - options->windowSize = std::max(options->windowSize, 1); + --options_->windowSize; + options_->windowSize = std::max(options_->windowSize, 1); setVideoMode(0); } // Aumenta el tamaño de la ventana void Screen::incWindowSize() { - ++options->windowSize; - options->windowSize = std::min(options->windowSize, 4); + ++options_->windowSize; + options_->windowSize = std::min(options_->windowSize, 4); setVideoMode(0); } // Cambia el color del borde void Screen::setBorderColor(color_t color) { - borderColor = color; - auto temp = SDL_GetRenderTarget(renderer); - SDL_SetRenderTarget(renderer, borderCanvas); - SDL_SetRenderDrawColor(renderer, borderColor.r, borderColor.g, borderColor.b, 0xFF); - SDL_RenderClear(renderer); - SDL_SetRenderTarget(renderer, temp); + border_color_ = color; + auto temp = SDL_GetRenderTarget(renderer_); + SDL_SetRenderTarget(renderer_, border_canvas_); + SDL_SetRenderDrawColor(renderer_, border_color_.r, border_color_.g, border_color_.b, 0xFF); + SDL_RenderClear(renderer_); + SDL_SetRenderTarget(renderer_, temp); } // Cambia el tipo de mezcla void Screen::setBlendMode(SDL_BlendMode blendMode) { - SDL_SetRenderDrawBlendMode(renderer, blendMode); + SDL_SetRenderDrawBlendMode(renderer_, blendMode); } // Establece el tamaño del borde void Screen::setBorderWidth(int s) { - options->borderWidth = s; + options_->borderWidth = s; } // Establece el tamaño del borde void Screen::setBorderHeight(int s) { - options->borderHeight = s; + options_->borderHeight = s; } // Establece si se ha de ver el borde en el modo ventana void Screen::setBorderEnabled(bool value) { - options->borderEnabled = value; + options_->borderEnabled = value; } // Cambia entre borde visible y no visible void Screen::toggleBorder() { - options->borderEnabled = !options->borderEnabled; + options_->borderEnabled = !options_->borderEnabled; setVideoMode(0); } // Activa el fade void Screen::setFade() { - fade = true; + fade_ = true; } // Comprueba si ha terminado el fade bool Screen::fadeEnded() { - if (fade || fadeCounter > 0) + if (fade_ || fade_counter_ > 0) { return false; } @@ -312,13 +330,13 @@ bool Screen::fadeEnded() // Activa el spectrum fade void Screen::setspectrumFade() { - spectrumFade = true; + spectrum_fade_ = true; } // Comprueba si ha terminado el spectrum fade bool Screen::spectrumFadeEnded() { - if (spectrumFade || spectrumFadeCounter > 0) + if (spectrum_fade_ || spectrum_fade_counter_ > 0) { return false; } @@ -329,21 +347,21 @@ bool Screen::spectrumFadeEnded() // Inicializa las variables para el fade void Screen::iniFade() { - fade = false; - fadeCounter = 0; - fadeLenght = 200; + fade_ = false; + fade_counter_ = 0; + fade_lenght_ = 200; } // Actualiza el fade void Screen::updateFade() { - if (!fade) + if (!fade_) { return; } - fadeCounter++; - if (fadeCounter > fadeLenght) + fade_counter_++; + if (fade_counter_ > fade_lenght_) { iniFade(); } @@ -352,65 +370,65 @@ void Screen::updateFade() // Dibuja el fade void Screen::renderFade() { - if (!fade) + if (!fade_) { return; } - const SDL_Rect rect = {0, 0, gameCanvasWidth, gameCanvasHeight}; + const SDL_Rect rect = {0, 0, game_canvas_width_, game_canvas_height_}; color_t color = {0, 0, 0}; - const float step = (float)fadeCounter / (float)fadeLenght; + const float step = (float)fade_counter_ / (float)fade_lenght_; const int alpha = 0 + (255 - 0) * step; - SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, alpha); - SDL_RenderFillRect(renderer, &rect); + SDL_SetRenderDrawColor(renderer_, color.r, color.g, color.b, alpha); + SDL_RenderFillRect(renderer_, &rect); } // Inicializa las variables para el fade spectrum void Screen::iniSpectrumFade() { - spectrumFade = false; - spectrumFadeCounter = 0; - spectrumFadeLenght = 50; + spectrum_fade_ = false; + spectrum_fade_counter_ = 0; + spectrum_fade_lenght_ = 50; - spectrumColor.clear(); + spectrum_color_.clear(); // Inicializa el vector de colores const std::vector<std::string> vColors = {"black", "blue", "red", "magenta", "green", "cyan", "yellow", "bright_white"}; for (auto v : vColors) { - spectrumColor.push_back(stringToColor(options->palette, v)); + spectrum_color_.push_back(stringToColor(options_->palette, v)); } } // Actualiza el spectrum fade void Screen::updateSpectrumFade() { - if (!spectrumFade) + if (!spectrum_fade_) { return; } - spectrumFadeCounter++; - if (spectrumFadeCounter > spectrumFadeLenght) + spectrum_fade_counter_++; + if (spectrum_fade_counter_ > spectrum_fade_lenght_) { iniSpectrumFade(); - SDL_SetTextureColorMod(gameCanvas, 255, 255, 255); + SDL_SetTextureColorMod(game_canvas_, 255, 255, 255); } } // Dibuja el spectrum fade void Screen::renderSpectrumFade() { - if (!spectrumFade) + if (!spectrum_fade_) { return; } - const float step = (float)spectrumFadeCounter / (float)spectrumFadeLenght; - const int max = spectrumColor.size() - 1; + const float step = (float)spectrum_fade_counter_ / (float)spectrum_fade_lenght_; + const int max = spectrum_color_.size() - 1; const int index = max + (0 - max) * step; - const color_t c = spectrumColor[index]; - SDL_SetTextureColorMod(gameCanvas, c.r, c.g, c.b); + const color_t c = spectrum_color_[index]; + SDL_SetTextureColorMod(game_canvas_, c.r, c.g, c.b); } // Actualiza los efectos @@ -430,89 +448,89 @@ void Screen::renderFX() // Actualiza el notificador void Screen::updateNotifier() { - notify->update(); - notifyActive = notify->active(); + notify_->update(); + notify_active_ = notify_->active(); } // Muestra una notificación de texto por pantalla; void Screen::showNotification(std::string text1, std::string text2, int icon) { - notify->showText(text1, text2, icon); + notify_->showText(text1, text2, icon); } // Dibuja las notificaciones void Screen::renderNotifications() { - if (notifyActive) + if (notify_active_) { - notify->render(); + notify_->render(); } } // Establece el tamaño de las notificaciones void Screen::setNotificationSize() { - if (options->videoMode == 0) + if (options_->videoMode == 0) { - if (options->windowSize == 3) + if (options_->windowSize == 3) { - notificationLogicalWidth = (windowWidth * 3) / 2; - notificationLogicalHeight = (windowHeight * 3) / 2; + notification_logical_width_ = (window_width_ * 3) / 2; + notification_logical_height_ = (window_height_ * 3) / 2; } else { - notificationLogicalWidth = windowWidth * 2; - notificationLogicalHeight = windowHeight * 2; + notification_logical_width_ = window_width_ * 2; + notification_logical_height_ = window_height_ * 2; } } - if (options->videoMode == SDL_WINDOW_FULLSCREEN_DESKTOP) + if (options_->videoMode == SDL_WINDOW_FULLSCREEN_DESKTOP) { - notificationLogicalWidth = windowWidth / 3; - notificationLogicalHeight = windowHeight / 3; + notification_logical_width_ = window_width_ / 3; + notification_logical_height_ = window_height_ / 3; } } // Copia el gameCanvas en el borderCanvas void Screen::gameCanvasToBorderCanvas() { - auto temp = SDL_GetRenderTarget(renderer); - SDL_SetRenderTarget(renderer, borderCanvas); - SDL_SetRenderDrawColor(renderer, borderColor.r, borderColor.g, borderColor.b, 0xFF); - SDL_RenderClear(renderer); - SDL_RenderCopy(renderer, gameCanvas, nullptr, &dest); - SDL_SetRenderTarget(renderer, temp); + auto temp = SDL_GetRenderTarget(renderer_); + SDL_SetRenderTarget(renderer_, border_canvas_); + SDL_SetRenderDrawColor(renderer_, border_color_.r, border_color_.g, border_color_.b, 0xFF); + SDL_RenderClear(renderer_); + SDL_RenderCopy(renderer_, game_canvas_, nullptr, &dest_); + SDL_SetRenderTarget(renderer_, temp); } // Muestra el contenido de Screen por pantalla void Screen::renderPresent() { - SDL_SetRenderTarget(renderer, nullptr); - SDL_SetRenderDrawColor(renderer, borderColor.r, borderColor.g, borderColor.b, 0xFF); - SDL_RenderClear(renderer); + SDL_SetRenderTarget(renderer_, nullptr); + SDL_SetRenderDrawColor(renderer_, border_color_.r, border_color_.g, border_color_.b, 0xFF); + SDL_RenderClear(renderer_); - if (options->shaders) + if (options_->shaders) { // Aplica shaders y renderiza el contenido shader::render(); } else { - if (options->borderEnabled) + if (options_->borderEnabled) { - SDL_RenderCopy(renderer, borderCanvas, nullptr, nullptr); + SDL_RenderCopy(renderer_, border_canvas_, nullptr, nullptr); } else { - SDL_RenderCopy(renderer, gameCanvas, nullptr, &dest); + SDL_RenderCopy(renderer_, game_canvas_, nullptr, &dest_); } - SDL_RenderPresent(renderer); + SDL_RenderPresent(renderer_); } } // Cambia el estado de los shaders void Screen::toggleShaders() { - options->shaders = !options->shaders; - setVideoMode(options->videoMode); + options_->shaders = !options_->shaders; + setVideoMode(options_->videoMode); } \ No newline at end of file diff --git a/source/screen.h b/source/screen.h index 1cb26613..cef9d80e 100644 --- a/source/screen.h +++ b/source/screen.h @@ -16,34 +16,37 @@ constexpr int FILTER_LINEAR = 1; class Screen { private: + // [SINGLETON] Objeto privado + static Screen *screen_; + // Objetos y punteros - SDL_Window *window; // Ventana de la aplicación - SDL_Renderer *renderer; // El renderizador de la ventana - Asset *asset; // Objeto con el listado de recursos - SDL_Texture *gameCanvas; // Textura donde se dibuja el juego - SDL_Texture *borderCanvas; // Textura donde se dibuja el borde del juego - options_t *options; // Variable con todas las opciones del programa - Notify *notify; // Dibuja notificaciones por pantalla + SDL_Window *window_; // Ventana de la aplicación + SDL_Renderer *renderer_; // El renderizador de la ventana + Asset *asset_; // Objeto con el listado de recursos + SDL_Texture *game_canvas_; // Textura donde se dibuja el juego + SDL_Texture *border_canvas_; // Textura donde se dibuja el borde del juego + options_t *options_; // Variable con todas las opciones del programa + Notify *notify_; // Dibuja notificaciones por pantalla // Variables - int windowWidth; // Ancho de la pantalla o ventana - int windowHeight; // Alto de la pantalla o ventana - int gameCanvasWidth; // Resolución interna del juego. Es el ancho de la textura donde se dibuja el juego - int gameCanvasHeight; // Resolución interna del juego. Es el alto de la textura donde se dibuja el juego - SDL_Rect dest; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana - color_t borderColor; // Color del borde añadido a la textura de juego para rellenar la pantalla - bool notifyActive; // Indica si hay notificaciones activas - int notificationLogicalWidth; // Ancho lógico de las notificaciones en relación al tamaño de pantalla - int notificationLogicalHeight; // Alto lógico de las notificaciones en relación al tamaño de pantalla + int window_width_; // Ancho de la pantalla o ventana + int window_height_; // Alto de la pantalla o ventana + int game_canvas_width_; // Resolución interna del juego. Es el ancho de la textura donde se dibuja el juego + int game_canvas_height_; // Resolución interna del juego. Es el alto de la textura donde se dibuja el juego + SDL_Rect dest_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana + color_t border_color_; // Color del borde añadido a la textura de juego para rellenar la pantalla + bool notify_active_; // Indica si hay notificaciones activas + int notification_logical_width_; // Ancho lógico de las notificaciones en relación al tamaño de pantalla + int notification_logical_height_; // Alto lógico de las notificaciones en relación al tamaño de pantalla // Variables - Efectos - bool fade; // Indica si esta activo el efecto de fade - int fadeCounter; // Temporizador para el efecto de fade - int fadeLenght; // Duración del fade - bool spectrumFade; // Indica si esta activo el efecto de fade spectrum - int spectrumFadeCounter; // Temporizador para el efecto de fade spectrum - int spectrumFadeLenght; // Duración del fade spectrum - std::vector<color_t> spectrumColor; // Colores para el fade spectrum + bool fade_; // Indica si esta activo el efecto de fade + int fade_counter_; // Temporizador para el efecto de fade + int fade_lenght_; // Duración del fade + bool spectrum_fade_; // Indica si esta activo el efecto de fade spectrum + int spectrum_fade_counter_; // Temporizador para el efecto de fade spectrum + int spectrum_fade_lenght_; // Duración del fade spectrum + std::vector<color_t> spectrum_color_; // Colores para el fade spectrum // Inicializa las variables para el fade void iniFade(); @@ -75,13 +78,22 @@ private: // Muestra el contenido de Screen por pantalla void renderPresent(); -public: // Constructor - Screen(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, options_t *options); + Screen(SDL_Window *window, SDL_Renderer *renderer); // Destructor ~Screen(); +public: + // [SINGLETON] Crearemos el objeto con esta función estática + static void init(SDL_Window *window, SDL_Renderer *renderer); + + // [SINGLETON] Destruiremos el objeto con esta función estática + static void destroy(); + + // [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él + static Screen *get(); + // Limpia la pantalla void clean(color_t color = {0x00, 0x00, 0x00}); @@ -151,4 +163,7 @@ public: // Cambia el estado de los shaders void toggleShaders(); + + // Getters + SDL_Renderer *getRenderer() { return renderer_; } }; \ No newline at end of file diff --git a/source/title.cpp b/source/title.cpp index 0867b834..92255c8b 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -17,17 +17,17 @@ #include "utils.h" // Para color_t, stringToColor, options_t // Constructor -Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Input *input, options_t *options, section_t *section) - : renderer_(renderer), - screen_(screen), +Title::Title(Resource *resource, options_t *options, section_t *section) + : screen_(Screen::get()), + renderer_(Screen::get()->getRenderer()), resource_(resource), - input_(input), + input_(Input::get()), options_(options), section_(section) { // Reserva memoria para los punteros event_handler_ = new SDL_Event(); - cheevos_ = std::make_unique<Cheevos>(screen, options, Asset::get()->get("cheevos.bin")); + cheevos_ = std::make_unique<Cheevos>(screen_, options, Asset::get()->get("cheevos.bin")); if (options->palette == p_zxspectrum) { texture_ = resource->getTexture("title_logo.png"); @@ -36,12 +36,12 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Input * { texture_ = resource->getTexture("title_logo.png"); } - sprite_ = new Sprite(0, 0, texture_->getWidth(), texture_->getHeight(), texture_, renderer); - text_ = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer); - info_text_ = new Text(resource->getOffset("subatomic.txt"), resource->getTexture("subatomic.png"), renderer); + sprite_ = new Sprite(0, 0, texture_->getWidth(), texture_->getHeight(), texture_, renderer_); + text_ = new Text(resource->getOffset("smb2.txt"), resource->getTexture("smb2.png"), renderer_); + info_text_ = new Text(resource->getOffset("subatomic.txt"), resource->getTexture("subatomic.png"), renderer_); // Crea la textura para los graficos que aparecen en el fondo de la pantalla de titulo - bg_texture_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); + bg_texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); if (bg_texture_ == nullptr) { if (options->console) @@ -52,7 +52,7 @@ Title::Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Input * SDL_SetTextureBlendMode(bg_texture_, SDL_BLENDMODE_BLEND); // Carga la surface con los gráficos de la pantalla de carga - pInit(renderer, 256, 128); + pInit(renderer_, 256, 128); loading_screen_ = pLoadSurface(Asset::get()->get("loading_screen_color.gif").c_str()); pLoadPal(Asset::get()->get("loading_screen_color.gif").c_str()); pSetSource(loading_screen_); diff --git a/source/title.h b/source/title.h index 5876a249..856ccd68 100644 --- a/source/title.h +++ b/source/title.h @@ -37,8 +37,8 @@ private: }; // Objetos y punteros - SDL_Renderer *renderer_; // El renderizador de la ventana Screen *screen_; // Objeto encargado de dibujar en pantalla + SDL_Renderer *renderer_; // El renderizador de la ventana Resource *resource_; // Objeto con los recursos Input *input_; // Objeto pata gestionar la entrada SDL_Event *event_handler_; // Manejador de eventos @@ -109,7 +109,7 @@ private: public: // Constructor - Title(SDL_Renderer *renderer, Screen *screen, Resource *resource, Input *input, options_t *options, section_t *section); + Title(Resource *resource, options_t *options, section_t *section); // Destructor ~Title();