• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
3 *
4 * This software is provided 'as-is', without any express or implied
5 * warranty.  In no event will the authors be held liable for any damages
6 * arising from the use of this software.
7 * Permission is granted to anyone to use this software for any purpose,
8 * including commercial applications, and to alter it and redistribute it
9 * freely, subject to the following restrictions:
10 * 1. The origin of this software must not be misrepresented; you must not
11 * claim that you wrote the original software. If you use this software
12 * in a product, an acknowledgment in the product documentation would be
13 * appreciated but is not required.
14 * 2. Altered source versions must be plainly marked as such, and must not be
15 * misrepresented as being the original software.
16 * 3. This notice may not be removed or altered from any source distribution.
17 */
18 
19 #ifndef B2_BROAD_PHASE_H
20 #define B2_BROAD_PHASE_H
21 
22 #include <Box2D/Common/b2Settings.h>
23 #include <Box2D/Collision/b2Collision.h>
24 #include <Box2D/Collision/b2DynamicTree.h>
25 //#include <algorithm>
26 #include <stdlib.h>
27 
28 struct b2Pair
29 {
30 	int32 proxyIdA;
31 	int32 proxyIdB;
32 };
33 
34 /// The broad-phase is used for computing pairs and performing volume queries and ray casts.
35 /// This broad-phase does not persist pairs. Instead, this reports potentially new pairs.
36 /// It is up to the client to consume the new pairs and to track subsequent overlap.
37 class b2BroadPhase
38 {
39 public:
40 
41 	enum
42 	{
43 		e_nullProxy = -1
44 	};
45 
46 	b2BroadPhase();
47 	~b2BroadPhase();
48 
49 	/// Create a proxy with an initial AABB. Pairs are not reported until
50 	/// UpdatePairs is called.
51 	int32 CreateProxy(const b2AABB& aabb, void* userData);
52 
53 	/// Destroy a proxy. It is up to the client to remove any pairs.
54 	void DestroyProxy(int32 proxyId);
55 
56 	/// Call MoveProxy as many times as you like, then when you are done
57 	/// call UpdatePairs to finalized the proxy pairs (for your time step).
58 	void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement);
59 
60 	/// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs.
61 	void TouchProxy(int32 proxyId);
62 
63 	/// Get the fat AABB for a proxy.
64 	const b2AABB& GetFatAABB(int32 proxyId) const;
65 
66 	/// Get user data from a proxy. Returns NULL if the id is invalid.
67 	void* GetUserData(int32 proxyId) const;
68 
69 	/// Test overlap of fat AABBs.
70 	bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const;
71 
72 	/// Get the number of proxies.
73 	int32 GetProxyCount() const;
74 
75 	/// Update the pairs. This results in pair callbacks. This can only add pairs.
76 	template <typename T>
77 	void UpdatePairs(T* callback);
78 
79 	/// Query an AABB for overlapping proxies. The callback class
80 	/// is called for each proxy that overlaps the supplied AABB.
81 	template <typename T>
82 	void Query(T* callback, const b2AABB& aabb) const;
83 
84 	/// Ray-cast against the proxies in the tree. This relies on the callback
85 	/// to perform a exact ray-cast in the case were the proxy contains a shape.
86 	/// The callback also performs the any collision filtering. This has performance
87 	/// roughly equal to k * log(n), where k is the number of collisions and n is the
88 	/// number of proxies in the tree.
89 	/// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
90 	/// @param callback a callback class that is called for each proxy that is hit by the ray.
91 	template <typename T>
92 	void RayCast(T* callback, const b2RayCastInput& input) const;
93 
94 	/// Get the height of the embedded tree.
95 	int32 GetTreeHeight() const;
96 
97 	/// Get the balance of the embedded tree.
98 	int32 GetTreeBalance() const;
99 
100 	/// Get the quality metric of the embedded tree.
101 	float32 GetTreeQuality() const;
102 
103 	/// Shift the world origin. Useful for large worlds.
104 	/// The shift formula is: position -= newOrigin
105 	/// @param newOrigin the new origin with respect to the old origin
106 	void ShiftOrigin(const b2Vec2& newOrigin);
107 
108 private:
109 
110 	friend class b2DynamicTree;
111 
112 	void BufferMove(int32 proxyId);
113 	void UnBufferMove(int32 proxyId);
114 
115 	bool QueryCallback(int32 proxyId);
116 
117 	b2DynamicTree m_tree;
118 
119 	int32 m_proxyCount;
120 
121 	int32* m_moveBuffer;
122 	int32 m_moveCapacity;
123 	int32 m_moveCount;
124 
125 	b2Pair* m_pairBuffer;
126 	int32 m_pairCapacity;
127 	int32 m_pairCount;
128 
129 	int32 m_queryProxyId;
130 };
131 
132 //The return value of this function should represent whether elem1 is considered less than,
133 //equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.
b2PairCompareQSort(const void * elem1,const void * elem2)134 inline int b2PairCompareQSort(const void * elem1, const void * elem2)
135 {
136    b2Pair* pair1 = (b2Pair*) elem1;
137    b2Pair* pair2 = (b2Pair*) elem2;
138 
139    if (pair1->proxyIdA < pair2->proxyIdA)
140    {
141       return -1;
142    }
143 
144    if (pair1->proxyIdA == pair2->proxyIdA)
145    {
146       if( pair1->proxyIdB < pair2->proxyIdB ) {
147          return -1;
148       }
149       else if(pair1->proxyIdB > pair2->proxyIdB) {
150          return 1;
151       }
152       else {
153          return 0;
154       }
155    }
156    else {
157       return 1;
158    }
159 
160 }
161 
162 /// This is used to sort pairs.
b2PairLessThan(const b2Pair & pair1,const b2Pair & pair2)163 inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2)
164 {
165 	if (pair1.proxyIdA < pair2.proxyIdA)
166 	{
167 		return true;
168 	}
169 
170 	if (pair1.proxyIdA == pair2.proxyIdA)
171 	{
172 		return pair1.proxyIdB < pair2.proxyIdB;
173 	}
174 
175 	return false;
176 }
177 
GetUserData(int32 proxyId)178 inline void* b2BroadPhase::GetUserData(int32 proxyId) const
179 {
180 	return m_tree.GetUserData(proxyId);
181 }
182 
TestOverlap(int32 proxyIdA,int32 proxyIdB)183 inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const
184 {
185 	const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA);
186 	const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB);
187 	return b2TestOverlap(aabbA, aabbB);
188 }
189 
GetFatAABB(int32 proxyId)190 inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const
191 {
192 	return m_tree.GetFatAABB(proxyId);
193 }
194 
GetProxyCount()195 inline int32 b2BroadPhase::GetProxyCount() const
196 {
197 	return m_proxyCount;
198 }
199 
GetTreeHeight()200 inline int32 b2BroadPhase::GetTreeHeight() const
201 {
202 	return m_tree.GetHeight();
203 }
204 
GetTreeBalance()205 inline int32 b2BroadPhase::GetTreeBalance() const
206 {
207 	return m_tree.GetMaxBalance();
208 }
209 
GetTreeQuality()210 inline float32 b2BroadPhase::GetTreeQuality() const
211 {
212 	return m_tree.GetAreaRatio();
213 }
214 
215 template <typename T>
UpdatePairs(T * callback)216 void b2BroadPhase::UpdatePairs(T* callback)
217 {
218 	// Reset pair buffer
219 	m_pairCount = 0;
220 
221 	// Perform tree queries for all moving proxies.
222 	for (int32 i = 0; i < m_moveCount; ++i)
223 	{
224 		m_queryProxyId = m_moveBuffer[i];
225 		if (m_queryProxyId == e_nullProxy)
226 		{
227 			continue;
228 		}
229 
230 		// We have to query the tree with the fat AABB so that
231 		// we don't fail to create a pair that may touch later.
232 		const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId);
233 
234 		// Query tree, create pairs and add them pair buffer.
235 		m_tree.Query(this, fatAABB);
236 	}
237 
238 	// Reset move buffer
239 	m_moveCount = 0;
240 
241 	// Sort the pair buffer to expose duplicates.
242 	//std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan);
243 
244 	// FIX from http://www.box2d.org/forum/viewtopic.php?f=7&t=4756&start=0 to get rid of stl dependency
245 	qsort(m_pairBuffer, sizeof(m_pairBuffer) / sizeof(struct b2Pair) , sizeof(struct b2Pair), b2PairCompareQSort);
246 	// Send the pairs back to the client.
247 	int32 i = 0;
248 	while (i < m_pairCount)
249 	{
250 		b2Pair* primaryPair = m_pairBuffer + i;
251 		void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA);
252 		void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB);
253 
254 		callback->AddPair(userDataA, userDataB);
255 		++i;
256 
257 		// Skip any duplicate pairs.
258 		while (i < m_pairCount)
259 		{
260 			b2Pair* pair = m_pairBuffer + i;
261 			if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB)
262 			{
263 				break;
264 			}
265 			++i;
266 		}
267 	}
268 
269 	// Try to keep the tree balanced.
270 	//m_tree.Rebalance(4);
271 }
272 
273 template <typename T>
Query(T * callback,const b2AABB & aabb)274 inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const
275 {
276 	m_tree.Query(callback, aabb);
277 }
278 
279 template <typename T>
RayCast(T * callback,const b2RayCastInput & input)280 inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const
281 {
282 	m_tree.RayCast(callback, input);
283 }
284 
ShiftOrigin(const b2Vec2 & newOrigin)285 inline void b2BroadPhase::ShiftOrigin(const b2Vec2& newOrigin)
286 {
287 	m_tree.ShiftOrigin(newOrigin);
288 }
289 
290 #endif
291