#include "PostProcessing.h"
#include <crtdbg.h>

HRESULT PostProcessing::init()
{
	HRESULT hr = S_OK;

    DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
	#if defined( DEBUG ) || defined( _DEBUG )
		dwShaderFlags |= D3D10_SHADER_DEBUG;
	#endif

	ID3D10Blob *pErrorMsg;
	hr = D3DX10CreateEffectFromFile( L"../../shaders/PostProcessing.fx", NULL, NULL, "fx_4_0", dwShaderFlags, 0, DXUTGetD3D10Device(), NULL,
                                         NULL, &effect, &pErrorMsg, NULL );

	if(pErrorMsg)
	{
		 _RPT1(_CRT_WARN, "compilation error : %s\n", (char*) pErrorMsg->GetBufferPointer()); 
		  SAFE_RELEASE(pErrorMsg);

	}
    if( FAILED( hr ) )
    {
        MessageBox( NULL,
                    L"The FX file cannot be located.  Please run this executable from the directory that contains the FX file.", L"Error", MB_OK );
		V_RETURN(hr);
    }
	technique = effect->GetTechniqueByName("Render");
	gaussTechnique = effect->GetTechniqueByName("Blur");
	diffuseTexture = effect->GetVariableByName("screenTexture")->AsShaderResource();
	depthTexture = effect->GetVariableByName("depthTexture")->AsShaderResource();
	blurredTexture = effect->GetVariableByName("blurredTexture")->AsShaderResource();

	depthInfo = effect->GetVariableByName("depthInfo")->AsVector();
	gaussOffsetsVariable = effect->GetVariableByName("gaussSampleOffsets");
	gaussWeightsVariable = effect->GetVariableByName("gaussSampleWeights");

	ID3D10Device* pd3dDevice = DXUTGetD3D10Device();
	
	D3D10_PASS_DESC PassDesc;
	technique->GetPassByIndex( 0 )->GetDesc( &PassDesc );
	pd3dDevice->IASetInputLayout( NULL );

	return S_OK;
}

void PostProcessing::setDiffuseTexture(ID3D10ShaderResourceView* textureResrc)
{
	diffuseTexture->SetResource(textureResrc);
}

void PostProcessing::setDepthTexture(ID3D10ShaderResourceView* textureResrc)
{
	depthTexture->SetResource(textureResrc);
}

void PostProcessing::setBlurredTexture(ID3D10ShaderResourceView* textureResrc)
{
	blurredTexture->SetResource(textureResrc);
}

void PostProcessing::setModelMatrix(D3DXMATRIX* modelMatrix)
{}

void PostProcessing::setViewMatrix(D3DXMATRIX* viewMatrix)
{}

void PostProcessing::setProjectionMatrix(D3DXMATRIX* projMatrix)
{}

void PostProcessing::setInputLayout()
{
	DXUTGetD3D10Device()->IASetInputLayout( NULL );
}

ID3D10Effect* PostProcessing::getEffectVariable()
{
	return effect;
}

ID3D10EffectTechnique* PostProcessing::getTechniqueVariable()
{
	return technique;
}

ID3D10EffectTechnique* PostProcessing::getGaussTechniqueVariable()
{
	return gaussTechnique;
}

void PostProcessing::setDepthInfo(D3DXVECTOR4* depthInf)
{
	depthInfo->SetFloatVector((float*)depthInf);
}

void PostProcessing::setGaussOffsets(D3DXVECTOR4* gaussOffsets)
{
	gaussOffsetsVariable->SetRawValue(gaussOffsets,0,sizeof(D3DXVECTOR4)*16);
}

void PostProcessing::setGaussWeights(D3DXVECTOR2* gaussWeights)
{
	gaussWeightsVariable->SetRawValue(gaussWeights,0,sizeof(D3DXVECTOR2)*16);
}

PostProcessing::~PostProcessing()
{
	SAFE_RELEASE(effect);
}
