/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2008.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: src/drivers/common/opengl/oglmatrix.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/graphics/graphics.hpp"

#include "drivers/common/opengl/opengl.hpp"

//
// Simple OpenGL matrix handling
//
oglMatrix::oglMatrix()
{
	glPushMatrix();
}

oglMatrix::oglMatrix(const sgxVector3 &pos)
{
	glPushMatrix();
	glTranslatef(pos.x, pos.y, pos.z);
}

oglMatrix::oglMatrix(const sgxMatrix43 &transform)
{
	GLfloat matrix[16];
	glPushMatrix();

	convertToGL(matrix, transform);

#if SGX_FORMAL_VERSION
	GLfloat matrix[] = {
		transform.right.x, transform.right.y, transform.right.z, 0, 
		transform.up.x, transform.up.y, transform.up.z, 0,
		transform.at.x, transform.at.y, transform.at.z, 0,
		0,0,0,				1,
	};
#endif
	glMultMatrixf(matrix);
}

void
oglMatrix::convertToSgx(sgxMatrix43 &transform, const GLfloat *m44)
{
	sgxAssert(m44);
	sgxMemcpy(&transform.right, &m44[0], sizeof(sgxVector3));
	sgxMemcpy(&transform.up, &m44[4], sizeof(sgxVector3));
	sgxMemcpy(&transform.at, &m44[8], sizeof(sgxVector3));
	sgxMemcpy(&transform.pos, &m44[12], sizeof(sgxVector3));
}

void
oglMatrix::convertToSgx(sgxMatrix44 &transform, const GLfloat *m44)
{
	sgxAssert(m44);
	sgxMemcpy(&transform.right, &m44[0], sizeof(sgxVector4));
	sgxMemcpy(&transform.up, &m44[4], sizeof(sgxVector4));
	sgxMemcpy(&transform.at, &m44[8], sizeof(sgxVector4));
	sgxMemcpy(&transform.pos, &m44[12], sizeof(sgxVector4));
}

void
oglMatrix::convertToGL(GLfloat *m44, const sgxMatrix43 &transform)
{
	sgxAssert(m44);
	sgxMemcpy(&m44[0], &transform.right, sizeof(sgxVector3));
	sgxMemcpy(&m44[4], &transform.up, sizeof(sgxVector3));
	sgxMemcpy(&m44[8], &transform.at, sizeof(sgxVector3));
	sgxMemcpy(&m44[12], &transform.pos, sizeof(sgxVector3));

	m44[3] = m44[7] = m44[11] = 0;
	m44[15] = 1;
}

void
oglMatrix::convertToGL(GLfloat *m44, const sgxMatrix44 &transform)
{
	sgxAssert(m44);
	sgxMemcpy(&m44[0], &transform.right, sizeof(sgxVector4));
	sgxMemcpy(&m44[4], &transform.up, sizeof(sgxVector4));
	sgxMemcpy(&m44[8], &transform.at, sizeof(sgxVector4));
	sgxMemcpy(&m44[12], &transform.pos, sizeof(sgxVector4));
}

oglMatrix::~oglMatrix()
{
	glPopMatrix();
}

