text:
//Bullet Continuous Collision Detection and Physics Library
//Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

//
// btAxisSweep3.h
//
// Copyright (c) 2006 Simon Hobbs
//
// This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.

#ifndef BT_AXIS_SWEEP_3_H
#define BT_AXIS_SWEEP_3_H

#include "LinearMath/btVector3.h"
#include "btOverlappingPairCache.h"
#include "btBroadphaseInterface.h"
#include "btBroadphaseProxy.h"
#include "btOverlappingPairCallback.h"
#include "btDbvtBroadphase.h"
#include "btAxisSweep3Internal.h"

/// The btAxisSweep3 is an efficient implementation of the 3d axis sweep and prune broadphase.
/// It uses arrays rather then lists for storage of the 3 axis. Also it operates using 16 bit integer coordinates instead of floats.
/// For large worlds and many objects, use bt32BitAxisSweep3 or btDbvtBroadphase instead. bt32BitAxisSweep3 has higher precision and allows more then 16384 objects at the cost of more memory and bit of performance.
class btAxisSweep3 : public btAxisSweep3Internal<unsigned short int>
{
public:

	btAxisSweep3(const btVector3& worldAabbMin,const btVector3& worldAabbMax, unsigned short int maxHandles = 16384, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false);

};

/// The bt32BitAxisSweep3 allows higher precision quantization and more objects compared to the btAxisSweep3 sweep and prune.
/// This comes at the cost of more memory per handle, and a bit slower performance.
/// It uses arrays rather then lists for storage of the 3 axis.
class bt32BitAxisSweep3 : public btAxisSweep3Internal<unsigned int>
{
public:

	bt32BitAxisSweep3(const btVector3& worldAabbMin,const btVector3& worldAabbMax, unsigned int maxHandles = 1500000, btOverlappingPairCache* pairCache = 0, bool disableRaycastAccelerator = false);

};

#endif


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

///btDbvtBroadphase implementation by Nathanael Presson
#ifndef BT_DBVT_BROADPHASE_H
#define BT_DBVT_BROADPHASE_H

#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"

// Compile time config
#define DBVT_BP_PROFILE            0
//#define DBVT_BP_SORTPAIRS          1
#define DBVT_BP_PREVENTFALSEUPDATE 0
#define DBVT_BP_ACCURATESLEEPING   0
#define DBVT_BP_ENABLE_BENCHMARK   0
#define DBVT_BP_MARGIN (btScalar) 0.05

#if DBVT_BP_PROFILE
#define	DBVT_BP_PROFILING_RATE	256
#include "LinearMath/btQuickprof.h"
#endif

struct btDbvtProxy : btBroadphaseProxy
{
	//btDbvtAabbMm	aabb;
	btDbvtNode*  leaf;
	btDbvtProxy* links[2];
	int          stage;

	btDbvtProxy(
	    const btVector3& aabbMin,
	    const btVector3& aabbMax,
	    void*            userPtr,
	    int              collisionFilterGroup,
	    int              collisionFilterMask)
	    : btBroadphaseProxy(aabbMin, aabbMax, userPtr, collisionFilterGroup, collisionFilterMask)
	{
		links[0] = links[1] = 0;
	}
};

typedef btAlignedObjectArray<btDbvtProxy*>	btDbvtProxyArray;

/// The btDbvtBroadphase implements a broadphase using two dynamic AABB bounding
/// volume hierarchies/trees (see btDbvt). One tree is used for
/// static/non-moving objects, and another tree is used for dynamic objects.
/// Objects can move from one tree to the other. This is a very fast broadphase,
/// especially for very dynamic worlds where many objects are moving. Its
/// insert/add and remove of objects is generally faster than the sweep and
/// prune broadphases btAxisSweep3 and bt32BitAxisSweep3.
struct	btDbvtBroadphase : btBroadphaseInterface
{
	// Config
	enum
	{
		DYNAMIC_SET = 0, // Dynamic set index
		FIXED_SET   = 1, // Fixed set index
		STAGECOUNT  = 2  // Number of stages
	};

	// Fields
	btDbvt                  m_sets[2];                    // Dbvt sets
	btDbvtProxy*            m_stageRoots[STAGECOUNT + 1]; // Stages list
	btOverlappingPairCache* m_paircache;                  // Pair cache
	btScalar                m_prediction;                 // Velocity prediction
	int                     m_stageCurrent;               // Current stage
	int                     m_fupdates;                   // % of fixed updates per frame
	int                     m_dupdates;                   // % of dynamic updates per frame
	int                     m_cupdates;                   // % of cleanup updates per frame
	int                     m_newpairs;                   // Number of pairs created
	int                     m_fixedleft;                  // Fixed optimization left
	unsigned                m_updates_call;               // Number of updates call
	unsigned                m_updates_done;               // Number of updates done
	btScalar                m_updates_ratio;              // m_updates_done/m_updates_call
	int                     m_pid;                        // Parse id
	int                     m_cid;                        // Cleanup index
	int                     m_gid;                        // Gen id
	bool                    m_releasepaircache;           // Release pair cache on delete
	bool                    m_deferedcollide;             // Defere dynamic/static collision to collide call
	bool                    m_needcleanup;                // Need to run cleanup?

	btAlignedObjectArray<btAlignedObjectArray<const btDbvtNode*>> m_rayTestStacks;

#if DBVT_BP_PROFILE
	btClock m_clock;
	struct
	{
		unsigned long m_total;
		unsigned long m_ddcollide;
		unsigned long m_fdcollide;
		unsigned long m_cleanup;
		unsigned long m_jobcount;
	} m_profiling;
#endif

	// Methods
	btDbvtBroadphase(btOverlappingPairCache* paircache = 0);
	~btDbvtBroadphase();
	void collide(btDispatcher* dispatcher);
	void optimize();

	// btBroadphaseInterface Implementation
	btBroadphaseProxy* createProxy(const btVector3& aabbMin, const btVector3& aabbMax, int shapeType, void* userPtr, int collisionFilterGroup, int collisionFilterMask, btDispatcher* dispatcher);
	virtual void       destroyProxy(btBroadphaseProxy* proxy, btDispatcher* dispatcher);
	virtual void       setAabb(btBroadphaseProxy* proxy, const btVector3& aabbMin, const btVector3& aabbMax, btDispatcher* dispatcher);
	virtual void       rayTest(const btVector3& rayFrom, const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin = btVector3(0, 0, 0), const btVector3& aabbMax = btVector3(0, 0, 0));
	virtual void       aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback);

	virtual void                          getAabb(btBroadphaseProxy* proxy, btVector3& aabbMin, btVector3& aabbMax) const;
	virtual void                          calculateOverlappingPairs(btDispatcher* dispatcher);
	virtual btOverlappingPairCache*       getOverlappingPairCache();
	virtual const btOverlappingPairCache* getOverlappingPairCache() const;
	virtual void                          getBroadphaseAabb(btVector3& aabbMin, btVector3& aabbMax) const;
	virtual void                          printStats();

	/// reset broadphase internal structures, to ensure determinism/reproducibility
	virtual void resetPool(btDispatcher* dispatcher);

	void performDeferredRemoval(btDispatcher* dispatcher);

	void     setVelocityPrediction(btScalar prediction) { m_prediction = prediction; }
	btScalar getVelocityPrediction() const { return m_prediction; }

	/// this setAabbForceUpdate is similar to setAabb but always forces the aabb
	/// update. it is not part of the btBroadphaseInterface but specific to
	/// btDbvtBroadphase. it bypasses certain optimizations that prevent aabb
	/// updates (when the aabb shrinks), see
	/// http://code.google.com/p/bullet/issues/detail?id=223
	void setAabbForceUpdate(btBroadphaseProxy* absproxy, const btVector3& aabbMin, const btVector3& aabbMax, btDispatcher* /*dispatcher*/);

	static void benchmark(btBroadphaseInterface*);
};

#endif

repo_name: JoshParnell/libphx

repo_language: C

mime_type: text/x-c++


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2007 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///btDbvt implementation by Nathanael Presson

#ifndef BT_DYNAMIC_BOUNDING_VOLUME_TREE_H
#define BT_DYNAMIC_BOUNDING_VOLUME_TREE_H

#include "LinearMath/btAlignedObjectArray.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btTransform.h"
#include "LinearMath/btAabbUtil2.h"

//
// Compile time configuration
//

// Implementation profiles
#define DBVT_IMPL_GENERIC		0	// Generic implementation
#define DBVT_IMPL_SSE			1	// SSE

// Template implementation of ICollide
#ifdef _WIN32
#if (defined (_MSC_VER) && _MSC_VER >= 1400)
#define	DBVT_USE_TEMPLATE		1
#else
#define	DBVT_USE_TEMPLATE		0
#endif
#else
#define	DBVT_USE_TEMPLATE		0
#endif

// Use only intrinsics instead of inline asm
#define DBVT_USE_INTRINSIC_SSE	1

// Using memmov for collideOCL
#define DBVT_USE_MEMMOVE		1

// Enable benchmarking code
#define	DBVT_ENABLE_BENCHMARK	0

// Inlining
#define DBVT_INLINE				SIMD_FORCE_INLINE

// Specific methods implementation

//SSE gives errors on a MSVC 7.1
#if defined (BT_USE_SSE) //&& defined (_WIN32)
#define DBVT_SELECT_IMPL		DBVT_IMPL_SSE
#define DBVT_MERGE_IMPL			DBVT_IMPL_SSE
#define DBVT_INT0_IMPL			DBVT_IMPL_SSE
#else
#define DBVT_SELECT_IMPL		DBVT_IMPL_GENERIC
#define DBVT_MERGE_IMPL			DBVT_IMPL_GENERIC
#define DBVT_INT0_IMPL			DBVT_IMPL_GENERIC
#endif

#if	(DBVT_SELECT_IMPL==DBVT_IMPL_SSE)||	\
	(DBVT_MERGE_IMPL==DBVT_IMPL_SSE)||	\
	(DBVT_INT0_IMPL==DBVT_IMPL_SSE)
#include <emmintrin.h>
#endif

//
// Auto config and checks
//

#if DBVT_USE_TEMPLATE
#define	DBVT_VIRTUAL
#define DBVT_VIRTUAL_DTOR(a)
#define DBVT_PREFIX					template <typename T>
#define DBVT_IPOLICY				T& policy
#define DBVT_CHECKTYPE				static const ICollide&	typechecker=*(T*)1;(void)typechecker;
#else
#define	DBVT_VIRTUAL_DTOR(a)		virtual ~a() {}
#define DBVT_VIRTUAL				virtual
#define DBVT_PREFIX
#define DBVT_IPOLICY				ICollide& policy
#define DBVT_CHECKTYPE
#endif

#if DBVT_USE_MEMMOVE
#if !defined( __CELLOS_LV2__) && !defined(__MWERKS__)
#include <memory.h>
#endif
#include <string.h>
#endif

#ifndef DBVT_USE_TEMPLATE
#error "DBVT_USE_TEMPLATE undefined"
#endif

#ifndef DBVT_USE_MEMMOVE
#error "DBVT_USE_MEMMOVE undefined"
#endif

#ifndef DBVT_ENABLE_BENCHMARK
#error "DBVT_ENABLE_BENCHMARK undefined"
#endif

#ifndef DBVT_SELECT_IMPL
#error "DBVT_SELECT_IMPL undefined"
#endif

#ifndef DBVT_MERGE_IMPL
#error "DBVT_MERGE_IMPL undefined"
#endif

#ifndef DBVT_INT0_IMPL
#error "DBVT_INT0_IMPL undefined"
#endif

//
// Defaults volumes
//

