/*
	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.
*/

#ifndef GAME_DOOM_COLLISION_H
#define GAME_DOOM_COLLISION_H

//=====================================================================================================================
//=====================================================================================================================

namespace Game
{
	//=================================================================================================================
	//=================================================================================================================
		
	class	DoomLevel;
	struct	DoomPPSeg;
	struct	DoomPPNode;
	struct	DoomGLSubsectorV2;
	struct	DoomSector;

	//=================================================================================================================
	/// @brief		This helper class performs collision testing with the level. 
	//=================================================================================================================

	class DoomCollision
	{
		public:
		
			//=========================================================================================================
			// Structures
			//=========================================================================================================
			
				/// This structure represents the result of a raycast test
				
				struct RaycastResult
				{
					/// If true then there was a hit
					
					bool m_hit;
					
					/// This is the point we started from
					
					Vec3f m_start_point;
					
					/// This is the direction of the raycast
					
					Vec3f m_direction;
					
					/// If there was a hit then this is the point we hit
					
					Vec3f m_hit_point;
					
					/// If the hit was a wall hit then this is the line segment hit. Otherwise null.
					
					const DoomPPSeg * m_hit_seg;
					
					/// If the hit was a floor/ceiling hit then this is the subsector in which the hit occured. Otherwise null.
					
					const DoomGLSubsectorV2 * m_hit_subsector;
				};
		
			//=========================================================================================================
			// Functions
			//=========================================================================================================
			
				/// Creates the collision helper with the given doom level
				
				DoomCollision( DoomLevel * level );
				
				/// Does a raycast against the level
				
				RaycastResult Raycast( const Vec3f & from , const Vec3f & to ) const;
				
				/// Does a 2D raycast against the level: ignores lower and upper walls and floors/ceilings.
				
				RaycastResult Raycast2D( const Vec3f & from , const Vec3f & to ) const;

				/// Collides the given thing with the level: returns it's output position thereafter

				Vec3f Collide( const Vec3f & pos , float radius , float height ) const;
				
				/// Tells if the two edges intersect. This function takes two points and a line segment.
				
				bool EdgeIntersect( const Vec3f & p1 , const Vec3f & p2 , const DoomPPSeg & seg ) const;

				/// Tells if one sector is potentially visible from another

				bool IsPotentiallyVisible( const DoomSector & from , const DoomSector & to ) const;
		
		private:
		
			//=========================================================================================================
			// Functions
			//=========================================================================================================		
				
				/// Gets which seg in a subsector the two points cross, if any
				
				const DoomPPSeg * GetCrossingSeg( const DoomGLSubsectorV2 & subsector , const Vec3f & from , const Vec3f & to ) const;
				
				/// Finds the intersection of the given ray with the given wall plane and returns it:
				
				Vec3f WallIntersect( const Vec3f & dir , const Vec3f & start , const DoomPPSeg & seg ) const;
				
				/// Finds the intersection of the given ray with the given floor plane and returns it:
				
				Vec3f FloorIntersect( const Vec3f & dir , const Vec3f & start , float floor_height ) const;

				/// Finds the intersection of the given ray with the given ceiling plane and returns it:
				
				Vec3f CeilingIntersect( const Vec3f & dir , const Vec3f & start , float floor_height ) const;

				/// Recursively builds a list of subsectors that the given point is in. Used for bounding sphere collision.

				unsigned BuildCollisionSubsectorsRecursive( const DoomPPNode & node , const Vec3f & pos , float radius ) const;
				
				/// Performs planar collision with the given subsector
				
				Vec3f SubsectorPlaneCollide( const DoomGLSubsectorV2 & subsector, const Vec3f & pos , float radius , float height ) const;
				
				/// Performs edge collisions with the given subsector
				
				Vec3f SubsectorEdgeCollide( const DoomGLSubsectorV2 & subsector, const Vec3f & pos , float radius , float height ) const;
				
				/// Performs point collisions with the given subsector
				
				Vec3f SubsectorPointCollide( const DoomGLSubsectorV2 & subsector, const Vec3f & pos , float radius , float height ) const;
				
				/// Tells if the given point is within the given subsector
				
				bool WithinSubsector( const DoomGLSubsectorV2 & subsector, const Vec3f & pos ) const;
				
				//=====================================================================================================
				/// @brief		Collides the given point with the other given point and saves the result in the given point
				/// @param		p1 - point to collide. output is saved here also.
				/// @param		p2 - point to collide with.
				/// @param		radius - radius of the first point's bounding sphere
				/// @param		sq_radius - square radius of the first point's bounding sphere
				/// @returns	True if there was a collision
				//=====================================================================================================
				
				static bool PointCollide( Vec3f & p1 , const Vec3f & p2 , float radius , float sq_radius )
				{
					// Get a relative vector between them
					
					Vec3f rel = p1 - p2; 
					
					// Get the square distance:
					
					float sq_distance = rel.SqLength();
					
					// See if in range:
					
					if ( sq_distance < sq_radius )
					{
						// Collision: get the length between the points
						
						float len = Float::Sqrt(sq_distance);
						
						// Normalize the vector between them:
						
						rel *= 1.0f / len;
						
						// Correct the position of the first point:
						
						p1 += rel * ( radius - len );
						
						// Collision
						
						return true;
					}
					else
					{
						// No collision:
						
						return false;
					}
				}
		
			//=========================================================================================================
			// Variables
			//=========================================================================================================
			
				/// This is the doom level used for collision
				
				DoomLevel * m_level;

				/// This is a pointer to the game stack. Used for collision detection to store a list of potential collideables.

				Stack * m_stack;

				/// This is a pointer to the game secondary stack. Used for collision detection to store a list of potential collideables.

				Stack * m_secondary_stack;
	};
};

#endif
