Blob Blame Raw

#include <SDL_image.h>

#include "private.h"
#include "sprite.h"
#include "window.h"
#include "animation.h"

static HeliArray cache;
static Animation first, last;

typedef struct _HeliTexture {
	const char *key;
	unsigned int id;
	int own;
	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 imageLoadFromSDL(SDL_Surface *surface, int *outWidth, int *outHeight, unsigned char **outPixels) {
	*outWidth = 0;
	*outHeight = 0;
	*outPixels = NULL;
	if (!surface) 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);
		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);
	
	*outPixels = pixels;
	*outWidth = w;
	*outHeight = h;
	return TRUE;
}

int imageLoadFromMemory(const void *data, int size, int *outWidth, int *outHeight, unsigned char **outPixels) {
	SDL_RWops *rw = data && size > 0 ? SDL_RWFromMem((void*)data, size) : NULL;
	SDL_Surface *surface = rw ? IMG_Load_RW(rw, SDL_TRUE) : NULL;
	int res = imageLoadFromSDL(surface, outWidth, outHeight, outPixels);
	if (surface) {
		SDL_FreeSurface(surface);
	} else {
		fprintf(stderr, "helianthus: cannot load image from memory\n");
	}
	return res;
}

int imageLoad(const char *path, int *outWidth, int *outHeight, unsigned char **outPixels) {
	SDL_Surface *surface = IMG_Load(path);
	int res = imageLoadFromSDL(surface, outWidth, outHeight, outPixels);
	if (surface) {
		SDL_FreeSurface(surface);
	} else {
		fprintf(stderr, "helianthus: cannot load image: %s\n", path);
	}
	return res;
}


int imageSave(const char *path, int width, int height, const void *pixels) {
	#if SDL_BYTEORDER == SDL_BIG_ENDIAN
		Uint32 rm = 0xff000000,
		       gm = 0x00ff0000,
		       bm = 0x0000ff00,
		       am = 0x000000ff;
	#else
		Uint32 rm = 0x000000ff,
		       gm = 0x0000ff00,
		       bm = 0x00ff0000,
		       am = 0xff000000;
	#endif
	
	SDL_Surface *surface = SDL_CreateRGBSurfaceFrom(SDL_const_cast(void*, pixels), width, height, 32, width*4, rm, gm, bm, am);
	
	if (!surface) {
		fprintf(stderr, "helianthus: cannot create SDL surface to save image: %s\n", SDL_GetError());
		return FALSE;
	}
	
	if (IMG_SavePNG(surface, path) != 0) {
		fprintf(stderr, "helianthus: cannot save image to file: %s, : %s\n", path, SDL_GetError());
		SDL_FreeSurface(surface);
		return FALSE;
	}
	
	SDL_FreeSurface(surface);
	return TRUE;
}


unsigned int imageToGLTexture(int width, int height, const void *pixels, int wrap)
	{ return imageToGLTextureEx(width, height, pixels, wrap, wrap, TRUE, TRUE); }


int imageToExistingGLTexture(unsigned int texid, int width, int height, const void *pixels) {
	if (!texid || width <= 0 || height <= 0 || !pixels) return FALSE;
	
	// 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 = (const unsigned char *)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);
	
	
	// upload to OpenGL texture
	unsigned int prevtex = 0;
	int minFilter = 0;
	glGetIntegerv(GL_TEXTURE_BINDING_2D, (int*)&prevtex);
	glBindTexture(GL_TEXTURE_2D, texid);
	glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, &minFilter);
	
	int mipMap = minFilter == GL_NEAREST_MIPMAP_NEAREST
	          || minFilter == GL_NEAREST_MIPMAP_LINEAR
	          || minFilter == GL_LINEAR_MIPMAP_NEAREST
	          || minFilter == GL_LINEAR_MIPMAP_LINEAR;
	
	// 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 (!mipMap) break;
		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, prevtex);
	
	return TRUE;
}

unsigned int imageToGLTextureEx(int width, int height, const void *pixels, int horWrap, int vertWrap, int smooth, int mipMap) {
	// create OpenGL texture
	unsigned int texid = 0, prevtex = 0;
	glGetIntegerv(GL_TEXTURE_BINDING_2D, (int*)&prevtex);
	glGenTextures(1, &texid);
	glBindTexture(GL_TEXTURE_2D, texid);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smooth ? (mipMap ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR): (mipMap ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST));
	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);
	imageToExistingGLTexture(texid, width, height, pixels);
	glBindTexture(GL_TEXTURE_2D, prevtex);
	return texid;
}

int imageFromGLTexture(unsigned int texid, int *outWidth, int *outHeight, unsigned char **outPixels) {
	*outWidth = *outHeight = 0; *outPixels = NULL;
	
	int w = 0, h = 0;
	unsigned int prevtex = 0;
	glGetIntegerv(GL_TEXTURE_BINDING_2D, (int*)&prevtex);
	glBindTexture(GL_TEXTURE_2D, texid);
	glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w);
	glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &h);
	if (w > 0 && h > 0) {
		*outWidth = w;
		*outHeight = h;
		*outPixels = malloc(sizeof(**outPixels)*w*h*4);
		glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, *outPixels);
	}
	glBindTexture(GL_TEXTURE_2D, prevtex);
	
	return outPixels != NULL;
}

int viewportSave(const char *path) {
	int width = 0;
	int height = 0;
	unsigned char *pixels = NULL;
	if (!imageFromViewport(&width, &height, &pixels)) return FALSE;
	int result = imageSave(path, width, height, pixels);
	free(pixels);
	return result;
}

