Blob Blame Raw

#include <SDL_image.h>

#include "private.h"
#include "world.h"
#include "animation.h"


static HeliArray cache;
static Animation first, last;

typedef struct _HeliTexture {
	const char *key;
	unsigned int id;
	int refcount;
} HeliTexture;

struct _Animation {
	int playing;
	int loop;
	double fps;
	double pos;
	HeliArray frames;
	Animation prev, next;
};



static int fixsize(int x) {
	int p = (int)ceil(log2(x > 1 ? x : 1) - 0.25);
	if (p > 30) p = 30;
	return 1 << p;
}


static float colorclamp(float x)
	{ return x > 0.f ? (x < 1.f ? x : 1.f) : 0.f; }


static void mipx(float *buffer, int *w, int *h) {
	*w /= 2;
	if (*w <= 0) return;
	for(float *d = buffer, *s = buffer, *end = d + (*w)*(*h)*4; d < end; d += 4, s += 8)
		for(int i = 0; i < 4; ++i)
			d[i] = (s[i] + s[i + 4])*0.5f;
}


static void mipy(float *buffer, int *w, int *h) {
	*h /= 2;
	if (*h <= 0) return;
	int rstep = (*w)*4;
	float *d = buffer, *s0 = buffer, *s1 = s0 + rstep;
	for(float *end = d + (*h)*rstep; d < end; s0 += rstep, s1 += rstep)
		for(float *rend = d + rstep; d < rend; ++d, ++s0, ++s1)
			*d = (*s0 + *s1)*0.5f;
}


int imageLoad(const char *path, int *outWidth, int *outHeight, unsigned char **outPixels) {
	*outWidth = 0;
	*outHeight = 0;
	*outPixels = NULL;
	
	// load image
	SDL_Surface *surface = IMG_Load(path);
	if (!surface) {
		fprintf(stderr, "helianthus: cannot load image: %s\n", path);
		return FALSE;
	}
	
	// convert to RGBA
	if (surface->format->format != SDL_PIXELFORMAT_RGBA8888) {
		SDL_PixelFormat *format = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888);
		SDL_Surface *converted = SDL_ConvertSurface(surface, format, 0);
		SDL_FreeFormat(format);
		SDL_FreeSurface(surface);
		surface = converted;
	}
	
	// copy
	SDL_LockSurface(surface);
	int w = surface->w;
	int h = surface->h;
	assert(w > 0 && h > 0);
	size_t rsize = (size_t)w*4;
	unsigned char *pixels = malloc(h*rsize);
	for(int i = 0; i < h; ++i) {
		const unsigned char *pp = surface->pixels + surface->pitch*i;
		for(unsigned char *p = pixels + i*rsize, *end = p + rsize; p < end; p += 4, pp += 4) {
			p[0] = pp[3];
			p[1] = pp[2];
			p[2] = pp[1];
			p[3] = pp[0];
		}
	}
	SDL_UnlockSurface(surface);
	SDL_FreeSurface(surface);
	
	*outPixels = pixels;
	*outWidth = w;
	*outHeight = h;
	return TRUE;
}