/* btDbvtAabbMm			*/
struct	btDbvtAabbMm
{
	DBVT_INLINE btVector3			Center() const	{ return((mi+mx)/2); }
	DBVT_INLINE btVector3			Lengths() const	{ return(mx-mi); }
	DBVT_INLINE btVector3			Extents() const	{ return((mx-mi)/2); }
	DBVT_INLINE const btVector3&	Mins() const	{ return(mi); }
	DBVT_INLINE const btVector3&	Maxs() const	{ return(mx); }
	static inline btDbvtAabbMm		FromCE(const btVector3& c,const btVector3& e);
	static inline btDbvtAabbMm		FromCR(const btVector3& c,btScalar r);
	static inline btDbvtAabbMm		FromMM(const btVector3& mi,const btVector3& mx);
	static inline btDbvtAabbMm		FromPoints(const btVector3* pts,int n);
	static inline btDbvtAabbMm		FromPoints(const btVector3** ppts,int n);
	DBVT_INLINE void				Expand(const btVector3& e);
	DBVT_INLINE void				SignedExpand(const btVector3& e);
	DBVT_INLINE bool				Contain(const btDbvtAabbMm& a) const;
	DBVT_INLINE int					Classify(const btVector3& n,btScalar o,int s) const;
	DBVT_INLINE btScalar			ProjectMinimum(const btVector3& v,unsigned signs) const;
	DBVT_INLINE friend bool			Intersect(	const btDbvtAabbMm& a,
		const btDbvtAabbMm& b);

	DBVT_INLINE friend bool			Intersect(	const btDbvtAabbMm& a,
		const btVector3& b);

	DBVT_INLINE friend btScalar		Proximity(	const btDbvtAabbMm& a,
		const btDbvtAabbMm& b);
	DBVT_INLINE friend int			Select(		const btDbvtAabbMm& o,
		const btDbvtAabbMm& a,
		const btDbvtAabbMm& b);
	DBVT_INLINE friend void			Merge(		const btDbvtAabbMm& a,
		const btDbvtAabbMm& b,
		btDbvtAabbMm& r);
	DBVT_INLINE friend bool			NotEqual(	const btDbvtAabbMm& a,
		const btDbvtAabbMm& b);

    DBVT_INLINE btVector3&	tMins()	{ return(mi); }
	DBVT_INLINE btVector3&	tMaxs()	{ return(mx); }

private:
	DBVT_INLINE void				AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const;
private:
	btVector3	mi,mx;
};

// Types
typedef	btDbvtAabbMm	btDbvtVolume;

/* btDbvtNode				*/
struct	btDbvtNode
{
	btDbvtVolume	volume;
	btDbvtNode*		parent;
	DBVT_INLINE bool	isleaf() const		{ return(childs[1]==0); }
	DBVT_INLINE bool	isinternal() const	{ return(!isleaf()); }
	union
	{
		btDbvtNode*	childs[2];
		void*	data;
		int		dataAsInt;
	};
};

typedef btAlignedObjectArray<const btDbvtNode*> btNodeStack;

///The btDbvt class implements a fast dynamic bounding volume tree based on axis aligned bounding boxes (aabb tree).
///This btDbvt is used for soft body collision detection and for the btDbvtBroadphase. It has a fast insert, remove and update of nodes.
///Unlike the btQuantizedBvh, nodes can be dynamically moved around, which allows for change in topology of the underlying data structure.
struct	btDbvt
{
	/* Stack element	*/
	struct	sStkNN
	{
		const btDbvtNode*	a;
		const btDbvtNode*	b;
		sStkNN() {}
		sStkNN(const btDbvtNode* na,const btDbvtNode* nb) : a(na),b(nb) {}
	};
	struct	sStkNP
	{
		const btDbvtNode*	node;
		int			mask;
		sStkNP(const btDbvtNode* n,unsigned m) : node(n),mask(m) {}
	};
	struct	sStkNPS
	{
		const btDbvtNode*	node;
		int			mask;
		btScalar	value;
		sStkNPS() {}
		sStkNPS(const btDbvtNode* n,unsigned m,btScalar v) : node(n),mask(m),value(v) {}
	};
	struct	sStkCLN
	{
		const btDbvtNode*	node;
		btDbvtNode*		parent;
		sStkCLN(const btDbvtNode* n,btDbvtNode* p) : node(n),parent(p) {}
	};
	// Policies/Interfaces

	/* ICollide	*/
	struct	ICollide
	{
		DBVT_VIRTUAL_DTOR(ICollide)
			DBVT_VIRTUAL void	Process(const btDbvtNode*,const btDbvtNode*)		{}
		DBVT_VIRTUAL void	Process(const btDbvtNode*)					{}
		DBVT_VIRTUAL void	Process(const btDbvtNode* n,btScalar)			{ Process(n); }
		DBVT_VIRTUAL bool	Descent(const btDbvtNode*)					{ return(true); }
		DBVT_VIRTUAL bool	AllLeaves(const btDbvtNode*)					{ return(true); }
	};
	/* IWriter	*/
	struct	IWriter
	{
		virtual ~IWriter() {}
		virtual void		Prepare(const btDbvtNode* root,int numnodes)=0;
		virtual void		WriteNode(const btDbvtNode*,int index,int parent,int child0,int child1)=0;
		virtual void		WriteLeaf(const btDbvtNode*,int index,int parent)=0;
	};
	/* IClone	*/
	struct	IClone
	{
		virtual ~IClone()	{}
		virtual void		CloneLeaf(btDbvtNode*) {}
	};

	// Constants
	enum	{
		SIMPLE_STACKSIZE	=	64,
		DOUBLE_STACKSIZE	=	SIMPLE_STACKSIZE*2
	};

	// Fields
	btDbvtNode*		m_root;
	btDbvtNode*		m_free;
	int				m_lkhd;
	int				m_leaves;
	unsigned		m_opath;

	btAlignedObjectArray<sStkNN>	m_stkStack;

	// Methods
	btDbvt();
	~btDbvt();
	void			clear();
	bool			empty() const { return(0==m_root); }
	void			optimizeBottomUp();
	void			optimizeTopDown(int bu_treshold=128);
	void			optimizeIncremental(int passes);
	btDbvtNode*		insert(const btDbvtVolume& box,void* data);
	void			update(btDbvtNode* leaf,int lookahead=-1);
	void			update(btDbvtNode* leaf,btDbvtVolume& volume);
	bool			update(btDbvtNode* leaf,btDbvtVolume& volume,const btVector3& velocity,btScalar margin);
	bool			update(btDbvtNode* leaf,btDbvtVolume& volume,const btVector3& velocity);
	bool			update(btDbvtNode* leaf,btDbvtVolume& volume,btScalar margin);
	void			remove(btDbvtNode* leaf);
	void			write(IWriter* iwriter) const;
	void			clone(btDbvt& dest,IClone* iclone=0) const;
	static int		maxdepth(const btDbvtNode* node);
	static int		countLeaves(const btDbvtNode* node);
	static void		extractLeaves(const btDbvtNode* node,btAlignedObjectArray<const btDbvtNode*>& leaves);
#if DBVT_ENABLE_BENCHMARK
	static void		benchmark();
#else
	static void		benchmark(){}
#endif
	// DBVT_IPOLICY must support ICollide policy/interface
	DBVT_PREFIX
		static void		enumNodes(	const btDbvtNode* root,
		DBVT_IPOLICY);
	DBVT_PREFIX
		static void		enumLeaves(	const btDbvtNode* root,
		DBVT_IPOLICY);
	DBVT_PREFIX
		void		collideTT(	const btDbvtNode* root0,
		const btDbvtNode* root1,
		DBVT_IPOLICY);

	DBVT_PREFIX
		void		collideTTpersistentStack(	const btDbvtNode* root0,
		  const btDbvtNode* root1,
		  DBVT_IPOLICY);
#if 0
	DBVT_PREFIX
		void		collideTT(	const btDbvtNode* root0,
		const btDbvtNode* root1,
		const btTransform& xform,
		DBVT_IPOLICY);
	DBVT_PREFIX
		void		collideTT(	const btDbvtNode* root0,
		const btTransform& xform0,
		const btDbvtNode* root1,
		const btTransform& xform1,
		DBVT_IPOLICY);
#endif

	DBVT_PREFIX
		void		collideTV(	const btDbvtNode* root,
		const btDbvtVolume& volume,
		DBVT_IPOLICY) const;

	DBVT_PREFIX
	void		collideTVNoStackAlloc(	const btDbvtNode* root,
						  const btDbvtVolume& volume,
						  btNodeStack& stack,
						  DBVT_IPOLICY) const;

	///rayTest is a re-entrant ray test, and can be called in parallel as long as the btAlignedAlloc is thread-safe (uses locking etc)
	///rayTest is slower than rayTestInternal, because it builds a local stack, using memory allocations, and it recomputes signs/rayDirectionInverses each time
	DBVT_PREFIX
		static void		rayTest(	const btDbvtNode* root,
		const btVector3& rayFrom,
		const btVector3& rayTo,
		DBVT_IPOLICY);
	///rayTestInternal is faster than rayTest, because it uses a persistent stack (to reduce dynamic memory allocations to a minimum) and it uses precomputed signs/rayInverseDirections
	///rayTestInternal is used by btDbvtBroadphase to accelerate world ray casts
	DBVT_PREFIX
		void		rayTestInternal(	const btDbvtNode* root,
								const btVector3& rayFrom,
								const btVector3& rayTo,
								const btVector3& rayDirectionInverse,
								unsigned int signs[3],
								btScalar lambda_max,
								const btVector3& aabbMin,
								const btVector3& aabbMax,
                                btAlignedObjectArray<const btDbvtNode*>& stack,
								DBVT_IPOLICY) const;

	DBVT_PREFIX
		static void		collideKDOP(const btDbvtNode* root,
		const btVector3* normals,
		const btScalar* offsets,
		int count,
		DBVT_IPOLICY);
	DBVT_PREFIX
		static void		collideOCL(	const btDbvtNode* root,
		const btVector3* normals,
		const btScalar* offsets,
		const btVector3& sortaxis,
		int count,
		DBVT_IPOLICY,
		bool fullsort=true);
	DBVT_PREFIX
		static void		collideTU(	const btDbvtNode* root,
		DBVT_IPOLICY);
	// Helpers
	static DBVT_INLINE int	nearest(const int* i,const btDbvt::sStkNPS* a,btScalar v,int l,int h)
	{
		int	m=0;
		while(l<h)
		{
			m=(l+h)>>1;
			if(a[i[m]].value>=v) l=m+1; else h=m;
		}
		return(h);
	}
	static DBVT_INLINE int	allocate(	btAlignedObjectArray<int>& ifree,
		btAlignedObjectArray<sStkNPS>& stock,
		const sStkNPS& value)
	{
		int	i;
		if(ifree.size()>0)
		{ i=ifree[ifree.size()-1];ifree.pop_back();stock[i]=value; }
		else
		{ i=stock.size();stock.push_back(value); }
		return(i);
	}
	//
private:
	btDbvt(const btDbvt&)	{}
};

//
// Inline's
//

//
inline btDbvtAabbMm			btDbvtAabbMm::FromCE(const btVector3& c,const btVector3& e)
{
	btDbvtAabbMm box;
	box.mi=c-e;box.mx=c+e;
	return(box);
}

//
inline btDbvtAabbMm			btDbvtAabbMm::FromCR(const btVector3& c,btScalar r)
{
	return(FromCE(c,btVector3(r,r,r)));
}

//
inline btDbvtAabbMm			btDbvtAabbMm::FromMM(const btVector3& mi,const btVector3& mx)
{
	btDbvtAabbMm box;
	box.mi=mi;box.mx=mx;
	return(box);
}

//
inline btDbvtAabbMm			btDbvtAabbMm::FromPoints(const btVector3* pts,int n)
{
	btDbvtAabbMm box;
	box.mi=box.mx=pts[0];
	for(int i=1;i<n;++i)
	{
		box.mi.setMin(pts[i]);
		box.mx.setMax(pts[i]);
	}
	return(box);
}

//
inline btDbvtAabbMm			btDbvtAabbMm::FromPoints(const btVector3** ppts,int n)
{
	btDbvtAabbMm box;
	box.mi=box.mx=*ppts[0];
	for(int i=1;i<n;++i)
	{
		box.mi.setMin(*ppts[i]);
		box.mx.setMax(*ppts[i]);
	}
	return(box);
}

