//
// Asura_Attractor_EntityRelative.cpp
//
// Created by RAR 11/10/06
//
// Copyright (C) 2006 Rebellion, All Rights Reserved.
//


#include "Core/Asura.h"
#include "Attractors/Asura_Attractor_EntityRelative.h"

#ifdef ASURA_USE_ATTRACTORS

#include "Core/Asura_Timers.h"
#include "Entity/PhysicalObject/Asura_ClientEntity_PhysicalObject.h"
#include "Entity/PhysicalObject/Asura_ServerEntity_PhysicalObject.h"
#include "Network/Asura_Network.h" 


Asura_Attractor_EntityRelative::Asura_Attractor_EntityRelative()
{
	m_uFrameStamp = 0xffffffff;
	m_bPositionValid = false;
}


bool Asura_Attractor_EntityRelative::UpdatePosition()
{
	//already done this frame?
	u_int uFrame = Asura_Timers::GetFrameNumber();
	if(uFrame == m_uFrameStamp)
	{
		return m_bPositionValid;
	}

	m_bPositionValid = false;
	m_uFrameStamp = uFrame;


	//working on client or server?
	if(Asura_Network::IsServer())
	{
		Asura_ServerEntity_PhysicalObject* pxEntity = Asura_ServerEntity_PhysicalObject::FindEntity(m_uParentGuid);

		if(pxEntity)
		{
			GetNode(0)->SetPosition(m_axRelativePosition[0] * pxEntity->GetOrientation() + pxEntity->GetPosition());
			GetNode(1)->SetPosition(m_axRelativePosition[1] * pxEntity->GetOrientation() + pxEntity->GetPosition());
			m_bPositionValid = true;
		}
	}
	else if(Asura_Network::IsClient())
	{
		Asura_ClientEntity_PhysicalObject* pxEntity = Asura_ClientEntity_PhysicalObject::FindEntity(m_uParentGuid);

		if(pxEntity)
		{
			GetNode(0)->SetPosition(m_axRelativePosition[0] * pxEntity->GetCurrentOrientation() + pxEntity->GetCurrentPosition());
			GetNode(1)->SetPosition(m_axRelativePosition[1] * pxEntity->GetCurrentOrientation() + pxEntity->GetCurrentPosition());
			m_bPositionValid = true;
		}
	}

	return m_bPositionValid;
	
}

void Asura_Attractor_EntityRelative::GetNormal(Asura_Vector_3& xNormal) const
{
	Asura_Attractor_Compiled::GetNormal(xNormal);

	if(Asura_Network::IsServer())
	{
		const Asura_ServerEntity_PhysicalObject* pxEntity = Asura_ServerEntity_PhysicalObject::FindEntity(m_uParentGuid);

		if(pxEntity)
		{
			xNormal = xNormal * pxEntity->GetOrientation();
		}
	}
	else if(Asura_Network::IsClient())
	{
		const Asura_ClientEntity_PhysicalObject* pxEntity = Asura_ClientEntity_PhysicalObject::FindEntity(m_uParentGuid);

		if(pxEntity)
		{
			xNormal = xNormal * pxEntity->GetCurrentOrientation();
		}
	}
}

#endif //ASURA_USE_ATTRACTORS

