farmlands/src/components/basic/Sprite.h

98 lines
1.8 KiB
C++

/*
* Sprite.h
*
* Created on: Nov 29, 2016
* Author: tibi
*/
#ifndef MODEL_SPRITE_H_
#define MODEL_SPRITE_H_
#include <model/Component.h>
#include <utils/Exceptions.h>
#include <utils/Rect.h>
#include <vector>
#include <unordered_map>
namespace farmlands {
namespace components {
namespace basic {
/**
* Defines an animation frame
*/
struct Frame
{
uint32_t tileSetId;
uint32_t tileSetCell;
float duration;
};
/**
* Defines a sprite state (i.e. an animation).
*/
struct SpriteState
{
std::string name;
std::vector<Frame> frames;
};
/**
* Defines a sprite
*/
class Sprite : public model::Component
{
public:
Sprite();
virtual ~Sprite();
virtual model::Component* clone() override;
virtual void dump(unsigned level) override;
virtual void onPreRender() override;
/**
* Computes the boundaries of the sprite, considering all the elements:
* - global coordinates and scale
* - width and height
* - anchor point
*/
utils::RectF boundaries() const;
// State management
void addState(const SpriteState& state);
SpriteState& createState(const std::string& name);
SpriteState& state(const std::string& name);
SpriteState& state(size_t stateId);
size_t stateCount() const;
// Current state & frame
void setState(size_t stateId);
void setState(const std::string& name);
SpriteState& currentState();
Frame& currentFrame();
// Public fields
float w, h;
float anchorX, anchorY;
float animationSpeed;
private:
void advanceTime(float fractions);
std::vector<SpriteState> m_states;
std::unordered_map<std::string, size_t> m_stateNames;
size_t m_currentState;
size_t m_currentFrame;
float m_currentFrameTimeLeft;
};
}
} /* namespace components */
} /* namespace farmlands */
#endif /* MODEL_SPRITE_H_ */