#include "Mix/Tool/Win32/Core/Dynamics/Impl/CompoundShape.h"
#include "btBulletCollisionCommon.h"

namespace Mix{ namespace Tool{ namespace Win32{ namespace Dynamics{ namespace Impl{

CompoundShape::CompoundShape( void ) :
m_pShape( NULL )
{
}

CompoundShape::~CompoundShape( void )
{
	MIX_DELETE( m_pShape );
}

bool CompoundShape::Initialize( void )
{
	if( m_pShape != NULL )
	{
		return false;
	}

	m_pShape = new btCompoundShape();
	if( m_pShape == NULL )
	{
		return false;
	}

	return true;
}

bool CompoundShape::AddChild( Mix::Tool::Win32::Dynamics::Shape* pChild, const D3DXVECTOR3& centerPos, const D3DXQUATERNION& centerRot )
{
	if( pChild == NULL )
	{
		return false;
	}

	if( std::find( m_ChildList.begin(), m_ChildList.end(), pChild ) != m_ChildList.end() )
	{
		return false;
	}

	btTransform center;

	center.setOrigin( btVector3( centerPos.x, centerPos.y, centerPos.z ) );
	center.setRotation( btQuaternion( centerRot.x, centerRot.y, centerRot.z, centerRot.w ) );

	m_pShape->addChildShape( center, static_cast<btCollisionShape*>( pChild->Bullet_GetCollisionShape() ) );
	m_ChildList.push_back( pChild );

	return true;
}

bool CompoundShape::RemoveChild( Mix::Tool::Win32::Dynamics::Shape* pChild )
{
	if( pChild == NULL )
	{
		return false;
	}

	CompoundShape::ChildList::iterator it = std::find( m_ChildList.begin(), m_ChildList.end(), pChild );

	if( it == m_ChildList.end() )
	{
		return false;
	}

	m_pShape->removeChildShape( static_cast<btCollisionShape*>( pChild->Bullet_GetCollisionShape() ) );
	m_ChildList.erase( it );

	return true;
}

int CompoundShape::GetChildCount( void ) const
{
	return static_cast<int>( m_ChildList.size() );
}

const Mix::Tool::Win32::Dynamics::Shape* CompoundShape::GetChildPtr( int index ) const
{
	if( ( index < 0 ) ||
		( static_cast<int>( m_ChildList.size() ) <= index ) )
	{
		return false;
	}

	return m_ChildList[index];
}

void* CompoundShape::Bullet_GetCollisionShape( void )
{
	return m_pShape;
}

}}}}}
