Resource: afegida pantalla de progres de càrrega

Screen: Afegit objecte de text propi per a la clase
This commit is contained in:
2025-06-10 22:08:17 +02:00
parent 02b111e4fd
commit cabee86ee0
7 changed files with 160 additions and 128 deletions

View File

@@ -131,8 +131,6 @@ std::string Asset::getTypeName(AssetType type) const
return "ANIMATION"; return "ANIMATION";
case AssetType::PALETTE: case AssetType::PALETTE:
return "PALETTE"; return "PALETTE";
case AssetType::ITEM:
return "ITEM";
default: default:
return "ERROR"; return "ERROR";
} }

View File

@@ -15,9 +15,9 @@ enum class AssetType : int
FONT, FONT,
LANG, LANG,
DATA, DATA,
DEMODATA,
ANIMATION, ANIMATION,
PALETTE, PALETTE,
ITEM,
COUNT, COUNT,
}; };

View File

@@ -103,12 +103,6 @@ void Director::init()
Notifier::init(std::string(), Resource::get()->getText("8bithud")); // Inicialización del sistema de notificaciones Notifier::init(std::string(), Resource::get()->getText("8bithud")); // Inicialización del sistema de notificaciones
Screen::get()->getSingletons(); // Obtiene los punteros al resto de singletones Screen::get()->getSingletons(); // Obtiene los punteros al resto de singletones
#ifdef DEBUG
// Configuración adicional en modo depuración
Screen::get()->initDebugInfo();
Screen::get()->setDebugInfoEnabled(true);
#endif
} }
// Cierra todo y libera recursos del sistema y de los singletons // Cierra todo y libera recursos del sistema y de los singletons
@@ -287,8 +281,8 @@ void Director::setFileList()
Asset::get()->add(system_folder_ + "/score.bin", AssetType::DATA, false, true); Asset::get()->add(system_folder_ + "/score.bin", AssetType::DATA, false, true);
Asset::get()->add(prefix + "/data/config/param_320x240.txt", AssetType::DATA); Asset::get()->add(prefix + "/data/config/param_320x240.txt", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/param_320x256.txt", AssetType::DATA); Asset::get()->add(prefix + "/data/config/param_320x256.txt", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/demo1.bin", AssetType::DATA); Asset::get()->add(prefix + "/data/config/demo1.bin", AssetType::DEMODATA);
Asset::get()->add(prefix + "/data/config/demo2.bin", AssetType::DATA); Asset::get()->add(prefix + "/data/config/demo2.bin", AssetType::DEMODATA);
Asset::get()->add(prefix + "/data/config/gamecontrollerdb.txt", AssetType::DATA); Asset::get()->add(prefix + "/data/config/gamecontrollerdb.txt", AssetType::DATA);
// Musicas // Musicas

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL_log.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError #include <SDL3/SDL_log.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_LogError
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <algorithm> // Para find_if #include <algorithm> // Para find_if
#include <array>
#include <stdexcept> // Para runtime_error #include <stdexcept> // Para runtime_error
#include "asset.h" // Para Asset, AssetType #include "asset.h" // Para Asset, AssetType
#include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic #include "jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_LoadMusic
@@ -24,7 +25,7 @@ void Resource::destroy() { delete Resource::instance_; }
Resource *Resource::get() { return Resource::instance_; } Resource *Resource::get() { return Resource::instance_; }
// Constructor // Constructor
Resource::Resource() { load(); } Resource::Resource() : loading_text_(Screen::get()->getText()) { load(); }
// Vacia todos los vectores de recursos // Vacia todos los vectores de recursos
void Resource::clear() void Resource::clear()
@@ -38,33 +39,43 @@ void Resource::clear()
demos_.clear(); demos_.clear();
} }
// Carga todos los recursos // Carga todos los recursos del juego y muestra el progreso de carga
void Resource::load() void Resource::load()
{ {
// Calcula el total de recursos a cargar
calculateTotal(); calculateTotal();
Screen::get()->show();
// Muerstra la ventana y desactiva el sincronismo vertical
auto screen = Screen::get();
auto vsync = screen->getVSync();
screen->show();
screen->setVSync(false);
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** LOADING RESOURCES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** LOADING RESOURCES");
loadSounds(); loadSounds(); // Carga sonidos
loadMusics(); loadMusics(); // Carga músicas
loadTextures(); loadTextures(); // Carga texturas
loadTextFiles(); loadTextFiles(); // Carga ficheros de texto
loadAnimations(); loadAnimations(); // Carga animaciones
loadDemoData(); loadDemoData(); // Carga datos de demo
addPalettes(); addPalettes(); // Añade paletas a las texturas
createText(); createText(); // Crea objetos de texto
createTextures(); createTextures(); // Crea texturas a partir de texto
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** RESOURCES LOADED"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n** RESOURCES LOADED");
// Restablece el sincronismo vertical a su valor original
screen->setVSync(vsync);
SDL_Delay(1000);
} }
// Recarga todos los recursos // Recarga todos los recursos (limpia y vuelve a cargar)
void Resource::reload() void Resource::reload()
{ {
clear(); clear();
load(); load();
} }
// Recarga las texturas // Recarga solo las texturas y paletas
void Resource::reloadTextures() void Resource::reloadTextures()
{ {
loadTextures(); loadTextures();
@@ -72,7 +83,7 @@ void Resource::reloadTextures()
createTextures(); createTextures();
} }
// Obtiene el sonido a partir de un nombre // Obtiene el sonido a partir de un nombre. Lanza excepción si no existe.
JA_Sound_t *Resource::getSound(const std::string &name) JA_Sound_t *Resource::getSound(const std::string &name)
{ {
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s) auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s)
@@ -87,7 +98,7 @@ JA_Sound_t *Resource::getSound(const std::string &name)
throw std::runtime_error("Sonido no encontrado: " + name); throw std::runtime_error("Sonido no encontrado: " + name);
} }
// Obtiene la música a partir de un nombre // Obtiene la música a partir de un nombre. Lanza excepción si no existe.
JA_Music_t *Resource::getMusic(const std::string &name) JA_Music_t *Resource::getMusic(const std::string &name)
{ {
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m) auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m)
@@ -102,7 +113,7 @@ JA_Music_t *Resource::getMusic(const std::string &name)
throw std::runtime_error("Música no encontrada: " + name); throw std::runtime_error("Música no encontrada: " + name);
} }
// Obtiene la textura a partir de un nombre // Obtiene la textura a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<Texture> Resource::getTexture(const std::string &name) std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
{ {
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t)
@@ -117,7 +128,7 @@ std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
throw std::runtime_error("Imagen no encontrada: " + name); throw std::runtime_error("Imagen no encontrada: " + name);
} }
// Obtiene el fichero de texto a partir de un nombre // Obtiene el fichero de texto a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
{ {
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t)
@@ -132,7 +143,7 @@ std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
throw std::runtime_error("TextFile no encontrado: " + name); throw std::runtime_error("TextFile no encontrado: " + name);
} }
// Obtiene el objeto de texto a partir de un nombre // Obtiene el objeto de texto a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<Text> Resource::getText(const std::string &name) std::shared_ptr<Text> Resource::getText(const std::string &name)
{ {
auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t) auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t)
@@ -147,7 +158,7 @@ std::shared_ptr<Text> Resource::getText(const std::string &name)
throw std::runtime_error("Text no encontrado: " + name); throw std::runtime_error("Text no encontrado: " + name);
} }
// Obtiene la animación a partir de un nombre // Obtiene la animación a partir de un nombre. Lanza excepción si no existe.
AnimationsFileBuffer &Resource::getAnimation(const std::string &name) AnimationsFileBuffer &Resource::getAnimation(const std::string &name)
{ {
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a) auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a)
@@ -162,13 +173,13 @@ AnimationsFileBuffer &Resource::getAnimation(const std::string &name)
throw std::runtime_error("Animación no encontrada: " + name); throw std::runtime_error("Animación no encontrada: " + name);
} }
// Obtiene el fichero con los datos para el modo demostración a partir de un çindice // Obtiene el fichero con los datos para el modo demostración a partir de un índice
DemoData &Resource::getDemoData(int index) DemoData &Resource::getDemoData(int index)
{ {
return demos_.at(index); return demos_.at(index);
} }
// Carga los sonidos // Carga los sonidos del juego
void Resource::loadSounds() void Resource::loadSounds()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> SOUND FILES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> SOUND FILES");
@@ -180,11 +191,11 @@ void Resource::loadSounds()
auto name = getFileName(l); auto name = getFileName(l);
sounds_.emplace_back(Resource::ResourceSound(name, JA_LoadSound(l.c_str()))); sounds_.emplace_back(Resource::ResourceSound(name, JA_LoadSound(l.c_str())));
printWithDots("Sound : ", name, "[ LOADED ]"); printWithDots("Sound : ", name, "[ LOADED ]");
updateLoadingProgress(); updateLoadingProgress(name);
} }
} }
// Carga las músicas // Carga las músicas del juego
void Resource::loadMusics() void Resource::loadMusics()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> MUSIC FILES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> MUSIC FILES");
@@ -196,11 +207,11 @@ void Resource::loadMusics()
auto name = getFileName(l); auto name = getFileName(l);
musics_.emplace_back(Resource::ResourceMusic(name, JA_LoadMusic(l.c_str()))); musics_.emplace_back(Resource::ResourceMusic(name, JA_LoadMusic(l.c_str())));
printWithDots("Music : ", name, "[ LOADED ]"); printWithDots("Music : ", name, "[ LOADED ]");
updateLoadingProgress(); updateLoadingProgress(name);
} }
} }
// Carga las texturas // Carga las texturas del juego
void Resource::loadTextures() void Resource::loadTextures()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXTURES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXTURES");
@@ -211,11 +222,11 @@ void Resource::loadTextures()
{ {
auto name = getFileName(l); auto name = getFileName(l);
textures_.emplace_back(Resource::ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l))); textures_.emplace_back(Resource::ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
updateLoadingProgress(); updateLoadingProgress(name);
} }
} }
// Carga los ficheros de texto // Carga los ficheros de texto del juego
void Resource::loadTextFiles() void Resource::loadTextFiles()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXT FILES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> TEXT FILES");
@@ -226,11 +237,11 @@ void Resource::loadTextFiles()
{ {
auto name = getFileName(l); auto name = getFileName(l);
text_files_.emplace_back(Resource::ResourceTextFile(name, loadTextFile(l))); text_files_.emplace_back(Resource::ResourceTextFile(name, loadTextFile(l)));
updateLoadingProgress(); updateLoadingProgress(name);
} }
} }
// Carga las animaciones // Carga las animaciones del juego
void Resource::loadAnimations() void Resource::loadAnimations()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> ANIMATIONS"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> ANIMATIONS");
@@ -241,7 +252,7 @@ void Resource::loadAnimations()
{ {
auto name = getFileName(l); auto name = getFileName(l);
animations_.emplace_back(Resource::ResourceAnimation(name, loadAnimationsFromFile(l))); animations_.emplace_back(Resource::ResourceAnimation(name, loadAnimationsFromFile(l)));
updateLoadingProgress(); updateLoadingProgress(name);
} }
} }
@@ -249,32 +260,36 @@ void Resource::loadAnimations()
void Resource::loadDemoData() void Resource::loadDemoData()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES");
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo1.bin")));
updateLoadingProgress(); constexpr std::array<const char *, 2> demo_files = {"demo1.bin", "demo2.bin"};
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get("demo2.bin")));
updateLoadingProgress(); for (const auto &file : demo_files)
{
demos_.emplace_back(loadDemoDataFromFile(Asset::get()->get(file)));
updateLoadingProgress(file);
}
} }
// Añade paletas a las texturas // Añade paletas de colores a las texturas principales
void Resource::addPalettes() void Resource::addPalettes()
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> PALETTES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> PALETTES");
// Jugador 1 // Paletas para el jugador 1
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_1_coffee_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_1_coffee_palette.gif"));
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_2_coffee_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_2_coffee_palette.gif"));
getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_invencible_palette.gif")); getTexture("player1.gif")->addPaletteFromFile(Asset::get()->get("player1_invencible_palette.gif"));
// Jugador 2 // Paletas para el jugador 2
getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_1_coffee_palette.gif")); getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_1_coffee_palette.gif"));
getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_2_coffee_palette.gif")); getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_2_coffee_palette.gif"));
getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_invencible_palette.gif")); getTexture("player2.gif")->addPaletteFromFile(Asset::get()->get("player2_invencible_palette.gif"));
// Fuentes // Paleta para la fuente SMB2
getTexture("smb2.gif")->addPaletteFromFile(Asset::get()->get("smb2_palette1.pal")); getTexture("smb2.gif")->addPaletteFromFile(Asset::get()->get("smb2_palette1.pal"));
} }
// Crea texturas // Crea texturas a partir de textos para mostrar puntuaciones y mensajes
void Resource::createTextures() void Resource::createTextures()
{ {
struct NameAndText struct NameAndText
@@ -288,7 +303,7 @@ void Resource::createTextures()
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES"); SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES");
// Tamaño normal // Texturas de tamaño normal
std::vector<NameAndText> strings = { std::vector<NameAndText> strings = {
{"game_text_1000_points", "1.000"}, {"game_text_1000_points", "1.000"},
{"game_text_2500_points", "2.500"}, {"game_text_2500_points", "2.500"},
@@ -305,7 +320,7 @@ void Resource::createTextures()
printWithDots("Texture : ", s.name, "[ DONE ]"); printWithDots("Texture : ", s.name, "[ DONE ]");
} }
// Tamaño doble // Texturas de tamaño doble
std::vector<NameAndText> strings2X = { std::vector<NameAndText> strings2X = {
{"game_text_100000_points", "100.000"}, {"game_text_100000_points", "100.000"},
{"game_text_get_ready", lang::getText("[GAME_TEXT] 7")}, {"game_text_get_ready", lang::getText("[GAME_TEXT] 7")},
@@ -321,6 +336,7 @@ void Resource::createTextures()
} }
} }
// Crea los objetos de texto a partir de los archivos de textura y texto
void Resource::createText() void Resource::createText()
{ {
struct ResourceInfo struct ResourceInfo
@@ -357,7 +373,7 @@ void Resource::createText()
} }
} }
// Vacía el vector de sonidos // Vacía el vector de sonidos y libera la memoria asociada
void Resource::clearSounds() void Resource::clearSounds()
{ {
for (auto &sound : sounds_) for (auto &sound : sounds_)
@@ -371,7 +387,7 @@ void Resource::clearSounds()
sounds_.clear(); sounds_.clear();
} }
// Vacía el vector de músicas // Vacía el vector de músicas y libera la memoria asociada
void Resource::clearMusics() void Resource::clearMusics()
{ {
for (auto &music : musics_) for (auto &music : musics_)
@@ -385,46 +401,60 @@ void Resource::clearMusics()
musics_.clear(); musics_.clear();
} }
// Calcula el numero de recursos para cargar // Calcula el número total de recursos a cargar y reinicia el contador de carga
void Resource::calculateTotal() void Resource::calculateTotal()
{ {
const std::array<AssetType, 6> ASSET_TYPES = {
AssetType::SOUND,
AssetType::MUSIC,
AssetType::BITMAP,
AssetType::FONT,
AssetType::ANIMATION,
AssetType::DEMODATA};
size_t total = 0; size_t total = 0;
for (int i = 0; i < static_cast<int>(AssetType::COUNT); ++i) for (const auto &asset_type : ASSET_TYPES)
{ {
auto assetType = static_cast<AssetType>(i); auto list = Asset::get()->getListByType(asset_type);
auto list = Asset::get()->getListByType(assetType);
total += list.size(); total += list.size();
std::string log = std::to_string(list.size()) + " - " + std::to_string(total);
SDL_Log("%s", log.c_str());
} }
count_ = ResourceCount(total, 0); loading_count_ = ResourceCount(total);
} }
// Muestra el progreso de carga // Muestra el progreso de carga en pantalla (barra y texto)
void Resource::renderProgress() void Resource::renderProgress()
{ {
auto screen = Screen::get(); auto screen = Screen::get();
auto renderer = screen->getRenderer(); auto renderer = screen->getRenderer();
screen->update();
constexpr float X_PADDING = 10.0f; constexpr float X_PADDING = 10.0f;
constexpr float Y_PADDING = 10.0f; constexpr float Y_PADDING = 10.0f;
constexpr float BAR_HEIGHT = 10.0f; constexpr float BAR_HEIGHT = 10.0f;
const float bar_position = param.game.height - BAR_HEIGHT - Y_PADDING; const float BAR_Y_POSITION = param.game.height - BAR_HEIGHT - Y_PADDING;
screen->start(); screen->start();
screen->clean(); screen->clean();
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
const float wired_bar_width = param.game.width - (X_PADDING * 2); const float wired_bar_width = param.game.width - (X_PADDING * 2);
SDL_FRect rect_wired = {X_PADDING, bar_position, wired_bar_width, X_PADDING}; SDL_FRect rect_wired = {X_PADDING, BAR_Y_POSITION, wired_bar_width, X_PADDING};
SDL_RenderRect(renderer, &rect_wired); SDL_RenderRect(renderer, &rect_wired);
const float full_bar_width = wired_bar_width * count_.getPercentage(); const float full_bar_width = wired_bar_width * loading_count_.getPercentage();
SDL_FRect rect_full = {X_PADDING, bar_position, full_bar_width, X_PADDING}; SDL_FRect rect_full = {X_PADDING, BAR_Y_POSITION, full_bar_width, X_PADDING};
SDL_RenderFillRect(renderer, &rect_full); SDL_RenderFillRect(renderer, &rect_full);
loading_text_->write(X_PADDING, BAR_Y_POSITION - 9, "Loading : " + loading_resource_name_);
screen->render(); screen->render();
} }
// Comprueba los eventos de la pantalla de carga // Comprueba los eventos durante la carga (permite salir con ESC o cerrar ventana)
void Resource::checkEvents() void Resource::checkEvents()
{ {
SDL_Event event; SDL_Event event;
@@ -445,13 +475,11 @@ void Resource::checkEvents()
} }
} }
// Actualiza el progreso de carga // Actualiza el progreso de carga, muestra la barra y procesa eventos
void Resource::updateLoadingProgress(int steps) void Resource::updateLoadingProgress(std::string name)
{
count_.add(1);
if (count_.loaded % steps == 0 || count_.loaded == count_.total)
{ {
loading_resource_name_ = name;
loading_count_.add(1);
renderProgress(); renderProgress();
}
checkEvents(); checkEvents();
} }

