// MeshFace.cpp: implementation of the CMeshFace class.
//
//////////////////////////////////////////////////////////////////////

#include "MeshFace.h"

#include "Material.h"
#include "Face.h"

#include "Kernel.h"

#include "OpenGL.h"

#include "..\Common\FileStream.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CMeshFace::CMeshFace()
{
	m_pszClassName = "CMeshFace";

	///////////////////////////////////////////////////////////////////////////
	m_pFaces = NULL;
	m_pMaterial = NULL;

	m_pIndices = NULL;
}

CMeshFace::~CMeshFace()
{
	Destroy();
}

void CMeshFace::Destroy()
{
	if (m_pIndices)
	{
		delete [] m_pIndices;
		m_pIndices = NULL;
	}

	if (m_pFaces)
	{
		delete [] m_pFaces;
		m_pFaces = NULL;
	}
}

bool CMeshFace::Read(CFileStream* lpStream)
{
	CFileStream* pStream = lpStream;

	char szName[80];
	pStream->ReadString(szName);

	// Find Material
	///////////////////////////////////////////////////////////////////////////
	m_pMaterial = CKernel::LookupMaterial(szName);
	if (!m_pMaterial)
		return false;

	///////////////////////////////////////////////////////////////////////////
	pStream->Read(&m_dwNumFaces, sizeof(DWORD), 1);

	m_pFaces = new CFace [m_dwNumFaces];
	if (!m_pFaces)
		return false;

	//
	m_dwNumIndices = 0;

	CFace* pFace = m_pFaces;
	for (int i=0; i<(int) m_dwNumFaces; i++)
	{
		pFace->Read(pStream);

		m_dwNumIndices += pFace->GetNumIndices();
		pFace ++;
	}

	// Make Index
	m_pIndices = new DWORD [m_dwNumIndices];
	LPDWORD pIndices = m_pIndices;

	pFace = m_pFaces;
	for (i=0; i<(int) m_dwNumFaces; i++)
	{
		LPDWORD pFaceIndices = pFace->GetIndices();
		for (int j=0; j<(int) pFace->GetNumIndices(); j++)
			*(pIndices + j) = *(pFaceIndices + j);
		
		pIndices += pFace->GetNumIndices();

		pFace ++;
	}

	return true;
}

void CMeshFace::Render()
{
	if (m_pMaterial)
		m_pMaterial->Apply();

	/*CFace* pFace = m_pFaces;
	for (int i=0; i<(int) m_dwNumFaces; i++)
	{
		pFace->Render();
		pFace ++;
	}*/

	glDrawElements(GL_TRIANGLES, m_dwNumIndices, GL_UNSIGNED_INT, m_pIndices);
}