//
DBVT_INLINE void		btDbvtAabbMm::Expand(const btVector3& e)
{
	mi-=e;mx+=e;
}

//
DBVT_INLINE void		btDbvtAabbMm::SignedExpand(const btVector3& e)
{
	if(e.x()>0) mx.setX(mx.x()+e[0]); else mi.setX(mi.x()+e[0]);
	if(e.y()>0) mx.setY(mx.y()+e[1]); else mi.setY(mi.y()+e[1]);
	if(e.z()>0) mx.setZ(mx.z()+e[2]); else mi.setZ(mi.z()+e[2]);
}

//
DBVT_INLINE bool		btDbvtAabbMm::Contain(const btDbvtAabbMm& a) const
{
	return(	(mi.x()<=a.mi.x())&&
		(mi.y()<=a.mi.y())&&
		(mi.z()<=a.mi.z())&&
		(mx.x()>=a.mx.x())&&
		(mx.y()>=a.mx.y())&&
		(mx.z()>=a.mx.z()));
}

//
DBVT_INLINE int		btDbvtAabbMm::Classify(const btVector3& n,btScalar o,int s) const
{
	btVector3			pi,px;
	switch(s)
	{
	case	(0+0+0):	px=btVector3(mi.x(),mi.y(),mi.z());
		pi=btVector3(mx.x(),mx.y(),mx.z());break;
	case	(1+0+0):	px=btVector3(mx.x(),mi.y(),mi.z());
		pi=btVector3(mi.x(),mx.y(),mx.z());break;
	case	(0+2+0):	px=btVector3(mi.x(),mx.y(),mi.z());
		pi=btVector3(mx.x(),mi.y(),mx.z());break;
	case	(1+2+0):	px=btVector3(mx.x(),mx.y(),mi.z());
		pi=btVector3(mi.x(),mi.y(),mx.z());break;
	case	(0+0+4):	px=btVector3(mi.x(),mi.y(),mx.z());
		pi=btVector3(mx.x(),mx.y(),mi.z());break;
	case	(1+0+4):	px=btVector3(mx.x(),mi.y(),mx.z());
		pi=btVector3(mi.x(),mx.y(),mi.z());break;
	case	(0+2+4):	px=btVector3(mi.x(),mx.y(),mx.z());
		pi=btVector3(mx.x(),mi.y(),mi.z());break;
	case	(1+2+4):	px=btVector3(mx.x(),mx.y(),mx.z());
		pi=btVector3(mi.x(),mi.y(),mi.z());break;
	}
	if((btDot(n,px)+o)<0)		return(-1);
	if((btDot(n,pi)+o)>=0)	return(+1);
	return(0);
}

//
DBVT_INLINE btScalar	btDbvtAabbMm::ProjectMinimum(const btVector3& v,unsigned signs) const
{
	const btVector3*	b[]={&mx,&mi};
	const btVector3		p(	b[(signs>>0)&1]->x(),
		b[(signs>>1)&1]->y(),
		b[(signs>>2)&1]->z());
	return(btDot(p,v));
}

//
DBVT_INLINE void		btDbvtAabbMm::AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const
{
	for(int i=0;i<3;++i)
	{
		if(d[i]<0)
		{ smi+=mx[i]*d[i];smx+=mi[i]*d[i]; }
		else
		{ smi+=mi[i]*d[i];smx+=mx[i]*d[i]; }
	}
}

//
DBVT_INLINE bool		Intersect(	const btDbvtAabbMm& a,
								  const btDbvtAabbMm& b)
{
#if	DBVT_INT0_IMPL == DBVT_IMPL_SSE
	const __m128	rt(_mm_or_ps(	_mm_cmplt_ps(_mm_load_ps(b.mx),_mm_load_ps(a.mi)),
		_mm_cmplt_ps(_mm_load_ps(a.mx),_mm_load_ps(b.mi))));
#if defined (_WIN32)
	const __int32*	pu((const __int32*)&rt);
#else
    const int*	pu((const int*)&rt);
#endif
	return((pu[0]|pu[1]|pu[2])==0);
#else
	return(	(a.mi.x()<=b.mx.x())&&
		(a.mx.x()>=b.mi.x())&&
		(a.mi.y()<=b.mx.y())&&
		(a.mx.y()>=b.mi.y())&&
		(a.mi.z()<=b.mx.z())&&
		(a.mx.z()>=b.mi.z()));
#endif
}

//
DBVT_INLINE bool		Intersect(	const btDbvtAabbMm& a,
								  const btVector3& b)
{
	return(	(b.x()>=a.mi.x())&&
		(b.y()>=a.mi.y())&&
		(b.z()>=a.mi.z())&&
		(b.x()<=a.mx.x())&&
		(b.y()<=a.mx.y())&&
		(b.z()<=a.mx.z()));
}

//////////////////////////////////////

//
DBVT_INLINE btScalar	Proximity(	const btDbvtAabbMm& a,
								  const btDbvtAabbMm& b)
{
	const btVector3	d=(a.mi+a.mx)-(b.mi+b.mx);
	return(btFabs(d.x())+btFabs(d.y())+btFabs(d.z()));
}

//
DBVT_INLINE int			Select(	const btDbvtAabbMm& o,
							   const btDbvtAabbMm& a,
							   const btDbvtAabbMm& b)
{
#if	DBVT_SELECT_IMPL == DBVT_IMPL_SSE

#if defined (_WIN32)
	static ATTRIBUTE_ALIGNED16(const unsigned __int32)	mask[]={0x7fffffff,0x7fffffff,0x7fffffff,0x7fffffff};
#else
    static ATTRIBUTE_ALIGNED16(const unsigned int)	mask[]={0x7fffffff,0x7fffffff,0x7fffffff,0x00000000 /*0x7fffffff*/};
#endif
	///@todo: the intrinsic version is 11% slower
#if DBVT_USE_INTRINSIC_SSE

	union btSSEUnion ///NOTE: if we use more intrinsics, move btSSEUnion into the LinearMath directory
	{
	   __m128		ssereg;
	   float		floats[4];
	   int			ints[4];
	};

	__m128	omi(_mm_load_ps(o.mi));
	omi=_mm_add_ps(omi,_mm_load_ps(o.mx));
	__m128	ami(_mm_load_ps(a.mi));
	ami=_mm_add_ps(ami,_mm_load_ps(a.mx));
	ami=_mm_sub_ps(ami,omi);
	ami=_mm_and_ps(ami,_mm_load_ps((const float*)mask));
	__m128	bmi(_mm_load_ps(b.mi));
	bmi=_mm_add_ps(bmi,_mm_load_ps(b.mx));
	bmi=_mm_sub_ps(bmi,omi);
	bmi=_mm_and_ps(bmi,_mm_load_ps((const float*)mask));
	__m128	t0(_mm_movehl_ps(ami,ami));
	ami=_mm_add_ps(ami,t0);
	ami=_mm_add_ss(ami,_mm_shuffle_ps(ami,ami,1));
	__m128 t1(_mm_movehl_ps(bmi,bmi));
	bmi=_mm_add_ps(bmi,t1);
	bmi=_mm_add_ss(bmi,_mm_shuffle_ps(bmi,bmi,1));

	btSSEUnion tmp;
	tmp.ssereg = _mm_cmple_ss(bmi,ami);
	return tmp.ints[0]&1;

#else
	ATTRIBUTE_ALIGNED16(__int32	r[1]);
	__asm
	{
		mov		eax,o
			mov		ecx,a
			mov		edx,b
			movaps	xmm0,[eax]
		movaps	xmm5,mask
			addps	xmm0,[eax+16]
		movaps	xmm1,[ecx]
		movaps	xmm2,[edx]
		addps	xmm1,[ecx+16]
		addps	xmm2,[edx+16]
		subps	xmm1,xmm0
			subps	xmm2,xmm0
			andps	xmm1,xmm5
			andps	xmm2,xmm5
			movhlps	xmm3,xmm1
			movhlps	xmm4,xmm2
			addps	xmm1,xmm3
			addps	xmm2,xmm4
			pshufd	xmm3,xmm1,1
			pshufd	xmm4,xmm2,1
			addss	xmm1,xmm3
			addss	xmm2,xmm4
			cmpless	xmm2,xmm1
			movss	r,xmm2
	}
	return(r[0]&1);
#endif
#else
	return(Proximity(o,a)<Proximity(o,b)?0:1);
#endif
}

//
DBVT_INLINE void		Merge(	const btDbvtAabbMm& a,
							  const btDbvtAabbMm& b,
							  btDbvtAabbMm& r)
{
#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE
	__m128	ami(_mm_load_ps(a.mi));
	__m128	amx(_mm_load_ps(a.mx));
	__m128	bmi(_mm_load_ps(b.mi));
	__m128	bmx(_mm_load_ps(b.mx));
	ami=_mm_min_ps(ami,bmi);
	amx=_mm_max_ps(amx,bmx);
	_mm_store_ps(r.mi,ami);
	_mm_store_ps(r.mx,amx);
#else
	for(int i=0;i<3;++i)
	{
		if(a.mi[i]<b.mi[i]) r.mi[i]=a.mi[i]; else r.mi[i]=b.mi[i];
		if(a.mx[i]>b.mx[i]) r.mx[i]=a.mx[i]; else r.mx[i]=b.mx[i];
	}
#endif
}

//
DBVT_INLINE bool		NotEqual(	const btDbvtAabbMm& a,
								 const btDbvtAabbMm& b)
{
	return(	(a.mi.x()!=b.mi.x())||
		(a.mi.y()!=b.mi.y())||
		(a.mi.z()!=b.mi.z())||
		(a.mx.x()!=b.mx.x())||
		(a.mx.y()!=b.mx.y())||
		(a.mx.z()!=b.mx.z()));
}

//
// Inline's
//

//
DBVT_PREFIX
inline void		btDbvt::enumNodes(	const btDbvtNode* root,
								  DBVT_IPOLICY)
{
	DBVT_CHECKTYPE
		policy.Process(root);
	if(root->isinternal())
	{
		enumNodes(root->childs[0],policy);
		enumNodes(root->childs[1],policy);
	}
}

//
DBVT_PREFIX
inline void		btDbvt::enumLeaves(	const btDbvtNode* root,
								   DBVT_IPOLICY)
{
	DBVT_CHECKTYPE
		if(root->isinternal())
		{
			enumLeaves(root->childs[0],policy);
			enumLeaves(root->childs[1],policy);
		}
		else
		{
			policy.Process(root);
		}
}

//
DBVT_PREFIX
inline void		btDbvt::collideTT(	const btDbvtNode* root0,
								  const btDbvtNode* root1,
								  DBVT_IPOLICY)
{
	DBVT_CHECKTYPE
		if(root0&&root1)
		{
			int								depth=1;
			int								treshold=DOUBLE_STACKSIZE-4;
			btAlignedObjectArray<sStkNN>	stkStack;
			stkStack.resize(DOUBLE_STACKSIZE);
			stkStack[0]=sStkNN(root0,root1);
			do	{
				sStkNN	p=stkStack[--depth];
				if(depth>treshold)
				{
					stkStack.resize(stkStack.size()*2);
					treshold=stkStack.size()-4;
				}
				if(p.a==p.b)
				{
					if(p.a->isinternal())
					{
						stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[0]);
						stkStack[depth++]=sStkNN(p.a->childs[1],p.a->childs[1]);
						stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[1]);
					}
				}
				else if(Intersect(p.a->volume,p.b->volume))
				{
					if(p.a->isinternal())
					{
						if(p.b->isinternal())
						{
							stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]);
							stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]);
							stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]);
							stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]);
						}
						else
						{
							stkStack[depth++]=sStkNN(p.a->childs[0],p.b);
							stkStack[depth++]=sStkNN(p.a->childs[1],p.b);
						}
					}
					else
					{
						if(p.b->isinternal())
						{
							stkStack[depth++]=sStkNN(p.a,p.b->childs[0]);
							stkStack[depth++]=sStkNN(p.a,p.b->childs[1]);
						}
						else
						{
							policy.Process(p.a,p.b);
						}
					}
				}
			} while(depth);
		}
}