unsigned int imageToGLTexture(int width, int height, const unsigned char *pixels, int horWrap, int vertWrap) {
	// convert to float and premult alpha
	size_t count = (size_t)width*height*4;
	float *buffer = (float*)malloc(count*sizeof(float));
	const unsigned char *pp = pixels;
	for(float *p = buffer, *end = p + count; p < end; p += 4, pp += 4) {
		if (pp[3]) {
			float a = pp[3]/255.f;
			p[0] = pp[0]/255.f*a;
			p[1] = pp[1]/255.f*a;
			p[2] = pp[2]/255.f*a;
			p[3] = a;
		} else {
			p[0] = p[1] = p[2] = p[3] = 0;
		}
	}
	
	// resample to power of two
	int w = width, h = height;
	int fw = fixsize(w);
	int fh = fixsize(h);
	if (fw != w || fh != h) {
		float *fbuffer = (float*)malloc((size_t)fw*fh*4*sizeof(float));
		double kr = (double)h/fh;
		double kc = (double)w/fw;
		for(int r = 0; r < fh; ++r) {
			for(int c = 0; c < fw; ++c) {
				double pr1 = r*kr;
				int r0 = (int)floor(pr1 + HELI_PRECISION);
				pr1 -= r0;
				int r1 = r0 + 1;
				if (r1 >= h) r1 = h - 1;
				if (r0 > r1) r0 = r1;
				double pr0 = 1 - pr1;
				
				double pc1 = c*kc;
				int c0 = (int)floor(pc1 + HELI_PRECISION);
				pc1 -= c0;
				int c1 = c0 + 1;
				if (c1 >= w) c1 = w - 1;
				if (c0 > c1) c0 = c1;
				double pc0 = 1 - pc1;
				
				float *p = fbuffer + (r*fw + c)*4;
				const float *p00 = buffer + (r0*w + c0)*4;
				const float *p01 = buffer + (r0*w + c1)*4;
				const float *p10 = buffer + (r1*w + c0)*4;
				const float *p11 = buffer + (r1*w + c1)*4;
				for(int i = 0; i < 4; ++i)
					p[i] = p00[i]*pr0*pc0
					     + p01[i]*pr0*pc1
					     + p10[i]*pr1*pc0
					     + p11[i]*pr1*pc1;
			}
		}
		free(buffer);
		buffer = fbuffer;
		w = fw;
		h = fh;
	}
	
	// fix max texture size
	int maxSize = 0;
	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);
	if (maxSize < 64) maxSize = 64;
	while(w > maxSize) mipx(buffer, &w, &h);
	while(h > maxSize) mipy(buffer, &w, &h);
	
	// create OpenGL texture
	unsigned int texid = 0;
	glGenTextures(1, &texid);
	glBindTexture(GL_TEXTURE_2D, texid);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, horWrap ? GL_REPEAT : GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, vertWrap ? GL_REPEAT : GL_CLAMP_TO_EDGE);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, -0.7f);
	
	// build mip levels
	unsigned char *ibuffer = malloc((size_t)w*h*4);
	int level = 0;
	while(1) {
		float *pp = buffer;
		for(unsigned char *p = ibuffer, *end = p + (size_t)w*h*4; p < end; p += 4, pp += 4) {
			if (pp[3] > 1e-5) {
				float k = 1/pp[3];
				p[0] = (unsigned char)floor(colorclamp(pp[0]*k)*255.99);
				p[1] = (unsigned char)floor(colorclamp(pp[1]*k)*255.99);
				p[2] = (unsigned char)floor(colorclamp(pp[2]*k)*255.99);
				p[3] = (unsigned char)floor(colorclamp(pp[3])*255.99);
			} else {
				p[0] = (unsigned char)floor(colorclamp(pp[0])*255.99);
				p[1] = (unsigned char)floor(colorclamp(pp[1])*255.99);
				p[2] = (unsigned char)floor(colorclamp(pp[2])*255.99);
				p[3] = 0;
			}
		}
		glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ibuffer);
		++level;
		
		if (w <= 1 && h <= 1) break;
		if (w > 1) mipx(buffer, &w, &h);
		if (h > 1) mipy(buffer, &w, &h);
	}
	
	// done
	free(ibuffer);
	free(buffer);
	glBindTexture(GL_TEXTURE_2D, 0);
	
	return texid;
}


static void unloadTexture(HeliTexture *texture) {
	assert(!texture->refcount);
	glDeleteTextures(1, &texture->id);
}


static HeliTexture* loadTexture(const char *key) {
	HeliTexture *texture = calloc(1, sizeof(*texture));
	texture->key = heliStringCopy(key);
	int w = 0, h = 0;
	unsigned char *pixels = NULL;
	if (imageLoad(key+2, &w, &h, &pixels)) {
		texture->id = imageToGLTexture(w, h, pixels, key[0] == 'W', key[1] == 'W');
		free(pixels);
	}
	return texture;
}


static HeliTexture *getTexture(const char *key) {
	HeliPair *item = heliStringmapGet(&cache, key);
	if (!item) item = heliStringmapAdd(&cache, key, loadTexture(key), (HeliFreeCallback)&unloadTexture);
	HeliTexture *texture = (HeliTexture*)item->value;
	++texture->refcount;
	return texture;
}


static void unrefTexture(HeliTexture *texture) {
	if (--texture->refcount <= 0)
		heliStringmapRemove(&cache, texture->key);
}


static void heliAnimationFixPos(Animation animation) {
	double maxPos = animation->frames.count - HELI_PRECISION_SQR;
	if (!(animation->pos < maxPos)) animation->pos = maxPos;
	if (!(animation->pos > 0)) animation->pos = 0;
}


Animation createAnimationEmpty() {
	Animation animation = calloc(1, sizeof(*animation));
	animation->prev = last;
	*(animation->prev ? &animation->prev->next : &first) = last = animation;
	
	double minFps = worldGetMinFrameRate();
	double maxFps = worldGetMaxFrameRate();
	animation->fps = HELI_DEFAULT_FPS;
	if (animation->fps > maxFps) animation->fps = maxFps;
	if (animation->fps < minFps) animation->fps = minFps;
	animation->loop = TRUE;
	
	heliObjectRegister(animation, (HeliFreeCallback)&animationDestroy);
	return animation;
}

Animation createAnimationEx(const char* path, int horWrap, int vertWrap) {
	Animation animation = createAnimationEmpty();
	char *key = heliStringConcat("CC", path);
	if (horWrap) key[0] = 'W';
	if (vertWrap) key[1] = 'W';
	
	Directory d = openDirectory(key + 2);
	if (d) {
		int count = directoryGetCount(d);
		for(int i = 0; i < count; ++i) {
			const char *file = directoryGet(d, i);
			if (heliStringEndsWithLowcase(file, ".png")) {
				char *k = heliStringConcat3(key, "/", file);
				heliArrayInsert(&animation->frames, -1, getTexture(k), (HeliFreeCallback)&unrefTexture);
				free(k);
			}
		}
		closeDirectory(d);
	} else {
		heliArrayInsert(&animation->frames, -1, getTexture(key), (HeliFreeCallback)&unrefTexture);
	}
	
	return animation;
}

