#include "stdAfx.h"
#include "face.h"
#include "facegroup.h"
#include "vector3d.h"
#include "vector3dgroup.h"
#include "mesh.h"

Mesh::Mesh( int iMaxNumVector, int iMaxNumFace )
{
	setLockMem( 0 );

	pVector3DGroup = new Vector3DGroup( iMaxNumVector );
	pFaceGroup     = new FaceGroup    ( iMaxNumFace   );
}

Mesh::~Mesh()
{
	freeMem();
}

void Mesh::normalize()
{
	float maxCoord = 0;
	Vector3D tempV3D (0, 0, 0);
	for(int i = 0; i < pVector3DGroup->getNumElements(); i++) {
		tempV3D = pVector3DGroup->getElementAt(i);
		if((tempV3D.fX*tempV3D.fX) > (maxCoord*maxCoord)) {
			maxCoord = tempV3D.fX;
		}
		if((tempV3D.fY*tempV3D.fY) > (maxCoord*maxCoord)) {
			maxCoord = tempV3D.fY;
		}
		if((tempV3D.fZ*tempV3D.fZ) > (maxCoord*maxCoord)) {
			maxCoord = tempV3D.fZ;
		}
	}

	if(maxCoord < 0) {
		maxCoord *= -1;
	}
	if(maxCoord == 0) {
		maxCoord = 1;
	}
	maxCoord = 1/maxCoord;
	for(i = 0; i < pVector3DGroup->getNumElements(); i++) {
		tempV3D = pVector3DGroup->getElementAt(i);	
		tempV3D.multiply(maxCoord);
		pVector3DGroup->setElementAt(i, tempV3D);
	}
}

void Mesh::freeMem()
{
//	if ( ! getLockMem() )
//	{
		delete pVector3DGroup;
		delete pFaceGroup;
//	}
}

void Mesh::setLockMem( int iInLockMem )
{
	iLockMem = iInLockMem;
}

int Mesh::getLockMem()
{
	return iLockMem;
}

Vector3D Mesh::getGeometricCenter()
{
	Vector3D outVector( 0, 0, 0);

	for(int i = 0; i < pVector3DGroup->getNumElements(); i++) {
		outVector.add( pVector3DGroup->getElementAt(i) );
	}

	outVector.multiply( 1.f / pVector3DGroup->getNumElements() );

	return outVector;
}

Vector3DGroup *Mesh::getVector3DGroupPtr()
{
	return pVector3DGroup;
}


FaceGroup *Mesh::getFaceGroupPtr()
{
	return pFaceGroup;
}
