#include <v_lib.h>

GLuint	LoadTexture(int width,GLenum filter,GLenum clamp,GLenum env,void *texels)
{
	GLuint name;
	glGenTextures(1,&name);
	glBindTexture(GL_TEXTURE_2D,name);
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,width,0,GL_RGBA,
		GL_UNSIGNED_BYTE,texels);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,filter);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,filter);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,clamp);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,clamp);
	glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,env);
	glBindTexture(GL_TEXTURE_2D,0);
	return name;
}

void	save_mat(file_t f,GLfloat m[4][4])
{
	int i;
	for(i=0;i<4;i++)
		filePrintf(f,"[%g,\t%g,\t%g,\t%g]\n",m[i][0],m[i][1],m[i][2],m[i][3]);
}

void	save_tos(char *filename)
{
	GLfloat m[4][4];
	file_t f=fileOpenWrite(filename);
	glGetFloatv(GL_PROJECTION_MATRIX,(GLfloat*)m);
	filePuts(f,"Projection:\n");
	save_mat(f,m);
	glGetFloatv(GL_MODELVIEW_MATRIX,(GLfloat*)m);
	filePuts(f,"Modelview:\n");
	save_mat(f,m);
	fileClose(f);
}

void	rect(GLuint texture)
{
	glBindTexture(GL_TEXTURE_2D,texture);
	glBegin(GL_QUADS);
		glColor3f(.8f,.8f,.8f);
		glTexCoord2f(1,0);
		glVertex2f(1,1);

		glTexCoord2f(0,0);
		glVertex2f(-1,1);

		glColor3f(0,0,1);
		glTexCoord2f(0,1);
		glVertex2f(-1,-1);

		glTexCoord2f(1,1);
		glVertex2f(1,-1);
	glEnd();
}

void	main()
{
	void *pix;
	void *tex;
	GLuint name;
	
	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	
	tex=bmpLoad("../media/font8x8.bmp",NULL,NULL);
	if(!tex) return;

	vglCreateWindow("",0,0,320,240);

	glClearColor(0,.5,.5,.5);
	glClearDepth(1.0);
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glFrustum(-1,1,-1,1,1,10);
	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef(0,0,-1.1f);

	glPushMatrix();
	{
		vec_t angle=ANGLE_45;
		vec3_t axis={1,2,3};
		vec3_t pt={4,5,6};
		matrix4_t xform;
		matrix3x4_t	mat;
		mat4Zero(xform);
		vec3Unit(axis,axis);
		mat3x4Rotate(xform,axis,angle);
		mat3x4Translate(mat,pt);
		mat3x4ConcatAfter(xform,mat);
		{file_t f=fileOpenWrite("ref.txt");
		save_mat(f,xform);}
		glLoadIdentity();
		glRotatef(angle*RAD_TO_ANGLE,axis[0],axis[1],axis[2]);
		glTranslatef(pt[0],pt[1],pt[2]);
		save_tos("matrices");
	}
	glPopMatrix();
	
	name=LoadTexture(128,GL_LINEAR,GL_CLAMP,GL_MODULATE,tex);
	memFree(tex);
	
	glEnable(GL_TEXTURE_2D);
	rect(name);

	vglSwapBuffers();
	pix=vglReadPixels(NULL,NULL);
	tgaSave("out.tga",320,240,pix);
	memFree(pix);
	fgetc(stdin);
	
	vglDestroyWindow(vglGetCurrentWindow());
}
