xmario/xSDL/xSpriteGroup.cpp

106 lines
2.3 KiB
C++
Raw Permalink Normal View History

#include "xSpriteGroup.h"
/** clean SDL objects */
xSpriteGroup::~xSpriteGroup(){
_mutex.lock();
_sprites.clear();
_mutex.unlock();
}
/** default constructor */
xSpriteGroup::xSpriteGroup(){
}
/** adds a sprite to the group */
void xSpriteGroup::add(xSprite* sprite){
_mutex.lock();
_sprites.insert(sprite);
_mutex.unlock();
}
/** removes a sprite from the group */
void xSpriteGroup::remove(xSprite* sprite){
_mutex.lock();
_sprites.erase(sprite);
_mutex.unlock();
}
/** apply relative displace for each sprite */
void xSpriteGroup::displace(int x, int y, int w, int h){
displace( (SDL_Rect){x,y,w,h} );
}
void xSpriteGroup::displace(SDL_Rect relative_displace){
_mutex.lock();
for( set<xSprite*>::iterator it = _sprites.begin() ; it != _sprites.end() ; it++ ) {
xSprite* sprite = (*it);
const SDL_Rect actual_projection = sprite->projection();
sprite->project(
actual_projection.x + relative_displace.x,
actual_projection.y + relative_displace.y,
actual_projection.w + relative_displace.w,
actual_projection.h + relative_displace.h
);
}
_mutex.unlock();
}
/** draws to renderer */
void xSpriteGroup::draw(SDL_Renderer* renderer){
_mutex.lock();
// only draw active sprite if animated
if( _animated ){
// invalid active index
if( _active_sprite >= _sprites.size() ) {
_active_sprite = 0;
_mutex.unlock();
return;
}
set<xSprite*>::iterator at_index = _sprites.begin();
advance(at_index, _active_sprite);
if( at_index == _sprites.end() ){
_mutex.unlock();
return;
}
(*at_index)->draw(renderer);
_mutex.unlock();
return;
}
// else draw every sprite
set<xSprite*>::iterator it;
for( it = _sprites.begin() ; it != _sprites.end() ; it++ ){
(*it)->draw(renderer);
}
_mutex.unlock();
}
/** animation process */
void xSpriteGroup::tick(const uint32_t ticks){
_mutex.lock();
const uint32_t time_index = ticks / _animation_interval;
_active_sprite = time_index % _sprites.size();
_mutex.unlock();
}
/** orchestrate the animation */
void xSpriteGroup::animate(uint32_t interval){
_mutex.lock();
_animated = true;
_animation_interval = interval;
_active_sprite = 0;
xApplication::get()->addOrchestrable(this);
_mutex.unlock();
}
/** stops orchestrating the animation */
void xSpriteGroup::freeze(){
_mutex.lock();
xApplication::get()->removeOrchestrable(this);
_mutex.unlock();
}