#include "Model.h"

#include <Utility/AC3DFileReader.h>

#include <BulletCollision/CollisionShapes/btCompoundShape.h>
#include <BulletCollision/CollisionShapes/btBoxShape.h>
#include <BulletCollision/CollisionShapes/btConvexHullShape.h>

//////////////////////////////////////////////////////////////
namespace Dubious {
namespace Physics {

namespace
{
btCompoundShape* BuildShape( const Utility::AC3DModel& AC3DModel )
{
	btCompoundShape *pShape = new btCompoundShape();

	if (!AC3DModel.Points().empty()) {
		btConvexHullShape* pHull = new btConvexHullShape();
		pHull->setLocalScaling( btVector3( 1, 1, 1 ) );

		for (size_t i=0; i<AC3DModel.Points().size(); ++i) {
			const Utility::AC3DModel::Point& Point = AC3DModel.Points()[i];
			pHull->addPoint( btVector3(Point.X, Point.Y, Point.Z) );
		}
		btTransform Transform;
		Transform.setIdentity();
		pShape->addChildShape( Transform, pHull );
	}
	for (size_t i=0; i<AC3DModel.Kids().size(); ++i) {
		const Utility::AC3DModel::Point& Offset = AC3DModel.Kids()[i]->Offset();
		btTransform Transform;
		Transform.setIdentity();
		Transform.setOrigin( btVector3( Offset.X, Offset.Y, Offset.Z ) );
		btCompoundShape* pChildShape = BuildShape( *AC3DModel.Kids()[i] );
		pShape->addChildShape( Transform, pChildShape );
	}
	return pShape;
}
}

Model::Model( const Utility::AC3DFile& File )
{
	const Utility::AC3DModel& AC3DModel = *File.Model();
	m_pShape = BuildShape( AC3DModel );
}

Model::Model( const Math::CubeVector& Size )
{
	m_pShape = new btBoxShape( Size.Vector() );
}

Model::Model()
	: m_pShape( NULL )
{
}

Model::~Model()
{
	delete m_pShape;
}


}
}