unsigned int pixelGet(const void *pixel) {
	const unsigned char *p = (const unsigned char *)pixel;
	return (((unsigned int)p[0]) << 24)
	     | (((unsigned int)p[1]) << 16)
		 | (((unsigned int)p[2]) <<  8)
		 | (((unsigned int)p[3]) <<  0);
}

void pixelSet(void *pixel, unsigned int colorCode) {
	unsigned char *p = (unsigned char *)pixel;
	p[0] = (colorCode >> 24);
	p[1] = (colorCode >> 16) & 0xFF;
	p[2] = (colorCode >>  8) & 0xFF;
	p[3] = (colorCode      ) & 0xFF;
}

unsigned int imageGetPixel(int width, int height, const void *pixels, int x, int y) {
	if (x < 0 || x >= width || y < 0 || y >= height || !pixels) return 0;
	return pixelGet((const unsigned char *)pixels + 4*((size_t)width*y + x));
}

void imageSetPixel(int width, int height, void *pixels, int x, int y, unsigned int colorCode) {
	if (x < 0 || x >= width || y < 0 || y >= height || !pixels) return;
	pixelSet((unsigned char *)pixels + 4*((size_t)width*y + x), colorCode);
}



static void unloadTexture(HeliTexture *texture) {
	assert(!texture->refcount);
	if (texture->own && texture->id) {
		unsigned int prevtex = 0;
		glGetIntegerv(GL_TEXTURE_BINDING_2D, (int*)&prevtex);
		if (prevtex == texture->id) glBindTexture(GL_TEXTURE_2D, 0);
		glDeleteTextures(1, &texture->id);
	}
}


static HeliTexture* loadTexture(const char *key) {
	HeliTexture *texture = calloc(1, sizeof(*texture));
	texture->key = heliStringCopy(key);
	texture->own = TRUE;
	if (key[0] == 'T') {
		texture->id = (unsigned int)atoll(key + 3);
	} else {
		int w = 0, h = 0;
		unsigned char *pixels = NULL;
		if (imageLoad(key+3, &w, &h, &pixels)) {
			texture->id = imageToGLTextureEx(w, h, pixels, key[1] == 'W', key[2] == 'W', key[0] == 'L', TRUE);
			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 = windowGetMinFrameRate();
	double maxFps = windowGetMaxFrameRate();
	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 smooth, int horWrap, int vertWrap) {
	Animation animation = createAnimationEmpty();
	char *key = heliStringConcat("NCC", path);
	if (smooth) key[0] = 'L';
	if (horWrap) key[1] = 'W';
	if (vertWrap) key[2] = 'W';
	
	Directory d = openDirectory(key + 3);
	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 createAnimationFromGLTexId(unsigned int texid) {
	Animation animation = createAnimationEmpty();
	char key[256] = "TTT";
	sprintf(key+3, "%d", texid);
	heliArrayInsert(&animation->frames, -1, getTexture(key), (HeliFreeCallback)&unrefTexture);
	return animation;
}

void animationGLTexIdSetOwnership(unsigned int texid, int own) {
	char key[256] = "TTT";
	sprintf(key+3, "%d", texid);
	HeliPair *item = heliStringmapGet(&cache, key);
	if (item) {
		HeliTexture *texture = (HeliTexture*)item->value;
		texture->own = own != 0;
	}
}

Animation createAnimationFromImageEx(int width, int height, const void *pixels, int horWrap, int vertWrap, int smooth, int mipMap)
	{ return createAnimationFromGLTexId(imageToGLTextureEx(width, height, pixels, horWrap, vertWrap, smooth, mipMap)); }

Animation createAnimationFromImage(int width, int height, const void *pixels, int wrap)
	{ return createAnimationFromGLTexId(imageToGLTexture(width, height, pixels, wrap)); }

Animation createAnimationFromFramebuffer(Framebuffer framebuffer) {
	unsigned int texid = framebufferGetGLTexId(framebuffer);
	Animation animation = createAnimationFromGLTexId(texid);
	animationGLTexIdSetOwnership(texid, FALSE);
	return animation;
}

Animation createAnimationFromViewportEx(int horWrap, int vertWrap, int smooth, int mipMap) {
	int width = 0;
	int height = 0;
	unsigned char *pixels = NULL;
	if (!imageFromViewport(&width, &height, &pixels)) return createAnimationEmpty();
	return createAnimationFromImageEx(width, height, pixels, horWrap, vertWrap, smooth, mipMap);
}

Animation createAnimationFromViewport()
	{ return createAnimationFromViewportEx(FALSE, FALSE, TRUE, TRUE); }


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

void animationDestroy(Animation animation) {
	for(int i = spritesGetCount() - 1; i >= 0; --i) {
		Sprite s = spritesGet(i);
		if (spriteGetAnimation(s) == animation)
			spriteSetNoAnimation(s);
	}
	
	HeliDrawingState *ss = heliDrawingGetState();
	for(HeliDrawingState *s = heliDrawingGetStateStack(); s <= ss; ++s) {
		if (ss->fillTexture.animation == animation) ss->fillTexture.animation = NULL;
		if (ss->strokeTexture.animation == animation) ss->strokeTexture.animation = NULL;
	}
	
	*(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 animationGetFrameGLTexId(Animation animation, int frame) {
	int count = animationGetFramesCount(animation);
	if (frame < 0 || frame >= count) return 0;
	HeliTexture *texture = (HeliTexture*)animation->frames.items[frame].value;
	return texture->id;
}

unsigned int animationGetGLTexId(Animation animation)
	{ return animationGetFrameGLTexId(animation, animationGetFrame(animation)); }

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 - 1;
	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);
}