2017-11-30 21:00:47 +01:00
|
|
|
#include "sprite.h"
|
|
|
|
#include "util.h"
|
|
|
|
|
|
|
|
static
|
|
|
|
Sprite* sprite_create_default()
|
|
|
|
{
|
|
|
|
Position pos = { 0, 0 };
|
|
|
|
|
|
|
|
Sprite *s = ec_malloc(sizeof(Sprite));
|
2017-12-11 08:23:30 +01:00
|
|
|
*s = (Sprite) { { NULL, NULL }, false, pos, NULL, NULL };
|
|
|
|
|
|
|
|
s->renderTimer = timer_create();
|
2017-11-30 21:00:47 +01:00
|
|
|
|
|
|
|
return s;
|
|
|
|
}
|
|
|
|
|
|
|
|
Sprite* sprite_create()
|
|
|
|
{
|
|
|
|
return sprite_create_default();
|
|
|
|
}
|
|
|
|
|
2017-12-11 08:23:30 +01:00
|
|
|
void
|
|
|
|
sprite_load_texture(Sprite *sprite,
|
|
|
|
char *path,
|
|
|
|
int index,
|
|
|
|
SDL_Renderer *renderer)
|
2017-11-30 21:00:47 +01:00
|
|
|
{
|
2017-12-11 08:23:30 +01:00
|
|
|
if (index > 1)
|
|
|
|
fatal("in sprite_load_texture() index out of bounds");
|
|
|
|
|
|
|
|
if (sprite->destroyTextures && sprite->textures[index] != NULL) {
|
|
|
|
texture_destroy(sprite->textures[index]);
|
|
|
|
sprite->textures[index] = NULL;
|
2017-11-30 21:00:47 +01:00
|
|
|
}
|
|
|
|
|
2017-12-11 08:23:30 +01:00
|
|
|
sprite->textures[index] = texture_create(path, renderer);
|
|
|
|
sprite->destroyTextures = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
sprite_set_texture(Sprite *s, Texture *t, int index)
|
|
|
|
{
|
|
|
|
if (index > 1)
|
|
|
|
fatal("in sprite_set_texture() index out of bounds");
|
|
|
|
if (s->destroyTextures)
|
|
|
|
fatal("in sprite_set_texture() sprite contains loaded textures");
|
|
|
|
|
|
|
|
s->textures[index] = t;
|
2017-11-30 21:00:47 +01:00
|
|
|
}
|
|
|
|
|
2017-12-01 16:03:19 +01:00
|
|
|
void sprite_render(Sprite *s, Camera *cam)
|
2017-11-30 21:00:47 +01:00
|
|
|
{
|
2017-12-11 08:23:30 +01:00
|
|
|
static int t_index = 0;
|
|
|
|
|
|
|
|
if (!timer_started(s->renderTimer))
|
|
|
|
timer_start(s->renderTimer);
|
|
|
|
|
|
|
|
if (timer_get_ticks(s->renderTimer) > 300) {
|
|
|
|
timer_stop(s->renderTimer);
|
|
|
|
timer_start(s->renderTimer);
|
|
|
|
if (s->textures[1])
|
|
|
|
t_index = t_index == 0 ? 1 : 0;
|
|
|
|
}
|
|
|
|
|
2017-12-01 16:03:19 +01:00
|
|
|
Position cameraPos = camera_to_camera_position(cam, &s->pos);
|
2017-12-11 08:23:30 +01:00
|
|
|
texture_render(s->textures[t_index], &cameraPos, cam);
|
2017-11-30 21:00:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
void sprite_destroy(Sprite *sprite)
|
|
|
|
{
|
2017-12-11 08:23:30 +01:00
|
|
|
if (sprite->destroyTextures) {
|
|
|
|
if (sprite->textures[0])
|
|
|
|
texture_destroy(sprite->textures[0]);
|
|
|
|
if (sprite->textures[1])
|
|
|
|
texture_destroy(sprite->textures[1]);
|
|
|
|
}
|
|
|
|
timer_destroy(sprite->renderTimer);
|
2017-11-30 21:00:47 +01:00
|
|
|
free(sprite);
|
|
|
|
}
|