/*
	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		Base class for all game entities that have a position and an orientation
//=====================================================================================================================

#include "Precompiled.h"
#include "PositionalObject.h"
#include "Game\GameCore.h"
#include "Graphics\Camera2D.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Wraps the given coordinates. If they are off the side of the map they come back at the other side.
/// @param		p - position to wrap
/// @returns	Wrapped position
//=====================================================================================================================

Vec2f PositionalObject::WrapCoordinates( const Vec2f & p )
{
	// Save position to return here:
	
	Vec2f wrapped = p;
		
	// Wrap to map boundaries:
	
	if ( wrapped.x < -GameCore::MAP_AREA.x )
	{
		wrapped.x  = Float::Mod( -wrapped.x , GameCore::MAP_AREA.x );
		wrapped.x  = GameCore::MAP_AREA.x - wrapped.x;
	}
	else if ( wrapped.x > GameCore::MAP_AREA.x )
	{
		wrapped.x = Float::Mod( wrapped.x , GameCore::MAP_AREA.x );
		wrapped.x = wrapped.x - GameCore::MAP_AREA.y;
	}
	
	if ( wrapped.y < -GameCore::MAP_AREA.y )
	{
		wrapped.y  = Float::Mod( -wrapped.y , GameCore::MAP_AREA.y );
		wrapped.y  = GameCore::MAP_AREA.y - wrapped.y;
	}
	else if ( wrapped.y > GameCore::MAP_AREA.y )
	{
		wrapped.y = Float::Mod( wrapped.y , GameCore::MAP_AREA.y );
		wrapped.y = wrapped.y - GameCore::MAP_AREA.y;
	}

	// Return wrapped coords:

	return wrapped;
}

//=====================================================================================================================
/// @brief		Unwraps the given coordinates relative to the given point. Because of the way the wrapping works, 
///				a point can be near the edge of one side of the map and still be near to another point at the opposite
///				edge - even though technically their coordinates are miles apart. 
///
///				This function corrects the 2nd point given 'unwrapped' and places it beyond the edge of the map so that
///				it appears to be close to 'relative_to'. 
///
///				This function is used by AI to implement normal chasing (move directly towards target) across the 
///				wrapped borders of the map. It is also used by rendering to wrap objects correctly during rendering, 
///				even though objects are technically at the opposite ends of the map.
/// @param		relative_to - point to unwrap relative to. 'wrapped' will be unwrapped such that the closest unwrapped
///				version either inside or outside of the map boundaries will be returned relative to this point.
/// @param		wrapped - coordinate to unwrap, such that the closest version to 'relative_to' is returned.
/// @returns	Unwrapped coordinates
/// @pre		The point 'relative_to' must be wrapped. I.E it must fall within map boundaries.
/// @pre		The point 'wrapped' must be wrapped. I.E it must fall within map boundaries.
//=====================================================================================================================

Vec2f PositionalObject::UnwrapCoordinates( const Vec2f & relative_to , const Vec2f & wrapped  )
{
	// Make sure ok:

	ENSURE( IsWrapped(relative_to)	, "The point 'relative_to' must be wrapped. I.E it must fall within map boundaries."	);
	ENSURE( IsWrapped(wrapped)		, "The point 'wrapped' must be wrapped. I.E it must fall within map boundaries."		);

	// Position to return:

	Vec2f unwrapped = wrapped;

	// See what side of the map x position is on:

	if ( wrapped.x >= 0 )
	{
		// Only do if we are on the other side:

		if ( relative_to.x < 0 )
		{
			// Get the x distance between us:

			float xdist = wrapped.x - relative_to.x;

			// If more than map size half extents then unwrap position to be past left of the map:

			if ( xdist > GameCore::MAP_AREA.x )
			{
				unwrapped.x = wrapped.x - ( GameCore::MAP_AREA.x * 2 );
			}
		}
	}
	else
	{
		// Only do if we are on the other side:

		if ( relative_to.x >= 0 )
		{
			// Get the x distance between us:

			float xdist = relative_to.x - wrapped.x;

			// If more than map size half extents then unwrap position to be past right of the map:

			if ( xdist > GameCore::MAP_AREA.x )
			{
				unwrapped.x = ( GameCore::MAP_AREA.x * 2 ) + wrapped.x;
			}
		}
	}

	// See what side of the map y position is on:

	if ( wrapped.y >= 0 )
	{
		// Only do if we are on the other side:

		if ( relative_to.y < 0 )
		{
			// Get the x distance between us:

			float ydist = wrapped.y - relative_to.y;

			// If more than map size half extents then unwrap position to be past bottom of the map:

			if ( ydist > GameCore::MAP_AREA.y )
			{
				unwrapped.y = wrapped.y - ( GameCore::MAP_AREA.y * 2 );
			}
		}
	}
	else
	{
		// Only do if we are on the other side:

		if ( relative_to.y >= 0 )
		{
			// Get the x distance between us:

			float ydist = relative_to.y - wrapped.y;

			// If more than map size half extents then unwrap position to be past top of the map:

			if ( ydist > GameCore::MAP_AREA.y )
			{
				unwrapped.y = ( GameCore::MAP_AREA.y * 2 ) + wrapped.y;
			}
		}
	}

	// Return the answer 

	return unwrapped;
}

//=====================================================================================================================
/// @brief		Tells if the game object is onscreen, given a maximum x / y size and the given camera
/// @param		object_size - size of the game object
/// @param		c - camera that the scene is being viewed from
/// @pre		Given camera cannot be null
/// @pre		Given size cannot be zero or less
/// @remarks	Size given is the HALF-EXTENTS of the object about it's center, not the full extents.
//=====================================================================================================================

bool PositionalObject::IsOnscreen( const Vec2f & object_size , Camera2D * c ) const
{
	// Make sure ok:

	ENSURE( c					, "Given camera cannot be null"			);
	ENSURE( object_size.x > 0	, "Given size cannot be zero or less"	);
	ENSURE( object_size.y > 0	, "Given size cannot be zero or less"	);

	// Get the view area for the camera and get half extents:

	Vec2f view_area = c->GetViewArea() * 0.5f;

	// Get camera position:

	Vec2f cam_pos = c->GetPosition();

	// Get our unwrapped position:

	Vec2f pos = UnwrapCoordinates( cam_pos , GetPosition() );

	// Determine the maximum object dimension:

	float max_dim = max( object_size.x , object_size.y );

	// See if the object is offscreen:

	if ( pos.x + max_dim < cam_pos.x - view_area.x ) return false;
	if ( pos.x - max_dim > cam_pos.x + view_area.x ) return false;
	if ( pos.y - max_dim > cam_pos.y + view_area.y ) return false;
	if ( pos.y + max_dim < cam_pos.y - view_area.y ) return false;

	// If we got to here then we are onscreen:

	return true;
}
