// Kernel.cpp: implementation of the CKernel class.
//
//////////////////////////////////////////////////////////////////////

#include "Kernel.h"

#include "Texture.h"
#include "Material.h"

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

#include "..\Common\BMPImage.h"
#include "..\Common\DDSImage.h"
#include "..\Common\PCXImage.h"
#include "..\Common\TGAImage.h"

CMaterial*	CKernel::m_pMaterial = NULL;
CTexture*	CKernel::m_pTexture = NULL;

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

CKernel::CKernel()
{
	m_pszClassName = "CKernel";
}

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

void CKernel::Destroy()
{
	if (m_pMaterial)
	{
		delete m_pMaterial;
		m_pMaterial = NULL;
	}

	if (m_pTexture)
	{
		delete m_pTexture;
		m_pTexture = NULL;
	}
}

// static function
bool CKernel::ReadMaterial(CFileStream *lpStream)
{
	DWORD dwLength;
	lpStream->Read(&dwLength, sizeof(DWORD), 1);

	for (int i = 0; i < (int) dwLength; i ++)
	{
		CMaterial* pMaterial = new CMaterial;
		if (!pMaterial)
			return false;

		pMaterial->Read(lpStream);

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

	return true;
}

CMaterial* CKernel::LookupMaterial(LPSTR lpszName)
{
	CMaterial* pMaterial = NULL;
	if (m_pMaterial)
		pMaterial = (CMaterial *) m_pMaterial->Find(lpszName);

	return pMaterial;
}

CTexture* CKernel::LookupTexture(LPSTR lpszName)
{
	CTexture* pTexture = NULL;
	if (m_pTexture)
		pTexture = (CTexture *) m_pTexture->Find(lpszName);

	if (!pTexture)
	{
		char szPathName[80];
		wsprintf(szPathName, "%s.TGA", lpszName);
		//wsprintf(szPathName, "%s.BMP", lpszName);
		
		CImage* pImage = new CTGAImage;
		if (!pImage)
			return NULL;
		
		if (!pImage->Load(szPathName))
			return NULL;

		///////////////////////////////////////////////////////////////////////
		pTexture = new CTexture;
		if (!pTexture)
			return NULL;

		if (!pTexture->Create(lpszName))
			return NULL;

		pTexture->Upload(pImage);

		delete pImage;

		// Insert Texture
		if (!m_pTexture)
			m_pTexture = pTexture;
		else
			m_pTexture->SetLast(pTexture);
	}

	return pTexture;
}

