b2World.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343
  1. /*
  2. * Copyright (c) 2006-2011 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. #include <Box2D/Dynamics/b2World.h>
  19. #include <Box2D/Dynamics/b2Body.h>
  20. #include <Box2D/Dynamics/b2Fixture.h>
  21. #include <Box2D/Dynamics/b2Island.h>
  22. #include <Box2D/Dynamics/Joints/b2PulleyJoint.h>
  23. #include <Box2D/Dynamics/Contacts/b2Contact.h>
  24. #include <Box2D/Dynamics/Contacts/b2ContactSolver.h>
  25. #include <Box2D/Collision/b2Collision.h>
  26. #include <Box2D/Collision/b2BroadPhase.h>
  27. #include <Box2D/Collision/Shapes/b2CircleShape.h>
  28. #include <Box2D/Collision/Shapes/b2EdgeShape.h>
  29. #include <Box2D/Collision/Shapes/b2ChainShape.h>
  30. #include <Box2D/Collision/Shapes/b2PolygonShape.h>
  31. #include <Box2D/Collision/b2TimeOfImpact.h>
  32. #include <Box2D/Common/b2Draw.h>
  33. #include <Box2D/Common/b2Timer.h>
  34. #include <Box2D/b2ObjectDestroyNotifier.h>
  35. #include <new>
  36. b2World::b2World(const b2Vec2& gravity)
  37. {
  38. m_destructionListener = NULL;
  39. g_debugDraw = NULL;
  40. m_bodyList = NULL;
  41. m_jointList = NULL;
  42. m_bodyCount = 0;
  43. m_jointCount = 0;
  44. m_warmStarting = true;
  45. m_continuousPhysics = true;
  46. m_subStepping = false;
  47. m_stepComplete = true;
  48. m_allowSleep = true;
  49. m_gravity = gravity;
  50. m_flags = e_clearForces;
  51. m_inv_dt0 = 0.0f;
  52. m_contactManager.m_allocator = &m_blockAllocator;
  53. memset(&m_profile, 0, sizeof(b2Profile));
  54. }
  55. b2World::~b2World()
  56. {
  57. // Some shapes allocate using b2Alloc.
  58. b2Body* b = m_bodyList;
  59. while (b)
  60. {
  61. b2Body* bNext = b->m_next;
  62. b2Fixture* f = b->m_fixtureList;
  63. while (f)
  64. {
  65. b2Fixture* fNext = f->m_next;
  66. f->m_proxyCount = 0;
  67. f->Destroy(&m_blockAllocator);
  68. f = fNext;
  69. }
  70. b = bNext;
  71. }
  72. }
  73. void b2World::SetDestructionListener(b2DestructionListener* listener)
  74. {
  75. m_destructionListener = listener;
  76. }
  77. void b2World::SetContactFilter(b2ContactFilter* filter)
  78. {
  79. m_contactManager.m_contactFilter = filter;
  80. }
  81. void b2World::SetContactListener(b2ContactListener* listener)
  82. {
  83. m_contactManager.m_contactListener = listener;
  84. }
  85. void b2World::SetDebugDraw(b2Draw* debugDraw)
  86. {
  87. g_debugDraw = debugDraw;
  88. }
  89. b2Body* b2World::CreateBody(const b2BodyDef* def)
  90. {
  91. b2Assert(IsLocked() == false);
  92. if (IsLocked())
  93. {
  94. return NULL;
  95. }
  96. void* mem = m_blockAllocator.Allocate(sizeof(b2Body));
  97. b2Body* b = new (mem) b2Body(def, this);
  98. // Add to world doubly linked list.
  99. b->m_prev = NULL;
  100. b->m_next = m_bodyList;
  101. if (m_bodyList)
  102. {
  103. m_bodyList->m_prev = b;
  104. }
  105. m_bodyList = b;
  106. ++m_bodyCount;
  107. return b;
  108. }
  109. void b2World::DestroyBody(b2Body* b)
  110. {
  111. b2Assert(m_bodyCount > 0);
  112. b2Assert(IsLocked() == false);
  113. if (IsLocked())
  114. {
  115. return;
  116. }
  117. // Delete the attached joints.
  118. b2JointEdge* je = b->m_jointList;
  119. while (je)
  120. {
  121. b2JointEdge* je0 = je;
  122. je = je->next;
  123. if (m_destructionListener)
  124. {
  125. m_destructionListener->SayGoodbye(je0->joint);
  126. }
  127. DestroyJoint(je0->joint);
  128. b->m_jointList = je;
  129. }
  130. b->m_jointList = NULL;
  131. // Delete the attached contacts.
  132. b2ContactEdge* ce = b->m_contactList;
  133. while (ce)
  134. {
  135. b2ContactEdge* ce0 = ce;
  136. ce = ce->next;
  137. m_contactManager.Destroy(ce0->contact);
  138. }
  139. b->m_contactList = NULL;
  140. // Delete the attached fixtures. This destroys broad-phase proxies.
  141. b2Fixture* f = b->m_fixtureList;
  142. while (f)
  143. {
  144. b2Fixture* f0 = f;
  145. f = f->m_next;
  146. if (m_destructionListener)
  147. {
  148. m_destructionListener->SayGoodbye(f0);
  149. }
  150. f0->DestroyProxies(&m_contactManager.m_broadPhase);
  151. f0->Destroy(&m_blockAllocator);
  152. f0->~b2Fixture();
  153. m_blockAllocator.Free(f0, sizeof(b2Fixture));
  154. b->m_fixtureList = f;
  155. b->m_fixtureCount -= 1;
  156. }
  157. b->m_fixtureList = NULL;
  158. b->m_fixtureCount = 0;
  159. // Remove world body list.
  160. if (b->m_prev)
  161. {
  162. b->m_prev->m_next = b->m_next;
  163. }
  164. if (b->m_next)
  165. {
  166. b->m_next->m_prev = b->m_prev;
  167. }
  168. if (b == m_bodyList)
  169. {
  170. m_bodyList = b->m_next;
  171. }
  172. --m_bodyCount;
  173. b2NotifyObjectDestroyed(b, b2ObjectType::BODY, "b2Body");
  174. b->~b2Body();
  175. m_blockAllocator.Free(b, sizeof(b2Body));
  176. }
  177. b2Joint* b2World::CreateJoint(const b2JointDef* def)
  178. {
  179. b2Assert(IsLocked() == false);
  180. if (IsLocked())
  181. {
  182. return NULL;
  183. }
  184. b2Joint* j = b2Joint::Create(def, &m_blockAllocator);
  185. // Connect to the world list.
  186. j->m_prev = NULL;
  187. j->m_next = m_jointList;
  188. if (m_jointList)
  189. {
  190. m_jointList->m_prev = j;
  191. }
  192. m_jointList = j;
  193. ++m_jointCount;
  194. // Connect to the bodies' doubly linked lists.
  195. j->m_edgeA.joint = j;
  196. j->m_edgeA.other = j->m_bodyB;
  197. j->m_edgeA.prev = NULL;
  198. j->m_edgeA.next = j->m_bodyA->m_jointList;
  199. if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA;
  200. j->m_bodyA->m_jointList = &j->m_edgeA;
  201. j->m_edgeB.joint = j;
  202. j->m_edgeB.other = j->m_bodyA;
  203. j->m_edgeB.prev = NULL;
  204. j->m_edgeB.next = j->m_bodyB->m_jointList;
  205. if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB;
  206. j->m_bodyB->m_jointList = &j->m_edgeB;
  207. b2Body* bodyA = def->bodyA;
  208. b2Body* bodyB = def->bodyB;
  209. // If the joint prevents collisions, then flag any contacts for filtering.
  210. if (def->collideConnected == false)
  211. {
  212. b2ContactEdge* edge = bodyB->GetContactList();
  213. while (edge)
  214. {
  215. if (edge->other == bodyA)
  216. {
  217. // Flag the contact for filtering at the next time step (where either
  218. // body is awake).
  219. edge->contact->FlagForFiltering();
  220. }
  221. edge = edge->next;
  222. }
  223. }
  224. // Note: creating a joint doesn't wake the bodies.
  225. return j;
  226. }
  227. void b2World::DestroyJoint(b2Joint* j)
  228. {
  229. b2Assert(IsLocked() == false);
  230. if (IsLocked())
  231. {
  232. return;
  233. }
  234. bool collideConnected = j->m_collideConnected;
  235. // Remove from the doubly linked list.
  236. if (j->m_prev)
  237. {
  238. j->m_prev->m_next = j->m_next;
  239. }
  240. if (j->m_next)
  241. {
  242. j->m_next->m_prev = j->m_prev;
  243. }
  244. if (j == m_jointList)
  245. {
  246. m_jointList = j->m_next;
  247. }
  248. // Disconnect from island graph.
  249. b2Body* bodyA = j->m_bodyA;
  250. b2Body* bodyB = j->m_bodyB;
  251. // Wake up connected bodies.
  252. bodyA->SetAwake(true);
  253. bodyB->SetAwake(true);
  254. // Remove from body 1.
  255. if (j->m_edgeA.prev)
  256. {
  257. j->m_edgeA.prev->next = j->m_edgeA.next;
  258. }
  259. if (j->m_edgeA.next)
  260. {
  261. j->m_edgeA.next->prev = j->m_edgeA.prev;
  262. }
  263. if (&j->m_edgeA == bodyA->m_jointList)
  264. {
  265. bodyA->m_jointList = j->m_edgeA.next;
  266. }
  267. j->m_edgeA.prev = NULL;
  268. j->m_edgeA.next = NULL;
  269. // Remove from body 2
  270. if (j->m_edgeB.prev)
  271. {
  272. j->m_edgeB.prev->next = j->m_edgeB.next;
  273. }
  274. if (j->m_edgeB.next)
  275. {
  276. j->m_edgeB.next->prev = j->m_edgeB.prev;
  277. }
  278. if (&j->m_edgeB == bodyB->m_jointList)
  279. {
  280. bodyB->m_jointList = j->m_edgeB.next;
  281. }
  282. j->m_edgeB.prev = NULL;
  283. j->m_edgeB.next = NULL;
  284. b2Joint::Destroy(j, &m_blockAllocator);
  285. b2Assert(m_jointCount > 0);
  286. --m_jointCount;
  287. // If the joint prevents collisions, then flag any contacts for filtering.
  288. if (collideConnected == false)
  289. {
  290. b2ContactEdge* edge = bodyB->GetContactList();
  291. while (edge)
  292. {
  293. if (edge->other == bodyA)
  294. {
  295. // Flag the contact for filtering at the next time step (where either
  296. // body is awake).
  297. edge->contact->FlagForFiltering();
  298. }
  299. edge = edge->next;
  300. }
  301. }
  302. }
  303. //
  304. void b2World::SetAllowSleeping(bool flag)
  305. {
  306. if (flag == m_allowSleep)
  307. {
  308. return;
  309. }
  310. m_allowSleep = flag;
  311. if (m_allowSleep == false)
  312. {
  313. for (b2Body* b = m_bodyList; b; b = b->m_next)
  314. {
  315. b->SetAwake(true);
  316. }
  317. }
  318. }
  319. // Find islands, integrate and solve constraints, solve position constraints
  320. void b2World::Solve(const b2TimeStep& step)
  321. {
  322. m_profile.solveInit = 0.0f;
  323. m_profile.solveVelocity = 0.0f;
  324. m_profile.solvePosition = 0.0f;
  325. // Size the island for the worst case.
  326. b2Island island(m_bodyCount,
  327. m_contactManager.m_contactCount,
  328. m_jointCount,
  329. &m_stackAllocator,
  330. m_contactManager.m_contactListener);
  331. // Clear all the island flags.
  332. for (b2Body* b = m_bodyList; b; b = b->m_next)
  333. {
  334. b->m_flags &= ~b2Body::e_islandFlag;
  335. }
  336. for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
  337. {
  338. c->m_flags &= ~b2Contact::e_islandFlag;
  339. }
  340. for (b2Joint* j = m_jointList; j; j = j->m_next)
  341. {
  342. j->m_islandFlag = false;
  343. }
  344. // Build and simulate all awake islands.
  345. int32 stackSize = m_bodyCount;
  346. b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*));
  347. for (b2Body* seed = m_bodyList; seed; seed = seed->m_next)
  348. {
  349. if (seed->m_flags & b2Body::e_islandFlag)
  350. {
  351. continue;
  352. }
  353. if (seed->IsAwake() == false || seed->IsActive() == false)
  354. {
  355. continue;
  356. }
  357. // The seed can be dynamic or kinematic.
  358. if (seed->GetType() == b2_staticBody)
  359. {
  360. continue;
  361. }
  362. // Reset island and stack.
  363. island.Clear();
  364. int32 stackCount = 0;
  365. stack[stackCount++] = seed;
  366. seed->m_flags |= b2Body::e_islandFlag;
  367. // Perform a depth first search (DFS) on the constraint graph.
  368. while (stackCount > 0)
  369. {
  370. // Grab the next body off the stack and add it to the island.
  371. b2Body* b = stack[--stackCount];
  372. b2Assert(b->IsActive() == true);
  373. island.Add(b);
  374. // Make sure the body is awake.
  375. b->SetAwake(true);
  376. // To keep islands as small as possible, we don't
  377. // propagate islands across static bodies.
  378. if (b->GetType() == b2_staticBody)
  379. {
  380. continue;
  381. }
  382. // Search all contacts connected to this body.
  383. for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next)
  384. {
  385. b2Contact* contact = ce->contact;
  386. // Has this contact already been added to an island?
  387. if (contact->m_flags & b2Contact::e_islandFlag)
  388. {
  389. continue;
  390. }
  391. // Is this contact solid and touching?
  392. if (contact->IsEnabled() == false ||
  393. contact->IsTouching() == false)
  394. {
  395. continue;
  396. }
  397. // Skip sensors.
  398. bool sensorA = contact->m_fixtureA->m_isSensor;
  399. bool sensorB = contact->m_fixtureB->m_isSensor;
  400. if (sensorA || sensorB)
  401. {
  402. continue;
  403. }
  404. island.Add(contact);
  405. contact->m_flags |= b2Contact::e_islandFlag;
  406. b2Body* other = ce->other;
  407. // Was the other body already added to this island?
  408. if (other->m_flags & b2Body::e_islandFlag)
  409. {
  410. continue;
  411. }
  412. b2Assert(stackCount < stackSize);
  413. stack[stackCount++] = other;
  414. other->m_flags |= b2Body::e_islandFlag;
  415. }
  416. // Search all joints connect to this body.
  417. for (b2JointEdge* je = b->m_jointList; je; je = je->next)
  418. {
  419. if (je->joint->m_islandFlag == true)
  420. {
  421. continue;
  422. }
  423. b2Body* other = je->other;
  424. // Don't simulate joints connected to inactive bodies.
  425. if (other->IsActive() == false)
  426. {
  427. continue;
  428. }
  429. island.Add(je->joint);
  430. je->joint->m_islandFlag = true;
  431. if (other->m_flags & b2Body::e_islandFlag)
  432. {
  433. continue;
  434. }
  435. b2Assert(stackCount < stackSize);
  436. stack[stackCount++] = other;
  437. other->m_flags |= b2Body::e_islandFlag;
  438. }
  439. }
  440. b2Profile profile;
  441. island.Solve(&profile, step, m_gravity, m_allowSleep);
  442. m_profile.solveInit += profile.solveInit;
  443. m_profile.solveVelocity += profile.solveVelocity;
  444. m_profile.solvePosition += profile.solvePosition;
  445. // Post solve cleanup.
  446. for (int32 i = 0; i < island.m_bodyCount; ++i)
  447. {
  448. // Allow static bodies to participate in other islands.
  449. b2Body* b = island.m_bodies[i];
  450. if (b->GetType() == b2_staticBody)
  451. {
  452. b->m_flags &= ~b2Body::e_islandFlag;
  453. }
  454. }
  455. }
  456. m_stackAllocator.Free(stack);
  457. {
  458. b2Timer timer;
  459. // Synchronize fixtures, check for out of range bodies.
  460. for (b2Body* b = m_bodyList; b; b = b->GetNext())
  461. {
  462. // If a body was not in an island then it did not move.
  463. if ((b->m_flags & b2Body::e_islandFlag) == 0)
  464. {
  465. continue;
  466. }
  467. if (b->GetType() == b2_staticBody)
  468. {
  469. continue;
  470. }
  471. // Update fixtures (for broad-phase).
  472. b->SynchronizeFixtures();
  473. }
  474. // Look for new contacts.
  475. m_contactManager.FindNewContacts();
  476. m_profile.broadphase = timer.GetMilliseconds();
  477. }
  478. }
  479. // Find TOI contacts and solve them.
  480. void b2World::SolveTOI(const b2TimeStep& step)
  481. {
  482. b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener);
  483. if (m_stepComplete)
  484. {
  485. for (b2Body* b = m_bodyList; b; b = b->m_next)
  486. {
  487. b->m_flags &= ~b2Body::e_islandFlag;
  488. b->m_sweep.alpha0 = 0.0f;
  489. }
  490. for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
  491. {
  492. // Invalidate TOI
  493. c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
  494. c->m_toiCount = 0;
  495. c->m_toi = 1.0f;
  496. }
  497. }
  498. // Find TOI events and solve them.
  499. for (;;)
  500. {
  501. // Find the first TOI.
  502. b2Contact* minContact = NULL;
  503. float32 minAlpha = 1.0f;
  504. for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next)
  505. {
  506. // Is this contact disabled?
  507. if (c->IsEnabled() == false)
  508. {
  509. continue;
  510. }
  511. // Prevent excessive sub-stepping.
  512. if (c->m_toiCount > b2_maxSubSteps)
  513. {
  514. continue;
  515. }
  516. float32 alpha = 1.0f;
  517. if (c->m_flags & b2Contact::e_toiFlag)
  518. {
  519. // This contact has a valid cached TOI.
  520. alpha = c->m_toi;
  521. }
  522. else
  523. {
  524. b2Fixture* fA = c->GetFixtureA();
  525. b2Fixture* fB = c->GetFixtureB();
  526. // Is there a sensor?
  527. if (fA->IsSensor() || fB->IsSensor())
  528. {
  529. continue;
  530. }
  531. b2Body* bA = fA->GetBody();
  532. b2Body* bB = fB->GetBody();
  533. b2BodyType typeA = bA->m_type;
  534. b2BodyType typeB = bB->m_type;
  535. b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody);
  536. bool activeA = bA->IsAwake() && typeA != b2_staticBody;
  537. bool activeB = bB->IsAwake() && typeB != b2_staticBody;
  538. // Is at least one body active (awake and dynamic or kinematic)?
  539. if (activeA == false && activeB == false)
  540. {
  541. continue;
  542. }
  543. bool collideA = bA->IsBullet() || typeA != b2_dynamicBody;
  544. bool collideB = bB->IsBullet() || typeB != b2_dynamicBody;
  545. // Are these two non-bullet dynamic bodies?
  546. if (collideA == false && collideB == false)
  547. {
  548. continue;
  549. }
  550. // Compute the TOI for this contact.
  551. // Put the sweeps onto the same time interval.
  552. float32 alpha0 = bA->m_sweep.alpha0;
  553. if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0)
  554. {
  555. alpha0 = bB->m_sweep.alpha0;
  556. bA->m_sweep.Advance(alpha0);
  557. }
  558. else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0)
  559. {
  560. alpha0 = bA->m_sweep.alpha0;
  561. bB->m_sweep.Advance(alpha0);
  562. }
  563. b2Assert(alpha0 < 1.0f);
  564. int32 indexA = c->GetChildIndexA();
  565. int32 indexB = c->GetChildIndexB();
  566. // Compute the time of impact in interval [0, minTOI]
  567. b2TOIInput input;
  568. input.proxyA.Set(fA->GetShape(), indexA);
  569. input.proxyB.Set(fB->GetShape(), indexB);
  570. input.sweepA = bA->m_sweep;
  571. input.sweepB = bB->m_sweep;
  572. input.tMax = 1.0f;
  573. b2TOIOutput output;
  574. b2TimeOfImpact(&output, &input);
  575. // Beta is the fraction of the remaining portion of the .
  576. float32 beta = output.t;
  577. if (output.state == b2TOIOutput::e_touching)
  578. {
  579. alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f);
  580. }
  581. else
  582. {
  583. alpha = 1.0f;
  584. }
  585. c->m_toi = alpha;
  586. c->m_flags |= b2Contact::e_toiFlag;
  587. }
  588. if (alpha < minAlpha)
  589. {
  590. // This is the minimum TOI found so far.
  591. minContact = c;
  592. minAlpha = alpha;
  593. }
  594. }
  595. if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha)
  596. {
  597. // No more TOI events. Done!
  598. m_stepComplete = true;
  599. break;
  600. }
  601. // Advance the bodies to the TOI.
  602. b2Fixture* fA = minContact->GetFixtureA();
  603. b2Fixture* fB = minContact->GetFixtureB();
  604. b2Body* bA = fA->GetBody();
  605. b2Body* bB = fB->GetBody();
  606. b2Sweep backup1 = bA->m_sweep;
  607. b2Sweep backup2 = bB->m_sweep;
  608. bA->Advance(minAlpha);
  609. bB->Advance(minAlpha);
  610. // The TOI contact likely has some new contact points.
  611. minContact->Update(m_contactManager.m_contactListener);
  612. minContact->m_flags &= ~b2Contact::e_toiFlag;
  613. ++minContact->m_toiCount;
  614. // Is the contact solid?
  615. if (minContact->IsEnabled() == false || minContact->IsTouching() == false)
  616. {
  617. // Restore the sweeps.
  618. minContact->SetEnabled(false);
  619. bA->m_sweep = backup1;
  620. bB->m_sweep = backup2;
  621. bA->SynchronizeTransform();
  622. bB->SynchronizeTransform();
  623. continue;
  624. }
  625. bA->SetAwake(true);
  626. bB->SetAwake(true);
  627. // Build the island
  628. island.Clear();
  629. island.Add(bA);
  630. island.Add(bB);
  631. island.Add(minContact);
  632. bA->m_flags |= b2Body::e_islandFlag;
  633. bB->m_flags |= b2Body::e_islandFlag;
  634. minContact->m_flags |= b2Contact::e_islandFlag;
  635. // Get contacts on bodyA and bodyB.
  636. b2Body* bodies[2] = {bA, bB};
  637. for (int32 i = 0; i < 2; ++i)
  638. {
  639. b2Body* body = bodies[i];
  640. if (body->m_type == b2_dynamicBody)
  641. {
  642. for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next)
  643. {
  644. if (island.m_bodyCount == island.m_bodyCapacity)
  645. {
  646. break;
  647. }
  648. if (island.m_contactCount == island.m_contactCapacity)
  649. {
  650. break;
  651. }
  652. b2Contact* contact = ce->contact;
  653. // Has this contact already been added to the island?
  654. if (contact->m_flags & b2Contact::e_islandFlag)
  655. {
  656. continue;
  657. }
  658. // Only add static, kinematic, or bullet bodies.
  659. b2Body* other = ce->other;
  660. if (other->m_type == b2_dynamicBody &&
  661. body->IsBullet() == false && other->IsBullet() == false)
  662. {
  663. continue;
  664. }
  665. // Skip sensors.
  666. bool sensorA = contact->m_fixtureA->m_isSensor;
  667. bool sensorB = contact->m_fixtureB->m_isSensor;
  668. if (sensorA || sensorB)
  669. {
  670. continue;
  671. }
  672. // Tentatively advance the body to the TOI.
  673. b2Sweep backup = other->m_sweep;
  674. if ((other->m_flags & b2Body::e_islandFlag) == 0)
  675. {
  676. other->Advance(minAlpha);
  677. }
  678. // Update the contact points
  679. contact->Update(m_contactManager.m_contactListener);
  680. // Was the contact disabled by the user?
  681. if (contact->IsEnabled() == false)
  682. {
  683. other->m_sweep = backup;
  684. other->SynchronizeTransform();
  685. continue;
  686. }
  687. // Are there contact points?
  688. if (contact->IsTouching() == false)
  689. {
  690. other->m_sweep = backup;
  691. other->SynchronizeTransform();
  692. continue;
  693. }
  694. // Add the contact to the island
  695. contact->m_flags |= b2Contact::e_islandFlag;
  696. island.Add(contact);
  697. // Has the other body already been added to the island?
  698. if (other->m_flags & b2Body::e_islandFlag)
  699. {
  700. continue;
  701. }
  702. // Add the other body to the island.
  703. other->m_flags |= b2Body::e_islandFlag;
  704. if (other->m_type != b2_staticBody)
  705. {
  706. other->SetAwake(true);
  707. }
  708. island.Add(other);
  709. }
  710. }
  711. }
  712. b2TimeStep subStep;
  713. subStep.dt = (1.0f - minAlpha) * step.dt;
  714. subStep.inv_dt = 1.0f / subStep.dt;
  715. subStep.dtRatio = 1.0f;
  716. subStep.positionIterations = 20;
  717. subStep.velocityIterations = step.velocityIterations;
  718. subStep.warmStarting = false;
  719. island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex);
  720. // Reset island flags and synchronize broad-phase proxies.
  721. for (int32 i = 0; i < island.m_bodyCount; ++i)
  722. {
  723. b2Body* body = island.m_bodies[i];
  724. body->m_flags &= ~b2Body::e_islandFlag;
  725. if (body->m_type != b2_dynamicBody)
  726. {
  727. continue;
  728. }
  729. body->SynchronizeFixtures();
  730. // Invalidate all contact TOIs on this displaced body.
  731. for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next)
  732. {
  733. ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag);
  734. }
  735. }
  736. // Commit fixture proxy movements to the broad-phase so that new contacts are created.
  737. // Also, some contacts can be destroyed.
  738. m_contactManager.FindNewContacts();
  739. if (m_subStepping)
  740. {
  741. m_stepComplete = false;
  742. break;
  743. }
  744. }
  745. }
  746. void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations)
  747. {
  748. b2Timer stepTimer;
  749. // If new fixtures were added, we need to find the new contacts.
  750. if (m_flags & e_newFixture)
  751. {
  752. m_contactManager.FindNewContacts();
  753. m_flags &= ~e_newFixture;
  754. }
  755. m_flags |= e_locked;
  756. b2TimeStep step;
  757. step.dt = dt;
  758. step.velocityIterations = velocityIterations;
  759. step.positionIterations = positionIterations;
  760. if (dt > 0.0f)
  761. {
  762. step.inv_dt = 1.0f / dt;
  763. }
  764. else
  765. {
  766. step.inv_dt = 0.0f;
  767. }
  768. step.dtRatio = m_inv_dt0 * dt;
  769. step.warmStarting = m_warmStarting;
  770. // Update contacts. This is where some contacts are destroyed.
  771. {
  772. b2Timer timer;
  773. m_contactManager.Collide();
  774. m_profile.collide = timer.GetMilliseconds();
  775. }
  776. // Integrate velocities, solve velocity constraints, and integrate positions.
  777. if (m_stepComplete && step.dt > 0.0f)
  778. {
  779. b2Timer timer;
  780. Solve(step);
  781. m_profile.solve = timer.GetMilliseconds();
  782. }
  783. // Handle TOI events.
  784. if (m_continuousPhysics && step.dt > 0.0f)
  785. {
  786. b2Timer timer;
  787. SolveTOI(step);
  788. m_profile.solveTOI = timer.GetMilliseconds();
  789. }
  790. if (step.dt > 0.0f)
  791. {
  792. m_inv_dt0 = step.inv_dt;
  793. }
  794. if (m_flags & e_clearForces)
  795. {
  796. ClearForces();
  797. }
  798. m_flags &= ~e_locked;
  799. m_profile.step = stepTimer.GetMilliseconds();
  800. }
  801. void b2World::ClearForces()
  802. {
  803. for (b2Body* body = m_bodyList; body; body = body->GetNext())
  804. {
  805. body->m_force.SetZero();
  806. body->m_torque = 0.0f;
  807. }
  808. }
  809. struct b2WorldQueryWrapper
  810. {
  811. bool QueryCallback(int32 proxyId)
  812. {
  813. b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId);
  814. return callback->ReportFixture(proxy->fixture);
  815. }
  816. const b2BroadPhase* broadPhase;
  817. b2QueryCallback* callback;
  818. };
  819. void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const
  820. {
  821. b2WorldQueryWrapper wrapper;
  822. wrapper.broadPhase = &m_contactManager.m_broadPhase;
  823. wrapper.callback = callback;
  824. m_contactManager.m_broadPhase.Query(&wrapper, aabb);
  825. }
  826. struct b2WorldRayCastWrapper
  827. {
  828. float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId)
  829. {
  830. void* userData = broadPhase->GetUserData(proxyId);
  831. b2FixtureProxy* proxy = (b2FixtureProxy*)userData;
  832. b2Fixture* fixture = proxy->fixture;
  833. int32 index = proxy->childIndex;
  834. b2RayCastOutput output;
  835. bool hit = fixture->RayCast(&output, input, index);
  836. if (hit)
  837. {
  838. float32 fraction = output.fraction;
  839. b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2;
  840. return callback->ReportFixture(fixture, point, output.normal, fraction);
  841. }
  842. return input.maxFraction;
  843. }
  844. const b2BroadPhase* broadPhase;
  845. b2RayCastCallback* callback;
  846. };
  847. void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const
  848. {
  849. b2WorldRayCastWrapper wrapper;
  850. wrapper.broadPhase = &m_contactManager.m_broadPhase;
  851. wrapper.callback = callback;
  852. b2RayCastInput input;
  853. input.maxFraction = 1.0f;
  854. input.p1 = point1;
  855. input.p2 = point2;
  856. m_contactManager.m_broadPhase.RayCast(&wrapper, input);
  857. }
  858. void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color)
  859. {
  860. switch (fixture->GetType())
  861. {
  862. case b2Shape::e_circle:
  863. {
  864. b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();
  865. b2Vec2 center = b2Mul(xf, circle->m_p);
  866. float32 radius = circle->m_radius;
  867. b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f));
  868. g_debugDraw->DrawSolidCircle(center, radius, axis, color);
  869. }
  870. break;
  871. case b2Shape::e_edge:
  872. {
  873. b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape();
  874. b2Vec2 v1 = b2Mul(xf, edge->m_vertex1);
  875. b2Vec2 v2 = b2Mul(xf, edge->m_vertex2);
  876. g_debugDraw->DrawSegment(v1, v2, color);
  877. }
  878. break;
  879. case b2Shape::e_chain:
  880. {
  881. b2ChainShape* chain = (b2ChainShape*)fixture->GetShape();
  882. int32 count = chain->m_count;
  883. const b2Vec2* vertices = chain->m_vertices;
  884. b2Vec2 v1 = b2Mul(xf, vertices[0]);
  885. for (int32 i = 1; i < count; ++i)
  886. {
  887. b2Vec2 v2 = b2Mul(xf, vertices[i]);
  888. g_debugDraw->DrawSegment(v1, v2, color);
  889. g_debugDraw->DrawCircle(v1, 0.05f, color);
  890. v1 = v2;
  891. }
  892. }
  893. break;
  894. case b2Shape::e_polygon:
  895. {
  896. b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
  897. int32 vertexCount = poly->m_count;
  898. b2Assert(vertexCount <= b2_maxPolygonVertices);
  899. b2Vec2 vertices[b2_maxPolygonVertices];
  900. for (int32 i = 0; i < vertexCount; ++i)
  901. {
  902. vertices[i] = b2Mul(xf, poly->m_vertices[i]);
  903. }
  904. g_debugDraw->DrawSolidPolygon(vertices, vertexCount, color);
  905. }
  906. break;
  907. default:
  908. break;
  909. }
  910. }
  911. void b2World::DrawJoint(b2Joint* joint)
  912. {
  913. b2Body* bodyA = joint->GetBodyA();
  914. b2Body* bodyB = joint->GetBodyB();
  915. const b2Transform& xf1 = bodyA->GetTransform();
  916. const b2Transform& xf2 = bodyB->GetTransform();
  917. b2Vec2 x1 = xf1.p;
  918. b2Vec2 x2 = xf2.p;
  919. b2Vec2 p1 = joint->GetAnchorA();
  920. b2Vec2 p2 = joint->GetAnchorB();
  921. b2Color color(0.5f, 0.8f, 0.8f);
  922. switch (joint->GetType())
  923. {
  924. case e_distanceJoint:
  925. g_debugDraw->DrawSegment(p1, p2, color);
  926. break;
  927. case e_pulleyJoint:
  928. {
  929. b2PulleyJoint* pulley = (b2PulleyJoint*)joint;
  930. b2Vec2 s1 = pulley->GetGroundAnchorA();
  931. b2Vec2 s2 = pulley->GetGroundAnchorB();
  932. g_debugDraw->DrawSegment(s1, p1, color);
  933. g_debugDraw->DrawSegment(s2, p2, color);
  934. g_debugDraw->DrawSegment(s1, s2, color);
  935. }
  936. break;
  937. case e_mouseJoint:
  938. // don't draw this
  939. break;
  940. default:
  941. g_debugDraw->DrawSegment(x1, p1, color);
  942. g_debugDraw->DrawSegment(p1, p2, color);
  943. g_debugDraw->DrawSegment(x2, p2, color);
  944. }
  945. }
  946. void b2World::DrawDebugData()
  947. {
  948. if (g_debugDraw == NULL)
  949. {
  950. return;
  951. }
  952. g_debugDraw->ClearDraw();
  953. uint32 flags = g_debugDraw->GetFlags();
  954. if (flags & b2Draw::e_shapeBit)
  955. {
  956. for (b2Body* b = m_bodyList; b; b = b->GetNext())
  957. {
  958. const b2Transform& xf = b->GetTransform();
  959. for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
  960. {
  961. if (b->IsActive() == false)
  962. {
  963. DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f));
  964. }
  965. else if (b->GetType() == b2_staticBody)
  966. {
  967. DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f));
  968. }
  969. else if (b->GetType() == b2_kinematicBody)
  970. {
  971. DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f));
  972. }
  973. else if (b->IsAwake() == false)
  974. {
  975. DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f));
  976. }
  977. else
  978. {
  979. DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f));
  980. }
  981. }
  982. }
  983. }
  984. if (flags & b2Draw::e_jointBit)
  985. {
  986. for (b2Joint* j = m_jointList; j; j = j->GetNext())
  987. {
  988. DrawJoint(j);
  989. }
  990. }
  991. if (flags & b2Draw::e_pairBit)
  992. {
  993. b2Color color(0.3f, 0.9f, 0.9f);
  994. for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext())
  995. {
  996. //b2Fixture* fixtureA = c->GetFixtureA();
  997. //b2Fixture* fixtureB = c->GetFixtureB();
  998. //b2Vec2 cA = fixtureA->GetAABB().GetCenter();
  999. //b2Vec2 cB = fixtureB->GetAABB().GetCenter();
  1000. //g_debugDraw->DrawSegment(cA, cB, color);
  1001. }
  1002. }
  1003. if (flags & b2Draw::e_aabbBit)
  1004. {
  1005. b2Color color(0.9f, 0.3f, 0.9f);
  1006. b2BroadPhase* bp = &m_contactManager.m_broadPhase;
  1007. for (b2Body* b = m_bodyList; b; b = b->GetNext())
  1008. {
  1009. if (b->IsActive() == false)
  1010. {
  1011. continue;
  1012. }
  1013. for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext())
  1014. {
  1015. for (int32 i = 0; i < f->m_proxyCount; ++i)
  1016. {
  1017. b2FixtureProxy* proxy = f->m_proxies + i;
  1018. b2AABB aabb = bp->GetFatAABB(proxy->proxyId);
  1019. b2Vec2 vs[4];
  1020. vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y);
  1021. vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y);
  1022. vs[2].Set(aabb.upperBound.x, aabb.upperBound.y);
  1023. vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y);
  1024. g_debugDraw->DrawPolygon(vs, 4, color);
  1025. }
  1026. }
  1027. }
  1028. }
  1029. if (flags & b2Draw::e_centerOfMassBit)
  1030. {
  1031. for (b2Body* b = m_bodyList; b; b = b->GetNext())
  1032. {
  1033. b2Transform xf = b->GetTransform();
  1034. xf.p = b->GetWorldCenter();
  1035. g_debugDraw->DrawTransform(xf);
  1036. }
  1037. }
  1038. }
  1039. int32 b2World::GetProxyCount() const
  1040. {
  1041. return m_contactManager.m_broadPhase.GetProxyCount();
  1042. }
  1043. int32 b2World::GetTreeHeight() const
  1044. {
  1045. return m_contactManager.m_broadPhase.GetTreeHeight();
  1046. }
  1047. int32 b2World::GetTreeBalance() const
  1048. {
  1049. return m_contactManager.m_broadPhase.GetTreeBalance();
  1050. }
  1051. float32 b2World::GetTreeQuality() const
  1052. {
  1053. return m_contactManager.m_broadPhase.GetTreeQuality();
  1054. }
  1055. void b2World::ShiftOrigin(const b2Vec2& newOrigin)
  1056. {
  1057. b2Assert((m_flags & e_locked) == 0);
  1058. if ((m_flags & e_locked) == e_locked)
  1059. {
  1060. return;
  1061. }
  1062. for (b2Body* b = m_bodyList; b; b = b->m_next)
  1063. {
  1064. b->m_xf.p -= newOrigin;
  1065. b->m_sweep.c0 -= newOrigin;
  1066. b->m_sweep.c -= newOrigin;
  1067. }
  1068. for (b2Joint* j = m_jointList; j; j = j->m_next)
  1069. {
  1070. j->ShiftOrigin(newOrigin);
  1071. }
  1072. m_contactManager.m_broadPhase.ShiftOrigin(newOrigin);
  1073. }
  1074. void b2World::Dump()
  1075. {
  1076. if ((m_flags & e_locked) == e_locked)
  1077. {
  1078. return;
  1079. }
  1080. b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y);
  1081. b2Log("m_world->SetGravity(g);\n");
  1082. b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount);
  1083. b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount);
  1084. int32 i = 0;
  1085. for (b2Body* b = m_bodyList; b; b = b->m_next)
  1086. {
  1087. b->m_islandIndex = i;
  1088. b->Dump();
  1089. ++i;
  1090. }
  1091. i = 0;
  1092. for (b2Joint* j = m_jointList; j; j = j->m_next)
  1093. {
  1094. j->m_index = i;
  1095. ++i;
  1096. }
  1097. // First pass on joints, skip gear joints.
  1098. for (b2Joint* j = m_jointList; j; j = j->m_next)
  1099. {
  1100. if (j->m_type == e_gearJoint)
  1101. {
  1102. continue;
  1103. }
  1104. b2Log("{\n");
  1105. j->Dump();
  1106. b2Log("}\n");
  1107. }
  1108. // Second pass on joints, only gear joints.
  1109. for (b2Joint* j = m_jointList; j; j = j->m_next)
  1110. {
  1111. if (j->m_type != e_gearJoint)
  1112. {
  1113. continue;
  1114. }
  1115. b2Log("{\n");
  1116. j->Dump();
  1117. b2Log("}\n");
  1118. }
  1119. b2Log("b2Free(joints);\n");
  1120. b2Log("b2Free(bodies);\n");
  1121. b2Log("joints = NULL;\n");
  1122. b2Log("bodies = NULL;\n");
  1123. }