#include "spritesheet.h" #include "assets.h" #include "render.h" #include "debug.h" #include #include struct Spritesheet { asset_id asset_id; // The texture to sample. SDL_Texture* texture; // The resolution of the texture. IVector resolution; // The number of frames in the sheet. size_t frame_count; // The number of frames contained in the width of the texture. size_t frame_shear; // Rules for how to play the sheet's animation. AnimationType animation_type; // The resolution of a single frame of the sheet. IVector frame_size; // The time to wait before switching frames. float frame_interval; }; void _internal_spritesheet_destroy(Spritesheet* self) { SDL_DestroyTexture(self->texture); free(self); } Spritesheet* spritesheet_load(const char* texture_name, IVector frame_resolution) { SDL_Texture* texture = IMG_LoadTexture(g_renderer, texture_name); ASSERT_RETURN(texture != NULL, NULL, "Failed to load texture from file %s.", texture_name); return spritesheet_from_texture(texture, frame_resolution); } Spritesheet* spritesheet_from_texture(SDL_Texture* texture, IVector frame_resolution) { Spritesheet* self = malloc(sizeof(Spritesheet)); ASSERT_RETURN(self != NULL, NULL, "Failed to allocate spritesheet."); self->asset_id = store_asset(Spritesheet_as_Asset(self)); // Load the texture image and query it's size self->texture = texture; SDL_QueryTexture(self->texture, NULL, NULL, &self->resolution.x, &self->resolution.y); self->animation_type = ANIMTYPE_ONCE; self->frame_size = frame_resolution; self->frame_shear = self->resolution.x / self->frame_size.x; self->frame_count = self->resolution.x / self->frame_size.x + self->resolution.y / self->frame_size.y; self->frame_interval = 0.016f; return self; } void spritesheet_destroy(Spritesheet* self) { free_asset(self->asset_id); } SDL_Texture* spritesheet_get_texture(const Spritesheet* self) { return self->texture; } SDL_Rect spritesheet_get_frame_rect(const Spritesheet* self, size_t index) { IVector tile_coord = {index % self->frame_shear, index / self->frame_shear}; tile_coord = vmuli(tile_coord, self->frame_size); return (SDL_Rect) { tile_coord.x, tile_coord.y, self->frame_size.x, self->frame_size.y }; } IVector spritesheet_get_resolution(const Spritesheet* self) { return self->resolution; } asset_id spritesheet_get_asset_id(Spritesheet* self) { return self->asset_id; } void spritesheet_set_asset_id(Spritesheet* self, asset_id id) { self->asset_id = id; }