#include "project.h"

void tx_CreateRGBA(byte* image, byte* alpha, byte* dest, unsigned long width, unsigned long height)
{
	if (dest!=NULL) delete [] dest;
	dest=(byte*)malloc(width*height*4);
	for (unsigned int i=0; i<width*height; i++)
	{
		*(dest++)=*(image++);
		*(dest++)=*(image++);
		*(dest++)=*(image++);
		*(dest++)=(int)(0.32f**alpha+++0.57f**alpha+++0.11f**alpha++);
	}
}

unsigned int tx_UploadTexture3(void *p, unsigned int w, unsigned int h)
{
	unsigned int texnum;
	glGenTextures(1,&texnum);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D,texnum);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
	gluBuild2DMipmaps(GL_TEXTURE_2D, 3, w, h, GL_RGB, GL_UNSIGNED_BYTE, p);
	glTexImage2D ( GL_TEXTURE_2D, 0, 3, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, p);
	return texnum;
}

unsigned int tx_UploadTexture4(void *p, unsigned int w, unsigned int h)
{
	unsigned int texnum;
	glGenTextures(1,&texnum);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D,texnum);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
	gluBuild2DMipmaps(GL_TEXTURE_2D, 4, w, h, GL_RGBA, GL_UNSIGNED_BYTE, p);
	glTexImage2D ( GL_TEXTURE_2D, 0, 4, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, p);
	return texnum;
}

void tx_UpdateTexture3(void *tdata, int w, int h)
{
	glTexImage2D(GL_TEXTURE_2D, 0, 3, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, tdata);
}

void tx_UpdateTexture4(void *tdata, int w, int h)
{
	glTexImage2D(GL_TEXTURE_2D, 0, 4, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, tdata);
}

void tx_BeginEnvMap(void)
{
	glEnable(GL_TEXTURE_GEN_S);
	glEnable(GL_TEXTURE_GEN_T);
	glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
	glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
}

void tx_EndEnvMap(void)
{
	glDisable(GL_TEXTURE_GEN_S);
	glDisable(GL_TEXTURE_GEN_T);
}

unsigned int tx_CreateR2T(int size) 
{
	unsigned int hret;
	byte *p = new byte [size*size*3];
	memset(p,0,size*size*3);
	glGenTextures(1, &hret);								
	glBindTexture(GL_TEXTURE_2D, hret);
	glTexImage2D(GL_TEXTURE_2D, 0, 3, size, size, 0, GL_RGB, GL_UNSIGNED_BYTE, p);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	delete [] p;
	return hret;
}

void tx_BeginR2T(int size)	// size must be power of two
{
	glPushMatrix();
	glViewport(0, 0, size, size);
}

void tx_R2T(UINT texture, int size)
{
	glBindTexture(GL_TEXTURE_2D,texture);
	glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, size, size, 0);
}

void tx_EndR2T(int w, int h)
{
	glPopMatrix();
	glViewport(0, 0, w, h);
}