#include "DXMaterial.h"
#include "DeviceStateManager.h"

void DXMaterial::SetTexture(DeviceStateManager*device,XString texture)
{
	SAFERELEASE(m_Texture);
	/*if(device && texture.getlen())
	{
		m_Texture = device->GetTextureManager()->CreateTexture(texture,FMT_A8R8G8B8,POOL_MANAGED);
	}
	else*/
		m_Texture = NULL;

	m_TextureFilename = texture;
}

bool DXMaterial::LoadTexture(DeviceStateManager* const device)
{
	SAFERELEASE(m_Texture);

	if(device && m_TextureFilename.getlen())
	{
		m_Texture = device->GetTextureManager()->CreateTexture(m_TextureFilename, FMT_A8R8G8B8, POOL_MANAGED);
		if (m_Texture->GetSurface())
			return true;

		SAFERELEASE(m_Texture);
	}

	return false;
}

void DXMaterial::Setup(DeviceStateManager* const device)
{
	device->SetAmbientMaterial(m_Material.Ambient);
	device->SetDiffuseMaterial(m_Material.Diffuse);
	if(m_Material.Specular.r || m_Material.Specular.g || m_Material.Specular.b)
	{
		device->SetSpecularEnable(true);
		device->SetSpecularMaterial(m_Material.Specular);
		device->SetMaterialPower(m_Material.Power);
	}
	else
	{
		device->SetSpecularEnable(false);
	}
	device->SetEmissiveMaterial(m_Material.Emissive);

	device->SetTexture(0,m_Texture);

	D3DTEXTUREOP op;
	if(m_Texture)
		op = D3DTOP_MODULATE;
	else
		op = D3DTOP_DISABLE;

	device->SetStageAlphaOperation(0, D3DTA_TEXTURE, op, D3DTA_CURRENT);
	device->SetStageColorOperation(0, D3DTA_TEXTURE, op, D3DTA_CURRENT);
}