unificats els resources en un namespace

This commit is contained in:
2025-11-11 10:04:57 +01:00
parent 1821b84e73
commit 54fc6d2902
35 changed files with 356 additions and 341 deletions

View File

@@ -1,4 +1,4 @@
#include "core/resources/resource.hpp"
#include "core/resources/resource_cache.hpp"
#include <SDL3/SDL.h>
@@ -8,40 +8,42 @@
#include <stdexcept> // Para runtime_error
#include <utility>
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/text.hpp" // Para Text, loadTextFile
#include "core/resources/asset.hpp" // Para AssetType, Asset
#include "core/resources/resource_helper.hpp" // Para ResourceHelper
#include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_Loa...
#include "game/defaults.hpp" // Para GameDefaults::VERSION
#include "game/gameplay/room.hpp" // Para RoomData, loadRoomFile, loadRoomTileFile
#include "game/options.hpp" // Para Options, OptionsGame, options
#include "utils/defines.hpp" // Para WINDOW_CAPTION
#include "utils/utils.hpp" // Para getFileName, printWithDots, PaletteColor
#include "version.h" // Para Version::GIT_HASH
struct JA_Music_t; // lines 17-17
struct JA_Sound_t; // lines 18-18
#include "core/rendering/screen.hpp" // Para Screen
#include "core/rendering/text.hpp" // Para Text, loadTextFile
#include "core/resources/resource_list.hpp" // Para List, List::Type
#include "core/resources/resource_helper.hpp" // Para Helper
#include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_Loa...
#include "game/defaults.hpp" // Para GameDefaults::VERSION
#include "game/gameplay/room.hpp" // Para RoomData, loadRoomFile, loadRoomTileFile
#include "game/options.hpp" // Para Options, OptionsGame, options
#include "utils/defines.hpp" // Para WINDOW_CAPTION
#include "utils/utils.hpp" // Para getFileName, printWithDots, PaletteColor
#include "version.h" // Para Version::GIT_HASH
struct JA_Music_t; // lines 17-17
struct JA_Sound_t; // lines 18-18
namespace Resource {
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Resource* Resource::resource = nullptr;
Cache* Cache::cache = nullptr;
// [SINGLETON] Crearemos el objeto screen con esta función estática
void Resource::init() { Resource::resource = new Resource(); }
// [SINGLETON] Crearemos el objeto cache con esta función estática
void Cache::init() { Cache::cache = new Cache(); }
// [SINGLETON] Destruiremos el objeto screen con esta función estática
void Resource::destroy() { delete Resource::resource; }
// [SINGLETON] Destruiremos el objeto cache con esta función estática
void Cache::destroy() { delete Cache::cache; }
// [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
auto Resource::get() -> Resource* { return Resource::resource; }
// [SINGLETON] Con este método obtenemos el objeto cache y podemos trabajar con él
auto Cache::get() -> Cache* { return Cache::cache; }
// Constructor
Resource::Resource()
Cache::Cache()
: loading_text_(Screen::get()->getText()) {
load();
}
// Vacia todos los vectores de recursos
void Resource::clear() {
void Cache::clear() {
clearSounds();
clearMusics();
surfaces_.clear();
@@ -52,7 +54,7 @@ void Resource::clear() {
}
// Carga todos los recursos
void Resource::load() {
void Cache::load() {
calculateTotal();
Screen::get()->setBorderColor(static_cast<Uint8>(PaletteColor::BLACK));
std::cout << "** LOADING RESOURCES" << '\n';
@@ -69,13 +71,13 @@ void Resource::load() {
}
// Recarga todos los recursos
void Resource::reload() {
void Cache::reload() {
clear();
load();
}
// Obtiene el sonido a partir de un nombre
auto Resource::getSound(const std::string& name) -> JA_Sound_t* {
auto Cache::getSound(const std::string& name) -> JA_Sound_t* {
auto it = std::ranges::find_if(sounds_, [&name](const auto& s) { return s.name == name; });
if (it != sounds_.end()) {
@@ -87,7 +89,7 @@ auto Resource::getSound(const std::string& name) -> JA_Sound_t* {
}
// Obtiene la música a partir de un nombre
auto Resource::getMusic(const std::string& name) -> JA_Music_t* {
auto Cache::getMusic(const std::string& name) -> JA_Music_t* {
auto it = std::ranges::find_if(musics_, [&name](const auto& m) { return m.name == name; });
if (it != musics_.end()) {
@@ -99,7 +101,7 @@ auto Resource::getMusic(const std::string& name) -> JA_Music_t* {
}
// Obtiene la surface a partir de un nombre
auto Resource::getSurface(const std::string& name) -> std::shared_ptr<Surface> {
auto Cache::getSurface(const std::string& name) -> std::shared_ptr<Surface> {
auto it = std::ranges::find_if(surfaces_, [&name](const auto& t) { return t.name == name; });
if (it != surfaces_.end()) {
@@ -111,7 +113,7 @@ auto Resource::getSurface(const std::string& name) -> std::shared_ptr<Surface> {
}
// Obtiene la paleta a partir de un nombre
auto Resource::getPalette(const std::string& name) -> Palette {
auto Cache::getPalette(const std::string& name) -> Palette {
auto it = std::ranges::find_if(palettes_, [&name](const auto& t) { return t.name == name; });
if (it != palettes_.end()) {
@@ -123,7 +125,7 @@ auto Resource::getPalette(const std::string& name) -> Palette {
}
// Obtiene el fichero de texto a partir de un nombre
auto Resource::getTextFile(const std::string& name) -> std::shared_ptr<TextFile> {
auto Cache::getTextFile(const std::string& name) -> std::shared_ptr<TextFile> {
auto it = std::ranges::find_if(text_files_, [&name](const auto& t) { return t.name == name; });
if (it != text_files_.end()) {
@@ -135,7 +137,7 @@ auto Resource::getTextFile(const std::string& name) -> std::shared_ptr<TextFile>
}
// Obtiene el objeto de texto a partir de un nombre
auto Resource::getText(const std::string& name) -> std::shared_ptr<Text> {
auto Cache::getText(const std::string& name) -> std::shared_ptr<Text> {
auto it = std::ranges::find_if(texts_, [&name](const auto& t) { return t.name == name; });
if (it != texts_.end()) {
@@ -147,7 +149,7 @@ auto Resource::getText(const std::string& name) -> std::shared_ptr<Text> {
}
// Obtiene la animación a partir de un nombre
auto Resource::getAnimations(const std::string& name) -> Animations& {
auto Cache::getAnimations(const std::string& name) -> Animations& {
auto it = std::ranges::find_if(animations_, [&name](const auto& a) { return a.name == name; });
if (it != animations_.end()) {
@@ -159,7 +161,7 @@ auto Resource::getAnimations(const std::string& name) -> Animations& {
}
// Obtiene el mapa de tiles a partir de un nombre
auto Resource::getTileMap(const std::string& name) -> std::vector<int>& {
auto Cache::getTileMap(const std::string& name) -> std::vector<int>& {
auto it = std::ranges::find_if(tile_maps_, [&name](const auto& t) { return t.name == name; });
if (it != tile_maps_.end()) {
@@ -171,7 +173,7 @@ auto Resource::getTileMap(const std::string& name) -> std::vector<int>& {
}
// Obtiene la habitación a partir de un nombre
auto Resource::getRoom(const std::string& name) -> std::shared_ptr<Room::Data> {
auto Cache::getRoom(const std::string& name) -> std::shared_ptr<Room::Data> {
auto it = std::ranges::find_if(rooms_, [&name](const auto& r) { return r.name == name; });
if (it != rooms_.end()) {
@@ -183,14 +185,14 @@ auto Resource::getRoom(const std::string& name) -> std::shared_ptr<Room::Data> {
}
// Obtiene todas las habitaciones
auto Resource::getRooms() -> std::vector<ResourceRoom>& {
auto Cache::getRooms() -> std::vector<ResourceRoom>& {
return rooms_;
}
// Carga los sonidos
void Resource::loadSounds() {
void Cache::loadSounds() {
std::cout << "\n>> SOUND FILES" << '\n';
auto list = Asset::get()->getListByType(Asset::Type::SOUND);
auto list = List::get()->getListByType(List::Type::SOUND);
sounds_.clear();
for (const auto& l : list) {
@@ -198,7 +200,7 @@ void Resource::loadSounds() {
JA_Sound_t* sound = nullptr;
// Try loading from resource pack first
auto audio_data = Jdd::ResourceHelper::loadFile(l);
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
sound = JA_LoadSound(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
@@ -215,9 +217,9 @@ void Resource::loadSounds() {
}
// Carga las musicas
void Resource::loadMusics() {
void Cache::loadMusics() {
std::cout << "\n>> MUSIC FILES" << '\n';
auto list = Asset::get()->getListByType(Asset::Type::MUSIC);
auto list = List::get()->getListByType(List::Type::MUSIC);
musics_.clear();
for (const auto& l : list) {
@@ -225,7 +227,7 @@ void Resource::loadMusics() {
JA_Music_t* music = nullptr;
// Try loading from resource pack first
auto audio_data = Jdd::ResourceHelper::loadFile(l);
auto audio_data = Helper::loadFile(l);
if (!audio_data.empty()) {
music = JA_LoadMusic(audio_data.data(), static_cast<Uint32>(audio_data.size()));
}
@@ -242,9 +244,9 @@ void Resource::loadMusics() {
}
// Carga las texturas
void Resource::loadSurfaces() {
void Cache::loadSurfaces() {
std::cout << "\n>> SURFACES" << '\n';
auto list = Asset::get()->getListByType(Asset::Type::BITMAP);
auto list = List::get()->getListByType(List::Type::BITMAP);
surfaces_.clear();
for (const auto& l : list) {
@@ -265,9 +267,9 @@ void Resource::loadSurfaces() {
}
// Carga las paletas
void Resource::loadPalettes() {
void Cache::loadPalettes() {
std::cout << "\n>> PALETTES" << '\n';
auto list = Asset::get()->getListByType(Asset::Type::PALETTE);
auto list = List::get()->getListByType(List::Type::PALETTE);
palettes_.clear();
for (const auto& l : list) {
@@ -278,9 +280,9 @@ void Resource::loadPalettes() {
}
// Carga los ficheros de texto
void Resource::loadTextFiles() {
void Cache::loadTextFiles() {
std::cout << "\n>> TEXT FILES" << '\n';
auto list = Asset::get()->getListByType(Asset::Type::FONT);
auto list = List::get()->getListByType(List::Type::FONT);
text_files_.clear();
for (const auto& l : list) {
@@ -291,9 +293,9 @@ void Resource::loadTextFiles() {
}
// Carga las animaciones
void Resource::loadAnimations() {
void Cache::loadAnimations() {
std::cout << "\n>> ANIMATIONS" << '\n';
auto list = Asset::get()->getListByType(Asset::Type::ANIMATION);
auto list = List::get()->getListByType(List::Type::ANIMATION);
animations_.clear();
for (const auto& l : list) {
@@ -304,9 +306,9 @@ void Resource::loadAnimations() {
}
// Carga los mapas de tiles
void Resource::loadTileMaps() {
void Cache::loadTileMaps() {
std::cout << "\n>> TILE MAPS" << '\n';
auto list = Asset::get()->getListByType(Asset::Type::TILEMAP);
auto list = List::get()->getListByType(List::Type::TILEMAP);
tile_maps_.clear();
for (const auto& l : list) {
@@ -318,9 +320,9 @@ void Resource::loadTileMaps() {
}
// Carga las habitaciones
void Resource::loadRooms() {
void Cache::loadRooms() {
std::cout << "\n>> ROOMS" << '\n';
auto list = Asset::get()->getListByType(Asset::Type::ROOM);
auto list = List::get()->getListByType(List::Type::ROOM);
rooms_.clear();
for (const auto& l : list) {
@@ -331,7 +333,7 @@ void Resource::loadRooms() {
}
}
void Resource::createText() {
void Cache::createText() {
struct ResourceInfo {
std::string key; // Identificador del recurso
std::string texture_file; // Nombre del archivo de textura
@@ -360,7 +362,7 @@ void Resource::createText() {
}
// Vacía el vector de sonidos
void Resource::clearSounds() {
void Cache::clearSounds() {
// Itera sobre el vector y libera los recursos asociados a cada JA_Sound_t
for (auto& sound : sounds_) {
if (sound.sound != nullptr) {
@@ -372,7 +374,7 @@ void Resource::clearSounds() {
}
// Vacía el vector de musicas
void Resource::clearMusics() {
void Cache::clearMusics() {
// Itera sobre el vector y libera los recursos asociados a cada JA_Music_t
for (auto& music : musics_) {
if (music.music != nullptr) {
@@ -384,20 +386,20 @@ void Resource::clearMusics() {
}
// Calcula el numero de recursos para cargar
void Resource::calculateTotal() {
std::vector<Asset::Type> asset_types = {
Asset::Type::SOUND,
Asset::Type::MUSIC,
Asset::Type::BITMAP,
Asset::Type::PALETTE,
Asset::Type::FONT,
Asset::Type::ANIMATION,
Asset::Type::TILEMAP,
Asset::Type::ROOM};
void Cache::calculateTotal() {
std::vector<List::Type> asset_types = {
List::Type::SOUND,
List::Type::MUSIC,
List::Type::BITMAP,
List::Type::PALETTE,
List::Type::FONT,
List::Type::ANIMATION,
List::Type::TILEMAP,
List::Type::ROOM};
size_t total = 0;
for (const auto& asset_type : asset_types) {
auto list = Asset::get()->getListByType(asset_type);
auto list = List::get()->getListByType(asset_type);
total += list.size();
}
@@ -405,7 +407,7 @@ void Resource::calculateTotal() {
}
// Muestra el progreso de carga
void Resource::renderProgress() {
void Cache::renderProgress() {
constexpr float X_PADDING = 60.0F;
constexpr float Y_PADDING = 10.0F;
constexpr float BAR_HEIGHT = 5.0F;
@@ -451,7 +453,7 @@ void Resource::renderProgress() {
}
// Comprueba los eventos de la pantalla de carga
void Resource::checkEvents() {
void Cache::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
@@ -468,10 +470,12 @@ void Resource::checkEvents() {
}
// Actualiza el progreso de carga
void Resource::updateLoadingProgress(int steps) {
void Cache::updateLoadingProgress(int steps) {
count_.add(1);
if (count_.loaded % steps == 0 || count_.loaded == count_.total) {
renderProgress();
}
checkEvents();
}
}
} // namespace Resource

View File

@@ -137,10 +137,12 @@ struct ResourceCount {
}
};
class Resource {
namespace Resource {
class Cache {
private:
// [SINGLETON] Objeto resource privado para Don Melitón
static Resource* resource;
// [SINGLETON] Objeto cache privado para Don Melitón
static Cache* cache;
std::vector<ResourceSound> sounds_; // Vector con los sonidos
std::vector<ResourceMusic> musics_; // Vector con las musicas
@@ -206,23 +208,23 @@ class Resource {
// Actualiza el progreso de carga
void updateLoadingProgress(int steps = 5);
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos resource desde fuera
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos cache desde fuera
// Constructor
Resource();
Cache();
// Destructor
~Resource() = default;
~Cache() = default;
public:
// [SINGLETON] Crearemos el objeto resource con esta función estática
// [SINGLETON] Crearemos el objeto cache con esta función estática
static void init();
// [SINGLETON] Destruiremos el objeto resource con esta función estática
// [SINGLETON] Destruiremos el objeto cache con esta función estática
static void destroy();
// [SINGLETON] Con este método obtenemos el objeto resource y podemos trabajar con él
static auto get() -> Resource*;
// [SINGLETON] Con este método obtenemos el objeto cache y podemos trabajar con él
static auto get() -> Cache*;
// Obtiene el sonido a partir de un nombre
auto getSound(const std::string& name) -> JA_Sound_t*;
@@ -256,4 +258,6 @@ class Resource {
// Recarga todos los recursos
void reload();
};
};
} // namespace Resource

View File

@@ -10,7 +10,7 @@
#include "resource_loader.hpp"
namespace Jdd::ResourceHelper {
namespace Resource::Helper {
static bool resource_system_initialized = false;
@@ -26,7 +26,7 @@ auto initializeResourceSystem(const std::string& pack_file, bool enable_fallback
std::cout << "ResourceHelper: Fallback enabled: " << (enable_fallback ? "Yes" : "No")
<< '\n';
bool success = ResourceLoader::get().initialize(pack_file, enable_fallback);
bool success = Loader::get().initialize(pack_file, enable_fallback);
if (success) {
resource_system_initialized = true;
std::cout << "ResourceHelper: Initialization successful\n";
@@ -40,7 +40,7 @@ auto initializeResourceSystem(const std::string& pack_file, bool enable_fallback
// Shutdown the resource system
void shutdownResourceSystem() {
if (resource_system_initialized) {
ResourceLoader::get().shutdown();
Loader::get().shutdown();
resource_system_initialized = false;
std::cout << "ResourceHelper: Shutdown complete\n";
}
@@ -68,7 +68,7 @@ auto loadFile(const std::string& filepath) -> std::vector<uint8_t> {
std::string pack_path = getPackPath(filepath);
// Try to load from pack
auto data = ResourceLoader::get().loadResource(pack_path);
auto data = Loader::get().loadResource(pack_path);
if (!data.empty()) {
return data;
}
@@ -79,7 +79,7 @@ auto loadFile(const std::string& filepath) -> std::vector<uint8_t> {
}
// Load from filesystem
return ResourceLoader::get().loadResource(filepath);
return Loader::get().loadResource(filepath);
}
// Check if a file exists
@@ -91,7 +91,7 @@ auto fileExists(const std::string& filepath) -> bool {
// Check pack if appropriate
if (shouldUseResourcePack(filepath)) {
std::string pack_path = getPackPath(filepath);
if (ResourceLoader::get().resourceExists(pack_path)) {
if (Loader::get().resourceExists(pack_path)) {
return true;
}
}
@@ -150,7 +150,7 @@ auto shouldUseResourcePack(const std::string& filepath) -> bool {
std::ranges::replace(path, '\\', '/');
// Don't use pack for most config files (except config/assets.txt which is loaded
// directly via ResourceLoader::loadAssetsConfig() in release builds)
// directly via Loader::loadAssetsConfig() in release builds)
if (path.find("config/") != std::string::npos) {
return false;
}
@@ -177,7 +177,7 @@ auto isPackLoaded() -> bool {
if (!resource_system_initialized) {
return false;
}
return ResourceLoader::get().isPackLoaded();
return Loader::get().isPackLoaded();
}
} // namespace Jdd::ResourceHelper
} // namespace Resource::Helper

View File

@@ -8,7 +8,7 @@
#include <string>
#include <vector>
namespace Jdd::ResourceHelper {
namespace Resource::Helper {
// Initialize the resource system
// pack_file: Path to resources.pack
@@ -36,6 +36,6 @@ auto shouldUseResourcePack(const std::string& filepath) -> bool;
// Check if pack is loaded
auto isPackLoaded() -> bool;
} // namespace Jdd::ResourceHelper
} // namespace Resource::Helper
#endif // RESOURCE_HELPER_HPP

View File

@@ -1,4 +1,4 @@
#include "core/resources/asset.hpp"
#include "core/resources/resource_list.hpp"
#include <SDL3/SDL.h> // Para SDL_LogWarn, SDL_LogCategory, SDL_LogError
@@ -13,23 +13,25 @@
#include "utils/utils.hpp" // Para getFileName, printWithDots
namespace Resource {
// Singleton
Asset* Asset::instance = nullptr;
List* List::instance = nullptr;
void Asset::init(const std::string& executable_path) {
Asset::instance = new Asset(executable_path);
void List::init(const std::string& executable_path) {
List::instance = new List(executable_path);
}
void Asset::destroy() {
delete Asset::instance;
void List::destroy() {
delete List::instance;
}
auto Asset::get() -> Asset* {
return Asset::instance;
auto List::get() -> List* {
return List::instance;
}
// Añade un elemento al mapa (función auxiliar)
void Asset::addToMap(const std::string& file_path, Type type, bool required, bool absolute) {
void List::addToMap(const std::string& file_path, Type type, bool required, bool absolute) {
std::string full_path = absolute ? file_path : executable_path_ + file_path;
std::string filename = getFileName(full_path);
@@ -44,12 +46,12 @@ void Asset::addToMap(const std::string& file_path, Type type, bool required, boo
}
// Añade un elemento a la lista
void Asset::add(const std::string& file_path, Type type, bool required, bool absolute) {
void List::add(const std::string& file_path, Type type, bool required, bool absolute) {
addToMap(file_path, type, required, absolute);
}
// Carga recursos desde un archivo de configuración con soporte para variables
void Asset::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) {
void List::loadFromFile(const std::string& config_file_path, const std::string& prefix, const std::string& system_folder) {
std::ifstream file(config_file_path);
if (!file.is_open()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
@@ -68,7 +70,7 @@ void Asset::loadFromFile(const std::string& config_file_path, const std::string&
}
// Carga recursos desde un string de configuración (para release con pack)
void Asset::loadFromString(const std::string& config_content, const std::string& prefix, const std::string& system_folder) {
void List::loadFromString(const std::string& config_content, const std::string& prefix, const std::string& system_folder) {
std::istringstream stream(config_content);
std::string line;
int line_number = 0;
@@ -136,7 +138,7 @@ void Asset::loadFromString(const std::string& config_content, const std::string&
}
// Devuelve la ruta completa a un fichero (búsqueda O(1))
auto Asset::get(const std::string& filename) const -> std::string {
auto List::get(const std::string& filename) const -> std::string {
auto it = file_list_.find(filename);
if (it != file_list_.end()) {
return it->second.file;
@@ -147,7 +149,7 @@ auto Asset::get(const std::string& filename) const -> std::string {
}
// Carga datos del archivo
auto Asset::loadData(const std::string& filename) const -> std::vector<uint8_t> {
auto List::loadData(const std::string& filename) const -> std::vector<uint8_t> {
auto it = file_list_.find(filename);
if (it != file_list_.end()) {
std::ifstream file(it->second.file, std::ios::binary);
@@ -176,12 +178,12 @@ auto Asset::loadData(const std::string& filename) const -> std::vector<uint8_t>
}
// Verifica si un recurso existe
auto Asset::exists(const std::string& filename) const -> bool {
auto List::exists(const std::string& filename) const -> bool {
return file_list_.find(filename) != file_list_.end();
}
// Comprueba que existen todos los elementos
auto Asset::check() const -> bool {
auto List::check() const -> bool {
bool success = true;
std::cout << "\n** CHECKING FILES" << '\n';
@@ -223,7 +225,7 @@ auto Asset::check() const -> bool {
}
// Comprueba que existe un fichero
auto Asset::checkFile(const std::string& path) -> bool {
auto List::checkFile(const std::string& path) -> bool {
std::ifstream file(path);
bool success = file.good();
file.close();
@@ -236,7 +238,7 @@ auto Asset::checkFile(const std::string& path) -> bool {
}
// Parsea string a Type
auto Asset::parseAssetType(const std::string& type_str) -> Type {
auto List::parseAssetType(const std::string& type_str) -> Type {
if (type_str == "DATA") {
return Type::DATA;
}
@@ -269,7 +271,7 @@ auto Asset::parseAssetType(const std::string& type_str) -> Type {
}
// Devuelve el nombre del tipo de recurso
auto Asset::getTypeName(Type type) -> std::string {
auto List::getTypeName(Type type) -> std::string {
switch (type) {
case Type::DATA:
return "DATA";
@@ -295,7 +297,7 @@ auto Asset::getTypeName(Type type) -> std::string {
}
// Devuelve la lista de recursos de un tipo
auto Asset::getListByType(Type type) const -> std::vector<std::string> {
auto List::getListByType(Type type) const -> std::vector<std::string> {
std::vector<std::string> list;
for (const auto& [filename, item] : file_list_) {
@@ -311,7 +313,7 @@ auto Asset::getListByType(Type type) const -> std::vector<std::string> {
}
// Reemplaza variables en las rutas
auto Asset::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string {
auto List::replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string {
std::string result = path;
// Reemplazar ${PREFIX}
@@ -332,7 +334,7 @@ auto Asset::replaceVariables(const std::string& path, const std::string& prefix,
}
// Parsea las opciones de una línea de configuración
auto Asset::parseOptions(const std::string& options, bool& required, bool& absolute) -> void {
auto List::parseOptions(const std::string& options, bool& required, bool& absolute) -> void {
if (options.empty()) {
return;
}
@@ -352,3 +354,5 @@ auto Asset::parseOptions(const std::string& options, bool& required, bool& absol
}
}
}
} // namespace Resource

View File

@@ -6,8 +6,10 @@
#include <utility> // Para move
#include <vector> // Para vector
// --- Clase Asset: gestor optimizado de recursos (singleton) ---
class Asset {
namespace Resource {
// --- Clase List: gestor optimizado de recursos (singleton) ---
class List {
public:
// --- Enums ---
enum class Type : int {
@@ -26,9 +28,9 @@ class Asset {
// --- Métodos de singleton ---
static void init(const std::string& executable_path);
static void destroy();
static auto get() -> Asset*;
Asset(const Asset&) = delete;
auto operator=(const Asset&) -> Asset& = delete;
static auto get() -> List*;
List(const List&) = delete;
auto operator=(const List&) -> List& = delete;
// --- Métodos para la gestión de recursos ---
void add(const std::string& file_path, Type type, bool required = true, bool absolute = false);
@@ -66,10 +68,12 @@ class Asset {
static auto parseOptions(const std::string& options, bool& required, bool& absolute) -> void; // Parsea opciones
// --- Constructores y destructor privados (singleton) ---
explicit Asset(std::string executable_path) // Constructor privado
explicit List(std::string executable_path) // Constructor privado
: executable_path_(std::move(executable_path)) {}
~Asset() = default; // Destructor privado
~List() = default; // Destructor privado
// --- Instancia singleton ---
static Asset* instance; // Instancia única de Asset
static List* instance; // Instancia única de List
};
} // namespace Resource

View File

@@ -7,19 +7,19 @@
#include <fstream>
#include <iostream>
namespace Jdd {
namespace Resource {
// Get singleton instance
auto ResourceLoader::get() -> ResourceLoader& {
static ResourceLoader instance_;
auto Loader::get() -> Loader& {
static Loader instance_;
return instance_;
}
// Initialize with a pack file
auto ResourceLoader::initialize(const std::string& pack_file, bool enable_fallback)
auto Loader::initialize(const std::string& pack_file, bool enable_fallback)
-> bool {
if (initialized_) {
std::cout << "ResourceLoader: Already initialized\n";
std::cout << "Loader: Already initialized\n";
return true;
}
@@ -27,35 +27,35 @@ auto ResourceLoader::initialize(const std::string& pack_file, bool enable_fallba
// Try to load the pack file
if (!pack_file.empty() && fileExistsOnFilesystem(pack_file)) {
std::cout << "ResourceLoader: Loading pack file: " << pack_file << '\n';
resource_pack_ = std::make_unique<ResourcePack>();
std::cout << "Loader: Loading pack file: " << pack_file << '\n';
resource_pack_ = std::make_unique<Pack>();
if (resource_pack_->loadPack(pack_file)) {
std::cout << "ResourceLoader: Pack loaded successfully\n";
std::cout << "Loader: Pack loaded successfully\n";
initialized_ = true;
return true;
}
std::cerr << "ResourceLoader: Failed to load pack file\n";
std::cerr << "Loader: Failed to load pack file\n";
resource_pack_.reset();
} else {
std::cout << "ResourceLoader: Pack file not found: " << pack_file << '\n';
std::cout << "Loader: Pack file not found: " << pack_file << '\n';
}
// If pack loading failed and fallback is disabled, fail
if (!fallback_to_files_) {
std::cerr << "ResourceLoader: Pack required but not found (fallback disabled)\n";
std::cerr << "Loader: Pack required but not found (fallback disabled)\n";
return false;
}
// Otherwise, fallback to filesystem
std::cout << "ResourceLoader: Using filesystem fallback\n";
std::cout << "Loader: Using filesystem fallback\n";
initialized_ = true;
return true;
}
// Load a resource
auto ResourceLoader::loadResource(const std::string& filename) -> std::vector<uint8_t> {
auto Loader::loadResource(const std::string& filename) -> std::vector<uint8_t> {
if (!initialized_) {
std::cerr << "ResourceLoader: Not initialized\n";
std::cerr << "Loader: Not initialized\n";
return {};
}
@@ -66,7 +66,7 @@ auto ResourceLoader::loadResource(const std::string& filename) -> std::vector<ui
if (!data.empty()) {
return data;
}
std::cerr << "ResourceLoader: Failed to extract from pack: " << filename
std::cerr << "Loader: Failed to extract from pack: " << filename
<< '\n';
}
}
@@ -76,12 +76,12 @@ auto ResourceLoader::loadResource(const std::string& filename) -> std::vector<ui
return loadFromFilesystem(filename);
}
std::cerr << "ResourceLoader: Resource not found: " << filename << '\n';
std::cerr << "Loader: Resource not found: " << filename << '\n';
return {};
}
// Check if a resource exists
auto ResourceLoader::resourceExists(const std::string& filename) -> bool {
auto Loader::resourceExists(const std::string& filename) -> bool {
if (!initialized_) {
return false;
}
@@ -102,12 +102,12 @@ auto ResourceLoader::resourceExists(const std::string& filename) -> bool {
}
// Check if pack is loaded
auto ResourceLoader::isPackLoaded() const -> bool {
auto Loader::isPackLoaded() const -> bool {
return resource_pack_ && resource_pack_->isLoaded();
}
// Get pack statistics
auto ResourceLoader::getPackResourceCount() const -> size_t {
auto Loader::getPackResourceCount() const -> size_t {
if (resource_pack_ && resource_pack_->isLoaded()) {
return resource_pack_->getResourceCount();
}
@@ -115,14 +115,14 @@ auto ResourceLoader::getPackResourceCount() const -> size_t {
}
// Cleanup
void ResourceLoader::shutdown() {
void Loader::shutdown() {
resource_pack_.reset();
initialized_ = false;
std::cout << "ResourceLoader: Shutdown complete\n";
std::cout << "Loader: Shutdown complete\n";
}
// Load from filesystem
auto ResourceLoader::loadFromFilesystem(const std::string& filepath)
auto Loader::loadFromFilesystem(const std::string& filepath)
-> std::vector<uint8_t> {
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
if (!file) {
@@ -134,7 +134,7 @@ auto ResourceLoader::loadFromFilesystem(const std::string& filepath)
std::vector<uint8_t> data(file_size);
if (!file.read(reinterpret_cast<char*>(data.data()), file_size)) {
std::cerr << "ResourceLoader: Failed to read file: " << filepath << '\n';
std::cerr << "Loader: Failed to read file: " << filepath << '\n';
return {};
}
@@ -142,14 +142,14 @@ auto ResourceLoader::loadFromFilesystem(const std::string& filepath)
}
// Check if file exists on filesystem
auto ResourceLoader::fileExistsOnFilesystem(const std::string& filepath) -> bool {
auto Loader::fileExistsOnFilesystem(const std::string& filepath) -> bool {
return std::filesystem::exists(filepath);
}
// Validate pack integrity
auto ResourceLoader::validatePack() const -> bool {
auto Loader::validatePack() const -> bool {
if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) {
std::cerr << "ResourceLoader: Cannot validate - pack not loaded\n";
std::cerr << "Loader: Cannot validate - pack not loaded\n";
return false;
}
@@ -157,20 +157,20 @@ auto ResourceLoader::validatePack() const -> bool {
uint32_t checksum = resource_pack_->calculatePackChecksum();
if (checksum == 0) {
std::cerr << "ResourceLoader: Pack checksum is zero (invalid)\n";
std::cerr << "Loader: Pack checksum is zero (invalid)\n";
return false;
}
std::cout << "ResourceLoader: Pack checksum: 0x" << std::hex << checksum << std::dec
std::cout << "Loader: Pack checksum: 0x" << std::hex << checksum << std::dec
<< '\n';
std::cout << "ResourceLoader: Pack validation successful\n";
std::cout << "Loader: Pack validation successful\n";
return true;
}
// Load assets.txt from pack
auto ResourceLoader::loadAssetsConfig() const -> std::string {
auto Loader::loadAssetsConfig() const -> std::string {
if (!initialized_ || !resource_pack_ || !resource_pack_->isLoaded()) {
std::cerr << "ResourceLoader: Cannot load assets config - pack not loaded\n";
std::cerr << "Loader: Cannot load assets config - pack not loaded\n";
return "";
}
@@ -178,22 +178,22 @@ auto ResourceLoader::loadAssetsConfig() const -> std::string {
std::string config_path = "config/assets.txt";
if (!resource_pack_->hasResource(config_path)) {
std::cerr << "ResourceLoader: assets.txt not found in pack: " << config_path << '\n';
std::cerr << "Loader: assets.txt not found in pack: " << config_path << '\n';
return "";
}
auto data = resource_pack_->getResource(config_path);
if (data.empty()) {
std::cerr << "ResourceLoader: Failed to load assets.txt from pack\n";
std::cerr << "Loader: Failed to load assets.txt from pack\n";
return "";
}
// Convert bytes to string
std::string config_content(data.begin(), data.end());
std::cout << "ResourceLoader: Loaded assets.txt from pack (" << data.size()
std::cout << "Loader: Loaded assets.txt from pack (" << data.size()
<< " bytes)\n";
return config_content;
}
} // namespace Jdd
} // namespace Resource

View File

@@ -10,13 +10,13 @@
#include "resource_pack.hpp"
namespace Jdd {
namespace Resource {
// Singleton class for loading resources from pack or filesystem
class ResourceLoader {
class Loader {
public:
// Get singleton instance
static auto get() -> ResourceLoader&;
static auto get() -> Loader&;
// Initialize with a pack file (optional)
auto initialize(const std::string& pack_file, bool enable_fallback = true) -> bool;
@@ -43,14 +43,14 @@ class ResourceLoader {
void shutdown();
// Disable copy/move
ResourceLoader(const ResourceLoader&) = delete;
auto operator=(const ResourceLoader&) -> ResourceLoader& = delete;
ResourceLoader(ResourceLoader&&) = delete;
auto operator=(ResourceLoader&&) -> ResourceLoader& = delete;
Loader(const Loader&) = delete;
auto operator=(const Loader&) -> Loader& = delete;
Loader(Loader&&) = delete;
auto operator=(Loader&&) -> Loader& = delete;
private:
ResourceLoader() = default;
~ResourceLoader() = default;
Loader() = default;
~Loader() = default;
// Load from filesystem
static auto loadFromFilesystem(const std::string& filepath) -> std::vector<uint8_t>;
@@ -59,11 +59,11 @@ class ResourceLoader {
static auto fileExistsOnFilesystem(const std::string& filepath) -> bool;
// Member data
std::unique_ptr<ResourcePack> resource_pack_;
std::unique_ptr<Pack> resource_pack_;
bool fallback_to_files_{true};
bool initialized_{false};
};
} // namespace Jdd
} // namespace Resource
#endif // RESOURCE_LOADER_HPP

View File

@@ -10,10 +10,10 @@
#include <fstream>
#include <iostream>
namespace Jdd {
namespace Resource {
// Calculate CRC32 checksum for data verification
auto ResourcePack::calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t {
auto Pack::calculateChecksum(const std::vector<uint8_t>& data) -> uint32_t {
uint32_t checksum = 0x12345678;
for (unsigned char byte : data) {
checksum = ((checksum << 5) + checksum) + byte;
@@ -22,7 +22,7 @@ auto ResourcePack::calculateChecksum(const std::vector<uint8_t>& data) -> uint32
}
// XOR encryption (symmetric - same function for encrypt/decrypt)
void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
void Pack::encryptData(std::vector<uint8_t>& data, const std::string& key) {
if (key.empty()) {
return;
}
@@ -31,13 +31,13 @@ void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& ke
}
}
void ResourcePack::decryptData(std::vector<uint8_t>& data, const std::string& key) {
void Pack::decryptData(std::vector<uint8_t>& data, const std::string& key) {
// XOR is symmetric
encryptData(data, key);
}
// Read entire file into memory
auto ResourcePack::readFile(const std::string& filepath) -> std::vector<uint8_t> {
auto Pack::readFile(const std::string& filepath) -> std::vector<uint8_t> {
std::ifstream file(filepath, std::ios::binary | std::ios::ate);
if (!file) {
std::cerr << "ResourcePack: Failed to open file: " << filepath << '\n';
@@ -57,7 +57,7 @@ auto ResourcePack::readFile(const std::string& filepath) -> std::vector<uint8_t>
}
// Add a single file to the pack
auto ResourcePack::addFile(const std::string& filepath, const std::string& pack_name)
auto Pack::addFile(const std::string& filepath, const std::string& pack_name)
-> bool {
auto file_data = readFile(filepath);
if (file_data.empty()) {
@@ -80,7 +80,7 @@ auto ResourcePack::addFile(const std::string& filepath, const std::string& pack_
}
// Add all files from a directory recursively
auto ResourcePack::addDirectory(const std::string& dir_path,
auto Pack::addDirectory(const std::string& dir_path,
const std::string& base_path) -> bool {
namespace fs = std::filesystem;
@@ -117,7 +117,7 @@ auto ResourcePack::addDirectory(const std::string& dir_path,
}
// Save the pack to a file
auto ResourcePack::savePack(const std::string& pack_file) -> bool {
auto Pack::savePack(const std::string& pack_file) -> bool {
std::ofstream file(pack_file, std::ios::binary);
if (!file) {
std::cerr << "ResourcePack: Failed to create pack file: " << pack_file << '\n';
@@ -162,7 +162,7 @@ auto ResourcePack::savePack(const std::string& pack_file) -> bool {
}
// Load a pack from a file
auto ResourcePack::loadPack(const std::string& pack_file) -> bool {
auto Pack::loadPack(const std::string& pack_file) -> bool {
std::ifstream file(pack_file, std::ios::binary);
if (!file) {
std::cerr << "ResourcePack: Failed to open pack file: " << pack_file << '\n';
@@ -229,7 +229,7 @@ auto ResourcePack::loadPack(const std::string& pack_file) -> bool {
}
// Get a resource by name
auto ResourcePack::getResource(const std::string& filename) -> std::vector<uint8_t> {
auto Pack::getResource(const std::string& filename) -> std::vector<uint8_t> {
auto it = resources_.find(filename);
if (it == resources_.end()) {
return {};
@@ -258,12 +258,12 @@ auto ResourcePack::getResource(const std::string& filename) -> std::vector<uint8
}
// Check if a resource exists
auto ResourcePack::hasResource(const std::string& filename) const -> bool {
auto Pack::hasResource(const std::string& filename) const -> bool {
return resources_.find(filename) != resources_.end();
}
// Get list of all resources
auto ResourcePack::getResourceList() const -> std::vector<std::string> {
auto Pack::getResourceList() const -> std::vector<std::string> {
std::vector<std::string> list;
list.reserve(resources_.size());
for (const auto& [name, entry] : resources_) {
@@ -274,7 +274,7 @@ auto ResourcePack::getResourceList() const -> std::vector<std::string> {
}
// Calculate overall pack checksum for validation
auto ResourcePack::calculatePackChecksum() const -> uint32_t {
auto Pack::calculatePackChecksum() const -> uint32_t {
if (!loaded_ || data_.empty()) {
return 0;
}
@@ -300,4 +300,4 @@ auto ResourcePack::calculatePackChecksum() const -> uint32_t {
return global_checksum;
}
} // namespace Jdd
} // namespace Resource

View File

@@ -11,7 +11,7 @@
#include <unordered_map>
#include <vector>
namespace Jdd {
namespace Resource {
// Entry metadata for each resource in the pack
struct ResourceEntry {
@@ -25,16 +25,16 @@ struct ResourceEntry {
// Header: "JDDI" (4 bytes) + Version (4 bytes)
// Metadata: Count + array of ResourceEntry
// Data: Encrypted data block
class ResourcePack {
class Pack {
public:
ResourcePack() = default;
~ResourcePack() = default;
Pack() = default;
~Pack() = default;
// Disable copy/move
ResourcePack(const ResourcePack&) = delete;
auto operator=(const ResourcePack&) -> ResourcePack& = delete;
ResourcePack(ResourcePack&&) = delete;
auto operator=(ResourcePack&&) -> ResourcePack& = delete;
Pack(const Pack&) = delete;
auto operator=(const Pack&) -> Pack& = delete;
Pack(Pack&&) = delete;
auto operator=(Pack&&) -> Pack& = delete;
// Add a single file to the pack
auto addFile(const std::string& filepath, const std::string& pack_name) -> bool;
@@ -89,6 +89,6 @@ class ResourcePack {
bool loaded_{false};
};
} // namespace Jdd
} // namespace Resource
#endif // RESOURCE_PACK_HPP