b2World.cpp 29 KB

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