#include "CompiledEffect.h"
#include "EffectCompiler.h"
#include "ShaderManager.h"
#include "DeviceStateManager.h"

CompiledEffect::CompiledEffect(EffectCompiler* const compiler, D3DXMACRO* pDefines) : ShaderEffect(compiler->GetManager(), "")
{
	m_pDefines = pDefines;
	m_Compiler = compiler;
	m_Type = SH_CMPFX;
}

CompiledEffect::~CompiledEffect(void)
{
	delete [] m_pDefines;
}

void CompiledEffect::Compile(bool debug)
{
	if(!m_Compiler)
		return;

	LPD3DXBUFFER pErrors = NULL;

	DWORD flags = 0;
	if(debug)
		flags |= D3DXSHADER_SKIPOPTIMIZATION | D3DXSHADER_DEBUG;

	HRESULT hr = D3DXCreateEffect(m_Manager->GetDevice()->GetDevice(), m_Compiler->GetCode().getbuffer(), m_Compiler->GetCode().getlen(), m_pDefines, NULL, flags, m_Compiler->GetPool(),&m_Shader, &pErrors );

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

	SAFERELEASE(pErrors);
}