#include "core/resources/resource_helper.hpp" #include #include #include #include #include "core/resources/resource_pack.hpp" namespace Resource::Helper { namespace { std::string g_data_root; Pack g_pack; bool g_pack_loaded = false; bool g_fallback_enabled = true; auto readFromDisk(const std::string& filepath) -> std::vector { const auto FULL = resolve(filepath); std::ifstream file(FULL, std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Resource::Helper: cannot open " << FULL << '\n'; return {}; } std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector data(static_cast(size)); if (!file.read(reinterpret_cast(data.data()), size)) { std::cerr << "Resource::Helper: failed to read " << FULL << '\n'; return {}; } return data; } } // namespace auto initializeResourceSystem(const std::string& pack_file, bool enable_fallback) -> bool { g_fallback_enabled = enable_fallback; g_pack_loaded = g_pack.loadPack(pack_file); if (g_pack_loaded) { std::cout << "Resource::Helper: pack loaded (" << g_pack.getResourceCount() << " entries) from " << pack_file << '\n'; } else if (enable_fallback) { std::cout << "Resource::Helper: no pack at " << pack_file << " — using filesystem fallback\n"; } else { std::cerr << "Resource::Helper: FATAL — no pack at " << pack_file << " and fallback disabled\n"; return false; } return true; } void shutdownResourceSystem() { g_pack.clear(); g_pack_loaded = false; } auto hasPack() -> bool { return g_pack_loaded; } void setDataRoot(const std::string& absolute_path) { g_data_root = absolute_path; if (!g_data_root.empty() && g_data_root.back() != '/') { g_data_root += '/'; } } auto resolve(const std::string& filepath) -> std::string { if (filepath.empty() || filepath.front() == '/') { return filepath; } if (g_data_root.empty()) { return filepath; } return g_data_root + filepath; } auto loadFile(const std::string& filepath) -> std::vector { if (g_pack_loaded) { // El pack està indexat relatiu a `data/` (la carpeta que // s'empaqueta), però els callers passen "data/foo.yaml" amb // prefix. Fem el strip ací perquè no hagin de tenir-ho en compte. constexpr std::string_view PREFIX = "data/"; std::string key = filepath; if (key.starts_with(PREFIX)) { key.erase(0, PREFIX.size()); } if (g_pack.hasResource(key)) { return g_pack.getResource(key); } } if (g_fallback_enabled) { return readFromDisk(filepath); } return {}; } } // namespace Resource::Helper