View File

@@ -90,13 +90,13 @@ private:
// --- Estructura para el progreso de carga --- // --- Estructura para el progreso de carga ---
struct ResourceCount struct ResourceCount
{ {
int total; // Número total de recursos size_t total; // Número total de recursos
int loaded; // Número de recursos cargados size_t loaded; // Número de recursos cargados
ResourceCount() : total(0), loaded(0) {} ResourceCount() : total(0), loaded(0) {}
ResourceCount(int total, int loaded) : total(total), loaded(loaded) {} ResourceCount(size_t total) : total(total), loaded(0) {}
void add(int amount) { loaded += amount; } void add(size_t amount) { loaded += amount; }
float getPercentage() const float getPercentage() const
{ {
return total > 0 ? static_cast<float>(loaded) / static_cast<float>(total) : 0.0f; return total > 0 ? static_cast<float>(loaded) / static_cast<float>(total) : 0.0f;
@@ -116,7 +116,9 @@ private:
std::vector<DemoData> demos_; // Vector con los ficheros de datos para el modo demostración std::vector<DemoData> demos_; // Vector con los ficheros de datos para el modo demostración
// --- Progreso de carga --- // --- Progreso de carga ---
ResourceCount count_; // Contador de recursos cargados ResourceCount loading_count_; // Contador de recursos cargados
std::shared_ptr<Text> loading_text_; // Texto para escribir en pantalla
std::string loading_resource_name_; // Nombre del recurso que se está cargando
// --- Métodos internos de carga y gestión --- // --- Métodos internos de carga y gestión ---
void loadSounds(); // Carga los sonidos void loadSounds(); // Carga los sonidos
@@ -137,7 +139,7 @@ private:
void calculateTotal(); // Calcula el número de recursos para cargar void calculateTotal(); // Calcula el número de recursos para cargar
void renderProgress(); // Muestra el progreso de carga void renderProgress(); // Muestra el progreso de carga
void checkEvents(); // Comprueba los eventos durante la carga void checkEvents(); // Comprueba los eventos durante la carga
void updateLoadingProgress(int steps = 1); // Actualiza el progreso de carga void updateLoadingProgress(std::string name); // Actualiza el progreso de carga
// --- Constructores y destructor privados (singleton) --- // --- Constructores y destructor privados (singleton) ---
Resource(); // Constructor privado Resource(); // Constructor privado

View File

@@ -53,18 +53,22 @@ Screen::Screen()
// Inicializa variables // Inicializa variables
adjustRenderLogicalSize(); adjustRenderLogicalSize();
// Muestra la ventana
show();
// Inicializa los shaders // Inicializa los shaders
initShaders(); // Se ha de ejecutar con la ventana visible initShaders();
// Crea el objeto de texto
createText();
#ifdef DEBUG
debug_info_.text = text_;
setDebugInfoEnabled(true);
#endif
} }
// Destructor // Destructor
Screen::~Screen() Screen::~Screen()
{ {
SDL_DestroyTexture(game_canvas_); SDL_DestroyTexture(game_canvas_);
SDL_DestroyRenderer(renderer_); SDL_DestroyRenderer(renderer_);
SDL_DestroyWindow(window_); SDL_DestroyWindow(window_);
} }
@@ -238,19 +242,20 @@ void Screen::renderInfo()
#endif #endif
// Carga el contenido del archivo GLSL // Carga el contenido del archivo GLSL
void Screen::loadShaders() void Screen::loadShaders()
{
if (shader_source_.empty())
{ {
const std::string GLSL_FILE = param.game.game_area.rect.h == 256 ? "crtpi_256.glsl" : "crtpi_240.glsl"; const std::string GLSL_FILE = param.game.game_area.rect.h == 256 ? "crtpi_256.glsl" : "crtpi_240.glsl";
std::ifstream f(Asset::get()->get(GLSL_FILE).c_str()); std::ifstream f(Asset::get()->get(GLSL_FILE).c_str());
shader_source_ = std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); shader_source_ = std::string((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
} }
}
// Inicializa los shaders // Inicializa los shaders
void Screen::initShaders() void Screen::initShaders()
{ {
if (shader_source_.empty()) show(); // Se ha de ejecutar con la ventana visible
{
loadShaders(); loadShaders();
}
shader::init(window_, game_canvas_, shader_source_); shader::init(window_, game_canvas_, shader_source_);
} }
@@ -401,20 +406,27 @@ void Screen::getDisplayInfo()
} }
} }
// Activa / desactiva el escalado entero // Alterna entre activar y desactivar el escalado entero
void Screen::toggleIntegerScale() void Screen::toggleIntegerScale()
{ {
options.video.integer_scale = !options.video.integer_scale; options.video.integer_scale = !options.video.integer_scale;
SDL_SetRenderLogicalPresentation(Screen::get()->getRenderer(), param.game.width, param.game.height, options.video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX); SDL_SetRenderLogicalPresentation(Screen::get()->getRenderer(), param.game.width, param.game.height, options.video.integer_scale ? SDL_LOGICAL_PRESENTATION_INTEGER_SCALE : SDL_LOGICAL_PRESENTATION_LETTERBOX);
} }
// Activa / desactiva el vsync // Alterna entre activar y desactivar el V-Sync
void Screen::toggleVSync() void Screen::toggleVSync()
{ {
options.video.v_sync = !options.video.v_sync; options.video.v_sync = !options.video.v_sync;
SDL_SetRenderVSync(renderer_, options.video.v_sync ? 1 : SDL_RENDERER_VSYNC_DISABLED); SDL_SetRenderVSync(renderer_, options.video.v_sync ? 1 : SDL_RENDERER_VSYNC_DISABLED);
} }
// Establece el estado del V-Sync
void Screen::setVSync(bool enabled)
{
options.video.v_sync = enabled;
SDL_SetRenderVSync(renderer_, enabled ? 1 : SDL_RENDERER_VSYNC_DISABLED);
}
// Obtiene los punteros a los singletones // Obtiene los punteros a los singletones
void Screen::getSingletons() void Screen::getSingletons()
{ {
@@ -430,3 +442,10 @@ void Screen::applySettings()
adjustWindowSize(); adjustWindowSize();
setFullscreenMode(); setFullscreenMode();
} }
// Crea el objeto de texto
void Screen::createText()
{
auto texture = std::make_shared<Texture>(getRenderer(), Asset::get()->get("aseprite.png"));
text_ = std::make_unique<Text>(texture, Asset::get()->get("aseprite.txt"));
}

