// MaxKernel.cpp: implementation of the CMaxKernel class.
//
//////////////////////////////////////////////////////////////////////

#include "MaxKernel.h"

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

DWORD CMaxKernel::m_dwNumMaterials = 0;

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

CMaxKernel::CMaxKernel()
{
}

CMaxKernel::~CMaxKernel()
{

}

CMaxMaterial* CMaxKernel::LookupMaterial(DWORD dwID)
{
	CMaxMaterial* pMaterial = (CMaxMaterial*) m_pMaterial;
	for (int i = 0; i < (int) m_dwNumMaterials; i ++)
	{
		if (pMaterial->GetID() == dwID)
			break;

		pMaterial = (CMaxMaterial*) pMaterial->GetNext();
	}

	return pMaterial;
}

DWORD CMaxKernel::LookupMaterial(CMaxMaterial* lpMaterial)
{
	DWORD dwIndex = 0xffffffff;

	CMaxMaterial* pMaterial = (CMaxMaterial*) m_pMaterial;
	for (int i = 0; i < (int) m_dwNumMaterials; i ++)
	{
		if (!strcmp(pMaterial->GetName(), lpMaterial->GetName()))
		{
			dwIndex = i;
			break;
		}

		pMaterial = (CMaxMaterial*) pMaterial->GetNext();
	}

	if (dwIndex == 0xffffffff)
	{
		// count material
		dwIndex = m_dwNumMaterials;
		m_dwNumMaterials ++;


		// Copy Material
		pMaterial = new CMaxMaterial;
		if (!pMaterial)
			return 0xffffffff;

		if (!pMaterial->Create(lpMaterial->GetName()))
			return 0xffffffff;

		pMaterial->SetID(dwIndex);

		pMaterial->m_diffuse.red   = lpMaterial->m_diffuse.red;
		pMaterial->m_diffuse.green = lpMaterial->m_diffuse.green;
		pMaterial->m_diffuse.blue  = lpMaterial->m_diffuse.blue;
		pMaterial->m_diffuse.alpha = 1.0f;

		pMaterial->m_ambient.red   = lpMaterial->m_ambient.red;
		pMaterial->m_ambient.green = lpMaterial->m_ambient.green;
		pMaterial->m_ambient.blue  = lpMaterial->m_ambient.blue;
		pMaterial->m_ambient.alpha = 1.0f;

		pMaterial->m_specular.red   = lpMaterial->m_specular.red;  
		pMaterial->m_specular.green = lpMaterial->m_specular.green;
		pMaterial->m_specular.blue  = lpMaterial->m_specular.blue; 
		pMaterial->m_specular.alpha = 1.0f;

		pMaterial->m_shininess = lpMaterial->m_shininess;
		
		pMaterial->SelectTexture(lpMaterial->GetTexture());

		// Insert Material
		if (!m_pMaterial)
			m_pMaterial = pMaterial;
		else
			m_pMaterial->SetLast(pMaterial);
	}

	return dwIndex;
}

void CMaxKernel::WriteMaterial(CFileStream* lpStream)
{
	CFileStream* pStream = lpStream;

	///////////////////////////////////////////////////////////////////////////////////////////////
	pStream->Write(&m_dwNumMaterials, sizeof(DWORD), 1);

	CMaxMaterial* pMaterial = (CMaxMaterial*) m_pMaterial;
	for (int i = 0; i < (int) m_dwNumMaterials; i ++)
	{
		pMaterial->Write(pStream);

		pMaterial = (CMaxMaterial*) pMaterial->GetNext();
	}
}