/*
	Trig Wars.
	Copyright (c) 2008, Darragh Coy.
	All rights reserved.
	Original work(s), source code & author(s) details available at: http://www.darraghcoy.com

	Redistribution and use in source and binary forms, with or without modification, are permitted 
	provided that the following conditions are met:

		* 	Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* 	Redistributions in binary form must reproduce the above copyright notice, this list of 
			conditions and the following disclaimer in the documentation.
		* 	Neither the name of the author nor the names of contributors may be used to endorse or 
			promote products derived from this software without specific prior written permission.
		* 	The use of any third party libraries, modules or data files provided with the source 
			form of the program must follow and respect the individual licensing terms of these 
			components. You do not have permission to modify or circumvent the licensing terms for 
			provided third party components unless the third party licenses specifically allow this. 
			If you do not agree to the terms of provided third party components then you do not have 
			permission to use them in your derived work(s).
		* 	The terms of this license do not apply to separate (but related) distributions if supplied 
			by the author(s), only to the contents of this source distribution, derived works, and the 
			binaries produced by either modified or unmodified versions of the source code. The terms 
			of this license do not also apply to any third party libraries or components provided with 
			the source distribution. Such third party elements are licensed under their own separate 
			agreements.

	THIS SOFTWARE IS PROVIDED BY DARRAGH COY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL DARRAGH COY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
	OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//=====================================================================================================================
/// @brief		This class does post screen processing (the glow effect) for the game. It handles render targets
///				and everything else.
//=====================================================================================================================

#include "Precompiled.h"
#include "Game\GamePostFX.h"
#include "Graphics\Display.h"
#include "Graphics\RenderTarget.h"
#include "Graphics\DepthBuffer.h"
#include "Graphics\ShaderUniform.h"
#include "Windows\Window.h"
#include "Resources\VertexShaderManager.h"
#include "Resources\PixelShaderManager.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Creates the post processing fx unit
/// @param		display - display that the game uses
/// @param		vs_mgr - vertex shader manager for loading vertex shaders
/// @param		ps_mgr - pixel shader manager for loading pixel shaders
/// @pre		display cannot be null and must be valid
/// @pre		vertex shader manager cannot be null
/// @pre		pixel shader manager cannot be null
//=====================================================================================================================

GamePostFX::GamePostFX( Display * display , VertexShaderManager * vs_mgr , PixelShaderManager * ps_mgr )
{
	// Debug checks:

	ENSURE(	display && display->IsValid()	, "display cannot be null and must be valid"		)
	ENSURE( vs_mgr							, "vertex shader manager cannot be null"			)
	ENSURE( ps_mgr							, "pixel shader manager cannot be null"				)
	
	// Save the display and add a reference to it:
	
	m_display = display; display->AddReference();
	
	// Load our vertex and pixel shaders:
	
	m_textured_vs	= vs_mgr->GetVertexShader("Shaders\\Textured.vsh.bin");
	m_textured_ps	= ps_mgr->GetPixelShader("Shaders\\Textured.psh.bin");
	m_glow_ps		= ps_mgr->GetPixelShader("Shaders\\Glow.psh.bin");
	
	// Need to create our vertex format:
	
	VertexFormat::ElementUsage usages[] = 
	{
		VertexFormat::VF_USAGE_POSITION	,
		VertexFormat::VF_USAGE_COLOR	,
		VertexFormat::VF_USAGE_TEXCOORD	
	};
	
	VertexFormat::ElementType types[] = 
	{
		VertexFormat::VF_TYPE_FLOAT3	,
		VertexFormat::VF_TYPE_FLOAT4	,
		VertexFormat::VF_TYPE_FLOAT2
	};	
	
	m_vf = VertexFormat( display , 3 , usages , types );
	
	// Create the render target and depth buffer to use for rendering the game:
	
	m_game_target = new RenderTarget
	( 
		display , display->GetWindow()->GetClientSize() , RenderTarget::FORMAT_X8R8G8B8	, display->GetAALevel() 
	);

	m_game_depth_buffer	= new DepthBuffer
	( 
		display , display->GetWindow()->GetClientSize() , DepthBuffer::FORMAT_D24S8	, display->GetAALevel() 
	);

	// Create the render target depth buffer for doing the glow effect:

	m_glow_target = new RenderTarget
	(
		display , Vec2u(1024,1024) , RenderTarget::FORMAT_X8R8G8B8 
	);

	m_glow_depth_buffer = new DepthBuffer
	(
		display , Vec2u(1024,1024) , DepthBuffer::FORMAT_D24S8 
	);
	
	// If for some reason the aa levels of the two game buffers do not match then drop the aa level until they match:
	
	if ( m_game_target->IsValid() && m_game_depth_buffer->IsValid() )
	{
		// Make sure their formats match:
		
		if ( m_game_target->GetAALevel() != m_game_depth_buffer->GetAALevel() )
		{
			// Pick the lowest aa level:
			
			Display::AntialiasingLevel level = m_game_target->GetAALevel();
			
			// See if depth buffer has less:
			
			if ( m_game_depth_buffer->GetAALevel() <	level )
			{
				level = m_game_depth_buffer->GetAALevel();
			}
			
			// Destroy both buffers:
			
			m_game_target->RemoveReference();
			m_game_depth_buffer->RemoveReference();
			
			// Recreate with lowest aa level:
			
			m_game_target = new RenderTarget( display , display->GetWindow()->GetClientSize() , RenderTarget::FORMAT_X8R8G8B8 , level );
			m_game_depth_buffer = new DepthBuffer( display , display->GetWindow()->GetClientSize() , DepthBuffer::FORMAT_D24S8 , level );
			
			// If they still don't match (highly unlikely) then use no aa:
			
			if ( m_game_target->GetAALevel() != m_game_depth_buffer->GetAALevel() )
			{
				// Destroy both buffers:
				
				m_game_target->RemoveReference();
				m_game_depth_buffer->RemoveReference();
				
				// Recreate with no aa:
				
				m_game_target = new RenderTarget( display , display->GetWindow()->GetClientSize() , RenderTarget::FORMAT_X8R8G8B8 , Display::ANTIALIAS_NONE );
				m_game_depth_buffer = new DepthBuffer( display , display->GetWindow()->GetClientSize() , DepthBuffer::FORMAT_D24S8 , Display::ANTIALIAS_NONE );				
			}
		}
	}
	
	// Setup our rendering vertices:
	
	m_vertices[0].m_pos = Vec3f( -1 , +1 , 0 );
	m_vertices[1].m_pos = Vec3f( -1 , -1 , 0 );
	m_vertices[2].m_pos = Vec3f( +1 , +1 , 0 );
	m_vertices[3].m_pos = Vec3f( +1 , -1 , 0 );
	
	Vec2f hp = Vec2f( display->GetWindow()->GetClientSize() ); 
	
	// Need to calculate the width of half a pixel to fix texel offset problem with d3d
	
	hp.x = 1.0f / ( hp.x * 2 );
	hp.y = 1.0f / ( hp.y * 2 );
		
	m_vertices[0].m_tex = Vec2f( 0 , 0 );
	m_vertices[1].m_tex = Vec2f( 0 , 1 );
	m_vertices[2].m_tex = Vec2f( 1 , 0 );
	m_vertices[3].m_tex = Vec2f( 1 , 1 );
	
	m_vertices[1].m_tex.y -= hp.y;
	m_vertices[2].m_tex.x -= hp.x;
	m_vertices[3].m_tex.x -= hp.x;
	m_vertices[3].m_tex.y -= hp.y;
	
	m_vertices[0].m_col = Color::White();
	m_vertices[1].m_col = Color::White();
	m_vertices[2].m_col = Color::White();
	m_vertices[3].m_col = Color::White();
	
	// If we have a valid textured vs then try and get the transform uniform:
	
	if ( m_textured_vs.IsValid() )
	{
		m_u_transform = m_textured_vs.GetUniform("Transform");
	}
	
	// If we have a valid glow ps then get the glow kernel uniform:
	
	if ( m_glow_ps.IsValid() )
	{
		m_u_glow_kernel = m_glow_ps.GetUniform("KernelSize");
	}
	
	// Make sure everything is valid:
	
	if 
	( 
		m_textured_vs.IsValid()			&& 
		m_textured_ps.IsValid()			&& 
		m_glow_ps.IsValid()				&&
		m_game_target->IsValid()		&& 
		m_game_depth_buffer->IsValid()	&&
		m_glow_target->IsValid()		&&
		m_glow_depth_buffer->IsValid()	&&
		m_u_transform.IsValid()			&&
		m_u_glow_kernel.IsValid()
	)
	{
		m_valid_resources = true;
	}
	else
	{
		m_valid_resources = false;
	}
}

//=====================================================================================================================
/// @brief		Destroys the post processing fx unit
//=====================================================================================================================

GamePostFX::~GamePostFX()
{
	// Cleanup all render targets and depth buffers
	
	m_game_target->RemoveReference();
	m_glow_target->RemoveReference();

	m_game_depth_buffer->RemoveReference();
	m_glow_depth_buffer->RemoveReference();
	
	// Done with the display:
	
	m_display->RemoveReference();
}

//=====================================================================================================================
/// @brief		Annouces the type name for this object.
/// @returns	Type name of this object
//=====================================================================================================================

const char * GamePostFX::GetTypeName() const
{
	return "GamePostFX";
}

//=====================================================================================================================
/// @brief		Begins post processing effects. Routes all rendering into an internal render target.
//=====================================================================================================================

void GamePostFX::BeginPostProcessing()
{
	// Only if rt and depth buffer are valid:
	
	if ( m_valid_resources )
	{
		// Setup the render target:
		
		m_display->SetDepthBuffer( m_game_depth_buffer );
		m_display->SetRenderTarget( m_game_target );
		
		// Clear everything:
		
		m_display->Clear( Color::Black() , 0 , 1000 );
	}
}

//=====================================================================================================================
/// @brief		Ends post processing effects. Displays output of render target output plus effects to the screen.
//=====================================================================================================================

void GamePostFX::EndPostProcessing()
{
	// Only if rt and depth buffer are valid:
	
	if ( m_valid_resources )
	{
		// Copy the contents of the render target to a texture:
		
		m_game_target->UpdateTexture();
		
		// Now apply the texture to the first sampler unit:
		
		m_game_target->ApplyTexture(0);
		
		// Get the graphics device:
		
		IDirect3DDevice9 * d = m_display->GetDevice();	
		
		// Get the current sampler filters:
		
		D3DTEXTUREFILTERTYPE min_filter;	d->GetSamplerState( 0 , D3DSAMP_MINFILTER , (DWORD*) &min_filter );
		D3DTEXTUREFILTERTYPE mag_filter;	d->GetSamplerState( 0 , D3DSAMP_MAGFILTER , (DWORD*) &mag_filter );
		D3DTEXTUREFILTERTYPE mip_filter;	d->GetSamplerState( 0 , D3DSAMP_MIPFILTER , (DWORD*) &mip_filter );

		// Need to clear RTs first

		m_display->SetRenderTarget(0);
		m_display->SetDepthBuffer(0);	

		// Change to the glow render target:

		m_display->SetRenderTarget( m_glow_target );
		m_display->SetDepthBuffer( m_glow_depth_buffer );

		// Clear all:

		m_display->Clear( Color::Black() , 0 , 10000 );
		
		// No depth buffer or depth testing:
		
		m_display->SetRenderState( D3DRS_ZWRITEENABLE	, 0 );
		m_display->SetRenderState( D3DRS_ZENABLE		, 0 );
		
		// Apply vertex and pixel shaders and vertex format:
		
		m_vf.Apply();
		m_textured_vs.Apply();
		m_glow_ps.Apply();
		
		// Set transform uniform:
		
		m_u_transform.SetMatrix( Matrix4f::Orthographic(2,2,1,10000) );		
	
		// Set the size of the glow kernel
		
		m_u_glow_kernel.SetFloat( 0.0025f );

		// Save blend state:

		D3DBLEND src_blend; d->GetRenderState( D3DRS_SRCBLEND	, (DWORD*) & src_blend );
		D3DBLEND dst_blend; d->GetRenderState( D3DRS_DESTBLEND	, (DWORD*) & dst_blend );

		// Use additive blending

		m_display->SetRenderState( D3DRS_SRCBLEND	, D3DBLEND_ONE );
		m_display->SetRenderState( D3DRS_DESTBLEND	, D3DBLEND_ONE );
						
		// Draw the rendered scene to the screen and apply the post processing effect: do this a number of times
		
		for ( int i = 0 ; i < 4 ; i++ )
		{
			// Do post processing:
		
			m_display->DrawUserPrimitives( Display::PT_TRIANGLE_STRIP , m_vertices , 2 );
			
			// Update the texture:
		
			m_glow_target->UpdateTexture();

			// Bind the glow texture to 1st sampler unit:

			m_glow_target->ApplyTexture(0);
		}
		
		// Done with these
				
		m_display->SetRenderTarget(0);
		m_display->SetDepthBuffer(0);
		
		// Now reapply the normal textured shader:
		
		m_textured_vs.Apply();
		m_textured_ps.Apply();

		// Set current sampler filters:
		
		d->SetSamplerState( 0 , D3DSAMP_MINFILTER , D3DTEXF_POINT );
		d->SetSamplerState( 0 , D3DSAMP_MAGFILTER , D3DTEXF_POINT );
		d->SetSamplerState( 0 , D3DSAMP_MIPFILTER , D3DTEXF_POINT );

		// Firstly draw the normal scene to the screen:

		{
			// Draw the game to the screen:

			m_game_target->ApplyTexture(0);
			
			// Draw the result to the screen:
			
			m_display->DrawUserPrimitives( Display::PT_TRIANGLE_STRIP , m_vertices , 2 );
		}

		// Restore current sampler filters:
		
		d->SetSamplerState( 0 , D3DSAMP_MINFILTER , (int) min_filter );
		d->SetSamplerState( 0 , D3DSAMP_MAGFILTER , (int) mag_filter );
		d->SetSamplerState( 0 , D3DSAMP_MIPFILTER , (int) mip_filter );

		// Now need to combine the glow buffer onto the screen:

		{
			// Draw the game to the screen:

			m_glow_target->ApplyTexture(0);
			
			// Draw the result to the screen:
			
			m_display->DrawUserPrimitives( Display::PT_TRIANGLE_STRIP , m_vertices , 2 );
		}

		// Restore normal blending:

		d->SetRenderState( D3DRS_SRCBLEND	, src_blend );
		d->SetRenderState( D3DRS_DESTBLEND	, dst_blend );		

		// Restore:
		
		m_display->SetRenderState( D3DRS_ZWRITEENABLE	, 1 );
		m_display->SetRenderState( D3DRS_ZENABLE		, 1 );
	}
}