DBVT_PREFIX
inline void		btDbvt::collideTTpersistentStack(	const btDbvtNode* root0,
								  const btDbvtNode* root1,
								  DBVT_IPOLICY)
{
	DBVT_CHECKTYPE
		if(root0&&root1)
		{
			int								depth=1;
			int								treshold=DOUBLE_STACKSIZE-4;

			m_stkStack.resize(DOUBLE_STACKSIZE);
			m_stkStack[0]=sStkNN(root0,root1);
			do	{
				sStkNN	p=m_stkStack[--depth];
				if(depth>treshold)
				{
					m_stkStack.resize(m_stkStack.size()*2);
					treshold=m_stkStack.size()-4;
				}
				if(p.a==p.b)
				{
					if(p.a->isinternal())
					{
						m_stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[0]);
						m_stkStack[depth++]=sStkNN(p.a->childs[1],p.a->childs[1]);
						m_stkStack[depth++]=sStkNN(p.a->childs[0],p.a->childs[1]);
					}
				}
				else if(Intersect(p.a->volume,p.b->volume))
				{
					if(p.a->isinternal())
					{
						if(p.b->isinternal())
						{
							m_stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]);
							m_stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]);
							m_stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]);
							m_stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]);
						}
						else
						{
							m_stkStack[depth++]=sStkNN(p.a->childs[0],p.b);
							m_stkStack[depth++]=sStkNN(p.a->childs[1],p.b);
						}
					}
					else
					{
						if(p.b->isinternal())
						{
							m_stkStack[depth++]=sStkNN(p.a,p.b->childs[0]);
							m_stkStack[depth++]=sStkNN(p.a,p.b->childs[1]);
						}
						else
						{
							policy.Process(p.a,p.b);
						}
					}
				}
			} while(depth);
		}
}

#if 0
//
DBVT_PREFIX
inline void		btDbvt::collideTT(	const btDbvtNode* root0,
								  const btDbvtNode* root1,
								  const btTransform& xform,
								  DBVT_IPOLICY)
{
	DBVT_CHECKTYPE
		if(root0&&root1)
		{
			int								depth=1;
			int								treshold=DOUBLE_STACKSIZE-4;
			btAlignedObjectArray<sStkNN>	stkStack;
			stkStack.resize(DOUBLE_STACKSIZE);
			stkStack[0]=sStkNN(root0,root1);
			do	{
				sStkNN	p=stkStack[--depth];
				if(Intersect(p.a->volume,p.b->volume,xform))
				{
					if(depth>treshold)
					{
						stkStack.resize(stkStack.size()*2);
						treshold=stkStack.size()-4;
					}
					if(p.a->isinternal())
					{
						if(p.b->isinternal())
						{
							stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]);
							stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]);
							stkStack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]);
							stkStack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]);
						}
						else
						{
							stkStack[depth++]=sStkNN(p.a->childs[0],p.b);
							stkStack[depth++]=sStkNN(p.a->childs[1],p.b);
						}
					}
					else
					{
						if(p.b->isinternal())
						{
							stkStack[depth++]=sStkNN(p.a,p.b->childs[0]);
							stkStack[depth++]=sStkNN(p.a,p.b->childs[1]);
						}
						else
						{
							policy.Process(p.a,p.b);
						}
					}
				}
			} while(depth);
		}
}
//
DBVT_PREFIX
inline void		btDbvt::collideTT(	const btDbvtNode* root0,
								  const btTransform& xform0,
								  const btDbvtNode* root1,
								  const btTransform& xform1,
								  DBVT_IPOLICY)
{
	const btTransform	xform=xform0.inverse()*xform1;
	collideTT(root0,root1,xform,policy);
}
#endif

DBVT_PREFIX
inline void		btDbvt::collideTV(	const btDbvtNode* root,
								  const btDbvtVolume& vol,
								  DBVT_IPOLICY) const
{
	DBVT_CHECKTYPE
	if(root)
	{
		ATTRIBUTE_ALIGNED16(btDbvtVolume)		volume(vol);
		btAlignedObjectArray<const btDbvtNode*>	stack;
		stack.resize(0);
#ifndef BT_DISABLE_STACK_TEMP_MEMORY
		char tempmemory[SIMPLE_STACKSIZE*sizeof(const btDbvtNode*)];
		stack.initializeFromBuffer(tempmemory, 0, SIMPLE_STACKSIZE);
#else
		stack.reserve(SIMPLE_STACKSIZE);
#endif //BT_DISABLE_STACK_TEMP_MEMORY

		stack.push_back(root);
		do	{
			const btDbvtNode*	n=stack[stack.size()-1];
			stack.pop_back();
			if(Intersect(n->volume,volume))
			{
				if(n->isinternal())
				{
					stack.push_back(n->childs[0]);
					stack.push_back(n->childs[1]);
				}
				else
				{
					policy.Process(n);
				}
			}
		} while(stack.size()>0);
	}
}

//
DBVT_PREFIX
inline void		btDbvt::collideTVNoStackAlloc(	const btDbvtNode* root,
											 const btDbvtVolume& vol,
											 btNodeStack& stack,
											 DBVT_IPOLICY) const
{
	DBVT_CHECKTYPE
	if(root)
	{
		ATTRIBUTE_ALIGNED16(btDbvtVolume)		volume(vol);
		stack.resize(0);
		stack.reserve(SIMPLE_STACKSIZE);
		stack.push_back(root);
		do	{
			const btDbvtNode*	n=stack[stack.size()-1];
			stack.pop_back();
			if(Intersect(n->volume,volume))
			{
				if(n->isinternal())
				{
					stack.push_back(n->childs[0]);
					stack.push_back(n->childs[1]);
				}
				else
				{
					policy.Process(n);
				}
			}
		} while(stack.size()>0);
	}
}

DBVT_PREFIX
inline void		btDbvt::rayTestInternal(	const btDbvtNode* root,
								const btVector3& rayFrom,
								const btVector3& rayTo,
								const btVector3& rayDirectionInverse,
								unsigned int signs[3],
								btScalar lambda_max,
								const btVector3& aabbMin,
								const btVector3& aabbMax,
                                btAlignedObjectArray<const btDbvtNode*>& stack,
                                DBVT_IPOLICY ) const
{
        (void) rayTo;
	DBVT_CHECKTYPE
	if(root)
	{
		btVector3 resultNormal;

		int								depth=1;
		int								treshold=DOUBLE_STACKSIZE-2;
		stack.resize(DOUBLE_STACKSIZE);
		stack[0]=root;
		btVector3 bounds[2];
		do
		{
			const btDbvtNode*	node=stack[--depth];
			bounds[0] = node->volume.Mins()-aabbMax;
			bounds[1] = node->volume.Maxs()-aabbMin;
			btScalar tmin=1.f,lambda_min=0.f;
			unsigned int result1=false;
			result1 = btRayAabb2(rayFrom,rayDirectionInverse,signs,bounds,tmin,lambda_min,lambda_max);
			if(result1)
			{
				if(node->isinternal())
				{
					if(depth>treshold)
					{
						stack.resize(stack.size()*2);
						treshold=stack.size()-2;
					}
					stack[depth++]=node->childs[0];
					stack[depth++]=node->childs[1];
				}
				else
				{
					policy.Process(node);
				}
			}
		} while(depth);
	}
}

//
DBVT_PREFIX
inline void		btDbvt::rayTest(	const btDbvtNode* root,
								const btVector3& rayFrom,
								const btVector3& rayTo,
								DBVT_IPOLICY)
{
	DBVT_CHECKTYPE
		if(root)
		{
			btVector3 rayDir = (rayTo-rayFrom);
			rayDir.normalize ();

			///what about division by zero? --> just set rayDirection[i] to INF/BT_LARGE_FLOAT
			btVector3 rayDirectionInverse;
			rayDirectionInverse[0] = rayDir[0] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[0];
			rayDirectionInverse[1] = rayDir[1] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[1];
			rayDirectionInverse[2] = rayDir[2] == btScalar(0.0) ? btScalar(BT_LARGE_FLOAT) : btScalar(1.0) / rayDir[2];
			unsigned int signs[3] = { rayDirectionInverse[0] < 0.0, rayDirectionInverse[1] < 0.0, rayDirectionInverse[2] < 0.0};

			btScalar lambda_max = rayDir.dot(rayTo-rayFrom);

			btVector3 resultNormal;

			btAlignedObjectArray<const btDbvtNode*>	stack;

			int								depth=1;
			int								treshold=DOUBLE_STACKSIZE-2;

			char tempmemory[DOUBLE_STACKSIZE * sizeof(const btDbvtNode*)];
#ifndef BT_DISABLE_STACK_TEMP_MEMORY
			stack.initializeFromBuffer(tempmemory, DOUBLE_STACKSIZE, DOUBLE_STACKSIZE);
#else//BT_DISABLE_STACK_TEMP_MEMORY
			stack.resize(DOUBLE_STACKSIZE);
#endif //BT_DISABLE_STACK_TEMP_MEMORY
			stack[0]=root;
			btVector3 bounds[2];
			do	{
				const btDbvtNode*	node=stack[--depth];

				bounds[0] = node->volume.Mins();
				bounds[1] = node->volume.Maxs();

				btScalar tmin=1.f,lambda_min=0.f;
				unsigned int result1 = btRayAabb2(rayFrom,rayDirectionInverse,signs,bounds,tmin,lambda_min,lambda_max);

#ifdef COMPARE_BTRAY_AABB2
				btScalar param=1.f;
				bool result2 = btRayAabb(rayFrom,rayTo,node->volume.Mins(),node->volume.Maxs(),param,resultNormal);
				btAssert(result1 == result2);
#endif //TEST_BTRAY_AABB2

				if(result1)
				{
					if(node->isinternal())
					{
						if(depth>treshold)
						{
							stack.resize(stack.size()*2);
							treshold=stack.size()-2;
						}
						stack[depth++]=node->childs[0];
						stack[depth++]=node->childs[1];
					}
					else
					{
						policy.Process(node);
					}
				}
			} while(depth);

		}
}

//
DBVT_PREFIX
inline void		btDbvt::collideKDOP(const btDbvtNode* root,
									const btVector3* normals,
									const btScalar* offsets,
									int count,
									DBVT_IPOLICY)
{
	DBVT_CHECKTYPE
		if(root)
		{
			const int						inside=(1<<count)-1;
			btAlignedObjectArray<sStkNP>	stack;
			int								signs[sizeof(unsigned)*8];
			btAssert(count<int (sizeof(signs)/sizeof(signs[0])));
			for(int i=0;i<count;++i)
			{
				signs[i]=	((normals[i].x()>=0)?1:0)+
					((normals[i].y()>=0)?2:0)+
					((normals[i].z()>=0)?4:0);
			}
			stack.reserve(SIMPLE_STACKSIZE);
			stack.push_back(sStkNP(root,0));
			do	{
				sStkNP	se=stack[stack.size()-1];
				bool	out=false;
				stack.pop_back();
				for(int i=0,j=1;(!out)&&(i<count);++i,j<<=1)
				{
					if(0==(se.mask&j))
					{
						const int	side=se.node->volume.Classify(normals[i],offsets[i],signs[i]);
						switch(side)
						{
						case	-1:	out=true;break;
						case	+1:	se.mask|=j;break;
						}
					}
				}
				if(!out)
				{
					if((se.mask!=inside)&&(se.node->isinternal()))
					{
						stack.push_back(sStkNP(se.node->childs[0],se.mask));
						stack.push_back(sStkNP(se.node->childs[1],se.mask));
					}
					else
					{
						if(policy.AllLeaves(se.node)) enumLeaves(se.node,policy);
					}
				}
			} while(stack.size());
		}
}