Animation createAnimation(const char *path)
	{ return createAnimationEx(path, FALSE, FALSE); }

void animationDestroy(Animation animation) {
	*(animation->prev ? &animation->prev->next : &first) = animation->next;
	*(animation->next ? &animation->next->prev : &last ) = animation->prev;
	heliArrayDestroy(&animation->frames);
	heliObjectUnregister(animation);
	free(animation);
}

Animation animationCloneEx(Animation animation, int from, int to) {
	Animation a = createAnimationEmpty();
	animationInsertEx(a, 0, animation, from, to);
	animationSetFps(a, animationGetFps(animation));
	animationSetPos(a, animationGetPos(animation));
	if (animationIsPlaying(animation)) animationPlay(a); else animationPause(a);
	return a;
}

Animation animationClone(Animation animation)
	{ return animationCloneEx(animation, 0, animationGetFramesCount(animation)); }

unsigned int animationGetGLTexId(Animation animation) {
	if (animationGetFramesCount(animation) <= 0) return 0;
	int i = animationGetFrame(animation);
	HeliTexture *texture = (HeliTexture*)animation->frames.items[i].value;
	return texture->id;
}

int animationGetFramesCount(Animation animation)
	{ return animation->frames.count; }

void animationInsertEx(Animation animation, int index, Animation other, int start, int count) {
	int dcnt = animationGetFramesCount(animation);
	int scnt = animationGetFramesCount(other);
	int i0 = start;
	int i1 = i0 + count;
	if (i0 < 0) i0 = 0;
	if (i1 > scnt) i1 = scnt;
	if (index < 0 || index > dcnt) index = dcnt;
	for(int i = i0; i < i1; ++i, ++index) {
		HeliTexture *texture = (HeliTexture*)other->frames.items[i].value;
		++texture->refcount;
		heliArrayInsert(&animation->frames, index, texture, (HeliFreeCallback)&unrefTexture);
	}
}

void animationInsert(Animation animation, int index, Animation other)
	{ animationInsertEx(animation, index, other, 0, animationGetFramesCount(other)); }

void animationRemove(Animation animation, int start, int count) {
	int cnt = animationGetFramesCount(animation);
	int i0 = start;
	int i1 = i0 + count;
	if (i0 < 0) i0 = 0;
	if (i1 > cnt) i1 = cnt;
	for(int i = i1 - 1; i >= i0; --i)
		heliArrayRemove(&animation->frames, i);
	heliAnimationFixPos(animation);
}

void animationClear(Animation animation)
	{ animationRemove(animation, 0, animationGetFramesCount(animation)); }

double animationGetFps(Animation animation)
	{ return animation->fps; }
void animationSetFps(Animation animation, double fps) {
	animation->fps = !(fps > HELI_MIN_FPS) ? HELI_MIN_FPS
	               : !(fps > HELI_MAX_FPS) ? HELI_MAX_FPS : fps;
		
}

int animationIsPlaying(Animation animation)
	{ return animation->playing; }
void animationPlay(Animation animation)
	{ animation->playing = TRUE; }
void animationPause(Animation animation)
	{ animation->playing = FALSE; }

void animationAddTime(Animation animation, double time) {
	int cnt = animationGetFramesCount(animation);
	if (cnt <= 0) return;
	double t = animation->fps * time;
	if (animation->loop) {
		t /= cnt; t -= floor(t); t *= cnt;
		animation->pos += t;
		if (animation->pos > cnt) animation->pos -= cnt;
	} else {
		animation->pos += t;
	}
	heliAnimationFixPos(animation);
}

int animationGetLoop(Animation animation)
	{ return animation->loop; }
void animationSetLoop(Animation animation, int loop)
	{ animation->loop = loop != FALSE; }

double animationGetPos(Animation animation)
	{ return animation->pos; }

void animationSetPos(Animation animation, double pos)
	{ animation->pos = pos; heliAnimationFixPos(animation); }

int animationGetFrame(Animation animation) {
	int cnt = animationGetFramesCount(animation);
	int i = floor(animation->pos + HELI_PRECISION);
	if (i > cnt) i = cnt;
	if (i < 0) i = 0;
	return i;
}

void animationSetFrame(Animation animation, int frame)
	{ animationSetPos(animation, frame); }

void animationNextFrame(Animation animation)
	{ animationAddTime(animation, 1/animationGetFps(animation)); }


void heliAnimationUpdate(double dt) {
	for(Animation animation = first; animation; animation = animation->next)
		if (animationIsPlaying(animation))
			animationAddTime(animation, dt);
}

void heliAnimationFinish() {
	assert(!cache.count);
	heliArrayDestroy(&cache);
}