/*
	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		Class that handles the rendering of basic primitives. Uses the colored pixel
///				and vertex shaders. Also allows for drawing of sprites etc. 
/// @remarks	This class is not optimised for speed and should only be used for debug purposes
//=====================================================================================================================

#include "Precompiled.h"
#include "Graphics\PrimitivesRenderer.h"
#include "Graphics\Display.h"
#include "Graphics\PixelShader.h"
#include "Graphics\VertexShader.h"
#include "Graphics\Texture.h"
#include "Graphics\VertexFormat.h"
#include "Graphics\ShaderUniform.h"
#include "Graphics\Camera2D.h"

using namespace Game;

//=====================================================================================================================
/// @brief  Creates the primitives renderer for the given display
/// @param	display - direct3d display to render to
/// @param	vertex_shader_manager - manager for loading vertex shaders
/// @param	pixel_shader_manager - manager for loading pixel shaders
//=====================================================================================================================

PrimitivesRenderer::PrimitivesRenderer
(
	Display *				display					, 
	VertexShaderManager *	vertex_shader_manager	,
	PixelShaderManager *	pixel_shader_manager
)
{
	// Init everything:
	
	m_d3d_device				= 0;
	m_colored_vs				= 0;
	m_textured_vs				= 0;
	m_colored_ps				= 0;
	m_textured_ps				= 0;
	m_colored_format			= 0;
	m_textured_format			= 0;
	m_u_colored_transform		= 0;
	m_u_textured_transform		= 0;
	m_u_textured_texture		= 0;
	m_window					= 0;
	m_is_valid					= false;

	// Only if these are valid:

	if ( display && display->IsValid() && vertex_shader_manager && pixel_shader_manager )
	{
		// Save the display device
		
		m_d3d_device = display->GetDevice();

		// Save the window:

		m_window = display->GetWindow();
		
		// Add a reference to this device:
		
		m_d3d_device->AddRef();
	
		// Load all vertex and pixel shaders:

		m_colored_vs	= new VertexShader( vertex_shader_manager->GetVertexShader("Shaders\\colored.vsh.bin") );
		m_textured_vs	= new VertexShader( vertex_shader_manager->GetVertexShader("Shaders\\textured.vsh.bin") );
		m_colored_ps	= new PixelShader( pixel_shader_manager->GetPixelShader("Shaders\\colored.psh.bin") ) ;
		m_textured_ps	= new PixelShader( pixel_shader_manager->GetPixelShader("Shaders\\textured.psh.bin") );
		
		// Get all uniforms:
		
		m_u_colored_transform	= new ShaderUniform( m_colored_vs->GetUniform("Transform") );
		m_u_textured_transform	= new ShaderUniform( m_textured_vs->GetUniform("Transform") );
		m_u_textured_texture	= new ShaderUniform( m_textured_ps->GetUniform("Texture") );

		// Create the vertex formats:
		
			// COLORED
			
			{
				// Element usages:
				
				VertexFormat::ElementUsage usages[] =
				{
					VertexFormat::VF_USAGE_POSITION	,
					VertexFormat::VF_USAGE_COLOR	
				};

				// Element types:

				VertexFormat::ElementType types[] =
				{
					VertexFormat::VF_TYPE_FLOAT4	,
					VertexFormat::VF_TYPE_COLOR
				};

				// Now create the format:

				m_colored_format = new VertexFormat( display , 2 , usages , types );
			}
			
			// TEXTURED 
			
			{
				// Element usages:
				
				VertexFormat::ElementUsage usages[] =
				{
					VertexFormat::VF_USAGE_POSITION	,
					VertexFormat::VF_USAGE_COLOR	,
					VertexFormat::VF_USAGE_TEXCOORD
				};

				// Element types:

				VertexFormat::ElementType types[] =
				{
					VertexFormat::VF_TYPE_FLOAT4	,
					VertexFormat::VF_TYPE_COLOR		,
					VertexFormat::VF_TYPE_FLOAT2
				};

				// Now create the format:

				m_textured_format = new VertexFormat( display , 3 , usages , types );
			}		

		// Now make sure everything is ok:

		if 
		( 			
			m_colored_vs->IsValid()				&&
			m_textured_vs->IsValid()			&&
			m_colored_ps->IsValid()				&&
			m_textured_ps->IsValid()			&&
			m_colored_format->IsValid()			&&
			m_textured_format->IsValid()		&&
			m_u_colored_transform->IsValid()	&&
			m_u_textured_transform->IsValid()	&&
			m_u_textured_texture->IsValid()	
		)
		{
			// Good to go:

			m_is_valid = true;
		}
		else
		{
			// Bah.. release everything
			
			ReleaseResources();
		}
	}
}

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

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

//=====================================================================================================================
/// @brief  Frees all resources used by the primitives renderer
//=====================================================================================================================

void PrimitivesRenderer::ReleaseResources()
{	
	// Free up everything

	if ( m_d3d_device			) m_d3d_device->Release();			m_d3d_device			= 0;
	if ( m_colored_vs			) delete m_colored_vs;				m_colored_vs			= 0;
	if ( m_textured_vs			) delete m_textured_vs;				m_textured_vs			= 0;
	if ( m_colored_ps			) delete m_colored_ps;				m_colored_ps			= 0;
	if ( m_textured_ps			) delete m_textured_ps;				m_textured_ps			= 0;
	if ( m_colored_format		) delete m_colored_format;			m_colored_format		= 0;
	if ( m_textured_format		) delete m_textured_format;			m_textured_format		= 0;	
	if ( m_u_colored_transform	) delete m_u_colored_transform;		m_u_colored_transform	= 0;
	if ( m_u_textured_transform	) delete m_u_textured_transform;	m_u_textured_transform	= 0;	
	if ( m_u_textured_texture	) delete m_u_textured_texture;		m_u_textured_texture	= 0;	
	
	// No longer valid
	
	m_is_valid = false;
}

//=====================================================================================================================
/// @brief  Draws a 2D quadrilateral. Assumes points are given in either clockwise or anti-clockwise winding order
/// @param	camera - camera the scene is being viewed from
/// @param	p1 - 1st point
/// @param	p2 - 2nd point
/// @param	p3 - 3rd point
/// @param	p4 - 4th point
/// @param	color - color to draw quad in
//=====================================================================================================================

void PrimitivesRenderer::DrawQuad
( 
	Camera2D * camera	, 
	const Vec2f & p1	, 
	const Vec2f & p2	, 
	const Vec2f & p3	, 
	const Vec2f & p4	, 
	int color 
	
) const
{
	// Only if we are valid:

	if ( m_is_valid && camera )
	{
		// Structure of a point:

		struct PointFormat { Vec4f pos; int col; };

		// Store points here:

		PointFormat vertices[4];

		// Set positions:

			vertices[0].pos = p1; vertices[0].pos.z = -2;
			vertices[1].pos = p2; vertices[1].pos.z = -2;
			vertices[2].pos = p3; vertices[2].pos.z = -2;
			vertices[3].pos = p4; vertices[3].pos.z = -2;

		// Colors:

			vertices[0].col = color;
			vertices[1].col = color;
			vertices[2].col = color;
			vertices[3].col = color;

		// Bind vertex and pixel shaders

		m_colored_vs->Apply(); m_colored_ps->Apply();
		
		// Use vertex format:

		m_colored_format->Apply();

		// Set view projection matrix

		m_u_colored_transform->SetMatrix( camera->GetViewProjectionMatrix() );

		// Draw the quad:

		m_d3d_device->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP , 2 , (void*) &vertices  , sizeof(PointFormat) );
	}
}

//=====================================================================================================================
/// @brief  Draws a rectangular sprite
/// @param	camera - camera the scene is being viewed from
/// @param	pos - position of the sprite
/// @param	size - size of the sprite
/// @param	color - color of the sprite 
/// @param	texture - texture to draw the sprite with
//=====================================================================================================================

void PrimitivesRenderer::DrawSprite
(
	Camera2D * camera	,
	const Vec2f & pos	, 
	const Vec2f & size	, 
	int color			, 
	Texture & texture 
	
) const
{
	// Only if we are valid:

	if ( m_is_valid && camera )
	{
		// Structure of a point:

		struct PointFormat { Vec4f pos; int col; Vec2f tex; };

		// Store points here:

		PointFormat vertices[4];

		// Set positions:

			vertices[0].pos = pos; vertices[0].pos.x -= size.x; vertices[0].pos.y += size.y;
			vertices[1].pos = pos; vertices[1].pos.x -= size.x; vertices[1].pos.y -= size.y;
			vertices[2].pos = pos; vertices[2].pos.x += size.x; vertices[2].pos.y += size.y;
			vertices[3].pos = pos; vertices[3].pos.x += size.x; vertices[3].pos.y -= size.y;
			
			float z = - ( camera->GetNearDist() + camera->GetFarDist() ) * 0.5f;
			
			vertices[0].pos.z = z;
			vertices[1].pos.z = z;
			vertices[2].pos.z = z;
			vertices[3].pos.z = z;

		// Set the colors:

			vertices[0].col = color;
			vertices[1].col = color;
			vertices[2].col = color;
			vertices[3].col = color;
			
		// Set the texture coordinates:

			vertices[0].tex = Vec2f::Zero();
			vertices[1].tex = Vec2f::UnitY();
			vertices[2].tex = Vec2f::UnitX();
			vertices[3].tex = Vec2f::One();

		// Bind vertex and pixel shaders

		m_textured_vs->Apply(); m_textured_ps->Apply();
		
		// Use vertex format:

		m_textured_format->Apply();

		// Set view projection matrix

		m_u_textured_transform->SetMatrix( camera->GetViewProjectionMatrix() );
		
		// Apply the texture:
		
		m_u_textured_texture->BindTexture( texture );

		// Draw the quad:

		m_d3d_device->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP , 2 , (void*) &vertices  , sizeof(PointFormat) );
	}
}

//=====================================================================================================================
/// @brief  Draws an outline of a 2D quadrilateral. Assumes points are given in either clockwise or anti-clockwise 
///			winding order.
/// @param	camera - camera the scene is being viewed from
/// @param	p1 - 1st point
/// @param	p2 - 2nd point
/// @param	p3 - 3rd point
/// @param	p4 - 4th point
/// @param	color - color to draw quad in
//=====================================================================================================================

void PrimitivesRenderer::DrawQuadOutline
(
	Camera2D * camera	,  
	const Vec2f & p1	, 
	const Vec2f & p2	, 
	const Vec2f & p3	, 
	const Vec2f & p4	, 
	int color 
	
) const
{
	// Only if we are valid:

	if ( m_is_valid && camera )
	{
		// Structure of a point:

		struct PointFormat { Vec4f pos; int col; };

		// Store points here:

		PointFormat vertices[5];

		// Set positions:

			vertices[0].pos = p1; vertices[0].pos.z = -2;
			vertices[1].pos = p2; vertices[1].pos.z = -2;
			vertices[2].pos = p3; vertices[2].pos.z = -2;
			vertices[3].pos = p4; vertices[3].pos.z = -2;
			vertices[4].pos = p1; vertices[4].pos.z = -2;

		// Colors:

			vertices[0].col = color;
			vertices[1].col = color;
			vertices[2].col = color;
			vertices[3].col = color;
			vertices[4].col = color;

		// Bind vertex and pixel shaders

		m_colored_vs->Apply(); m_colored_ps->Apply();
		
		// Use vertex format:

		m_colored_format->Apply();

		// Set view projection matrix

		m_u_colored_transform->SetMatrix( camera->GetViewProjectionMatrix() );

		// Draw the quad:

		m_d3d_device->DrawPrimitiveUP( D3DPT_LINESTRIP , 4 , (void*) &vertices  , sizeof(PointFormat) );
	}
}

//=====================================================================================================================
/// @brief  Draws a 2D circle
/// @param	camera - camera the scene is being viewed from
/// @param	p - position of the circle
/// @param	radius - radius of the circle
/// @param	color - color to draw the circle in
//=====================================================================================================================

void PrimitivesRenderer::DrawCircle( Camera2D * camera,  const Vec2f & p , float radius , int color ) const
{
	// Only if we are valid:

	if ( m_is_valid && camera )
	{
		// Structure of a point:

		struct PointFormat { Vec4f pos; int col; };

		// Amount of points we will take on the border of the circle:

		const int SAMPLES = 256;

		// Store points here:

		PointFormat vertices[ SAMPLES + 1 ];

		// Set positions:

			// Center point:

			vertices[0].pos		= p;
			vertices[0].pos.z	= -2;

			// Subsequent points:

			for ( int i = 0 ; i < SAMPLES ; ++i )
			{
				// Figure out angle along circle

				float a = (( Float::PI() * 2.0f ) / float( SAMPLES - 1 )) * float(i);

				// Set the points position:
				
				vertices[i].pos.x	= ( Float::Cos(a) * radius ) + p.x;
				vertices[i].pos.y	= ( Float::Sin(a) * radius ) + p.y;
				vertices[i].pos.z	= -2;

				// Set the color

				vertices[i].col = color;
			}

		// Bind vertex and pixel shaders

		m_colored_vs->Apply(); m_colored_ps->Apply();
		
		// Use vertex format:

		m_colored_format->Apply();

		// Set view projection matrix

		m_u_colored_transform->SetMatrix( camera->GetViewProjectionMatrix() );

		// Draw the circle:

		m_d3d_device->DrawPrimitiveUP( D3DPT_TRIANGLEFAN , SAMPLES - 1 , (void*) &vertices  , sizeof(PointFormat) );
	}
}

//=====================================================================================================================
/// @brief  Draws a 2D line
/// @param	camera - camera the scene is being viewed from
/// @param	p1 - 1st line point
/// @param	p2 - 2nd line point
/// @param	color - color to draw the line in
//=====================================================================================================================

void PrimitivesRenderer::DrawLine( Camera2D * camera, const Vec2f & p1 , const Vec2f & p2 , int color ) const
{
	// Only if all valid:
	
	if ( m_is_valid && camera )
	{
		// Structure of a point:

		struct PointFormat { Vec4f pos; int col; };

		// Store points here:

		PointFormat vertices[2];

		// Set positions:

		vertices[0].pos = p1; vertices[0].pos.z = -2;
		vertices[1].pos = p2; vertices[1].pos.z = -2;
			
		// Set colors:
	
		vertices[0].col = color;
		vertices[1].col = color;
					
		// Bind vertex and pixel shaders

		m_colored_vs->Apply(); m_colored_ps->Apply();
		
		// Use vertex format:

		m_colored_format->Apply();

		// Set view projection matrix

		m_u_colored_transform->SetMatrix( camera->GetViewProjectionMatrix() );

		// Draw the circle:

		m_d3d_device->DrawPrimitiveUP( D3DPT_LINELIST, 1 , (void*) vertices  , sizeof(PointFormat) );	
	}
}

//=====================================================================================================================
/// @brief  Draws a 2D point
/// @param	camera - camera the scene is being viewed from
/// @param	p - point to draw
/// @param	color - color to draw the point in
//=====================================================================================================================

void PrimitivesRenderer::DrawPoint( Camera2D * camera, const Vec2f & p , int color ) const
{
	// Only if all valid:
	
	if ( m_is_valid && camera )
	{
		// Structure of a point:

		struct PointFormat { Vec4f pos; int col; };

		// Store point here:

		PointFormat vert;

		// Set position:

		vert.pos	= p; 
		vert.pos.z	= -2;
			
		// Set color:
	
		vert.col = color;
					
		// Bind vertex and pixel shaders

		m_colored_vs->Apply(); m_colored_ps->Apply();
		
		// Use vertex format:

		m_colored_format->Apply();

		// Set view projection matrix

		m_u_colored_transform->SetMatrix( camera->GetViewProjectionMatrix() );

		// Draw the circle:

		m_d3d_device->DrawPrimitiveUP( D3DPT_POINTLIST, 1 , (void*) &vert  , sizeof(PointFormat) );	
	}
}
