/*	Renegade Scripts.dll
	SimpleSceneShaderClass
	Copyright 2007 Mark Sararu, Jonathan Wilson

	This file is part of the Renegade scripts.dll
	The Renegade scripts.dll is free software; you can redistribute it and/or modify it under
	the terms of the GNU General Public License as published by the Free
	Software Foundation; either version 2, or (at your option) any later
	version. See the file COPYING for more details.
	In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence.
	Only the source code to the module(s) containing the licenced code has to be released.
*/
#include "scripts.h"
#include "shadereng.h"
#include "resourcemanager.h"
#include "shaderstatemanager.h"
#include "effect.h"
#include "shader_scene.h"
#include "simplesceneshader.h"

SimpleSceneShaderClass::SimpleSceneShaderClass()
{
#ifndef SDBEDIT
	Validated = false;
	ValidationResult = false;
	PassScales = 0;
	SceneTextureHandle = 0;
	InputTextureHandle = 0;
#endif
	SceneShaderClass::SceneShaderClass();
}
SimpleSceneShaderClass::~SimpleSceneShaderClass()
{
#ifndef SDBEDIT
	SAFE_DELETE_ARRAY(PassScales);
#endif
	SceneShaderClass::~SceneShaderClass();
}
void SimpleSceneShaderClass::Load(ChunkLoadClass& cload)
{
 	while (cload.Open_Micro_Chunk())
	{
		switch(cload.Cur_Micro_Chunk_ID())
		{
			case MC_SCENESHADER_UID:
				cload.Read(&UID,sizeof(unsigned int));
				break;
			case MC_SCENESHADER_NAME:
				Name = new char[cload.Cur_Micro_Chunk_Length()];
				cload.Read(Name,cload.Cur_Micro_Chunk_Length());
				break;
			case MC_SCENESHADER_FXFILENAME:
				FXFilename = new char[cload.Cur_Micro_Chunk_Length()];
				cload.Read(FXFilename,cload.Cur_Micro_Chunk_Length());
				#ifndef SDBEDIT
				Effect = new EffectClass(FXFilename);			
				#endif
				break;
		}
		cload.Close_Micro_Chunk();
	}	
}
void SimpleSceneShaderClass::Save(ChunkSaveClass& csave)
{
	csave.Begin_Chunk(CHUNK_SIMPLESCENESHADER);
	csave.Begin_Micro_Chunk(MC_SCENESHADER_UID);
	csave.Write(&UID,sizeof(unsigned int));
	csave.End_Micro_Chunk();
	csave.Begin_Micro_Chunk(MC_SCENESHADER_NAME);
	csave.Write(Name,strlen(Name) + 1);
	csave.End_Micro_Chunk();
 	csave.Begin_Micro_Chunk(MC_SCENESHADER_FXFILENAME);
	csave.Write(FXFilename,strlen(FXFilename) + 1);
	csave.End_Micro_Chunk();
	csave.End_Chunk();
}
#ifndef SDBEDIT
void SimpleSceneShaderClass::Initialize()
{
	SceneShaderClass::Initialize();
}
bool SimpleSceneShaderClass::Validate()
{
	if (Validated) 
	{
		return ValidationResult;
	}
	if (!Effect->Initialized)
	{
		if (Effect->EffectLoadTask)
		{
			return false;
		}
		else
		{
			ValidationResult = false;
			Validated = true;
			return false;
		}
	}
	D3DXHANDLE TechniqueHandle = Effect->GetTechniqueByName("SceneShader");
	HRESULT hr = Effect->ValidateTechnique(TechniqueHandle);
	if (FAILED(hr))
	{
		ValidationResult = false;
	} 
	else 
	{
		Effect->SetTechnique("SceneShader");
		InputTextureHandle = Effect->GetParameterBySemantic(NULL,"InputTexture");
		SceneTextureHandle = Effect->GetParameterBySemantic(NULL,"SceneTexture");
		SetKernals();
		ValidationResult = true;
	}
	Validated = true;
	return ValidationResult;
}
Vector2 SimpleSceneShaderClass::GetRenderScale(unsigned int pass)
{
	Vector2 scale = Vector2(1.0f,1.0f);
	D3DXHANDLE passHandle = Effect->GetPass("SceneShader",pass);
	D3DXHANDLE scaleXHandler = Effect->GetAnnotationByName(passHandle, "ScaleX");
	if (scaleXHandler)
	{
		Effect->GetFloat(scaleXHandler,&scale.X);
	}
	D3DXHANDLE scaleYHandler = Effect->GetAnnotationByName(passHandle, "ScaleY");
	if (scaleYHandler)
	{
		Effect->GetFloat(scaleYHandler,&scale.Y);
	}
	return scale;
}
void SimpleSceneShaderClass::SetKernals()
{
	D3DXHANDLE hParamToConvert;
	D3DXHANDLE hAnnotation;
	UINT uParamIndex = 0;
	while (NULL != (hParamToConvert = Effect->GetParameter(NULL, uParamIndex++)))
	{
		if (NULL != (hAnnotation = Effect->GetAnnotationByName(hParamToConvert, "ConvertPixelsToTexels")))
		{
			LPCSTR szSource;
			Effect->GetString(hAnnotation, &szSource);
			D3DXHANDLE hConvertSource = Effect->GetParameterByName(NULL, szSource);
			if (hConvertSource)
			{
				D3DXPARAMETER_DESC desc;
				Effect->GetParameterDesc(hConvertSource, &desc);
				DWORD cKernel = desc.Bytes / (2 * sizeof(float));
				Vector4 *pvKernel = new Vector4[cKernel];
				Effect->GetVectorArray(hConvertSource, pvKernel, cKernel);
				for (DWORD i = 0; i < cKernel; ++i)
				{
					pvKernel[i].X = pvKernel[i].X / parameters->BackBufferWidth;
					pvKernel[i].Y = pvKernel[i].Y / parameters->BackBufferHeight;
				}
				Effect->SetVectorArray(hParamToConvert, pvKernel, cKernel);
				delete[] pvKernel;
			}
		}
	}
}
void SimpleSceneShaderClass::Render(SceneShaderRenderInfo *render)
{
	unsigned int cPasses;
	Effect->Begin(&cPasses,0);
	if (!PassScales)
	{
		PassScales = new Vector2[cPasses];
		for (unsigned int pass = 0; pass < cPasses; pass++)
		{
			PassScales[pass] = GetRenderScale(pass);
		}
	}
	Effect->SetTexture(SceneTextureHandle,render->SceneBuffer);
	for (unsigned int pass = 0; pass < cPasses; pass++)
	{
		if (pass > 0) 
		{
			SceneShaderController->RequestNewBuffer(&render);
		}
		StateManager->SetRenderTarget(0,render->OutputSurface);
		Direct3DDevice->Clear(0,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,0),0,0);
		Effect->SetTexture(InputTextureHandle,render->InputBuffer);

		render->Width *= PassScales[pass].X;
		render->Height *= PassScales[pass].Y;

		Effect->BeginPass(pass);
		Effect->CommitChanges();
		Direct3DDevice->BeginScene();
		RenderQuad->Draw(0,0,render->Width,render->Height,render->UScale,render->VScale);
		Direct3DDevice->EndScene();
		Effect->EndPass();

		render->UScale *= PassScales[pass].X;
		render->VScale *= PassScales[pass].Y;
	}
	Effect->End();
}
#endif

SceneShaderRegistrant<SimpleSceneShaderClass> SimpleSceneShaderRegistrant(CHUNK_SIMPLESCENESHADER,"Simple Scene Shader");
