treball en curs: correccions de tidy

This commit is contained in:
2026-05-16 17:19:40 +02:00
parent 3421f34a84
commit ee2dd0bc2c
30 changed files with 1220 additions and 1479 deletions
+35 -61
View File
@@ -26,24 +26,24 @@ auto Asset::get() -> Asset * {
// Constructor
Asset::Asset(const std::string &executablePath)
: executablePath(executablePath.substr(0, executablePath.find_last_of("\\/"))) {
: executable_path_(executablePath.substr(0, executablePath.find_last_of("\\/"))) {
}
// Añade un elemento a la lista
void Asset::add(const std::string &file, enum AssetType type, bool required, bool absolute) {
void Asset::add(const std::string &file, Type type, bool required, bool absolute) {
Item temp;
temp.file = absolute ? file : executablePath + file;
temp.file = absolute ? file : executable_path_ + file;
temp.type = type;
temp.required = required;
fileList.push_back(temp);
file_list_.push_back(temp);
const std::string filename = file.substr(file.find_last_of("\\/") + 1);
longestName = SDL_max(longestName, filename.size());
longest_name_ = SDL_max(longest_name_, filename.size());
}
// Devuelve el fichero de un elemento de la lista a partir de una cadena
auto Asset::get(const std::string &text) -> std::string {
for (const auto &f : fileList) {
for (const auto &f : file_list_) {
const size_t lastIndex = f.file.find_last_of('/') + 1;
const std::string file = f.file.substr(lastIndex);
@@ -52,7 +52,7 @@ auto Asset::get(const std::string &text) -> std::string {
}
}
if (verbose) {
if (verbose_) {
std::cout << "Warning: file " << text.c_str() << " not found" << '\n';
}
return "";
@@ -62,32 +62,34 @@ auto Asset::get(const std::string &text) -> std::string {
auto Asset::check() -> bool {
bool success = true;
if (verbose) {
if (verbose_) {
std::cout << "\n** Checking files" << '\n';
std::cout << "Executable path is: " << executablePath << '\n';
std::cout << "Sample filepath: " << fileList.back().file << '\n';
std::cout << "Executable path is: " << executable_path_ << '\n';
std::cout << "Sample filepath: " << file_list_.back().file << '\n';
}
// Comprueba la lista de ficheros clasificandolos por tipo
for (int type = 0; type < t_maxAssetType; ++type) {
for (int i = 0; i < static_cast<int>(Type::COUNT); ++i) {
const Type TYPE = static_cast<Type>(i);
// Comprueba si hay ficheros de ese tipo
bool any = false;
for (const auto &f : fileList) {
if ((f.required) && (f.type == type)) {
for (const auto &f : file_list_) {
if (f.required && f.type == TYPE) {
any = true;
}
}
// Si hay ficheros de ese tipo, comprueba si existen
if (any) {
if (verbose) {
std::cout << "\n>> " << getTypeName(type).c_str() << " FILES" << '\n';
if (verbose_) {
std::cout << "\n>> " << getTypeName(TYPE).c_str() << " FILES" << '\n';
}
for (const auto &f : fileList) {
if ((f.required) && (f.type == type)) {
for (const auto &f : file_list_) {
if (f.required && f.type == TYPE) {
success &= checkFile(f.file);
}
}
@@ -95,7 +97,7 @@ auto Asset::check() -> bool {
}
// Resultado
if (verbose) {
if (verbose_) {
if (success) {
std::cout << "\n** All files OK.\n"
<< '\n';
@@ -130,10 +132,10 @@ auto Asset::checkFile(const std::string &path) const -> bool {
}
}
if (verbose) {
if (verbose_) {
std::cout.setf(std::ios::left, std::ios::adjustfield);
std::cout << "Checking file: ";
std::cout.width(longestName + 2);
std::cout.width(longest_name_ + 2);
std::cout.fill('.');
std::cout << filename + " ";
std::cout << " [" + result + "]" << '\n';
@@ -143,51 +145,23 @@ auto Asset::checkFile(const std::string &path) const -> bool {
}
// Devuelve el nombre del tipo de recurso
auto Asset::getTypeName(int type) -> std::string {
auto Asset::getTypeName(Type type) -> std::string {
switch (type) {
case t_bitmap:
return "BITMAP";
break;
case t_music:
return "MUSIC";
break;
case t_sound:
return "SOUND";
break;
case t_font:
return "FONT";
break;
case t_lang:
return "LANG";
break;
case t_data:
return "DATA";
break;
case t_room:
return "ROOM";
break;
case t_enemy:
return "ENEMY";
break;
case t_item:
return "ITEM";
break;
default:
return "ERROR";
break;
case Type::BITMAP: return "BITMAP";
case Type::MUSIC: return "MUSIC";
case Type::SOUND: return "SOUND";
case Type::FONT: return "FONT";
case Type::LANG: return "LANG";
case Type::DATA: return "DATA";
case Type::ROOM: return "ROOM";
case Type::ENEMY: return "ENEMY";
case Type::ITEM: return "ITEM";
case Type::COUNT:
default: return "ERROR";
}
}
// Establece si ha de mostrar texto por pantalla
void Asset::setVerbose(bool value) {
verbose = value;
verbose_ = value;
}
+36 -50
View File
@@ -4,66 +4,52 @@
#include <string> // for string, basic_string
#include <vector> // for vector
enum AssetType : std::uint8_t {
t_bitmap,
t_music,
t_sound,
t_font,
t_lang,
t_data,
t_room,
t_enemy,
t_item,
t_maxAssetType
};
// Clase Asset
class Asset {
public:
// Tipos de recurso
enum class Type : std::uint8_t {
BITMAP,
MUSIC,
SOUND,
FONT,
LANG,
DATA,
ROOM,
ENEMY,
ITEM,
COUNT // Centinela: número total de tipos
};
// Estructura para definir un item
struct Item {
std::string file; // Ruta del fichero desde la raiz del directorio
enum AssetType type; // Indica el tipo de recurso
bool required; // Indica si es un fichero que debe de existir
std::string file; // Ruta del fichero desde la raiz del directorio
Type type; // Indica el tipo de recurso
bool required; // Indica si es un fichero que debe de existir
};
// Singleton API
static void init(const std::string &executable_path); // Crea la instancia
static void destroy(); // Libera la instancia
static auto get() -> Asset *; // Obtiene el puntero a la instancia
void add(const std::string &file, Type type, bool required = true, bool absolute = false); // Añade un elemento a la lista
auto get(const std::string &text) -> std::string; // Devuelve un elemento de la lista a partir de una cadena
[[nodiscard]] auto getAll() const -> const std::vector<Item> & { return file_list_; } // Devuelve toda la lista de items registrados
auto check() -> bool; // Comprueba que existen todos los elementos
void setVerbose(bool value); // Establece si ha de mostrar texto por pantalla
private:
// Variables
int longestName{0}; // Contiene la longitud del nombre de fichero mas largo
std::vector<Item> fileList; // Listado con todas las rutas a los ficheros
std::string executablePath; // Ruta al ejecutable
bool verbose{true}; // Indica si ha de mostrar información por pantalla
int longest_name_{0}; // Contiene la longitud del nombre de fichero mas largo
std::vector<Item> file_list_; // Listado con todas las rutas a los ficheros
std::string executable_path_; // Ruta al ejecutable
bool verbose_{true}; // Indica si ha de mostrar información por pantalla
// Comprueba que existe un fichero
[[nodiscard]] auto checkFile(const std::string &executablePath) const -> bool;
static Asset *instance; // Instancia única
// Devuelve el nombre del tipo de recurso
static auto getTypeName(int type) -> std::string;
explicit Asset(const std::string &path); // Constructor privado (usar Asset::init)
// Constructor privado (usar Asset::init)
explicit Asset(const std::string &path);
// Instancia única
static Asset *instance;
public:
// Singleton API
static void init(const std::string &executablePath); // Crea la instancia
static void destroy(); // Libera la instancia
static auto get() -> Asset *; // Obtiene el puntero a la instancia
// Añade un elemento a la lista
void add(const std::string &file, enum AssetType type, bool required = true, bool absolute = false);
// Devuelve un elemento de la lista a partir de una cadena
auto get(const std::string &text) -> std::string;
// Devuelve toda la lista de items registrados
[[nodiscard]] auto getAll() const -> const std::vector<Item> & { return fileList; }
// Comprueba que existen todos los elementos
auto check() -> bool;
// Establece si ha de mostrar texto por pantalla
void setVerbose(bool value);
[[nodiscard]] auto checkFile(const std::string &executable_path) const -> bool; // Comprueba que existe un fichero
static auto getTypeName(Type type) -> std::string; // Devuelve el nombre del tipo de recurso
};
+86 -71
View File
@@ -1,7 +1,5 @@
#include "core/resources/resource.h"
#include <algorithm>
#include <filesystem>
#include <iostream>
#include <sstream>
@@ -15,7 +13,7 @@
// Nota: Asset::get() e Input::get() se consultan en preloadAll y al construir
// los menús; no se guardan punteros en el objeto Resource.
Resource *Resource::instance_ = nullptr;
Resource *Resource::instance = nullptr;
static auto basename(const std::string &path) -> std::string {
return path.substr(path.find_last_of("\\/") + 1);
@@ -31,19 +29,19 @@ static auto stem(const std::string &path) -> std::string {
}
void Resource::init(SDL_Renderer *renderer) {
if (instance_ == nullptr) {
instance_ = new Resource(renderer);
instance_->preloadAll();
if (instance == nullptr) {
instance = new Resource(renderer);
instance->preloadAll();
}
}
void Resource::destroy() {
delete instance_;
instance_ = nullptr;
delete instance;
instance = nullptr;
}
auto Resource::get() -> Resource * {
return instance_;
return instance;
}
Resource::Resource(SDL_Renderer *renderer)
@@ -77,11 +75,17 @@ Resource::~Resource() {
}
void Resource::preloadAll() {
preloadResources();
preloadFonts();
preloadMenus();
}
// Pass 1: texturas, sonidos, músicas y datos (animaciones / demo / menús)
void Resource::preloadResources() {
const auto &items = Asset::get()->getAll();
// Pass 1: texturas, sonidos, músicas, animaciones (raw lines), demo, lenguajes
for (const auto &it : items) {
if (!ResourceHelper::shouldUseResourcePack(it.file) && it.type != t_lang) {
if (!ResourceHelper::shouldUseResourcePack(it.file) && it.type != Asset::Type::LANG) {
// Ficheros absolutos (config.txt, score.bin, systemFolder) — no se precargan
continue;
}
@@ -90,97 +94,108 @@ void Resource::preloadAll() {
continue;
}
const std::string bname = basename(it.file);
const std::string BASE_NAME = basename(it.file);
switch (it.type) {
case t_bitmap: {
case Asset::Type::BITMAP: {
auto *tex = new Texture(renderer_, bytes);
textures_[bname] = tex;
textures_[BASE_NAME] = tex;
break;
}
case t_sound: {
case Asset::Type::SOUND: {
JA_Sound_t *s = JA_LoadSound(bytes.data(), (uint32_t)bytes.size());
if (s != nullptr) {
sounds_[bname] = s;
sounds_[BASE_NAME] = s;
}
break;
}
case t_music: {
case Asset::Type::MUSIC: {
JA_Music_t *m = JA_LoadMusic(bytes.data(), (Uint32)bytes.size());
if (m != nullptr) {
musics_[bname] = m;
musics_[BASE_NAME] = m;
}
break;
}
case t_data: {
if (bname.size() >= 4 && bname.substr(bname.size() - 4) == ".ani") {
std::string content(reinterpret_cast<const char *>(bytes.data()), bytes.size());
std::stringstream ss(content);
std::vector<std::string> lines;
std::string line;
while (std::getline(ss, line)) {
// Normalitza CRLF perquè loadFromVector compari línies amb literals
// ("[animation]", "[/animation]") sense \r residual.
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
lines.push_back(line);
}
animationLines_[bname] = std::move(lines);
} else if (bname == "demo.bin") {
demoBytes_ = bytes;
} else if (bname.size() >= 4 && bname.substr(bname.size() - 4) == ".men") {
// Menús: se construyen en pass 2 porque dependen de textos y sonidos
}
case Asset::Type::DATA:
loadDataAsset(BASE_NAME, bytes);
break;
}
case t_font: // Fonts: se emparejan en pass 2
case t_lang: // Lenguaje: lo sigue leyendo la clase Lang via ResourceHelper
case Asset::Type::FONT: // Fonts: se emparejan en pass 2
case Asset::Type::LANG: // Lenguaje: lo sigue leyendo la clase Lang via ResourceHelper
default:
break;
}
}
}
// Pass 2: Text (fuentes emparejadas png+txt) y Menus (dependen de Text+sonidos)
// Fuentes: construimos un Text por cada par basename.png + basename.txt
// Acumulamos los bytes encontrados por stem (basename sin ext.)
std::unordered_map<std::string, std::vector<uint8_t>> fontPngs;
std::unordered_map<std::string, std::vector<uint8_t>> fontTxts;
// Despacha un asset Asset::Type::DATA en función de la extensión / nombre
void Resource::loadDataAsset(const std::string &bname, const std::vector<uint8_t> &bytes) {
if (bname.size() >= 4 && bname.substr(bname.size() - 4) == ".ani") {
std::string content(reinterpret_cast<const char *>(bytes.data()), bytes.size());
std::stringstream ss(content);
std::vector<std::string> lines;
std::string line;
while (std::getline(ss, line)) {
// Normalitza CRLF perquè loadFromVector compari línies amb literals
// ("[animation]", "[/animation]") sense \r residual.
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
lines.push_back(line);
}
animation_lines_[bname] = std::move(lines);
} else if (bname == "demo.bin") {
demo_bytes_ = bytes;
}
// Menús (.men): se construyen en pass 2 porque dependen de textos y sonidos
}
// Pass 2a: construye Text por cada par basename.png + basename.txt
void Resource::preloadFonts() {
const auto &items = Asset::get()->getAll();
std::unordered_map<std::string, std::vector<uint8_t>> font_pngs;
std::unordered_map<std::string, std::vector<uint8_t>> font_txts;
for (const auto &it : items) {
if (it.type != t_font) {
if (it.type != Asset::Type::FONT) {
continue;
}
auto bytes = ResourceHelper::loadFile(it.file);
if (bytes.empty()) {
continue;
}
const std::string s = stem(it.file);
const std::string bname = basename(it.file);
if (bname.size() >= 4 && bname.substr(bname.size() - 4) == ".png") {
fontPngs[s] = std::move(bytes);
} else if (bname.size() >= 4 && bname.substr(bname.size() - 4) == ".txt") {
fontTxts[s] = std::move(bytes);
const std::string S = stem(it.file);
const std::string BASE_NAME = basename(it.file);
if (BASE_NAME.size() >= 4 && BASE_NAME.substr(BASE_NAME.size() - 4) == ".png") {
font_pngs[S] = std::move(bytes);
} else if (BASE_NAME.size() >= 4 && BASE_NAME.substr(BASE_NAME.size() - 4) == ".txt") {
font_txts[S] = std::move(bytes);
}
}
for (const auto &[s, png] : fontPngs) {
auto itTxt = fontTxts.find(s);
if (itTxt == fontTxts.end()) {
for (const auto &[s, png] : font_pngs) {
auto it_txt = font_txts.find(s);
if (it_txt == font_txts.end()) {
continue;
}
Text *t = new Text(png, itTxt->second, renderer_);
Text *t = new Text(png, it_txt->second, renderer_);
texts_[s] = t;
}
}
// Pass 2b: construye los Menu (dependen de Text+sonidos cargados antes)
//
// NOTA: Menu::loadFromBytes aún llama internamente a asset->get() y Text/
// JA_LoadSound por path. Funciona en modo fallback; en pack estricto requiere
// que Menu se adapte a cargar desde ResourceHelper. Migración pendiente.
void Resource::preloadMenus() {
const auto &items = Asset::get()->getAll();
// Menus: usan aún Menu::loadFromBytes que internamente llama a asset->get() y
// Text/JA_LoadSound por path. Funciona en modo fallback; en pack estricto
// requiere que Menu se adapte a cargar desde ResourceHelper. Por ahora
// lo dejamos así y será una migración del paso 7.
for (const auto &it : items) {
if (it.type != t_data) {
if (it.type != Asset::Type::DATA) {
continue;
}
const std::string bname = basename(it.file);
if (bname.size() < 4 || bname.substr(bname.size() - 4) != ".men") {
const std::string BASE_NAME = basename(it.file);
if (BASE_NAME.size() < 4 || BASE_NAME.substr(BASE_NAME.size() - 4) != ".men") {
continue;
}
auto bytes = ResourceHelper::loadFile(it.file);
@@ -188,9 +203,9 @@ void Resource::preloadAll() {
continue;
}
Menu *m = new Menu(renderer_, "");
m->loadFromBytes(bytes, bname);
const std::string s = stem(it.file);
menus_[s] = m;
m->loadFromBytes(bytes, BASE_NAME);
const std::string S = stem(it.file);
menus_[S] = m;
}
}
@@ -222,11 +237,11 @@ auto Resource::getMusic(const std::string &name) -> JA_Music_t * {
}
auto Resource::getAnimationLines(const std::string &name) -> std::vector<std::string> & {
auto it = animationLines_.find(name);
if (it == animationLines_.end()) {
static std::vector<std::string> empty;
auto it = animation_lines_.find(name);
if (it == animation_lines_.end()) {
static std::vector<std::string> empty_;
std::cerr << "Resource::getAnimationLines: missing " << name << '\n';
return empty;
return empty_;
}
return it->second;
}
+10 -4
View File
@@ -27,7 +27,7 @@ class Resource {
auto getAnimationLines(const std::string &name) -> std::vector<std::string> &;
auto getText(const std::string &name) -> Text *; // name sin extensión: "smb2", "nokia2", ...
auto getMenu(const std::string &name) -> Menu *; // name sin extensión: "title", "options", ...
auto getDemoBytes() const -> const std::vector<uint8_t> & { return demoBytes_; }
auto getDemoBytes() const -> const std::vector<uint8_t> & { return demo_bytes_; }
private:
explicit Resource(SDL_Renderer *renderer);
@@ -35,15 +35,21 @@ class Resource {
void preloadAll();
// Helpers de preloadAll
void preloadResources();
void loadDataAsset(const std::string &bname, const std::vector<uint8_t> &bytes);
void preloadFonts();
void preloadMenus();
SDL_Renderer *renderer_;
std::unordered_map<std::string, Texture *> textures_;
std::unordered_map<std::string, JA_Sound_t *> sounds_;
std::unordered_map<std::string, JA_Music_t *> musics_;
std::unordered_map<std::string, std::vector<std::string>> animationLines_;
std::unordered_map<std::string, std::vector<std::string>> animation_lines_;
std::unordered_map<std::string, Text *> texts_;
std::unordered_map<std::string, Menu *> menus_;
std::vector<uint8_t> demoBytes_;
std::vector<uint8_t> demo_bytes_;
static Resource *instance_;
static Resource *instance;
};