//
DBVT_PREFIX
inline void		btDbvt::collideOCL(	const btDbvtNode* root,
								   const btVector3* normals,
								   const btScalar* offsets,
								   const btVector3& sortaxis,
								   int count,
								   DBVT_IPOLICY,
								   bool fsort)
{
	DBVT_CHECKTYPE
		if(root)
		{
			const unsigned					srtsgns=(sortaxis[0]>=0?1:0)+
				(sortaxis[1]>=0?2:0)+
				(sortaxis[2]>=0?4:0);
			const int						inside=(1<<count)-1;
			btAlignedObjectArray<sStkNPS>	stock;
			btAlignedObjectArray<int>		ifree;
			btAlignedObjectArray<int>		stack;
			int								signs[sizeof(unsigned)*8];
			btAssert(count<int (sizeof(signs)/sizeof(signs[0])));
			for(int i=0;i<count;++i)
			{
				signs[i]=	((normals[i].x()>=0)?1:0)+
					((normals[i].y()>=0)?2:0)+
					((normals[i].z()>=0)?4:0);
			}
			stock.reserve(SIMPLE_STACKSIZE);
			stack.reserve(SIMPLE_STACKSIZE);
			ifree.reserve(SIMPLE_STACKSIZE);
			stack.push_back(allocate(ifree,stock,sStkNPS(root,0,root->volume.ProjectMinimum(sortaxis,srtsgns))));
			do	{
				const int	id=stack[stack.size()-1];
				sStkNPS		se=stock[id];
				stack.pop_back();ifree.push_back(id);
				if(se.mask!=inside)
				{
					bool	out=false;
					for(int i=0,j=1;(!out)&&(i<count);++i,j<<=1)
					{
						if(0==(se.mask&j))
						{
							const int	side=se.node->volume.Classify(normals[i],offsets[i],signs[i]);
							switch(side)
							{
							case	-1:	out=true;break;
							case	+1:	se.mask|=j;break;
							}
						}
					}
					if(out) continue;
				}
				if(policy.Descent(se.node))
				{
					if(se.node->isinternal())
					{
						const btDbvtNode* pns[]={	se.node->childs[0],se.node->childs[1]};
						sStkNPS		nes[]={	sStkNPS(pns[0],se.mask,pns[0]->volume.ProjectMinimum(sortaxis,srtsgns)),
							sStkNPS(pns[1],se.mask,pns[1]->volume.ProjectMinimum(sortaxis,srtsgns))};
						const int	q=nes[0].value<nes[1].value?1:0;
						int			j=stack.size();
						if(fsort&&(j>0))
						{
							/* Insert 0	*/
							j=nearest(&stack[0],&stock[0],nes[q].value,0,stack.size());
							stack.push_back(0);

							//void * memmove ( void * destination, const void * source, size_t num );

#if DBVT_USE_MEMMOVE
                     {
                     int num_items_to_move = stack.size()-1-j;
                     if(num_items_to_move > 0)
                        memmove(&stack[j+1],&stack[j],sizeof(int)*num_items_to_move);
                     }
#else
                     for(int k=stack.size()-1;k>j;--k) {
								stack[k]=stack[k-1];
                     }
#endif
							stack[j]=allocate(ifree,stock,nes[q]);
							/* Insert 1	*/
							j=nearest(&stack[0],&stock[0],nes[1-q].value,j,stack.size());
							stack.push_back(0);
#if DBVT_USE_MEMMOVE
                     {
                     int num_items_to_move = stack.size()-1-j;
                     if(num_items_to_move > 0)
                        memmove(&stack[j+1],&stack[j],sizeof(int)*num_items_to_move);
                     }
#else
                     for(int k=stack.size()-1;k>j;--k) {
                        stack[k]=stack[k-1];
                     }
#endif
							stack[j]=allocate(ifree,stock,nes[1-q]);
						}
						else
						{
							stack.push_back(allocate(ifree,stock,nes[q]));
							stack.push_back(allocate(ifree,stock,nes[1-q]));
						}
					}
					else
					{
						policy.Process(se.node,se.value);
					}
				}
			} while(stack.size());
		}
}

//
DBVT_PREFIX
inline void		btDbvt::collideTU(	const btDbvtNode* root,
								  DBVT_IPOLICY)
{
	DBVT_CHECKTYPE
		if(root)
		{
			btAlignedObjectArray<const btDbvtNode*>	stack;
			stack.reserve(SIMPLE_STACKSIZE);
			stack.push_back(root);
			do	{
				const btDbvtNode*	n=stack[stack.size()-1];
				stack.pop_back();
				if(policy.Descent(n))
				{
					if(n->isinternal())
					{ stack.push_back(n->childs[0]);stack.push_back(n->childs[1]); }
					else
					{ policy.Process(n); }
				}
			} while(stack.size()>0);
		}
}

//
// PP Cleanup
//

#undef DBVT_USE_MEMMOVE
#undef DBVT_USE_TEMPLATE
#undef DBVT_VIRTUAL_DTOR
#undef DBVT_VIRTUAL
#undef DBVT_PREFIX
#undef DBVT_IPOLICY
#undef DBVT_CHECKTYPE
#undef DBVT_IMPL_GENERIC
#undef DBVT_IMPL_SSE
#undef DBVT_USE_INTRINSIC_SSE
#undef DBVT_SELECT_IMPL
#undef DBVT_MERGE_IMPL
#undef DBVT_INT0_IMPL

#endif


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_COLLISION_ALGORITHM_H
#define BT_COLLISION_ALGORITHM_H

#include "LinearMath/btScalar.h"
#include "LinearMath/btAlignedObjectArray.h"

struct btBroadphaseProxy;
class btDispatcher;
class btManifoldResult;
class btCollisionObject;
struct btCollisionObjectWrapper;
struct btDispatcherInfo;
class	btPersistentManifold;

typedef btAlignedObjectArray<btPersistentManifold*>	btManifoldArray;

struct btCollisionAlgorithmConstructionInfo
{
	btCollisionAlgorithmConstructionInfo()
		:m_dispatcher1(0),
		m_manifold(0)
	{
	}
	btCollisionAlgorithmConstructionInfo(btDispatcher* dispatcher,int temp)
		:m_dispatcher1(dispatcher)
	{
		(void)temp;
	}

	btDispatcher*	m_dispatcher1;
	btPersistentManifold*	m_manifold;

//	int	getDispatcherId();

};

///btCollisionAlgorithm is an collision interface that is compatible with the Broadphase and btDispatcher.
///It is persistent over frames
class btCollisionAlgorithm
{

protected:

	btDispatcher*	m_dispatcher;

protected:
//	int	getDispatcherId();

public:

	btCollisionAlgorithm() {};

	btCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci);

	virtual ~btCollisionAlgorithm() {};

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) = 0;

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) = 0;

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray) = 0;
};

#endif //BT_COLLISION_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_OVERLAPPING_PAIR_CACHE_H
#define BT_OVERLAPPING_PAIR_CACHE_H

#include "btBroadphaseInterface.h"
#include "btBroadphaseProxy.h"
#include "btOverlappingPairCallback.h"

#include "LinearMath/btAlignedObjectArray.h"
class btDispatcher;

typedef btAlignedObjectArray<btBroadphasePair> btBroadphasePairArray;

struct btOverlapCallback
{
	virtual ~btOverlapCallback() { }

	/// return true for deletion of the pair
	virtual bool processOverlap(btBroadphasePair& pair) = 0;
};

struct btOverlapFilterCallback
{
	virtual ~btOverlapFilterCallback() {}

	/// return true when pairs need collision
	virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) const = 0;
};

extern int gRemovePairs;
extern int gAddedPairs;
extern int gFindPairs;

const int BT_NULL_PAIR = 0xffffffff;

/// The btOverlappingPairCache provides an interface for overlapping pair
/// management (add, remove, storage), used by the btBroadphaseInterface
/// broadphases. The btHashedOverlappingPairCache and
/// btSortedOverlappingPairCache classes are two implementations.
class btOverlappingPairCache : public btOverlappingPairCallback
{
public:
	/// this is needed so we can get to the derived class destructor
	virtual ~btOverlappingPairCache() {}

	virtual btBroadphasePair*       getOverlappingPairArrayPtr()                                               = 0;
	virtual const btBroadphasePair* getOverlappingPairArrayPtr() const                                         = 0;
	virtual btBroadphasePairArray&  getOverlappingPairArray()                                                  = 0;
	virtual void                    cleanOverlappingPair(btBroadphasePair& pair, btDispatcher* dispatcher)     = 0;
	virtual int                     getNumOverlappingPairs() const                                             = 0;
	virtual void                    cleanProxyFromPairs(btBroadphaseProxy* proxy, btDispatcher* dispatcher)    = 0;
	virtual void                    setOverlapFilterCallback(btOverlapFilterCallback* callback)                = 0;
	virtual void                    processAllOverlappingPairs(btOverlapCallback*, btDispatcher* dispatcher)   = 0;
	virtual btBroadphasePair*       findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1)             = 0;
	virtual bool                    hasDeferredRemoval()                                                       = 0;
	virtual void                    setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback) = 0;
	virtual void                    sortOverlappingPairs(btDispatcher* dispatcher)                             = 0;
};

/// Hash-space based Pair Cache, thanks to Erin Catto, Box2D,
/// http://www.box2d.org, and Pierre Terdiman, Codercorner,
/// http://codercorner.com
ATTRIBUTE_ALIGNED16(class) btHashedOverlappingPairCache : public btOverlappingPairCache
{
	btBroadphasePairArray    m_overlappingPairArray;
	btOverlapFilterCallback* m_overlapFilterCallback;

protected:
	btAlignedObjectArray<int>  m_hashTable;
	btAlignedObjectArray<int>  m_next;
	btOverlappingPairCallback* m_ghostPairCallback;

public:
	BT_DECLARE_ALIGNED_ALLOCATOR();

	btHashedOverlappingPairCache();
	virtual ~btHashedOverlappingPairCache();

	void          removeOverlappingPairsContainingProxy(btBroadphaseProxy * proxy, btDispatcher * dispatcher);
	virtual void* removeOverlappingPair(btBroadphaseProxy * proxy0, btBroadphaseProxy * proxy1, btDispatcher * dispatcher);

	SIMD_FORCE_INLINE bool needsBroadphaseCollision(btBroadphaseProxy * proxy0, btBroadphaseProxy * proxy1) const
	{
		if (m_overlapFilterCallback)
			return m_overlapFilterCallback->needBroadphaseCollision(proxy0, proxy1);

		bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
		collides      = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);

		return collides;
	}

	// Add a pair and return the new pair. If the pair already exists,
	// no new pair is created and the old one is returned.
	virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy * proxy0, btBroadphaseProxy * proxy1)
	{
		gAddedPairs++;

		if (!needsBroadphaseCollision(proxy0, proxy1))
			return 0;

		return internalAddPair(proxy0, proxy1);
	}

	void         cleanProxyFromPairs(btBroadphaseProxy * proxy, btDispatcher * dispatcher);
	virtual void processAllOverlappingPairs(btOverlapCallback*, btDispatcher * dispatcher);

	virtual btBroadphasePair*    getOverlappingPairArrayPtr() { return &m_overlappingPairArray[0]; }
	const btBroadphasePair*      getOverlappingPairArrayPtr() const { return &m_overlappingPairArray[0]; }
	btBroadphasePairArray&       getOverlappingPairArray() { return m_overlappingPairArray; }
	const btBroadphasePairArray& getOverlappingPairArray() const { return m_overlappingPairArray; }

	void              cleanOverlappingPair(btBroadphasePair & pair, btDispatcher * dispatcher);
	btBroadphasePair* findPair(btBroadphaseProxy * proxy0, btBroadphaseProxy * proxy1);
	int               GetCount() const { return m_overlappingPairArray.size(); }

	//btBroadphasePair* GetPairs() { return m_pairs; }

	btOverlapFilterCallback* getOverlapFilterCallback() { return m_overlapFilterCallback; }
	void                     setOverlapFilterCallback(btOverlapFilterCallback * callback) { m_overlapFilterCallback = callback; }
	int                      getNumOverlappingPairs() const { return m_overlappingPairArray.size(); }

