//-------------------------------------------------------------------------------
//zfxMesh.cpp
//-------------------------------------------------------------------------------
#include "zfxMesh.h"

///////////////////CZFXMesh class implementation////////////////////////////////////////////////////
CZFXMesh::CZFXMesh()
{
	m_dwMtrl = 0;
	m_pMeshMtrl = NULL;
	m_pMesh = NULL;
	m_ppTexture = NULL;
}

CZFXMesh::~CZFXMesh()
{
	Release();
}

void CZFXMesh::Release()
{
	SAFE_DELETE( m_pMeshMtrl );
	SAFE_RELEASE( m_pMesh );
	if(m_ppTexture)
	{
		for(DWORD i=0;i<m_dwMtrl;i++)
			SAFE_RELEASE( m_ppTexture[i] );
		SAFE_DELETE(m_ppTexture);
	}
}

HRESULT CZFXMesh::LoadMeshFromFile( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR strFileName, 
		DWORD options )
{
	HRESULT hr;
	ID3DXBuffer* pMtrlBuffer;
	if( FAILED( hr = D3DXLoadMeshFromX( strFileName, options, pd3dDevice,
		NULL, &pMtrlBuffer, NULL, &m_dwMtrl, &m_pMesh )))
		return hr;

	D3DXMATERIAL* pMtrlInBuf = (D3DXMATERIAL*)pMtrlBuffer->GetBufferPointer();
	m_pMeshMtrl = new D3DMATERIAL9[m_dwMtrl];
	for(DWORD i=0;i<m_dwMtrl;i++)
	{
		m_pMeshMtrl[i] = pMtrlInBuf[i].MatD3D;
	}

	m_ppTexture = new LPDIRECT3DTEXTURE9[m_dwMtrl];

	for(DWORD i=0;i<m_dwMtrl;i++)
	{
		if( NULL != pMtrlInBuf[i].pTextureFilename )
		{
			D3DXCreateTextureFromFileA( pd3dDevice, pMtrlInBuf[i].pTextureFilename, &m_ppTexture[i] );
		}
		else
		{
			m_ppTexture[i] = NULL;
		}

	}
	return hr;
}


void CZFXMesh::Render( LPDIRECT3DDEVICE9 pd3dDevice )
{
	for(DWORD i=0;i<m_dwMtrl;i++)
	{
		pd3dDevice->SetTexture( 0, m_ppTexture[i]);
		pd3dDevice->SetMaterial( &m_pMeshMtrl[i] );
		m_pMesh->DrawSubset(i);
	}
}

void CZFXMesh::Render( LPDIRECT3DDEVICE9 pd3dDevice, LPDIRECT3DTEXTURE9* ppTexture )
{
	for(DWORD i=0;i<m_dwMtrl;i++)
	{
		pd3dDevice->SetTexture( 0, ppTexture[i]);
		pd3dDevice->SetMaterial( &m_pMeshMtrl[i] );
		m_pMesh->DrawSubset(i);
	}
}