neteja final tidy/cppcheck: const*, static, renames de constants

This commit is contained in:
2026-05-16 19:40:33 +02:00
parent 37cb3c782a
commit 479d9d941a
14 changed files with 272 additions and 337 deletions
+117 -195
View File
@@ -1,95 +1,120 @@
#include "core/rendering/animatedsprite.h"
#include <fstream> // for basic_ostream, operator<<, basic_istream, basic...
#include <iostream> // for cout
#include <sstream> // for basic_stringstream
#include "core/rendering/texture.h" // for Texture
#include "core/resources/resource_helper.h" // for loadFile (pack + filesystem fallback)
namespace {
// Normalitza CRLF: fitxers .ani amb terminadors de Windows fan que
// line == "[animation]" no faci match i el parser entri en bucle
// infinit / no carregui cap animació.
void stripCr(std::string &s) {
if (!s.empty() && s.back() == '\r') {
s.pop_back();
}
}
void parseFramesList(const std::string &value, Animation &buffer, int frame_width, int frame_height, int frames_per_row, int max_tiles) {
std::stringstream ss(value);
std::string tmp;
SDL_Rect rect = {0, 0, frame_width, frame_height};
while (getline(ss, tmp, ',')) {
const int NUM_TILE = std::stoi(tmp) > max_tiles ? 0 : std::stoi(tmp);
rect.x = (NUM_TILE % frames_per_row) * frame_width;
rect.y = (NUM_TILE / frames_per_row) * frame_height;
buffer.frames.push_back(rect);
}
}
void parseAnimationField(const std::string &line, int pos, Animation &buffer, int frame_width, int frame_height, int frames_per_row, int max_tiles, const std::string &filename) {
const std::string KEY = line.substr(0, pos);
const std::string VALUE = line.substr(pos + 1, line.length());
if (KEY == "name") {
buffer.name = VALUE;
} else if (KEY == "speed") {
buffer.speed = std::stoi(VALUE);
} else if (KEY == "loop") {
buffer.loop = std::stoi(VALUE);
} else if (KEY == "frames") {
parseFramesList(VALUE, buffer, frame_width, frame_height, frames_per_row, max_tiles);
} else {
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << KEY.c_str() << "\"" << '\n';
}
}
auto parseAnimationBlock(std::istream &file, int frame_width, int frame_height, int frames_per_row, int max_tiles, const std::string &filename) -> Animation {
Animation buffer;
buffer.speed = 0;
buffer.loop = -1;
buffer.counter = 0;
buffer.current_frame = 0;
buffer.completed = false;
std::string line;
do {
if (!std::getline(file, line)) {
break;
}
stripCr(line);
int pos = line.find('=');
if (pos != (int)std::string::npos) {
parseAnimationField(line, pos, buffer, frame_width, frame_height, frames_per_row, max_tiles, filename);
}
} while (line != "[/animation]");
return buffer;
}
void parseGlobalField(const std::string &line, int pos, int &frames_per_row, int &frame_width, int &frame_height, int &max_tiles, const Texture *texture, const std::string &filename) {
const std::string KEY = line.substr(0, pos);
const std::string VALUE = line.substr(pos + 1, line.length());
if (KEY == "framesPerRow") {
frames_per_row = std::stoi(VALUE);
} else if (KEY == "frameWidth") {
frame_width = std::stoi(VALUE);
} else if (KEY == "frameHeight") {
frame_height = std::stoi(VALUE);
} else {
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << KEY.c_str() << "\"" << '\n';
}
if (frames_per_row == 0 && frame_width > 0) {
frames_per_row = texture->getWidth() / frame_width;
}
if (max_tiles == 0 && frame_width > 0 && frame_height > 0) {
const int W = texture->getWidth() / frame_width;
const int H = texture->getHeight() / frame_height;
max_tiles = W * H;
}
}
} // namespace
// Parser compartido: lee un istream con el formato .ani
static auto parseAnimationStream(std::istream &file, Texture *texture, const std::string &filename, bool verbose) -> AnimatedSpriteData {
AnimatedSpriteData as;
as.texture = texture;
int framesPerRow = 0;
int frameWidth = 0;
int frameHeight = 0;
int maxTiles = 0;
int frames_per_row = 0;
int frame_width = 0;
int frame_height = 0;
int max_tiles = 0;
std::string line;
if (verbose) {
std::cout << "Animation loaded: " << filename << '\n';
}
// Normalitza CRLF: fitxers .ani amb terminadors de Windows fan que
// line == "[animation]" no faci match i el parser entri en bucle
// infinit / no carregui cap animació.
auto strip_cr = [](std::string &s) {
if (!s.empty() && s.back() == '\r') {
s.pop_back();
}
};
while (std::getline(file, line)) {
strip_cr(line);
stripCr(line);
if (line == "[animation]") {
Animation buffer;
buffer.speed = 0;
buffer.loop = -1;
buffer.counter = 0;
buffer.current_frame = 0;
buffer.completed = false;
do {
if (!std::getline(file, line)) {
break;
}
strip_cr(line);
int pos = line.find('=');
if (pos != (int)std::string::npos) {
if (line.substr(0, pos) == "name") {
buffer.name = line.substr(pos + 1, line.length());
} else if (line.substr(0, pos) == "speed") {
buffer.speed = std::stoi(line.substr(pos + 1, line.length()));
} else if (line.substr(0, pos) == "loop") {
buffer.loop = std::stoi(line.substr(pos + 1, line.length()));
} else if (line.substr(0, pos) == "frames") {
std::stringstream ss(line.substr(pos + 1, line.length()));
std::string tmp;
SDL_Rect rect = {0, 0, frameWidth, frameHeight};
while (getline(ss, tmp, ',')) {
const int numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp);
rect.x = (numTile % framesPerRow) * frameWidth;
rect.y = (numTile / framesPerRow) * frameHeight;
buffer.frames.push_back(rect);
}
} else {
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << '\n';
}
}
} while (line != "[/animation]");
as.animations.push_back(buffer);
as.animations.push_back(parseAnimationBlock(file, frame_width, frame_height, frames_per_row, max_tiles, filename));
} else {
int pos = line.find('=');
if (pos != (int)std::string::npos) {
if (line.substr(0, pos) == "framesPerRow") {
framesPerRow = std::stoi(line.substr(pos + 1, line.length()));
} else if (line.substr(0, pos) == "frameWidth") {
frameWidth = std::stoi(line.substr(pos + 1, line.length()));
} else if (line.substr(0, pos) == "frameHeight") {
frameHeight = std::stoi(line.substr(pos + 1, line.length()));
} else {
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << '\n';
}
if (framesPerRow == 0 && frameWidth > 0) {
framesPerRow = texture->getWidth() / frameWidth;
}
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0) {
const int w = texture->getWidth() / frameWidth;
const int h = texture->getHeight() / frameHeight;
maxTiles = w * h;
}
parseGlobalField(line, pos, frames_per_row, frame_width, frame_height, max_tiles, texture, filename);
}
}
}
@@ -99,17 +124,17 @@ static auto parseAnimationStream(std::istream &file, Texture *texture, const std
// Carga la animación desde un fichero (vía ResourceHelper: pack si està inicialitzat, filesystem si no)
auto loadAnimationFromFile(Texture *texture, const std::string &file_path, bool verbose) -> AnimatedSpriteData {
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
const std::string FILE_NAME = file_path.substr(file_path.find_last_of("\\/") + 1);
auto bytes = ResourceHelper::loadFile(file_path);
if (bytes.empty()) {
if (verbose) {
std::cout << "Warning: Unable to open " << filename.c_str() << " file" << '\n';
std::cout << "Warning: Unable to open " << FILE_NAME.c_str() << " file" << '\n';
}
AnimatedSpriteData as;
as.texture = texture;
return as;
}
return loadAnimationFromMemory(texture, bytes, filename, verbose);
return loadAnimationFromMemory(texture, bytes, FILE_NAME, verbose);
}
// Carga la animación desde bytes en memoria
@@ -125,7 +150,7 @@ auto loadAnimationFromMemory(Texture *texture, const std::vector<uint8_t> &bytes
}
// Constructor
AnimatedSprite::AnimatedSprite(Texture *texture, SDL_Renderer *renderer, const std::string &file, std::vector<std::string> *buffer)
AnimatedSprite::AnimatedSprite(Texture *texture, SDL_Renderer *renderer, const std::string &file, const std::vector<std::string> *buffer)
: current_animation_(0) {
// Copia los punteros
setTexture(texture);
@@ -279,132 +304,29 @@ auto AnimatedSprite::getAnimationClip(int index_a, Uint8 index_f) -> SDL_Rect {
return animation_[index_a].frames[index_f];
}
// Carga la animación desde un vector
auto AnimatedSprite::loadFromVector(std::vector<std::string> *source) -> bool {
// Inicializa variables
int framesPerRow = 0;
int frameWidth = 0;
int frameHeight = 0;
int maxTiles = 0;
// Carga la animación desde un vector (reutiliza parseAnimationStream via stringstream)
auto AnimatedSprite::loadFromVector(const std::vector<std::string> *source) -> bool {
std::stringstream ss;
for (const auto &line : *source) {
ss << line << '\n';
}
AnimatedSpriteData as = parseAnimationStream(ss, texture_, "", false);
animation_.insert(animation_.end(), as.animations.begin(), as.animations.end());
// Indicador de éxito en el proceso
bool success = true;
std::string line;
// Recorre todo el vector
int index = 0;
while (index < (int)source->size()) {
// Lee desde el vector
line = source->at(index);
// Si la linea contiene el texto [animation_] se realiza el proceso de carga de una animación
if (line == "[animation]") {
Animation buffer;
buffer.speed = 0;
buffer.loop = -1;
buffer.counter = 0;
buffer.current_frame = 0;
buffer.completed = false;
do {
// Aumenta el indice para leer la siguiente linea
index++;
line = source->at(index);
// Encuentra la posición del caracter '='
int pos = line.find('=');
// Procesa las dos subcadenas
if (pos != (int)std::string::npos) {
if (line.substr(0, pos) == "name") {
buffer.name = line.substr(pos + 1, line.length());
}
else if (line.substr(0, pos) == "speed") {
buffer.speed = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "loop") {
buffer.loop = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frames") {
// Se introducen los valores separados por comas en un vector
std::stringstream ss(line.substr(pos + 1, line.length()));
std::string tmp;
SDL_Rect rect = {0, 0, frameWidth, frameHeight};
while (getline(ss, tmp, ',')) {
// Comprueba que el tile no sea mayor que el maximo indice permitido
const int numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp);
rect.x = (numTile % framesPerRow) * frameWidth;
rect.y = (numTile / framesPerRow) * frameHeight;
buffer.frames.push_back(rect);
}
}
else {
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << '\n';
success = false;
}
}
} while (line != "[/animation]");
// Añade la animación al vector de animaciones
animation_.push_back(buffer);
}
// En caso contrario se parsea el fichero para buscar las variables y los valores
else {
// Encuentra la posición del caracter '='
int pos = line.find('=');
// Procesa las dos subcadenas
if (pos != (int)std::string::npos) {
if (line.substr(0, pos) == "framesPerRow") {
framesPerRow = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameWidth") {
frameWidth = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frameHeight") {
frameHeight = std::stoi(line.substr(pos + 1, line.length()));
}
else {
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << '\n';
success = false;
}
// Normaliza valores
if (framesPerRow == 0 && frameWidth > 0) {
framesPerRow = texture_->getWidth() / frameWidth;
}
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0) {
const int w = texture_->getWidth() / frameWidth;
const int h = texture_->getHeight() / frameHeight;
maxTiles = w * h;
}
}
}
// Una vez procesada la linea, aumenta el indice para pasar a la siguiente
index++;
// El primer frame lleva frame_width/frame_height en .w/.h — los usamos como rect por defecto
if (!as.animations.empty() && !as.animations.front().frames.empty()) {
const auto &first = as.animations.front().frames.front();
setRect({0, 0, first.w, first.h});
}
// Pone un valor por defecto
setRect({0, 0, frameWidth, frameHeight});
return success;
return true;
}
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(const std::string &name) {
const int newAnimation = getIndex(name);
if (current_animation_ != newAnimation) {
current_animation_ = newAnimation;
const int NEW_ANIMATION = getIndex(name);
if (current_animation_ != NEW_ANIMATION) {
current_animation_ = NEW_ANIMATION;
animation_[current_animation_].current_frame = 0;
animation_[current_animation_].counter = 0;
animation_[current_animation_].completed = false;
@@ -413,9 +335,9 @@ void AnimatedSprite::setCurrentAnimation(const std::string &name) {
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(int index) {
const int newAnimation = index;
if (current_animation_ != newAnimation) {
current_animation_ = newAnimation;
const int NEW_ANIMATION = index;
if (current_animation_ != NEW_ANIMATION) {
current_animation_ = NEW_ANIMATION;
animation_[current_animation_].current_frame = 0;
animation_[current_animation_].counter = 0;
animation_[current_animation_].completed = false;
+2 -2
View File
@@ -32,7 +32,7 @@ auto loadAnimationFromMemory(Texture *texture, const std::vector<uint8_t> &bytes
class AnimatedSprite : public MovingSprite {
public:
explicit AnimatedSprite(Texture *texture = nullptr, SDL_Renderer *renderer = nullptr, const std::string &file = "", std::vector<std::string> *buffer = nullptr); // Constructor
explicit AnimatedSprite(Texture *texture = nullptr, SDL_Renderer *renderer = nullptr, const std::string &file = "", const std::vector<std::string> *buffer = nullptr); // Constructor
AnimatedSprite(SDL_Renderer *renderer, AnimatedSpriteData *data);
~AnimatedSprite() override; // Destructor
@@ -57,7 +57,7 @@ class AnimatedSprite : public MovingSprite {
auto getAnimationClip(int index_a = 0, Uint8 index_f = 0) -> SDL_Rect;
auto getIndex(const std::string &name) -> int; // Obtiene el indice de la animación a partir del nombre
auto loadFromVector(std::vector<std::string> *source) -> bool; // Carga la animación desde un vector
auto loadFromVector(const std::vector<std::string> *source) -> bool; // Carga la animación desde un vector
void setCurrentAnimation(const std::string &name = "default"); // Establece la animacion actual
void setCurrentAnimation(int index = 0);
+95 -84
View File
@@ -46,93 +46,15 @@ void Fade::init(Uint8 r, Uint8 g, Uint8 b) {
void Fade::render() {
if (enabled_ && !finished_) {
switch (fade_type_) {
case FADE_FULLSCREEN: {
if (!fullscreen_done_) {
SDL_FRect fRect1 = {0, 0, (float)GAMECANVAS_WIDTH, (float)GAMECANVAS_HEIGHT};
int alpha = counter_ * 4;
if (alpha >= 255) {
fullscreen_done_ = true;
// Deja todos los buffers del mismo color
SDL_SetRenderTarget(renderer_, backbuffer_);
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 255);
SDL_RenderClear(renderer_);
SDL_SetRenderTarget(renderer_, nullptr);
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 255);
SDL_RenderClear(renderer_);
finished_ = true;
} else {
// Dibujamos sobre el renderizador
SDL_SetRenderTarget(renderer_, nullptr);
// Copia el backbuffer con la imagen que había al renderizador
SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr);
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, alpha);
SDL_RenderFillRect(renderer_, &fRect1);
}
}
case FADE_FULLSCREEN:
renderFadeFullscreen();
break;
}
case FADE_CENTER: {
SDL_FRect fR1 = {0, 0, (float)GAMECANVAS_WIDTH, 0};
SDL_FRect fR2 = {0, 0, (float)GAMECANVAS_WIDTH, 0};
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 64);
for (int i = 0; i < counter_; i++) {
fR1.h = fR2.h = (float)(i * 4);
fR2.y = (float)(GAMECANVAS_HEIGHT - (i * 4));
SDL_RenderFillRect(renderer_, &fR1);
SDL_RenderFillRect(renderer_, &fR2);
}
if ((counter_ * 4) > GAMECANVAS_HEIGHT) {
finished_ = true;
}
case FADE_CENTER:
renderFadeCenter();
break;
}
case FADE_RANDOM_SQUARE: {
Uint32 now = SDL_GetTicks();
if (squares_drawn_ < 50 && now - last_square_ticks_ >= 100) {
last_square_ticks_ = now;
SDL_FRect fRs = {0, 0, 32, 32};
// Crea un color al azar
Uint8 r = 255 * (rand() % 2);
Uint8 g = 255 * (rand() % 2);
Uint8 b = 255 * (rand() % 2);
SDL_SetRenderDrawColor(renderer_, r, g, b, 64);
// Dibujamos sobre el backbuffer
SDL_SetRenderTarget(renderer_, backbuffer_);
fRs.x = (float)(rand() % (GAMECANVAS_WIDTH - 32));
fRs.y = (float)(rand() % (GAMECANVAS_HEIGHT - 32));
SDL_RenderFillRect(renderer_, &fRs);
// Volvemos a usar el renderizador de forma normal
SDL_SetRenderTarget(renderer_, nullptr);
squares_drawn_++;
}
// Copiamos el backbuffer al renderizador
SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr);
if (squares_drawn_ >= 50) {
finished_ = true;
}
case FADE_RANDOM_SQUARE:
renderFadeRandomSquare();
break;
}
default:
break;
}
@@ -144,6 +66,95 @@ void Fade::render() {
}
}
// Helper de render: tipo FADE_FULLSCREEN
void Fade::renderFadeFullscreen() {
if (fullscreen_done_) {
return;
}
const int ALPHA = counter_ * 4;
if (ALPHA >= 255) {
fullscreen_done_ = true;
// Deja todos los buffers del mismo color
SDL_SetRenderTarget(renderer_, backbuffer_);
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 255);
SDL_RenderClear(renderer_);
SDL_SetRenderTarget(renderer_, nullptr);
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 255);
SDL_RenderClear(renderer_);
finished_ = true;
return;
}
// Dibujamos sobre el renderizador
SDL_SetRenderTarget(renderer_, nullptr);
// Copia el backbuffer con la imagen que había al renderizador
SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr);
SDL_FRect f_rect1 = {0, 0, (float)GAMECANVAS_WIDTH, (float)GAMECANVAS_HEIGHT};
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, ALPHA);
SDL_RenderFillRect(renderer_, &f_rect1);
}
// Helper de render: tipo FADE_CENTER
void Fade::renderFadeCenter() {
SDL_FRect f_r1 = {0, 0, (float)GAMECANVAS_WIDTH, 0};
SDL_FRect f_r2 = {0, 0, (float)GAMECANVAS_WIDTH, 0};
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, 64);
for (int i = 0; i < counter_; i++) {
f_r1.h = f_r2.h = (float)(i * 4);
f_r2.y = (float)(GAMECANVAS_HEIGHT - (i * 4));
SDL_RenderFillRect(renderer_, &f_r1);
SDL_RenderFillRect(renderer_, &f_r2);
}
if ((counter_ * 4) > GAMECANVAS_HEIGHT) {
finished_ = true;
}
}
// Helper de render: tipo FADE_RANDOM_SQUARE
void Fade::renderFadeRandomSquare() {
const Uint32 NOW = SDL_GetTicks();
if (squares_drawn_ < 50 && NOW - last_square_ticks_ >= 100) {
last_square_ticks_ = NOW;
SDL_FRect f_rs = {0, 0, 32, 32};
// Crea un color al azar
const Uint8 R = 255 * (rand() % 2);
const Uint8 G = 255 * (rand() % 2);
const Uint8 B = 255 * (rand() % 2);
SDL_SetRenderDrawColor(renderer_, R, G, B, 64);
// Dibujamos sobre el backbuffer
SDL_SetRenderTarget(renderer_, backbuffer_);
f_rs.x = (float)(rand() % (GAMECANVAS_WIDTH - 32));
f_rs.y = (float)(rand() % (GAMECANVAS_HEIGHT - 32));
SDL_RenderFillRect(renderer_, &f_rs);
// Volvemos a usar el renderizador de forma normal
SDL_SetRenderTarget(renderer_, nullptr);
squares_drawn_++;
}
// Copiamos el backbuffer al renderizador
SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr);
if (squares_drawn_ >= 50) {
finished_ = true;
}
}
// Actualiza las variables internas
void Fade::update() {
if (enabled_) {
+4
View File
@@ -24,6 +24,10 @@ class Fade {
void setFadeType(Uint8 fade_type); // Establece el tipo de fade
private:
void renderFadeFullscreen(); // Helper de render: tipo FADE_FULLSCREEN
void renderFadeCenter(); // Helper de render: tipo FADE_CENTER
void renderFadeRandomSquare(); // Helper de render: tipo FADE_RANDOM_SQUARE
SDL_Renderer *renderer_ = nullptr; // El renderizador de la ventana
SDL_Texture *backbuffer_ = nullptr; // Textura para usar como backbuffer
Uint8 fade_type_ = FADE_FULLSCREEN; // Tipo de fade a realizar