private:
	btBroadphasePair* internalAddPair(btBroadphaseProxy * proxy0, btBroadphaseProxy * proxy1);
	void              growTables();

	SIMD_FORCE_INLINE bool equalsPair(const btBroadphasePair& pair, int proxyId1, int proxyId2)
	{
		return pair.m_pProxy0->getUid() == proxyId1 && pair.m_pProxy1->getUid() == proxyId2;
	}

	/*
	// Thomas Wang's hash, see: http://www.concentric.net/~Ttwang/tech/inthash.htm
	// This assumes proxyId1 and proxyId2 are 16-bit.
	SIMD_FORCE_INLINE int getHash(int proxyId1, int proxyId2)
	{
		int key = (proxyId2 << 16) | proxyId1;
		key = ~key + (key << 15);
		key = key ^ (key >> 12);
		key = key + (key << 2);
		key = key ^ (key >> 4);
		key = key * 2057;
		key = key ^ (key >> 16);
		return key;
	}
	*/

	SIMD_FORCE_INLINE unsigned int getHash(unsigned int proxyId1, unsigned int proxyId2)
	{
		unsigned int key = proxyId1 | (proxyId2 << 16);
		// Thomas Wang's hash

		key += ~(key << 15);
		key ^= (key >> 10);
		key += (key << 3);
		key ^= (key >> 6);
		key += ~(key << 11);
		key ^= (key >> 16);
		return key;
	}

	SIMD_FORCE_INLINE btBroadphasePair* internalFindPair(btBroadphaseProxy * proxy0, btBroadphaseProxy * proxy1, int hash)
	{
		int proxyId1 = proxy0->getUid();
		int proxyId2 = proxy1->getUid();
#if 0 // wrong, 'equalsPair' use unsorted uids, copy-past devil striked again. Nat.
		if (proxyId1 > proxyId2)
			btSwap(proxyId1, proxyId2);
#endif

		int index = m_hashTable[hash];

		while (index != BT_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyId1, proxyId2) == false)
		{
			index = m_next[index];
		}

		if (index == BT_NULL_PAIR)
		{
			return NULL;
		}

		btAssert(index < m_overlappingPairArray.size());

		return &m_overlappingPairArray[index];
	}

	virtual bool hasDeferredRemoval()
	{
		return false;
	}

	virtual void setInternalGhostPairCallback(btOverlappingPairCallback * ghostPairCallback)
	{
		m_ghostPairCallback = ghostPairCallback;
	}

	virtual void sortOverlappingPairs(btDispatcher * dispatcher);
};

///btSortedOverlappingPairCache maintains the objects with overlapping AABB
///Typically managed by the Broadphase, Axis3Sweep or btSimpleBroadphase
class btSortedOverlappingPairCache : public btOverlappingPairCache
{
protected:
	//avoid brute-force finding all the time
	btBroadphasePairArray m_overlappingPairArray;

	//during the dispatch, check that user doesn't destroy/create proxy
	bool m_blockedForChanges;

	///by default, do the removal during the pair traversal
	bool m_hasDeferredRemoval;

	//if set, use the callback instead of the built in filter in needBroadphaseCollision
	btOverlapFilterCallback* m_overlapFilterCallback;

	btOverlappingPairCallback* m_ghostPairCallback;

public:
	btSortedOverlappingPairCache();
	virtual ~btSortedOverlappingPairCache();

	virtual void      processAllOverlappingPairs(btOverlapCallback*, btDispatcher* dispatcher);
	void*             removeOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1, btDispatcher* dispatcher);
	void              cleanOverlappingPair(btBroadphasePair& pair, btDispatcher* dispatcher);
	btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1);
	btBroadphasePair* findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1);
	void              cleanProxyFromPairs(btBroadphaseProxy* proxy, btDispatcher* dispatcher);
	void              removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy, btDispatcher* dispatcher);

	inline bool needsBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) const
	{
		if (m_overlapFilterCallback)
			return m_overlapFilterCallback->needBroadphaseCollision(proxy0, proxy1);

		bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
		collides      = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);

		return collides;
	}

	btBroadphasePairArray&       getOverlappingPairArray() { return m_overlappingPairArray; }
	const btBroadphasePairArray& getOverlappingPairArray() const { return m_overlappingPairArray; }
	btBroadphasePair*            getOverlappingPairArrayPtr() { return &m_overlappingPairArray[0]; }
	const btBroadphasePair*      getOverlappingPairArrayPtr() const { return &m_overlappingPairArray[0]; }
	int                          getNumOverlappingPairs() const { return m_overlappingPairArray.size(); }
	btOverlapFilterCallback*     getOverlapFilterCallback() { return m_overlapFilterCallback; }
	void                         setOverlapFilterCallback(btOverlapFilterCallback* callback) { m_overlapFilterCallback = callback; }
	virtual bool                 hasDeferredRemoval() { return m_hasDeferredRemoval; }
	virtual void                 setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback) { m_ghostPairCallback = ghostPairCallback; }

	virtual void sortOverlappingPairs(btDispatcher* dispatcher);
};

/// btNullPairCache skips add/removal of overlapping pairs. Useful for
/// benchmarking and unit testing.
class btNullPairCache : public btOverlappingPairCache
{
	btBroadphasePairArray m_overlappingPairArray;

public:
	virtual btBroadphasePair* getOverlappingPairArrayPtr() { return &m_overlappingPairArray[0]; }
	const btBroadphasePair*   getOverlappingPairArrayPtr() const { return &m_overlappingPairArray[0]; }
	btBroadphasePairArray&    getOverlappingPairArray() { return m_overlappingPairArray; }
	virtual void              cleanOverlappingPair(btBroadphasePair& /*pair*/, btDispatcher* /*dispatcher*/) {}
	virtual int               getNumOverlappingPairs() const { return 0; }
	virtual void              cleanProxyFromPairs(btBroadphaseProxy* /*proxy*/, btDispatcher* /*dispatcher*/) {}
	virtual void              setOverlapFilterCallback(btOverlapFilterCallback* /*callback*/) {}
	virtual void              processAllOverlappingPairs(btOverlapCallback*, btDispatcher* /*dispatcher*/) {}
	virtual btBroadphasePair* findPair(btBroadphaseProxy* /*proxy0*/, btBroadphaseProxy* /*proxy1*/) { return 0; }
	virtual bool              hasDeferredRemoval() { return true; }
	virtual void              setInternalGhostPairCallback(btOverlappingPairCallback* /* ghostPairCallback */) {}
	virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* /*proxy0*/, btBroadphaseProxy* /*proxy1*/) { return 0; }
	virtual void*             removeOverlappingPair(btBroadphaseProxy* /*proxy0*/, btBroadphaseProxy* /*proxy1*/, btDispatcher* /*dispatcher*/) { return 0; }
	virtual void              removeOverlappingPairsContainingProxy(btBroadphaseProxy* /*proxy0*/, btDispatcher* /*dispatcher*/) {}
	virtual void              sortOverlappingPairs(btDispatcher* dispatcher) { (void) dispatcher; }
};

#endif //BT_OVERLAPPING_PAIR_CACHE_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_BROADPHASE_PROXY_H
#define BT_BROADPHASE_PROXY_H

#include "LinearMath/btScalar.h" //for SIMD_FORCE_INLINE
#include "LinearMath/btVector3.h"
#include "LinearMath/btAlignedAllocator.h"

/// btDispatcher uses these types
/// IMPORTANT NOTE:The types are ordered polyhedral, implicit convex and concave
/// to facilitate type checking
/// CUSTOM_POLYHEDRAL_SHAPE_TYPE,CUSTOM_CONVEX_SHAPE_TYPE and
/// CUSTOM_CONCAVE_SHAPE_TYPE can be used to extend Bullet without modifying
/// source code
enum BroadphaseNativeTypes
{
	// polyhedral convex shapes
	BOX_SHAPE_PROXYTYPE,
	TRIANGLE_SHAPE_PROXYTYPE,
	TETRAHEDRAL_SHAPE_PROXYTYPE,
	CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE,
	CONVEX_HULL_SHAPE_PROXYTYPE,
	CONVEX_POINT_CLOUD_SHAPE_PROXYTYPE,
	CUSTOM_POLYHEDRAL_SHAPE_TYPE,

	// implicit convex shapes
	IMPLICIT_CONVEX_SHAPES_START_HERE,
	SPHERE_SHAPE_PROXYTYPE,
	MULTI_SPHERE_SHAPE_PROXYTYPE,
	CAPSULE_SHAPE_PROXYTYPE,
	CONE_SHAPE_PROXYTYPE,
	CONVEX_SHAPE_PROXYTYPE,
	CYLINDER_SHAPE_PROXYTYPE,
	UNIFORM_SCALING_SHAPE_PROXYTYPE,
	MINKOWSKI_SUM_SHAPE_PROXYTYPE,
	MINKOWSKI_DIFFERENCE_SHAPE_PROXYTYPE,
	BOX_2D_SHAPE_PROXYTYPE,
	CONVEX_2D_SHAPE_PROXYTYPE,
	CUSTOM_CONVEX_SHAPE_TYPE,

	// concave shapes
	CONCAVE_SHAPES_START_HERE,

	// keep all the convex shapetype below here, for the check IsConvexShape in
	// broadphase proxy!

	TRIANGLE_MESH_SHAPE_PROXYTYPE,
	SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE,

	// used for demo integration FAST/Swift collision library and Bullet
	FAST_CONCAVE_MESH_PROXYTYPE,

	// terrain
	TERRAIN_SHAPE_PROXYTYPE,

	// Used for GIMPACT Trimesh integration
	GIMPACT_SHAPE_PROXYTYPE,

	// Multimaterial mesh
	MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE,

	EMPTY_SHAPE_PROXYTYPE,
	STATIC_PLANE_PROXYTYPE,
	CUSTOM_CONCAVE_SHAPE_TYPE,
	CONCAVE_SHAPES_END_HERE,
	COMPOUND_SHAPE_PROXYTYPE,
	SOFTBODY_SHAPE_PROXYTYPE,
	HFFLUID_SHAPE_PROXYTYPE,
	HFFLUID_BUOYANT_CONVEX_SHAPE_PROXYTYPE,
	INVALID_SHAPE_PROXYTYPE,

	MAX_BROADPHASE_COLLISION_TYPES
};

/// The btBroadphaseProxy is the main class that can be used with the Bullet
/// broadphases. It stores collision shape type information, collision filter
/// information and a client object, typically a btCollisionObject or
/// btRigidBody.
ATTRIBUTE_ALIGNED16(struct) btBroadphaseProxy
{
	BT_DECLARE_ALIGNED_ALLOCATOR();

	/// optional filtering to cull potential collisions
	enum CollisionFilterGroups
	{
		DefaultFilter   = 1,
		StaticFilter    = 2,
		KinematicFilter = 4,
		DebrisFilter    = 8,
		SensorTrigger   = 16,
		CharacterFilter = 32,
		AllFilter       = -1 // all bits sets: DefaultFilter | StaticFilter |
		                     // KinematicFilter | DebrisFilter | SensorTrigger
	};

	/// Usually the client btCollisionObject or Rigidbody class
	void* m_clientObject;

	int m_collisionFilterGroup;
	int m_collisionFilterMask;

	/// m_uniqueId is introduced for paircache. could get rid of this, by
	/// calculating the address offset etc.
	int m_uniqueId;

	btVector3 m_aabbMin;
	btVector3 m_aabbMax;

	SIMD_FORCE_INLINE int getUid() const { return m_uniqueId; }

	/// used for memory pools
	btBroadphaseProxy() : m_clientObject(0) { }

	btBroadphaseProxy(
	    const btVector3& aabbMin,
	    const btVector3& aabbMax,
	    void*            userPtr,
	    int              collisionFilterGroup,
	    int              collisionFilterMask)
	    : m_clientObject(userPtr),
	      m_collisionFilterGroup(collisionFilterGroup),
	      m_collisionFilterMask(collisionFilterMask),
	      m_aabbMin(aabbMin),
	      m_aabbMax(aabbMax)
	{
	}

	static SIMD_FORCE_INLINE bool isPolyhedral(int proxyType) { return (proxyType < IMPLICIT_CONVEX_SHAPES_START_HERE); }
	static SIMD_FORCE_INLINE bool isConvex(int proxyType) { return (proxyType < CONCAVE_SHAPES_START_HERE); }
	static SIMD_FORCE_INLINE bool isNonMoving(int proxyType) { return (isConcave(proxyType) && !(proxyType == GIMPACT_SHAPE_PROXYTYPE)); }
	static SIMD_FORCE_INLINE bool isConcave(int proxyType) { return ((proxyType > CONCAVE_SHAPES_START_HERE) && (proxyType < CONCAVE_SHAPES_END_HERE)); }
	static SIMD_FORCE_INLINE bool isCompound(int proxyType) { return (proxyType == COMPOUND_SHAPE_PROXYTYPE); }
	static SIMD_FORCE_INLINE bool isSoftBody(int proxyType) { return (proxyType == SOFTBODY_SHAPE_PROXYTYPE); }
	static SIMD_FORCE_INLINE bool isInfinite(int proxyType) { return (proxyType == STATIC_PLANE_PROXYTYPE); }
	static SIMD_FORCE_INLINE bool isConvex2d(int proxyType) { return (proxyType == BOX_2D_SHAPE_PROXYTYPE) || (proxyType == CONVEX_2D_SHAPE_PROXYTYPE); }
};

