From 2209ed5f97ae5eef65ff3d1fe1a90b7b2e59559b Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Wed, 28 Sep 2022 14:03:45 +0200 Subject: [PATCH] Trabajando en el TITULO --- source/director.cpp | 8 +-- source/ltexture.cpp | 5 ++ source/menu.cpp | 9 ++-- source/text.cpp | 64 +++++++++-------------- source/text.h | 20 ++++---- source/title.cpp | 122 +++++++++++--------------------------------- source/title.h | 87 +++++++++++++++---------------- 7 files changed, 121 insertions(+), 194 deletions(-) diff --git a/source/director.cpp b/source/director.cpp index b057b16..42aefe8 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -9,8 +9,8 @@ Director::Director(std::string path) { // Inicializa variables - section.name = PROG_SECTION_INTRO; - section.subsection = 0; + section.name = PROG_SECTION_TITLE; + section.subsection = TITLE_SECTION_1; // Crea el objeto que controla los ficheros de recursos asset = new Asset(path.substr(0, path.find_last_of("\\/")) + "/../"); @@ -391,8 +391,8 @@ void Director::runIntro() void Director::runTitle() { - title = new Title(window, renderer, screen, input, asset, options, lang); - setSection(title->run(section.subsection)); + title = new Title(renderer, screen, input, asset, options, lang, section); + setSection(title->run()); delete title; } diff --git a/source/ltexture.cpp b/source/ltexture.cpp index f6afbbb..1d01275 100644 --- a/source/ltexture.cpp +++ b/source/ltexture.cpp @@ -32,6 +32,7 @@ LTexture::~LTexture() // Carga una imagen desde un fichero bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer) { + const std::string filename = path.substr(path.find_last_of("\\/") + 1); int req_format = STBI_rgb_alpha; int width, height, orig_format; unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format); @@ -40,6 +41,10 @@ bool LTexture::loadFromFile(std::string path, SDL_Renderer *renderer) SDL_Log("Loading image failed: %s", stbi_failure_reason()); exit(1); } + else + { + printf("Image loaded: %s\n", filename.c_str()); + } int depth, pitch; Uint32 pixel_format; diff --git a/source/menu.cpp b/source/menu.cpp index 535578b..8adcecc 100644 --- a/source/menu.cpp +++ b/source/menu.cpp @@ -13,11 +13,11 @@ Menu::Menu(SDL_Renderer *renderer, Asset *asset, Input *input, std::string file) soundCancel = nullptr; init(); + if (file != "") { load(file); } - reorganize(); } Menu::~Menu() @@ -56,7 +56,7 @@ bool Menu::load(std::string file_path) // Indica si se ha creado ya el objeto de texto bool textAllocated = false; - std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); + const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); std::string line; std::ifstream file(file_path); @@ -128,6 +128,9 @@ bool Menu::load(std::string file_path) success = false; } + // Reorganiza el menu con los valores recien cargados + //reorganize(); + return success; } @@ -913,6 +916,6 @@ void Menu::setText(std::string font_png, std::string font_txt) { if (!text) { - text = new Text(asset->get(font_png), asset->get(font_txt), renderer); + text = new Text(font_png, font_txt, renderer); } } \ No newline at end of file diff --git a/source/text.cpp b/source/text.cpp index 653a156..91df9c3 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -6,13 +6,12 @@ // Constructor Text::Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer) { - texture = new LTexture(renderer, bitmapFile); - sprite = new Sprite({0, 0, 0, 0}, texture, renderer); - sprite->setTexture(texture); - sprite->setRenderer(renderer); - file = textFile; + // Carga los offsets desde el fichero + initOffsetFromFile(textFile); - init(); + // Crea los objetos + texture = new LTexture(renderer, bitmapFile); + sprite = new Sprite({0, 0, boxWidth, boxHeight}, texture, renderer); } // Destructor @@ -22,35 +21,6 @@ Text::~Text() delete sprite; } -// Inicializador -void Text::init() -{ - // Inicializa a cero el vector con las coordenadas - for (int i = 0; i < 128; ++i) - { - offset[i].x = 0; - offset[i].y = 0; - offset[i].w = 0; - } - - // Carga los offsets desde el fichero - initOffsetFromFile(); - - // Inicia los valores del sprite que dibuja las letras - sprite->setWidth(boxWidth); - sprite->setHeight(boxHeight); - sprite->setPosX(0); - sprite->setPosY(0); - sprite->setSpriteClip(0, 0, sprite->getWidth(), sprite->getHeight()); - - // Establece las coordenadas para cada caracter ascii de la cadena y su ancho - for (int i = 32; i < 128; ++i) - { - offset[i].x = ((i - 32) % 15) * boxWidth; - offset[i].y = ((i - 32) / 15) * boxHeight; - } -} - // Escribe texto en pantalla void Text::write(int x, int y, std::string text, int kerning, int lenght) { @@ -139,10 +109,19 @@ int Text::lenght(std::string text, int kerning) } // Inicializa el vector de offsets desde un fichero -void Text::initOffsetFromFile() +void Text::initOffsetFromFile(std::string file) { + // Inicializa a cero el vector con las coordenadas + for (int i = 0; i < 128; ++i) + { + offset[i].x = 0; + offset[i].y = 0; + offset[i].w = 0; + } + + // Abre el fichero para leer los valores + const std::string filename = file.substr(file.find_last_of("\\/") + 1).c_str(); std::ifstream rfile(file); - printf("Reading file %s\n", file.c_str()); if (rfile.is_open() && rfile.good()) { @@ -172,14 +151,21 @@ void Text::initOffsetFromFile() }; // Cierra el fichero - printf("Closing file %s\n\n", file.c_str()); + printf("Text loaded: %s\n\n", filename.c_str()); rfile.close(); } // El fichero no se puede abrir else { - printf("Warning: Unable to open %s file\n", file.c_str()); + printf("Warning: Unable to open %s file\n", filename.c_str()); + } + + // Establece las coordenadas para cada caracter ascii de la cadena y su ancho + for (int i = 32; i < 128; ++i) + { + offset[i].x = ((i - 32) % 15) * boxWidth; + offset[i].y = ((i - 32) / 15) * boxHeight; } } diff --git a/source/text.h b/source/text.h index fc32787..ef59417 100644 --- a/source/text.h +++ b/source/text.h @@ -15,26 +15,24 @@ class Text { private: - Sprite *sprite; // Objeto con los graficos para el texto - - struct Offset + struct offset_t { int x; int y; int w; }; - Offset offset[128]; // Vector con las posiciones y ancho de cada letra - - int boxWidth; // Anchura de la caja de cada caracter en el png - int boxHeight; // Altura de la caja de cada caracter en el png - std::string file; // Fichero con los descriptores de la fuente + + // Objetos + Sprite *sprite; // Objeto con los graficos para el texto LTexture *texture; // Textura con los bitmaps del texto - // Inicializador - void init(); + // Variables + int boxWidth; // Anchura de la caja de cada caracter en el png + int boxHeight; // Altura de la caja de cada caracter en el png + offset_t offset[128]; // Vector con las posiciones y ancho de cada letra // Inicializa el vector de offsets desde un fichero - void initOffsetFromFile(); + void initOffsetFromFile(std::string file); public: // Constructor diff --git a/source/title.cpp b/source/title.cpp index a1dc840..99b530a 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -1,10 +1,9 @@ #include "title.h" // Constructor -Title::Title(SDL_Window *window, SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset, options_t *options, Lang *lang) +Title::Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset, options_t *options, Lang *lang, section_t section) { // Copia las direcciones de los punteros - mWindow = window; mRenderer = renderer; mScreen = screen; mInput = input; @@ -29,7 +28,6 @@ Title::Title(SDL_Window *window, SDL_Renderer *renderer, Screen *screen, Input * mText = new Text(mAsset->get("smb2.png"), mAsset->get("smb2.txt"), mRenderer); mText2 = new Text(mAsset->get("8bithud.png"), mAsset->get("8bithud.txt"), mRenderer); - mMenu.title = new Menu(mRenderer, mAsset, mInput); mMenu.options = new Menu(mRenderer, mAsset, mInput); @@ -39,81 +37,15 @@ Title::Title(SDL_Window *window, SDL_Renderer *renderer, Screen *screen, Input * { printf("TitleSurface could not be created!\nSDL Error: %s\n", SDL_GetError()); } -} -// Destructor -Title::~Title() -{ - mWindow = nullptr; - mRenderer = nullptr; - mScreen = nullptr; - mInput = nullptr; - mAsset = nullptr; - mOptions = nullptr; - mLang = nullptr; + // Sonidos + mSound = JA_LoadSound(mAsset->get("title.wav").c_str()); - delete mEventHandler; - mEventHandler = nullptr; - - delete mText; - mText = nullptr; - - delete mText2; - mText2 = nullptr; - - delete mFade; - mFade = nullptr; - - mTitleTexture->unload(); - delete mTitleTexture; - mTitleTexture = nullptr; - - mItemsTexture->unload(); - delete mItemsTexture; - mItemsTexture = nullptr; - - delete mCoffeeBitmap; - mCoffeeBitmap = nullptr; - - delete mCrisisBitmap; - mCrisisBitmap = nullptr; - - delete mDustBitmapL; - mDustBitmapL = nullptr; - - delete mDustBitmapR; - mDustBitmapR = nullptr; - - delete mTile; - mTile = nullptr; - - delete mGradient; - mGradient = nullptr; - - delete mMenu.title; - mMenu.title = nullptr; - - delete mMenu.options; - mMenu.options = nullptr; - - mMenu.active = nullptr; - - JA_DeleteSound(mSound); - JA_DeleteMusic(mMusic); - - SDL_DestroyTexture(mBackground); - mBackground = nullptr; -} - -// Inicializa las variables necesarias para la sección 'Title' -void Title::init(bool demo, Uint8 subsection) -{ - // Carga los recursos - loadMedia(); + // Musicas + mMusic = JA_LoadMusic(mAsset->get("title.ogg").c_str()); // Inicializa variables - mSection.name = PROG_SECTION_TITLE; - mSection.subsection = subsection; + mSection = section; mCounter = TITLE_COUNTER; mBackgroundCounter = 0; mBackgroundMode = rand() % 2; @@ -124,7 +56,7 @@ void Title::init(bool demo, Uint8 subsection) mTicks = 0; mTicksSpeed = 15; mFade->init(0x17, 0x17, 0x26); - mDemo = demo; + mDemo = false; // Pone valores por defecto a las opciones de control mOptions->input[0].id = 0; @@ -233,7 +165,7 @@ void Title::init(bool demo, Uint8 subsection) mBackgroundWindow.h = GAME_HEIGHT; // Inicializa los valores del vector con los valores del seno - for (int i = 0; i < 360; i++) + for (int i = 0; i < 360; ++i) { mSin[i] = SDL_sinf((float)i * 3.14f / 180.0f); } @@ -283,19 +215,32 @@ void Title::init(bool demo, Uint8 subsection) updateMenuLabels(); } -// Carga los recursos necesarios para la sección 'Title' -bool Title::loadMedia() +// Destructor +Title::~Title() { - // Indicador de éxito en la carga - bool success = true; + mTitleTexture->unload(); + delete mTitleTexture; - // Sonidos - mSound = JA_LoadSound(mAsset->get("title.wav").c_str()); + mItemsTexture->unload(); + delete mItemsTexture; - // Musicas - mMusic = JA_LoadMusic(mAsset->get("title.ogg").c_str()); + delete mEventHandler; + delete mText; + delete mText2; + delete mFade; + delete mCoffeeBitmap; + delete mCrisisBitmap; + delete mDustBitmapL; + delete mDustBitmapR; + delete mTile; + delete mGradient; + delete mMenu.title; + delete mMenu.options; - return success; + JA_DeleteSound(mSound); + JA_DeleteMusic(mMusic); + + SDL_DestroyTexture(mBackground); } // Cambia el valor de la variable de modo de pantalla completa @@ -505,10 +450,8 @@ void Title::applyOptions() } // Bucle para el titulo del juego -section_t Title::run(Uint8 subsection) +section_t Title::run() { - init(subsection); - while (mSection.name == PROG_SECTION_TITLE) { // Sección 1 - Titulo desplazandose @@ -683,7 +626,6 @@ section_t Title::run(Uint8 subsection) { runDemoGame(); runInstructions(INSTRUCTIONS_MODE_AUTO); - init(false); } else mSection.name = PROG_SECTION_LOGO; @@ -882,7 +824,6 @@ section_t Title::run(Uint8 subsection) { runDemoGame(); runInstructions(INSTRUCTIONS_MODE_AUTO); - init(false); } else mSection.name = PROG_SECTION_LOGO; @@ -893,7 +834,6 @@ section_t Title::run(Uint8 subsection) if (mSection.subsection == TITLE_SECTION_INSTRUCTIONS) { runInstructions(INSTRUCTIONS_MODE_AUTO); - init(); } } diff --git a/source/title.h b/source/title.h index dd5e5bc..5dfc6bb 100644 --- a/source/title.h +++ b/source/title.h @@ -33,43 +33,6 @@ class Title { private: - SDL_Window *mWindow; // Ventana de la aplicación - SDL_Renderer *mRenderer; // El renderizador de la ventana - Screen *mScreen; // Objeto encargado de dibujar en pantalla - Asset *mAsset; // Objeto que gestiona todos los ficheros de recursos - Input *mInput; // Objeto para leer las entradas de teclado o mando - Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas - SDL_Event *mEventHandler; // Manejador de eventos - AnimatedSprite *mDustBitmapL; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo - AnimatedSprite *mDustBitmapR; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo - JA_Music mMusic; // Musica para el titulo - JA_Sound mSound; // Sonido con el impacto del título - LTexture *mItemsTexture; // Textura con los gráficos de los items para las instrucciones - LTexture *mTitleTexture; // Textura con los graficos para el titulo - SDL_Rect mBackgroundWindow; // Ventana visible para la textura de fondo del titulo - SDL_Texture *mBackground; // Textura dibujar el fondo del titulo - SmartSprite *mCoffeeBitmap; // Sprite con la palabra COFFEE para la pantalla de titulo - SmartSprite *mCrisisBitmap; // Sprite con la palabra CRISIS para la pantalla de titulo - Sprite *mTile; // Sprite para dibujar el fondo de pantalla del título - Sprite *mGradient; // Sprite para dibujar el degradado del titulo - Text *mText; // Objeto de texto para poder escribir textos en pantalla - Text *mText2; // Objeto de texto para poder escribir textos en pantalla - Fade *mFade; // Objeto para realizar fundidos en pantalla - Instructions *mInstructions; // Objeto para la sección de las instrucciones - Game *mDemoGame; // Objeto para lanzar la demo del juego - Uint16 mBackgroundCounter; // Temporizador para el fondo de tiles de la pantalla de titulo - Uint16 mCounter; // Temporizador para la pantalla de titulo - Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa - Uint8 mBackgroundMode; // Variable para almacenar el tipo de efecto que hará el fondo de la pantalla de titulo - Uint8 mEvents[TITLE_TOTAL_EVENTS]; // Vector para coordinar los eventos de la pantalla de titulo - float mSin[360]; // Vector con los valores del seno precalculados - bool mMenuVisible; // Indicador para saber si se muestra el menu del titulo o la frase intermitente - bool mDemo; // Indica si el modo demo estará activo - section_t mSection; // Indicador para el bucle del titulo - section_t mNextSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo - Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa - Uint8 mPostFade; // Opción a realizar cuando termina el fundido - struct menu_t { Menu *title; // Menu de la pantalla de título @@ -77,16 +40,51 @@ private: Menu *active; // Menu activo (de momento para la pantalla del titulo) bool keyPressed; // Variable para evitar la repetición de teclas en los menus }; - menu_t mMenu; // Variable con todos los objetos menus y sus variables + // Objetos + SDL_Renderer *mRenderer; // El renderizador de la ventana + Screen *mScreen; // Objeto encargado de dibujar en pantalla + Asset *mAsset; // Objeto que gestiona todos los ficheros de recursos + Input *mInput; // Objeto para leer las entradas de teclado o mando + Lang *mLang; // Objeto para gestionar los textos en diferentes idiomas + SDL_Event *mEventHandler; // Manejador de eventos + AnimatedSprite *mDustBitmapL; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo + AnimatedSprite *mDustBitmapR; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo + LTexture *mItemsTexture; // Textura con los gráficos de los items para las instrucciones + LTexture *mTitleTexture; // Textura con los graficos para el titulo + SDL_Rect mBackgroundWindow; // Ventana visible para la textura de fondo del titulo + SDL_Texture *mBackground; // Textura dibujar el fondo del titulo + SmartSprite *mCoffeeBitmap; // Sprite con la palabra COFFEE para la pantalla de titulo + SmartSprite *mCrisisBitmap; // Sprite con la palabra CRISIS para la pantalla de titulo + Sprite *mTile; // Sprite para dibujar el fondo de pantalla del título + Sprite *mGradient; // Sprite para dibujar el degradado del titulo + Text *mText; // Objeto de texto para poder escribir textos en pantalla + Text *mText2; // Objeto de texto para poder escribir textos en pantalla + Fade *mFade; // Objeto para realizar fundidos en pantalla + Instructions *mInstructions; // Objeto para la sección de las instrucciones + Game *mDemoGame; // Objeto para lanzar la demo del juego + + // Variable + JA_Music mMusic; // Musica para el titulo + JA_Sound mSound; // Sonido con el impacto del título + int mBackgroundCounter; // Temporizador para el fondo de tiles de la pantalla de titulo + int mCounter; // Temporizador para la pantalla de titulo + Uint32 mTicks; // Contador de ticks para ajustar la velocidad del programa + Uint8 mBackgroundMode; // Variable para almacenar el tipo de efecto que hará el fondo de la pantalla de titulo + Uint8 mEvents[TITLE_TOTAL_EVENTS]; // Vector para coordinar los eventos de la pantalla de titulo + float mSin[360]; // Vector con los valores del seno precalculados + bool mMenuVisible; // Indicador para saber si se muestra el menu del titulo o la frase intermitente + bool mDemo; // Indica si el modo demo estará activo + section_t mSection; // Indicador para el bucle del titulo + section_t mNextSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo + Uint8 mTicksSpeed; // Velocidad a la que se repiten los bucles del programa + Uint8 mPostFade; // Opción a realizar cuando termina el fundido + menu_t mMenu; // Variable con todos los objetos menus y sus variables struct options_t *mOptions; // Variable con todas las variables de las opciones del programa options_t mOptionsPrevious; // Variable de respaldo para las opciones std::vector mAvailableInputDevices; // Vector con todos los metodos de control disponibles int mDeviceIndex[2]; // Indice para el jugador [i] del vector de dispositivos de entrada disponibles - // Carga los recursos necesarios para la sección 'Title' - bool loadMedia(); - // Cambia el valor de la variable de modo de pantalla completa void switchFullScreenModeVar(); @@ -113,16 +111,13 @@ private: public: // Constructor - Title(SDL_Window *window, SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset, options_t *options, Lang *lang); + Title(SDL_Renderer *renderer, Screen *screen, Input *input, Asset *asset, options_t *options, Lang *lang, section_t section); // Destructor ~Title(); - // Inicializa las variables necesarias para la sección 'Title' - void init(bool demo = true, Uint8 subsection = TITLE_SECTION_1); - // Bucle para el titulo del juego - section_t run(Uint8 subsection = TITLE_SECTION_1); + section_t run(); }; #endif