Files
orni-attack/source/core/graphics/shape_loader.cpp
T
JailDesigner efbf2457a1 Lint: inicializadores + retornos const-ref + warnings preexistentes
Primera tanda mecánica sobre el lint pendiente. Arregla la causa raíz, no
silencia diagnósticos. Detalle por categoría:

- Uninit members (cppcheck warnings) → inicializadores en declaración:
  Bullet (esta_, owner_id_, grace_timer_), Enemy (drotacio_, rotacio_,
  esta_, type_, tracking_timer_, ship_position_, tracking_strength_,
  direction_change_timer_, timer_invulnerabilitat_), Ship (is_hit_,
  invulnerable_timer_), Shape (escala_defecte_) y TitleShip (todos los
  miembros del struct, que viven dentro de un std::array<,2>).

- returnByReference (cppcheck performance) → return const T&:
  Shape::getName, ResourceLoader::getBasePath. De paso, Shape::get_nom
  se renombra a getName y get_num_primitives a getNumPrimitives para
  cumplir la convención camelBack del proyecto (lint del .clang-tidy).

- useInitializationList (cppcheck performance) →
  Starfield::shape_estrella_ pasa a la lista de inicialización (reordenada
  según la declaración para no disparar -Wreorder-ctor).

- noExplicitConstructor (cppcheck style) → explicit en ctores de 1 arg:
  Bullet(Renderer*), Enemy(Renderer*), Ship(Renderer*,...) y VectorText(Renderer*).

- variableScope (cppcheck style) → en vector_text.cpp se elimina la
  variable 'c' intermedia y se usa el literal '\\xA9' directamente en el
  único punto donde se necesita.

- constParameterReference (cppcheck style) → drawScoreboardAnimated pasa
  el VectorText por const ref (la API render/renderCentered es const).

- Warnings preexistentes del compilador (resueltos de paso):
  - stage_config.hpp: stage_id <= 255 sobre uint8_t era siempre true; se
    elimina la comparación redundante y se explica con comentario.
  - director.cpp: 'struct stat st = {.st_dev = 0};' disparaba
    -Wmissing-field-initializers; pasa a 'struct stat st{};' (zero-init
    completo, robusto a las variantes específicas del SO).
  - game_scene.cpp: stepDeathSequence devolvía un bool [[nodiscard]] que
    el caller ignoraba; el valor era puramente interno. Cambiada la
    firma a void.

- cppcheck: añadido --suppress=useStlAlgorithm. Las 26 sugerencias
  'Consider using std::any_of/find_if/count_if' son cosméticas y no
  aportan claridad sobre las raw loops actuales.

- .clang-tidy de source/core/audio/ eliminado: deshabilitaba todos los
  checks en ese subdirectorio por dependencia de jail_audio.hpp, pero
  impedía ejecutar 'make tidy' (clang-tidy aborta con "no checks
  enabled" al primer archivo del directorio). El proyecto pasa a usar
  el mismo patrón de CCAE: solo source/external/ y source/legacy/
  quedan fuera del lint.

- lint-reports/ añadido a .gitignore. Carpeta donde 'make tidy' y
  'make cppcheck' vuelcan su salida completa para inspección posterior.

Build limpio, cero warnings activos.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 10:29:36 +02:00

87 lines
2.6 KiB
C++

// shape_loader.cpp - Implementació del carregador con caché
// © 2026 JailDesigner
#include "core/graphics/shape_loader.hpp"
#include <iostream>
#include "core/resources/resource_helper.hpp"
namespace Graphics {
// Inicialización de variables estàtiques
std::unordered_map<std::string, std::shared_ptr<Shape>> ShapeLoader::cache_;
std::string ShapeLoader::base_path_ = "data/shapes/";
std::shared_ptr<Shape> ShapeLoader::load(const std::string& filename) {
// Check cache first
auto it = cache_.find(filename);
if (it != cache_.end()) {
std::cout << "[ShapeLoader] Cache hit: " << filename << '\n';
return it->second; // Cache hit
}
// Normalize path: "ship.shp" → "shapes/ship.shp"
// "logo/letra_j.shp" → "shapes/logo/letra_j.shp"
std::string normalized = filename;
if (!normalized.starts_with("shapes/")) {
// Doesn't start with "shapes/", so add it
normalized = "shapes/" + normalized;
}
// Load from resource system
std::vector<uint8_t> data = Resource::Helper::loadFile(normalized);
if (data.empty()) {
std::cerr << "[ShapeLoader] Error: no s'ha pogut load " << normalized
<< '\n';
return nullptr;
}
// Convert bytes to string and parse
std::string file_content(data.begin(), data.end());
auto shape = std::make_shared<Shape>();
if (!shape->parseFile(file_content)) {
std::cerr << "[ShapeLoader] Error: no s'ha pogut parsejar " << normalized
<< '\n';
return nullptr;
}
// Verify shape is valid
if (!shape->isValid()) {
std::cerr << "[ShapeLoader] Error: shape invàlida " << normalized << '\n';
return nullptr;
}
// Cache and return
std::cout << "[ShapeLoader] Carregat: " << normalized << " (" << shape->getName()
<< ", " << shape->getNumPrimitives() << " primitives)" << '\n';
cache_[filename] = shape;
return shape;
}
void ShapeLoader::clear_cache() {
std::cout << "[ShapeLoader] Netejant caché (" << cache_.size() << " formes)"
<< '\n';
cache_.clear();
}
size_t ShapeLoader::get_cache_size() { return cache_.size(); }
std::string ShapeLoader::resolve_path(const std::string& filename) {
// Si es un path absolut (comença con '/'), usar-lo directament
if (!filename.empty() && filename[0] == '/') {
return filename;
}
// Si ya conté el prefix base_path, usar-lo directament
if (filename.starts_with(base_path_)) {
return filename;
}
// Altrament, añadir base_path (ara suporta subdirectoris)
return base_path_ + filename;
}
} // namespace Graphics