/*
	Trampoline Sim.
	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 represents a simple flat plane. It renders the plane as well as holding the plane's 
///				RigidBody and shape.
//=====================================================================================================================

#include "Precompiled.h"
#include "GameObjects/GamePlane.h"
#include "Game/GameCore.h"
#include "Graphics/Camera3D.h"
#include "Physics/ShapePlane.h"
#include "Physics/RigidBody.h"
#include "Physics/SimulationWorld.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Creates the plane at the specified height
/// @param		position - position to create at
/// @param		normal - plane normal
/// @param		texture - name of the texture to use for the plane
/// @pre		Texture name cannot be null
//=====================================================================================================================

GamePlane::GamePlane( const Vec3f & position , const Vec3f & normal , const char * texture )
{
	// Make sure ok
	
	ENSURE( texture , "Texture name cannot be null" )

	// Make our shape:

	ShapePlane * shape = new ShapePlane( normal , position );

	// Make our rigid body:

	m_body = new RigidBody(shape,false);
	
	// Position the body:
	
	m_body->SetWorldPosition(position);
	m_body->SetWorldOrientation(shape->GetOrientation());
	
	// Add to the world:
	
	GameCore::GetSingleton()->GetSimulationWorld()->Add(m_body);

	// Create our graphics resources
	
	m_ps		= GameCore::GetSingleton()->GetPixelShaderManager()->GetPixelShader("Shaders\\Textured.psh.bin");
	m_vs		= GameCore::GetSingleton()->GetVertexShaderManager()->GetVertexShader("Shaders\\Textured.vsh.bin");
	m_texture	= GameCore::GetSingleton()->GetTextureManager()->GetTexture(texture);
	
	// The transform shader uniform
	
	if ( m_vs.IsValid() ) m_u_transform = m_vs.GetUniform("Transform");
	
	// Make the vertex format:
	
	VertexFormat::ElementUsage usages[] = 
	{
		VertexFormat::VF_USAGE_POSITION ,
		VertexFormat::VF_USAGE_TEXCOORD ,
		VertexFormat::VF_USAGE_COLOR			
	};
	
	VertexFormat::ElementType types[] = 
	{
		VertexFormat::VF_TYPE_FLOAT3 ,
		VertexFormat::VF_TYPE_FLOAT2 ,
		VertexFormat::VF_TYPE_FLOAT4			
	};
	
	m_vf = VertexFormat(GameCore::GetSingleton()->GetDisplay(),3,usages,types);
	
	// See if everything is ok:	
	
	if ( m_vs.IsValid() && m_ps.IsValid() && m_texture.IsValid() && m_vf.IsValid() && m_u_transform.IsValid() )
	{
		m_valid_resources = true;
	}
	else
	{
		m_valid_resources = false;
	}
}

//=====================================================================================================================
/// @brief		Destroys the plane
//=====================================================================================================================

GamePlane::~GamePlane()
{
	// Remove from the world:
	
	GameCore::GetSingleton()->GetSimulationWorld()->Remove(m_body);	
	
	// Done:

	delete m_body;
}

//=====================================================================================================================
/// @brief		Renders the plane
/// @param		c - camera to draw from
/// @pre		Given camera cannot be null
//=====================================================================================================================

void GamePlane::OnDraw( Camera3D * c )
{
	// Make sure ok
	
	ENSURE( c , "Given camera cannot be null" )

	// Only if we have valid graphics resources
	
	if ( m_valid_resources )
	{
		// Apply texture
		
		m_texture.Apply(0);	
	
		// Apply shaders and vertex format
				
		m_vs.Apply();
		m_ps.Apply();
		m_vf.Apply();
		
		// Set the shader transform
		
		m_u_transform.SetMatrix
		( 
			m_body->GetWorldOrientation().ToMatrix4()			* 
			Matrix4f::Translation(m_body->GetWorldPosition())	* 
			c->GetViewProjectionMatrix() 
		);
		
		// Fill in the vertices
		
		const float SIZE = 4096.0f; const float TEX_SIZE = 64;
		
		m_vertices[0].m_position = Vec3f( - SIZE , 0 , + SIZE );
		m_vertices[1].m_position = Vec3f( + SIZE , 0 , + SIZE );
		m_vertices[2].m_position = Vec3f( + SIZE , 0 , - SIZE );
		m_vertices[3].m_position = Vec3f( + SIZE , 0 , - SIZE );
		m_vertices[4].m_position = Vec3f( - SIZE , 0 , - SIZE );
		m_vertices[5].m_position = Vec3f( - SIZE , 0 , + SIZE );
		
		m_vertices[0].m_texcoord = Vec2f( - TEX_SIZE , + TEX_SIZE );
		m_vertices[1].m_texcoord = Vec2f( + TEX_SIZE , + TEX_SIZE );
		m_vertices[2].m_texcoord = Vec2f( + TEX_SIZE , - TEX_SIZE );
		m_vertices[3].m_texcoord = Vec2f( + TEX_SIZE , - TEX_SIZE );
		m_vertices[4].m_texcoord = Vec2f( - TEX_SIZE , - TEX_SIZE );
		m_vertices[5].m_texcoord = Vec2f( - TEX_SIZE , + TEX_SIZE );
		
		for ( unsigned i = 0 ; i < 6 ; ++i ) 
		{
			m_vertices[i].m_color = Vec4f::One();
		}
		
		// Draw:
		
		GameCore::GetSingleton()->GetDisplay()->GetDevice()->DrawPrimitiveUP
		(
			D3DPT_TRIANGLELIST		,
			2						,
			m_vertices				,
			m_vf.GetVertexSize()
		);
	}
}
