/*
	Lan Wars.
	Copyright (c) 2009, 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 accepts a bunch of sprites to be drawn and renders them later on when requested to.
///				It renders sprites in batches for efficiency.
//=====================================================================================================================

#include "Precompiled.h"
#include "Windows\Window.h"
#include "Graphics\SpriteRenderer.h"
#include "Graphics\Display.h"
#include "Graphics\Camera3D.h"

using namespace Game;

//=====================================================================================================================
// Statics
//=====================================================================================================================

#ifdef USE_DEBUG_CONSOLE

	/// Debug only: if true then do no depth testing for sprites
	
	bool SpriteRenderer::s_sprite_depth_test = true;
	
#endif

//=====================================================================================================================
/// @brief		Default constructor: creates the renderer
/// @param		display - display the renderer is using
/// @param		vsmgr - vertex shader manager to use for loading resources
/// @param		psmgr - pixel shader manager to use for loading resources
/// @pre		Display cannot be null
/// @pre		Display must be valid
/// @pre		Vertex shader manager must not be null
/// @pre		Pixel shader manager must not be null
//=====================================================================================================================

SpriteRenderer::SpriteRenderer( Display * display , VertexShaderManager * vsmgr , PixelShaderManager * psmgr )
{
	// Make sure ok
	
	ENSURE( display != 0		, "Display cannot be null"					)
	ENSURE( display->IsValid()	, "Display must be valid"					)
	ENSURE( vsmgr != 0			, "Vertex shader manager must not be null"	)
	ENSURE( psmgr != 0			, "Pixel shader manager must not be null"	)
		
	// Load our vertex and pixel shaders

	m_vs = vsmgr->GetVertexShader( "Shaders\\Textured.vsh.bin" );
	m_ps = psmgr->GetPixelShader( "Shaders\\Textured.psh.bin" );

	// Vertex format elements

	VertexFormat::ElementUsage vf_usages[] =
	{
		VertexFormat::VF_USAGE_POSITION	,
		VertexFormat::VF_USAGE_TEXCOORD	,
		VertexFormat::VF_USAGE_COLOR	,
	};

	// Vertex format types

	VertexFormat::ElementType vf_types[] =
	{
		VertexFormat::VF_TYPE_FLOAT3	,
		VertexFormat::VF_TYPE_FLOAT2	,
		VertexFormat::VF_TYPE_FLOAT4
	};

	// Create our vertex format 

	m_vf = VertexFormat
	(
		display		,
		3			,
		vf_usages	,
		vf_types
	);

	// Load our shader uniform:

	if ( m_vs.IsValid() )
	{
		m_u_transform = m_vs.GetUniform("Transform");
	}

	// See if valid:

	if ( m_vf.IsValid() && m_ps.IsValid() && m_vs.IsValid() && m_u_transform.IsValid() )
	{
		// All valid:

		m_valid_resources = true;
	}
	else
	{
		// Invalid:

		m_valid_resources = false;
	}
		
	// Save the reference to the device
	
	m_device = display->GetDevice(); m_device->AddRef();
	
	// Debug only:
	
	#ifdef USE_DEBUG_CONSOLE
	
		DebugConsole::AddCommand( "R_SpriteZTest" , ConCmd_R_SpriteZTest );
	
	#endif
}

//=====================================================================================================================
/// @brief		Destructor. Frees the sprite renderer.
//=====================================================================================================================

SpriteRenderer::~SpriteRenderer()
{
	// Done with the device
	
	m_device->Release();
	
	// Debug only:
	
	#ifdef USE_DEBUG_CONSOLE
	
		DebugConsole::RemoveCommand( "R_SpriteZTest" );
	
	#endif	
}

//=====================================================================================================================
/// @brief		Adds the specified sprite to the list of sprites to be rendered
/// @param		sprite - the sprite to add to the queue of sprites to be rendered.
//=====================================================================================================================

void SpriteRenderer::AddSprite( const Sprite & sprite )
{
	// Only if we are valid:
	
	if ( m_valid_resources )
	{
		// Add to the queue
		
		m_sprites.push(sprite);
	}
}

//=====================================================================================================================
/// @brief		Draws all of the sprites within the sprite renderer
/// @param		camera - the camera we are being viewed from
/// @pre		The given camera cannot be null
//=====================================================================================================================

void SpriteRenderer::DrawAll( Camera3D * camera )
{
	// Make sure ok
	
	ENSURE( camera != 0 , "The given camera cannot be null" )
	
	// Only if we are valid:
	
	if ( m_valid_resources )
	{
		// Disable wrapping on the device:

		m_device->SetSamplerState(0,D3DSAMP_ADDRESSU,D3DTADDRESS_CLAMP);
		m_device->SetSamplerState(0,D3DSAMP_ADDRESSV,D3DTADDRESS_CLAMP);
		
		// Debug only:
		
		#ifdef USE_DEBUG_CONSOLE
		
			if ( s_sprite_depth_test == false )
			{
				m_device->SetRenderState( D3DRS_ZENABLE , 0 );
			}
		
		#endif
		
		// Enable blending:
		
		m_device->SetRenderState( D3DRS_ALPHABLENDENABLE , 1 );

		// Apply the vertex and pixel shaders
		
		m_vf.Apply();
		m_vs.Apply();
		m_ps.Apply();
		
		// Set the transform uniform:
		
		m_u_transform.SetMatrix(camera->GetViewProjectionMatrix());
		
		// Get the orientation of the camera
		
		Matrix4f cam_orientation = camera->GetViewMatrix();
		
		// Get the x, y and z axes of the camera
		
		Vec3f cam_x = cam_orientation.GetCol(0).ToVec3();
		Vec3f cam_y = cam_orientation.GetCol(1).ToVec3();
		Vec3f cam_z = cam_orientation.GetCol(2).ToVec3();
			
		// This is the current texture in use
		
		Texture current_tex;
		
		// If true then we are currently using additive blending
		
		bool additive = false;
	
		// Continune rendering until the queue is empty:
		
		while ( m_sprites.size() > 0 )
		{
			// Get the top sprite:
			
			const Sprite & top = m_sprites.top();
			
			// See if blend settings have changed:
			
			if ( top.IsAdditivelyBlended() != additive )
			{
				if ( top.IsAdditivelyBlended() )
				{
					m_device->SetRenderState( D3DRS_SRCBLEND	, D3DBLEND_ONE			);
					m_device->SetRenderState( D3DRS_DESTBLEND	, D3DBLEND_ONE			);
					m_device->SetRenderState( D3DRS_ZWRITEENABLE, 0						);
					
					additive = true;
				}
				else
				{
					m_device->SetRenderState( D3DRS_SRCBLEND	, D3DBLEND_SRCALPHA		);
					m_device->SetRenderState( D3DRS_DESTBLEND	, D3DBLEND_INVSRCALPHA	);
					m_device->SetRenderState( D3DRS_ZWRITEENABLE, 1						);
				
					additive = false;
				}
			}
			
			// See if the texture is different to the current:
			
			if ( top.GetTexture().IsValid() )
			{
				if ( top.GetTexture() != current_tex )
				{
					// Save:
				
					current_tex = top.GetTexture();
					
					// Apply the texture:
					
					current_tex.Apply(0);
				}
			}
			
			// Create the four vertices for rendering:
			
			SpriteVertex vertices[6];
			
			vertices[0].m_col = top.GetColor();
			vertices[1].m_col = top.GetColor();
			vertices[2].m_col = top.GetColor();
			vertices[3].m_col = top.GetColor();
			vertices[4].m_col = top.GetColor();
			vertices[5].m_col = top.GetColor();
			
			vertices[0].m_pos = top.GetPosition();
			vertices[1].m_pos = top.GetPosition();
			vertices[2].m_pos = top.GetPosition();
			vertices[3].m_pos = top.GetPosition();
			vertices[4].m_pos = top.GetPosition();
			vertices[5].m_pos = top.GetPosition();
			
			vertices[0].m_pos -= cam_x * top.GetSize().x;
			vertices[1].m_pos += cam_x * top.GetSize().x;
			vertices[2].m_pos += cam_x * top.GetSize().x;
			vertices[3].m_pos += cam_x * top.GetSize().x;
			vertices[4].m_pos -= cam_x * top.GetSize().x;
			vertices[5].m_pos -= cam_x * top.GetSize().x;			

			vertices[0].m_pos += cam_y * top.GetSize().y;
			vertices[1].m_pos += cam_y * top.GetSize().y;
			vertices[2].m_pos -= cam_y * top.GetSize().y;
			vertices[3].m_pos -= cam_y * top.GetSize().y;
			vertices[4].m_pos -= cam_y * top.GetSize().y;
			vertices[5].m_pos += cam_y * top.GetSize().y;
			
			// See if flipped horizontally:
			
			if ( top.IsHorizontallyFlipped() )
			{
				vertices[0].m_tex = Vec2f(1,0);
				vertices[1].m_tex = Vec2f(0,0);
				vertices[2].m_tex = Vec2f(0,1);
				vertices[3].m_tex = Vec2f(0,1);
				vertices[4].m_tex = Vec2f(1,1);
				vertices[5].m_tex = Vec2f(1,0);				
			}
			else
			{
				vertices[0].m_tex = Vec2f(0,0);
				vertices[1].m_tex = Vec2f(1,0);
				vertices[2].m_tex = Vec2f(1,1);
				vertices[3].m_tex = Vec2f(1,1);
				vertices[4].m_tex = Vec2f(0,1);
				vertices[5].m_tex = Vec2f(0,0);				
			}		
			
			// Draw the actual vertices:
			
			m_device->DrawPrimitiveUP( D3DPT_TRIANGLELIST , 2 , vertices , m_vf.GetVertexSize() );
						
			// Pop the top sprite off the queue
			
			m_sprites.pop();
		}	

		// Restore wrapping on the device:

		m_device->SetSamplerState(0,D3DSAMP_ADDRESSU,D3DTADDRESS_WRAP);
		m_device->SetSamplerState(0,D3DSAMP_ADDRESSV,D3DTADDRESS_WRAP);
		
		// Restore normal blending:
		
		if ( additive )
		{		
			m_device->SetRenderState( D3DRS_SRCBLEND	, D3DBLEND_SRCALPHA		);
			m_device->SetRenderState( D3DRS_DESTBLEND	, D3DBLEND_INVSRCALPHA	);
			m_device->SetRenderState( D3DRS_ZWRITEENABLE, 1						);
		}
		
		// Disable blending:
		
		m_device->SetRenderState( D3DRS_ALPHABLENDENABLE , 0 );		
		
		// Debug only:
		
		#ifdef USE_DEBUG_CONSOLE
		
			if ( s_sprite_depth_test == false )
			{
				m_device->SetRenderState( D3DRS_ZENABLE , 1 );
			}
		
		#endif		
	}	
}

#ifdef USE_DEBUG_CONSOLE

//=====================================================================================================================
/// @brief		Console command. Turns on/off z-testing for sprites
/// @param		arg - value of the argument
/// @param		arg_given - true if an argument was given
//=====================================================================================================================

bool SpriteRenderer::ConCmd_R_SpriteZTest( bool arg , bool arg_given )
{
	if ( arg_given ) s_sprite_depth_test = arg; return s_sprite_depth_test;
}

#endif		// #ifdef USE_DEBUG_CONSOLE