#include "HLPixelShader.h"
#include "ShaderManager.h"
#include "DeviceStateManager.h"

HLPixelShader::HLPixelShader(ShaderManager* const manager, const XString& fn, const XString& profile) : ShaderProgram(manager, SH_HLPS, fn)
{
	m_Profile = profile;
	m_Shader = NULL;
	m_ConstantTable = NULL;
	
	Open(m_Filename);
}

void HLPixelShader::Compile(bool debug)
{
	ReleaseSH();
	m_Compiled = false;

	if(!m_Manager)
		return;

	if(m_Code.getlen() == 0)
	{
		m_ErrorMsgs = "ERROR: File not found or empty!";
		return;
	}

	LPD3DXBUFFER pCode   = NULL;
	LPD3DXBUFFER pErrors = NULL;
	
	D3DXCompileShader(m_Code.getbuffer(),m_Code.getlen(), NULL, NULL, "PS", m_Profile.getbuffer(),debug?D3DXSHADER_SKIPOPTIMIZATION|D3DXSHADER_DEBUG:0, &pCode, &pErrors, &m_ConstantTable);
	if(pCode)
		m_Manager->GetDevice()->GetDevice()->CreatePixelShader( (DWORD*)pCode->GetBufferPointer(), &m_Shader );
	else
		m_Shader = NULL;

	if(pErrors)
	{
        m_ErrorMsgs = (char*)pErrors->GetBufferPointer();
	}
	else if(m_Shader)
	{
		m_Compiled = true;
        m_ErrorMsgs = "Compilation Successful!";
	}
	else
	{
		m_ErrorMsgs = "ERROR: Unknown Error!";
	}

	SAFERELEASE(pCode);
	SAFERELEASE(pErrors);
}

XString HLPixelShader::GetDisassembly(void)
{
	//D3DXDisassembleShader(code, true, "", dis);
	return "";
}

void HLPixelShader::ReleaseSH(void)
{
	SAFERELEASE(m_Shader);
	SAFERELEASE(m_ConstantTable);
}