class btCollisionAlgorithm;
struct btBroadphaseProxy;

/// The btBroadphasePair class contains a pair of aabb-overlapping objects. A
/// btDispatcher can search a btCollisionAlgorithm that performs
/// exact/narrowphase collision detection on the actual collision shapes.
ATTRIBUTE_ALIGNED16(struct) btBroadphasePair
{
	btBroadphasePair()
	    : m_pProxy0(0),
	      m_pProxy1(0),
	      m_algorithm(0),
	      m_internalInfo1(0)
	{
	}

	BT_DECLARE_ALIGNED_ALLOCATOR();

	btBroadphasePair(const btBroadphasePair& other)
	    : m_pProxy0(other.m_pProxy0),
	      m_pProxy1(other.m_pProxy1),
	      m_algorithm(other.m_algorithm),
	      m_internalInfo1(other.m_internalInfo1)
	{
	}
	btBroadphasePair(btBroadphaseProxy & proxy0, btBroadphaseProxy & proxy1)
	{
		// keep them sorted, so the std::set operations work
		if (proxy0.m_uniqueId < proxy1.m_uniqueId)
		{
			m_pProxy0 = &proxy0;
			m_pProxy1 = &proxy1;
		} else
		{
			m_pProxy0 = &proxy1;
			m_pProxy1 = &proxy0;
		}

		m_algorithm     = 0;
		m_internalInfo1 = 0;
	}

	btBroadphaseProxy* m_pProxy0;
	btBroadphaseProxy* m_pProxy1;

	mutable btCollisionAlgorithm* m_algorithm;
	union {
		void* m_internalInfo1;
		int   m_internalTmpValue;
	}; //don't use this data, it will be removed in future version.
};

/*
//comparison for set operation, see Solid DT_Encounter
SIMD_FORCE_INLINE bool operator<(const btBroadphasePair& a, const btBroadphasePair& b)
{
    return a.m_pProxy0 < b.m_pProxy0 ||
        (a.m_pProxy0 == b.m_pProxy0 && a.m_pProxy1 < b.m_pProxy1);
}
*/

class btBroadphasePairSortPredicate
{
public:
	bool operator()(const btBroadphasePair& a, const btBroadphasePair& b) const
	{
		const int uidA0 = a.m_pProxy0 ? a.m_pProxy0->m_uniqueId : -1;
		const int uidB0 = b.m_pProxy0 ? b.m_pProxy0->m_uniqueId : -1;
		const int uidA1 = a.m_pProxy1 ? a.m_pProxy1->m_uniqueId : -1;
		const int uidB1 = b.m_pProxy1 ? b.m_pProxy1->m_uniqueId : -1;

		return uidA0 > uidB0 ||
		       (a.m_pProxy0 == b.m_pProxy0 && uidA1 > uidB1) ||
		       (a.m_pProxy0 == b.m_pProxy0 && a.m_pProxy1 == b.m_pProxy1 && a.m_algorithm > b.m_algorithm);
	}
};

SIMD_FORCE_INLINE bool operator==(const btBroadphasePair& a, const btBroadphasePair& b)
{
	return (a.m_pProxy0 == b.m_pProxy0) && (a.m_pProxy1 == b.m_pProxy1);
}

#endif //BT_BROADPHASE_PROXY_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_CONVEX_CONCAVE_COLLISION_ALGORITHM_H
#define BT_CONVEX_CONCAVE_COLLISION_ALGORITHM_H

#include "btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
#include "BulletCollision/CollisionShapes/btTriangleCallback.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
class btDispatcher;
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "btCollisionCreateFunc.h"

///For each triangle in the concave mesh that overlaps with the AABB of a convex (m_convexProxy), processTriangle is called.
ATTRIBUTE_ALIGNED16(class)  btConvexTriangleCallback : public btTriangleCallback
{

	btVector3	m_aabbMin;
	btVector3	m_aabbMax ;

	const btCollisionObjectWrapper* m_convexBodyWrap;
	const btCollisionObjectWrapper* m_triBodyWrap;

	btManifoldResult* m_resultOut;
	btDispatcher*	m_dispatcher;
	const btDispatcherInfo* m_dispatchInfoPtr;
	btScalar m_collisionMarginTriangle;

public:
	BT_DECLARE_ALIGNED_ALLOCATOR();

int	m_triangleCount;

	btPersistentManifold*	m_manifoldPtr;

	btConvexTriangleCallback(btDispatcher* dispatcher,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped);

	void	setTimeStepAndCounters(btScalar collisionMarginTriangle,const btDispatcherInfo& dispatchInfo,const btCollisionObjectWrapper* convexBodyWrap, const btCollisionObjectWrapper* triBodyWrap, btManifoldResult* resultOut);

	void	clearWrapperData()
	{
		m_convexBodyWrap = 0;
		m_triBodyWrap = 0;
	}
	virtual ~btConvexTriangleCallback();

	virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex);

	void clearCache();

	SIMD_FORCE_INLINE const btVector3& getAabbMin() const
	{
		return m_aabbMin;
	}
	SIMD_FORCE_INLINE const btVector3& getAabbMax() const
	{
		return m_aabbMax;
	}

};

/// btConvexConcaveCollisionAlgorithm  supports collision between convex shapes and (concave) trianges meshes.
ATTRIBUTE_ALIGNED16(class)  btConvexConcaveCollisionAlgorithm  : public btActivatingCollisionAlgorithm
{

	btConvexTriangleCallback m_btConvexTriangleCallback;

	bool	m_isSwapped;

public:

	BT_DECLARE_ALIGNED_ALLOCATOR();

	btConvexConcaveCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped);

	virtual ~btConvexConcaveCollisionAlgorithm();

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	btScalar	calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray);

	void	clearCache();

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexConcaveCollisionAlgorithm));
			return new(mem) btConvexConcaveCollisionAlgorithm(ci,body0Wrap,body1Wrap,false);
		}
	};

	struct SwappedCreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexConcaveCollisionAlgorithm));
			return new(mem) btConvexConcaveCollisionAlgorithm(ci,body0Wrap,body1Wrap,true);
		}
	};

};

#endif //BT_CONVEX_CONCAVE_COLLISION_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_COLLISION__DISPATCHER_H
#define BT_COLLISION__DISPATCHER_H

#include "BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include "BulletCollision/CollisionDispatch/btManifoldResult.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "btCollisionCreateFunc.h"
class btIDebugDraw;
class btOverlappingPairCache;
class btPoolAllocator;
class btCollisionConfiguration;
class btCollisionDispatcher;

#define USE_DISPATCH_REGISTRY_ARRAY 1

/// user can override this nearcallback for collision filtering and more
/// fine-grained control over collision detection
typedef void (*btNearCallback)(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo);

/// btCollisionDispatcher supports algorithms that handle ConvexConvex and
/// ConvexConcave collision pairs. Time of Impact, Closest Points and
/// Penetration Depth.
class btCollisionDispatcher : public btDispatcher
{
protected:
	int                                         m_dispatcherFlags;
	btAlignedObjectArray<btPersistentManifold*> m_manifoldsPtr;
	btManifoldResult                            m_defaultManifoldResult;
	btNearCallback                              m_nearCallback;
	btPoolAllocator*                            m_collisionAlgorithmPoolAllocator;
	btPoolAllocator*                            m_persistentManifoldPoolAllocator;
	btCollisionAlgorithmCreateFunc*             m_doubleDispatchContactPoints[MAX_BROADPHASE_COLLISION_TYPES][MAX_BROADPHASE_COLLISION_TYPES];
	btCollisionAlgorithmCreateFunc*             m_doubleDispatchClosestPoints[MAX_BROADPHASE_COLLISION_TYPES][MAX_BROADPHASE_COLLISION_TYPES];
	btCollisionConfiguration*                   m_collisionConfiguration;

public:
	enum DispatcherFlags
	{
		CD_STATIC_STATIC_REPORTED                  = 1,
		CD_USE_RELATIVE_CONTACT_BREAKING_THRESHOLD = 2,
		CD_DISABLE_CONTACTPOOL_DYNAMIC_ALLOCATION  = 4
	};

	int getDispatcherFlags() const { return m_dispatcherFlags; }
	void setDispatcherFlags(int flags) { m_dispatcherFlags = flags; }

	/// registerCollisionCreateFunc allows registration of custom/alternative
	/// collision create functions
	void registerCollisionCreateFunc(int proxyType0, int proxyType1, btCollisionAlgorithmCreateFunc* createFunc);

	void registerClosestPointsCreateFunc(int proxyType0, int proxyType1, btCollisionAlgorithmCreateFunc* createFunc);

	int                         getNumManifolds() const { return int(m_manifoldsPtr.size()); }
	btPersistentManifold**      getInternalManifoldPointer() { return m_manifoldsPtr.size() ? &m_manifoldsPtr[0] : 0; }
	btPersistentManifold*       getManifoldByIndexInternal(int index) { return m_manifoldsPtr[index]; }
	const btPersistentManifold* getManifoldByIndexInternal(int index) const { return m_manifoldsPtr[index]; }

	btCollisionDispatcher(btCollisionConfiguration* collisionConfiguration);
	virtual ~btCollisionDispatcher();

	virtual btPersistentManifold* getNewManifold(const btCollisionObject* b0, const btCollisionObject* b1);
	virtual void                  releaseManifold(btPersistentManifold* manifold);
	virtual void                  clearManifold(btPersistentManifold* manifold);

	btCollisionAlgorithm* findAlgorithm(
	    const btCollisionObjectWrapper* body0Wrap,
	    const btCollisionObjectWrapper* body1Wrap,
	    btPersistentManifold*           sharedManifold,
	    ebtDispatcherQueryType          queryType);

	virtual bool needsCollision(const btCollisionObject* body0, const btCollisionObject* body1);
	virtual bool needsResponse(const btCollisionObject* body0, const btCollisionObject* body1);
	virtual void dispatchAllCollisionPairs(btOverlappingPairCache* pairCache, const btDispatcherInfo& dispatchInfo, btDispatcher* dispatcher);

	void           setNearCallback(btNearCallback nearCallback) { m_nearCallback = nearCallback; }
	btNearCallback getNearCallback() const { return m_nearCallback; }

	/// by default, Bullet will use this near callback
	static void defaultNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo);

	virtual void* allocateCollisionAlgorithm(int size);
	virtual void  freeCollisionAlgorithm(void* ptr);

	btCollisionConfiguration*       getCollisionConfiguration() { return m_collisionConfiguration; }
	const btCollisionConfiguration* getCollisionConfiguration() const { return m_collisionConfiguration; }
	void                            setCollisionConfiguration(btCollisionConfiguration* config) { m_collisionConfiguration = config; }
	virtual btPoolAllocator*        getInternalManifoldPool() { return m_persistentManifoldPoolAllocator; }
	virtual const btPoolAllocator*  getInternalManifoldPool() const { return m_persistentManifoldPoolAllocator; }
};

