feat(anim): suport de flip H/V per frame i per animació
This commit is contained in:
1 parent
39eda56c9d
commit
1d43a77800
5 files changed
+438
-87
No files matched your search
@@ -7,36 +7,19 @@
|
||||
|
||||
#include "core/rendering/surface.hpp"
|
||||
#include "core/resources/resource_cache.hpp"
|
||||
#include "external/fkyaml_node.hpp"
|
||||
|
||||
// El parser pure de YAML d'animacions (parseAnimationsFromYaml + helpers)
|
||||
// viu a `animated_sprite_parser.cpp` perquè és testable sense Surface ni
|
||||
// Resource::Cache. Aquesta unitat es queda amb el runtime de la classe i
|
||||
// amb el que sí toca el cache de surfaces (parseSpriteBlock).
|
||||
|
||||
namespace {
|
||||
|
||||
auto convertYamlFramesToRects(const fkyaml::node& frames_node, float frame_width, float frame_height, int frames_per_row, int max_tiles) -> std::vector<SDL_FRect> {
|
||||
std::vector<SDL_FRect> frames;
|
||||
SDL_FRect rect = {.x = 0.0F, .y = 0.0F, .w = frame_width, .h = frame_height};
|
||||
for (const auto& frame_index_node : frames_node) {
|
||||
const int NUM_TILE = frame_index_node.get_value<int>();
|
||||
if (NUM_TILE <= max_tiles) {
|
||||
rect.x = static_cast<float>(NUM_TILE % frames_per_row) * frame_width;
|
||||
rect.y = static_cast<float>(NUM_TILE / frames_per_row) * frame_height;
|
||||
frames.emplace_back(rect);
|
||||
}
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
struct SheetParams {
|
||||
float frame_width{0.0F};
|
||||
float frame_height{0.0F};
|
||||
int frames_per_row{1};
|
||||
int max_tiles{1};
|
||||
};
|
||||
|
||||
// Llegeix el bloc `sprite: { path, size: [w, h] }` — mateix format que
|
||||
// les plantilles d'entitat. La surface es resol via Resource::Cache amb
|
||||
// el basename del fitxer.
|
||||
auto parseSpriteBlock(const fkyaml::node& yaml, std::shared_ptr<Surface>& surface) -> SheetParams {
|
||||
SheetParams params;
|
||||
auto parseSpriteBlock(const fkyaml::node& yaml, std::shared_ptr<Surface>& surface) -> AnimatedSprite::SheetParams {
|
||||
AnimatedSprite::SheetParams params;
|
||||
if (!yaml.contains("sprite")) { return params; }
|
||||
const auto& s = yaml["sprite"];
|
||||
if (s.contains("path")) {
|
||||
@@ -57,62 +40,18 @@ namespace {
|
||||
return params;
|
||||
}
|
||||
|
||||
// `frame_ms` pot ser un escalar (temps uniforme) o una llista (per-frame).
|
||||
// Convertim sempre a segons perquè `animate()` treballa amb delta_time
|
||||
// en segons. Si falta o val 0, `speeds` queda buit i l'animació es
|
||||
// considera estàtica (no avança).
|
||||
void parseFrameTimes(const fkyaml::node& anim_node, AnimatedSprite::AnimationData& animation) {
|
||||
if (!anim_node.contains("frame_ms")) { return; }
|
||||
const auto& fm = anim_node["frame_ms"];
|
||||
if (fm.is_sequence()) {
|
||||
for (const auto& v : fm) {
|
||||
animation.speeds.push_back(static_cast<float>(v.get_value<int>()) / 1000.0F);
|
||||
}
|
||||
} else {
|
||||
const float SEC = static_cast<float>(fm.get_value<int>()) / 1000.0F;
|
||||
if (SEC > 0.0F) { animation.speeds.assign(animation.frames.size(), SEC); }
|
||||
}
|
||||
}
|
||||
|
||||
// Ordre de prioritat per a la política de loop:
|
||||
// 1) `loop_from: N` → rebota al frame N en passar del final (implica loop).
|
||||
// 2) `loop: false` → animació d'un sol tret (es queda al darrer frame).
|
||||
// 3) Res → loop complet des del frame 0 (default).
|
||||
void parseLoopPolicy(const fkyaml::node& anim_node, AnimatedSprite::AnimationData& animation) {
|
||||
if (anim_node.contains("loop_from")) {
|
||||
animation.loop_from = anim_node["loop_from"].get_value<int>();
|
||||
} else if (anim_node.contains("loop") && !anim_node["loop"].get_value<bool>()) {
|
||||
animation.loop_from = -1;
|
||||
} else {
|
||||
animation.loop_from = 0;
|
||||
}
|
||||
}
|
||||
|
||||
auto parseAnimations(const fkyaml::node& yaml, const SheetParams& params) -> std::unordered_map<std::string, AnimatedSprite::AnimationData> {
|
||||
std::unordered_map<std::string, AnimatedSprite::AnimationData> animations;
|
||||
if (!yaml.contains("animations") || !yaml["animations"].is_mapping()) {
|
||||
return animations;
|
||||
}
|
||||
const auto& anims_node = yaml["animations"];
|
||||
for (auto it = anims_node.begin(); it != anims_node.end(); ++it) {
|
||||
const auto NAME = it.key().get_value<std::string>();
|
||||
const auto& anim_node = *it;
|
||||
|
||||
AnimatedSprite::AnimationData animation;
|
||||
if (anim_node.contains("frames") && anim_node["frames"].is_sequence()) {
|
||||
animation.frames = convertYamlFramesToRects(
|
||||
anim_node["frames"],
|
||||
params.frame_width,
|
||||
params.frame_height,
|
||||
params.frames_per_row,
|
||||
params.max_tiles);
|
||||
}
|
||||
parseFrameTimes(anim_node, animation);
|
||||
parseLoopPolicy(anim_node, animation);
|
||||
|
||||
animations.emplace(NAME, std::move(animation));
|
||||
}
|
||||
return animations;
|
||||
// Tradueix els flags lògics flip_h/flip_v al `SDL_FlipMode` que admet
|
||||
// `Surface::render`. Important: a SDL3, `SDL_FlipMode` és un enum
|
||||
// exclusiu (NONE/HORIZONTAL/VERTICAL), no un bitmask combinable. Per
|
||||
// tant, V+H simultani al mateix frame no es pot expressar amb una
|
||||
// única crida — prioritzem H (suficient per als casos pràctics
|
||||
// d'animació, com `walk_west` o `death_spin`). Si en algun moment fa
|
||||
// falta combinar, caldrà ampliar `Surface::render` per a doble-flipar
|
||||
// a baix nivell.
|
||||
auto toFlipMode(bool flip_h, bool flip_v) -> SDL_FlipMode {
|
||||
if (flip_h) { return SDL_FLIP_HORIZONTAL; }
|
||||
if (flip_v) { return SDL_FLIP_VERTICAL; }
|
||||
return SDL_FLIP_NONE;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -122,7 +61,7 @@ AnimatedSprite::AnimatedSprite(const AnimationResource& cached_data) {
|
||||
try {
|
||||
auto yaml = fkyaml::node::deserialize(yaml_content);
|
||||
auto params = parseSpriteBlock(yaml, surface_);
|
||||
animations_ = parseAnimations(yaml, params);
|
||||
animations_ = parseAnimationsFromYaml(yaml, params);
|
||||
|
||||
setWidth(params.frame_width);
|
||||
setHeight(params.frame_height);
|
||||
@@ -132,7 +71,7 @@ AnimatedSprite::AnimatedSprite(const AnimationResource& cached_data) {
|
||||
// abans del primer `update()`, així que el valor real el posa ell.
|
||||
if (!animations_.empty()) {
|
||||
const auto& first = animations_.begin()->second;
|
||||
if (!first.frames.empty()) { setClip(first.frames[0]); }
|
||||
if (!first.frames.empty()) { setClip(first.frames[0].rect); }
|
||||
}
|
||||
} catch (const fkyaml::exception& e) {
|
||||
std::cerr << "YAML parsing error in animation " << cached_data.name << ": " << e.what() << '\n';
|
||||
@@ -154,11 +93,21 @@ void AnimatedSprite::animate(float delta_time) {
|
||||
|
||||
const float TOTAL = std::accumulate(anim.speeds.begin(), anim.speeds.end(), 0.0F);
|
||||
|
||||
// Helper local per a propagar el frame actual (clip + opcionalment flip)
|
||||
// al sprite. El flip només s'escriu si l'animació declara `controls_flip`,
|
||||
// per a no trepitjar el flip que el codi del joc encara controla
|
||||
// externament en animacions sense declaració de flip al YAML.
|
||||
auto apply_current_frame = [&](int frame_index) {
|
||||
const auto& frame = anim.frames[frame_index];
|
||||
setClip(frame.rect);
|
||||
if (anim.controls_flip) { setFlip(toFlipMode(frame.flip_h, frame.flip_v)); }
|
||||
};
|
||||
|
||||
if (anim.accumulated_time >= TOTAL) {
|
||||
if (anim.loop_from < 0) {
|
||||
anim.current_frame = static_cast<int>(anim.frames.size()) - 1;
|
||||
anim.completed = true;
|
||||
setClip(anim.frames[anim.current_frame]);
|
||||
apply_current_frame(anim.current_frame);
|
||||
return;
|
||||
}
|
||||
float loop_start = 0.0F;
|
||||
@@ -172,13 +121,13 @@ void AnimatedSprite::animate(float delta_time) {
|
||||
cursor += anim.speeds[i];
|
||||
if (anim.accumulated_time < cursor) {
|
||||
anim.current_frame = i;
|
||||
setClip(anim.frames[i]);
|
||||
apply_current_frame(i);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
anim.current_frame = static_cast<int>(anim.frames.size()) - 1;
|
||||
setClip(anim.frames[anim.current_frame]);
|
||||
apply_current_frame(anim.current_frame);
|
||||
}
|
||||
|
||||
auto AnimatedSprite::animationIsCompleted() -> bool {
|
||||
@@ -200,7 +149,10 @@ void AnimatedSprite::setCurrentAnimation(const std::string& name) {
|
||||
anim.current_frame = 0;
|
||||
anim.accumulated_time = 0.0F;
|
||||
anim.completed = false;
|
||||
if (!anim.frames.empty()) { setClip(anim.frames[0]); }
|
||||
if (!anim.frames.empty()) {
|
||||
setClip(anim.frames[0].rect);
|
||||
if (anim.controls_flip) { setFlip(toFlipMode(anim.frames[0].flip_h, anim.frames[0].flip_v)); }
|
||||
}
|
||||
}
|
||||
|
||||
void AnimatedSprite::update(float delta_time) {
|
||||
|
||||
@@ -8,14 +8,34 @@
|
||||
|
||||
#include "core/rendering/sprite/moving_sprite.hpp"
|
||||
#include "core/resources/resource_types.hpp"
|
||||
#include "external/fkyaml_node.hpp"
|
||||
|
||||
class AnimatedSprite : public MovingSprite {
|
||||
public:
|
||||
// Un frame d'animació = rectangle dins el spritesheet + flags de flip
|
||||
// associats. El flip s'aplica al sprite a `animate()` quan l'animació
|
||||
// declara que ella controla el flip (vegeu `AnimationData::controls_flip`).
|
||||
struct Frame {
|
||||
SDL_FRect rect{.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F};
|
||||
bool flip_h{false};
|
||||
bool flip_v{false};
|
||||
};
|
||||
|
||||
// Paràmetres geomètrics del spritesheet, derivats del bloc `sprite:`
|
||||
// del YAML. Es passen al parser d'animacions per a calcular els
|
||||
// rectangles de cada frame a partir dels seus índexs.
|
||||
struct SheetParams {
|
||||
float frame_width{0.0F};
|
||||
float frame_height{0.0F};
|
||||
int frames_per_row{1};
|
||||
int max_tiles{1};
|
||||
};
|
||||
|
||||
// Dades d'una animació concreta dins d'un spritesheet. Les claus del
|
||||
// mapa (`animations_`) són els noms; aquí només es guarden els fotogrames
|
||||
// i l'estat de reproducció.
|
||||
struct AnimationData {
|
||||
std::vector<SDL_FRect> frames;
|
||||
std::vector<Frame> frames;
|
||||
// Durada de cada frame en segons (convertit des de `frame_ms` al YAML).
|
||||
// Si té un sol valor, val per a tots els frames; altrament ha de tenir
|
||||
// la mateixa mida que `frames`.
|
||||
@@ -24,6 +44,13 @@ class AnimatedSprite : public MovingSprite {
|
||||
// 0 = loop complet des del primer frame.
|
||||
// N>0 = rebota al frame N en passar del final.
|
||||
int loop_from{0};
|
||||
// Si true, `animate()` escriu el flip del frame actual al sprite.
|
||||
// Si false (cas backward-compat per a animacions sense cap declaració
|
||||
// de flip), `animate()` no toca el flip — el codi del joc el segueix
|
||||
// controlant externament via `setFlip(...)`. Es marca a true quan
|
||||
// l'animació declara `flip_h`/`flip_v`, o quan algun frame es declara
|
||||
// amb la forma mapping `{ index, flip_h?, flip_v? }`.
|
||||
bool controls_flip{false};
|
||||
bool completed{false};
|
||||
int current_frame{0};
|
||||
float accumulated_time{0.0F};
|
||||
@@ -40,6 +67,12 @@ class AnimatedSprite : public MovingSprite {
|
||||
void resetAnimation();
|
||||
void animate(float delta_time);
|
||||
|
||||
// Helper de parsing exposat per a testabilitat. NO toca el cache de
|
||||
// recursos — només el bloc `animations:` del YAML i els paràmetres de
|
||||
// full ja calculats. El ctor d'`AnimatedSprite` el crida internament.
|
||||
static auto parseAnimationsFromYaml(const fkyaml::node& yaml, const SheetParams& params)
|
||||
-> std::unordered_map<std::string, AnimationData>;
|
||||
|
||||
private:
|
||||
std::unordered_map<std::string, AnimationData> animations_;
|
||||
// Nom de l'animació activa. Buit fins que algú crida `setCurrentAnimation`.
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
#include <algorithm>
|
||||
#include <ranges>
|
||||
|
||||
#include "core/rendering/sprite/animated_sprite.hpp"
|
||||
|
||||
// Implementació del parser pure de YAML d'animacions. Viu en una unitat
|
||||
// separada perquè NO depèn de Resource::Cache ni de Surface — només de
|
||||
// fkyaml — i això permet als tests stand-alone enllaçar només aquest .cpp
|
||||
// per a verificar el parsing sense haver d'arrossegar tot l'stack de
|
||||
// recursos i renderitzat.
|
||||
|
||||
namespace {
|
||||
|
||||
// Construeix el rectangle d'un frame a partir del seu índex dins del
|
||||
// spritesheet. Centralitzat per a no duplicar la fórmula als dos
|
||||
// formats (escalar / mapping) que admet `frames:` al YAML.
|
||||
auto rectFromIndex(int index, const AnimatedSprite::SheetParams& params) -> SDL_FRect {
|
||||
return SDL_FRect{
|
||||
.x = static_cast<float>(index % params.frames_per_row) * params.frame_width,
|
||||
.y = static_cast<float>(index / params.frames_per_row) * params.frame_height,
|
||||
.w = params.frame_width,
|
||||
.h = params.frame_height,
|
||||
};
|
||||
}
|
||||
|
||||
// Llig un node `frames` (seqüència) i el converteix a la nova
|
||||
// representació `vector<Frame>`. Cada element pot ser:
|
||||
// - escalar (int) → hereta `default_flip_h`/`default_flip_v` de l'animació.
|
||||
// - mapping `{ index: N, flip_h?: bool, flip_v?: bool }` → fully
|
||||
// explícit. Els flags absents defaulten a false (NO hereta de l'anim).
|
||||
auto convertYamlFrames(const fkyaml::node& frames_node, const AnimatedSprite::SheetParams& params, bool default_flip_h, bool default_flip_v) -> std::vector<AnimatedSprite::Frame> {
|
||||
std::vector<AnimatedSprite::Frame> frames;
|
||||
for (const auto& frame_node : frames_node) {
|
||||
if (frame_node.is_mapping()) {
|
||||
if (!frame_node.contains("index")) { continue; }
|
||||
const int NUM_TILE = frame_node["index"].get_value<int>();
|
||||
if (NUM_TILE > params.max_tiles) { continue; }
|
||||
AnimatedSprite::Frame frame;
|
||||
frame.rect = rectFromIndex(NUM_TILE, params);
|
||||
if (frame_node.contains("flip_h")) { frame.flip_h = frame_node["flip_h"].get_value<bool>(); }
|
||||
if (frame_node.contains("flip_v")) { frame.flip_v = frame_node["flip_v"].get_value<bool>(); }
|
||||
frames.emplace_back(frame);
|
||||
} else {
|
||||
const int NUM_TILE = frame_node.get_value<int>();
|
||||
if (NUM_TILE > params.max_tiles) { continue; }
|
||||
frames.emplace_back(AnimatedSprite::Frame{
|
||||
.rect = rectFromIndex(NUM_TILE, params),
|
||||
.flip_h = default_flip_h,
|
||||
.flip_v = default_flip_v,
|
||||
});
|
||||
}
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
// Detecta si dins de `frames_node` hi ha algun element en forma mapping.
|
||||
// Si n'hi ha (encara que els flags interns siguin false), l'animació
|
||||
// passa a controlar el flip — el mapping és senyal explícit que l'autor
|
||||
// del YAML vol governar el flip per frame.
|
||||
auto framesContainMapping(const fkyaml::node& frames_node) -> bool {
|
||||
return std::ranges::any_of(frames_node, [](const auto& frame_node) {
|
||||
return frame_node.is_mapping();
|
||||
});
|
||||
}
|
||||
|
||||
// `frame_ms` pot ser un escalar (temps uniforme) o una llista (per-frame).
|
||||
// Convertim sempre a segons perquè `animate()` treballa amb delta_time
|
||||
// en segons. Si falta o val 0, `speeds` queda buit i l'animació es
|
||||
// considera estàtica (no avança).
|
||||
void parseFrameTimes(const fkyaml::node& anim_node, AnimatedSprite::AnimationData& animation) {
|
||||
if (!anim_node.contains("frame_ms")) { return; }
|
||||
const auto& fm = anim_node["frame_ms"];
|
||||
if (fm.is_sequence()) {
|
||||
for (const auto& v : fm) {
|
||||
animation.speeds.push_back(static_cast<float>(v.get_value<int>()) / 1000.0F);
|
||||
}
|
||||
} else {
|
||||
const float SEC = static_cast<float>(fm.get_value<int>()) / 1000.0F;
|
||||
if (SEC > 0.0F) { animation.speeds.assign(animation.frames.size(), SEC); }
|
||||
}
|
||||
}
|
||||
|
||||
// Ordre de prioritat per a la política de loop:
|
||||
// 1) `loop_from: N` → rebota al frame N en passar del final (implica loop).
|
||||
// 2) `loop: false` → animació d'un sol tret (es queda al darrer frame).
|
||||
// 3) Res → loop complet des del frame 0 (default).
|
||||
void parseLoopPolicy(const fkyaml::node& anim_node, AnimatedSprite::AnimationData& animation) {
|
||||
if (anim_node.contains("loop_from")) {
|
||||
animation.loop_from = anim_node["loop_from"].get_value<int>();
|
||||
} else if (anim_node.contains("loop") && !anim_node["loop"].get_value<bool>()) {
|
||||
animation.loop_from = -1;
|
||||
} else {
|
||||
animation.loop_from = 0;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
auto AnimatedSprite::parseAnimationsFromYaml(const fkyaml::node& yaml, const SheetParams& params)
|
||||
-> std::unordered_map<std::string, AnimationData> {
|
||||
std::unordered_map<std::string, AnimationData> animations;
|
||||
if (!yaml.contains("animations") || !yaml["animations"].is_mapping()) {
|
||||
return animations;
|
||||
}
|
||||
const auto& anims_node = yaml["animations"];
|
||||
for (auto it = anims_node.begin(); it != anims_node.end(); ++it) {
|
||||
const auto NAME = it.key().get_value<std::string>();
|
||||
const auto& anim_node = *it;
|
||||
|
||||
// Flags de flip a nivell d'animació (defaults a false). Els frames
|
||||
// declarats com a int els hereten; els declarats com a mapping no.
|
||||
bool anim_flip_h = false;
|
||||
bool anim_flip_v = false;
|
||||
if (anim_node.contains("flip_h")) { anim_flip_h = anim_node["flip_h"].get_value<bool>(); }
|
||||
if (anim_node.contains("flip_v")) { anim_flip_v = anim_node["flip_v"].get_value<bool>(); }
|
||||
|
||||
AnimationData animation;
|
||||
if (anim_node.contains("frames") && anim_node["frames"].is_sequence()) {
|
||||
const auto& frames_node = anim_node["frames"];
|
||||
animation.frames = convertYamlFrames(frames_node, params, anim_flip_h, anim_flip_v);
|
||||
// L'animació passa a "controlar" el flip si l'autor ha
|
||||
// declarat qualsevol cosa relacionada amb flip — sigui a
|
||||
// nivell d'anim o a través d'un frame en forma mapping.
|
||||
// Sense cap declaració, ens mantenim passius i deixem el
|
||||
// flip al codi del joc (backward-compat amb sam.yaml).
|
||||
animation.controls_flip = anim_flip_h || anim_flip_v || framesContainMapping(frames_node);
|
||||
}
|
||||
parseFrameTimes(anim_node, animation);
|
||||
parseLoopPolicy(anim_node, animation);
|
||||
|
||||
animations.emplace(NAME, std::move(animation));
|
||||
}
|
||||
return animations;
|
||||
}
|
||||
Reference in new issue
Block a user