View File

@@ -10,11 +10,7 @@
#include "options.h" // Para Options, VideoOptions, options #include "options.h" // Para Options, VideoOptions, options
#include "param.h" // Para Param, ParamGame, param #include "param.h" // Para Param, ParamGame, param
#include "utils.h" // Para Color #include "utils.h" // Para Color
#ifdef DEBUG
#include "text.h" #include "text.h"
#include "resource.h"
#endif
class Notifier; class Notifier;
class ServiceMenu; class ServiceMenu;
@@ -45,9 +41,10 @@ public:
// --- Efectos visuales --- // --- Efectos visuales ---
void shake() { shake_effect_.enable(src_rect_, dst_rect_); } // Agita la pantalla void shake() { shake_effect_.enable(src_rect_, dst_rect_); } // Agita la pantalla
void flash(Color color, int lenght = 10, int delay = 0) { flash_effect_ = FlashEffect(true, lenght, delay, color); } // Pone la pantalla de color void flash(Color color, int lenght = 10, int delay = 0) { flash_effect_ = FlashEffect(true, lenght, delay, color); } // Pone la pantalla de color
void toggleShaders() { options.video.shaders = !options.video.shaders; } // Activa/desactiva los shaders void toggleShaders() { options.video.shaders = !options.video.shaders; } // Alterna entre activar y desactivar los shaders
void toggleIntegerScale(); // Activa/desactiva el escalado entero void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero
void toggleVSync(); // Activa/desactiva el vsync void toggleVSync(); // Alterna entre activar y desactivar el V-Sync
void setVSync(bool enabled); // Establece el estado del V-Sync
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
// --- Getters --- // --- Getters ---
@@ -55,12 +52,13 @@ public:
void show() { SDL_ShowWindow(window_); } // Muestra la ventana void show() { SDL_ShowWindow(window_); } // Muestra la ventana
void hide() { SDL_HideWindow(window_); } // Oculta la ventana void hide() { SDL_HideWindow(window_); } // Oculta la ventana
void getSingletons(); // Obtiene los punteros a los singletones void getSingletons(); // Obtiene los punteros a los singletones
bool getVSync() const { return options.video.v_sync; } // Obtiene el valor de V-Sync
std::shared_ptr<Text> getText() const { return text_; } // Obtiene el puntero al texto de Screen
#ifdef DEBUG #ifdef DEBUG
// --- Debug --- // --- Debug ---
void toggleDebugInfo() { debug_info_.show = !debug_info_.show; } void toggleDebugInfo() { debug_info_.show = !debug_info_.show; }
void setDebugInfoEnabled(bool value) { debug_info_.show = value; } void setDebugInfoEnabled(bool value) { debug_info_.show = value; }
void initDebugInfo() { debug_info_.init(); }
#endif #endif
private: private:
@@ -165,21 +163,10 @@ private:
#ifdef DEBUG #ifdef DEBUG
struct Debug struct Debug
{ {
std::shared_ptr<Text> text = nullptr; std::shared_ptr<Text> text;
bool show = false; bool show = false;
void init()
{
if (Resource::get())
{
text = Resource::get()->getText("aseprite");
if (!text)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to retrieve debug_.text object!");
return;
}
}
}
}; };
#endif #endif
// --- Singleton --- // --- Singleton ---
@@ -204,6 +191,9 @@ private:
Debug debug_info_; // Información de debug Debug debug_info_; // Información de debug
#endif #endif
// --- Texto ---
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
// --- Métodos internos --- // --- Métodos internos ---
bool initSDL(); // Arranca SDL VIDEO y crea la ventana bool initSDL(); // Arranca SDL VIDEO y crea la ventana
void renderFlash(); // Dibuja el efecto de flash en la pantalla void renderFlash(); // Dibuja el efecto de flash en la pantalla
@@ -217,6 +207,7 @@ private:
void getDisplayInfo(); // Obtiene información sobre la pantalla void getDisplayInfo(); // Obtiene información sobre la pantalla
void renderOverlays(); // Renderiza todos los overlays y efectos void renderOverlays(); // Renderiza todos los overlays y efectos
void renderAttenuate(); // Atenúa la pantalla void renderAttenuate(); // Atenúa la pantalla
void createText(); // Crea el objeto de texto
// --- Constructores y destructor --- // --- Constructores y destructor ---
Screen(); Screen();