#endif //BT_COLLISION__DISPATCHER_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_SPHERE_BOX_COLLISION_ALGORITHM_H
#define BT_SPHERE_BOX_COLLISION_ALGORITHM_H

#include "btActivatingCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
class btPersistentManifold;
#include "btCollisionDispatcher.h"

#include "LinearMath/btVector3.h"

/// btSphereBoxCollisionAlgorithm  provides sphere-box collision detection.
/// Other features are frame-coherency (persistent data) and collision response.
class btSphereBoxCollisionAlgorithm : public btActivatingCollisionAlgorithm
{
	bool	m_ownManifold;
	btPersistentManifold*	m_manifoldPtr;
	bool	m_isSwapped;

public:

	btSphereBoxCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap, bool isSwapped);

	virtual ~btSphereBoxCollisionAlgorithm();

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		if (m_manifoldPtr && m_ownManifold)
		{
			manifoldArray.push_back(m_manifoldPtr);
		}
	}

	bool getSphereDistance( const btCollisionObjectWrapper* boxObjWrap, btVector3& v3PointOnBox, btVector3& normal, btScalar& penetrationDepth, const btVector3& v3SphereCenter, btScalar fRadius, btScalar maxContactDistance );

	btScalar getSpherePenetration( btVector3 const &boxHalfExtent, btVector3 const &sphereRelPos, btVector3 &closestPoint, btVector3& normal );

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSphereBoxCollisionAlgorithm));
			if (!m_swapped)
			{
				return new(mem) btSphereBoxCollisionAlgorithm(0,ci,body0Wrap,body1Wrap,false);
			} else
			{
				return new(mem) btSphereBoxCollisionAlgorithm(0,ci,body0Wrap,body1Wrap,true);
			}
		}
	};

};

#endif //BT_SPHERE_BOX_COLLISION_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_CONVEX_CONVEX_ALGORITHM_H
#define BT_CONVEX_CONVEX_ALGORITHM_H

#include "btActivatingCollisionAlgorithm.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "btCollisionCreateFunc.h"
#include "btCollisionDispatcher.h"
#include "LinearMath/btTransformUtil.h" //for btConvexSeparatingDistanceUtil
#include "BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.h"

class btConvexPenetrationDepthSolver;

///Enabling USE_SEPDISTANCE_UTIL2 requires 100% reliable distance computation. However, when using large size ratios GJK can be imprecise
///so the distance is not conservative. In that case, enabling this USE_SEPDISTANCE_UTIL2 would result in failing/missing collisions.
///Either improve GJK for large size ratios (testing a 100 units versus a 0.1 unit object) or only enable the util
///for certain pairs that have a small size ratio

//#define USE_SEPDISTANCE_UTIL2 1

///The convexConvexAlgorithm collision algorithm implements time of impact, convex closest points and penetration depth calculations between two convex objects.
///Multiple contact points are calculated by perturbing the orientation of the smallest object orthogonal to the separating normal.
///This idea was described by Gino van den Bergen in this forum topic http://www.bulletphysics.com/Bullet/phpBB3/viewtopic.php?f=4&t=288&p=888#p888
class btConvexConvexAlgorithm : public btActivatingCollisionAlgorithm
{
#ifdef USE_SEPDISTANCE_UTIL2
	btConvexSeparatingDistanceUtil	m_sepDistance;
#endif
	btConvexPenetrationDepthSolver* m_pdSolver;

	btVertexArray worldVertsB1;
	btVertexArray worldVertsB2;

	bool	m_ownManifold;
	btPersistentManifold*	m_manifoldPtr;
	bool			m_lowLevelOfDetail;

	int m_numPerturbationIterations;
	int m_minimumPointsPerturbationThreshold;

	///cache separating vector to speedup collision detection

public:

	btConvexConvexAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap, btConvexPenetrationDepthSolver* pdSolver, int numPerturbationIterations, int minimumPointsPerturbationThreshold);

	virtual ~btConvexConvexAlgorithm();

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		///should we use m_ownManifold to avoid adding duplicates?
		if (m_manifoldPtr && m_ownManifold)
			manifoldArray.push_back(m_manifoldPtr);
	}

	void	setLowLevelOfDetail(bool useLowLevel);

	const btPersistentManifold*	getManifold()
	{
		return m_manifoldPtr;
	}

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{

		btConvexPenetrationDepthSolver*		m_pdSolver;
		int m_numPerturbationIterations;
		int m_minimumPointsPerturbationThreshold;

		CreateFunc(btConvexPenetrationDepthSolver* pdSolver);

		virtual ~CreateFunc();

		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexConvexAlgorithm));
			return new(mem) btConvexConvexAlgorithm(ci.m_manifold,ci,body0Wrap,body1Wrap,m_pdSolver,m_numPerturbationIterations,m_minimumPointsPerturbationThreshold);
		}
	};

};

#endif //BT_CONVEX_CONVEX_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_UNION_FIND_H
#define BT_UNION_FIND_H

#include "LinearMath/btAlignedObjectArray.h"

#define USE_PATH_COMPRESSION 1

///see for discussion of static island optimizations by Vroonsh here: http://code.google.com/p/bullet/issues/detail?id=406
#define STATIC_SIMULATION_ISLAND_OPTIMIZATION 1

struct	btElement
{
	int	m_id;
	int	m_sz;
};

///UnionFind calculates connected subsets
// Implements weighted Quick Union with path compression
// optimization: could use short ints instead of ints (halving memory, would limit the number of rigid bodies to 64k, sounds reasonable)
class btUnionFind
  {
    private:
		btAlignedObjectArray<btElement>	m_elements;

    public:

		btUnionFind();
		~btUnionFind();

		//this is a special operation, destroying the content of btUnionFind.
		//it sorts the elements, based on island id, in order to make it easy to iterate over islands
		void	sortIslands();

	  void	reset(int N);

	  SIMD_FORCE_INLINE int	getNumElements() const
	  {
		  return int(m_elements.size());
	  }
	  SIMD_FORCE_INLINE bool  isRoot(int x) const
	  {
		  return (x == m_elements[x].m_id);
	  }

	  btElement&	getElement(int index)
	  {
		  return m_elements[index];
	  }
	  const btElement& getElement(int index) const
	  {
		  return m_elements[index];
	  }

	  void	allocate(int N);
	  void	Free();

	  int find(int p, int q)
		{
			return (find(p) == find(q));
		}

		void unite(int p, int q)
		{
			int i = find(p), j = find(q);
			if (i == j)
				return;

#ifndef USE_PATH_COMPRESSION
			//weighted quick union, this keeps the 'trees' balanced, and keeps performance of unite O( log(n) )
			if (m_elements[i].m_sz < m_elements[j].m_sz)
			{
				m_elements[i].m_id = j; m_elements[j].m_sz += m_elements[i].m_sz;
			}
			else
			{
				m_elements[j].m_id = i; m_elements[i].m_sz += m_elements[j].m_sz;
			}
#else
			m_elements[i].m_id = j; m_elements[j].m_sz += m_elements[i].m_sz;
#endif //USE_PATH_COMPRESSION
		}

		int find(int x)
		{
			//btAssert(x < m_N);
			//btAssert(x >= 0);

			while (x != m_elements[x].m_id)
			{
		//not really a reason not to use path compression, and it flattens the trees/improves find performance dramatically

		#ifdef USE_PATH_COMPRESSION
				const btElement* elementPtr = &m_elements[m_elements[x].m_id];
				m_elements[x].m_id = elementPtr->m_id;
				x = elementPtr->m_id;
		#else//
				x = m_elements[x].m_id;
		#endif
				//btAssert(x < m_N);
				//btAssert(x >= 0);

			}
			return x;
		}

  };

#endif //BT_UNION_FIND_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_CONVEX_2D_CONVEX_2D_ALGORITHM_H
#define BT_CONVEX_2D_CONVEX_2D_ALGORITHM_H

#include "BulletCollision/CollisionDispatch/btActivatingCollisionAlgorithm.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
#include "LinearMath/btTransformUtil.h" //for btConvexSeparatingDistanceUtil

class btConvexPenetrationDepthSolver;

///The convex2dConvex2dAlgorithm collision algorithm support 2d collision detection for btConvex2dShape
///Currently it requires the btMinkowskiPenetrationDepthSolver, it has support for 2d penetration depth computation
class btConvex2dConvex2dAlgorithm : public btActivatingCollisionAlgorithm
{
	btSimplexSolverInterface*		m_simplexSolver;
	btConvexPenetrationDepthSolver* m_pdSolver;

	bool	m_ownManifold;
	btPersistentManifold*	m_manifoldPtr;
	bool			m_lowLevelOfDetail;

public:

	btConvex2dConvex2dAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap, btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver, int numPerturbationIterations, int minimumPointsPerturbationThreshold);

	virtual ~btConvex2dConvex2dAlgorithm();

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		///should we use m_ownManifold to avoid adding duplicates?
		if (m_manifoldPtr && m_ownManifold)
			manifoldArray.push_back(m_manifoldPtr);
	}

	void	setLowLevelOfDetail(bool useLowLevel);

	const btPersistentManifold*	getManifold()
	{
		return m_manifoldPtr;
	}

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{

		btConvexPenetrationDepthSolver*		m_pdSolver;
		btSimplexSolverInterface*			m_simplexSolver;
		int m_numPerturbationIterations;
		int m_minimumPointsPerturbationThreshold;

		CreateFunc(btSimplexSolverInterface*			simplexSolver, btConvexPenetrationDepthSolver* pdSolver);

		virtual ~CreateFunc();

		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvex2dConvex2dAlgorithm));
			return new(mem) btConvex2dConvex2dAlgorithm(ci.m_manifold,ci,body0Wrap,body1Wrap,m_simplexSolver,m_pdSolver,m_numPerturbationIterations,m_minimumPointsPerturbationThreshold);
		}
	};

};

#endif //BT_CONVEX_2D_CONVEX_2D_ALGORITHM_H


text:
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#ifndef BT_CONVEX_PLANE_COLLISION_ALGORITHM_H
#define BT_CONVEX_PLANE_COLLISION_ALGORITHM_H

#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h"
class btPersistentManifold;
#include "btCollisionDispatcher.h"

#include "LinearMath/btVector3.h"

/// btSphereBoxCollisionAlgorithm  provides sphere-box collision detection.
/// Other features are frame-coherency (persistent data) and collision response.
class btConvexPlaneCollisionAlgorithm : public btCollisionAlgorithm
{
	bool		m_ownManifold;
	btPersistentManifold*	m_manifoldPtr;
	bool		m_isSwapped;
	int			m_numPerturbationIterations;
	int			m_minimumPointsPerturbationThreshold;

public:

	btConvexPlaneCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap, bool isSwapped, int numPerturbationIterations,int minimumPointsPerturbationThreshold);

	virtual ~btConvexPlaneCollisionAlgorithm();

	virtual void processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	void collideSingleContact (const btQuaternion& perturbeRot, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		if (m_manifoldPtr && m_ownManifold)
		{
			manifoldArray.push_back(m_manifoldPtr);
		}
	}

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		int	m_numPerturbationIterations;
		int m_minimumPointsPerturbationThreshold;

		CreateFunc()
			: m_numPerturbationIterations(1),
			m_minimumPointsPerturbationThreshold(0)
		{
		}

		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexPlaneCollisionAlgorithm));
			if (!m_swapped)
			{
				return new(mem) btConvexPlaneCollisionAlgorithm(0,ci,body0Wrap,body1Wrap,false,m_numPerturbationIterations,m_minimumPointsPerturbationThreshold);
			} else
			{
				return new(mem) btConvexPlaneCollisionAlgorithm(0,ci,body0Wrap,body1Wrap,true,m_numPerturbationIterations,m_minimumPointsPerturbationThreshold);
			}
		}
	};

};

#endif //BT_CONVEX_PLANE_COLLISION_ALGORITHM_H