CCPhysicsWorld.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. /****************************************************************************
  2. Copyright (c) 2013-2017 Chukong Technologies Inc.
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #include "physics/CCPhysicsWorld.h"
  21. #if CC_USE_PHYSICS
  22. #include <algorithm>
  23. #include <climits>
  24. #include "chipmunk/chipmunk_private.h"
  25. #include "physics/CCPhysicsBody.h"
  26. #include "physics/CCPhysicsShape.h"
  27. #include "physics/CCPhysicsContact.h"
  28. #include "physics/CCPhysicsJoint.h"
  29. #include "physics/CCPhysicsHelper.h"
  30. #include "2d/CCDrawNode.h"
  31. #include "2d/CCScene.h"
  32. #include "base/CCDirector.h"
  33. #include "base/CCEventDispatcher.h"
  34. #include "base/CCEventCustom.h"
  35. NS_CC_BEGIN
  36. const float PHYSICS_INFINITY = FLT_MAX;
  37. extern const char* PHYSICSCONTACT_EVENT_NAME;
  38. const int PhysicsWorld::DEBUGDRAW_NONE = 0x00;
  39. const int PhysicsWorld::DEBUGDRAW_SHAPE = 0x01;
  40. const int PhysicsWorld::DEBUGDRAW_JOINT = 0x02;
  41. const int PhysicsWorld::DEBUGDRAW_CONTACT = 0x04;
  42. const int PhysicsWorld::DEBUGDRAW_ALL = DEBUGDRAW_SHAPE | DEBUGDRAW_JOINT | DEBUGDRAW_CONTACT;
  43. namespace
  44. {
  45. typedef struct RayCastCallbackInfo
  46. {
  47. PhysicsWorld* world;
  48. PhysicsRayCastCallbackFunc func;
  49. Vec2 p1;
  50. Vec2 p2;
  51. void* data;
  52. }RayCastCallbackInfo;
  53. typedef struct RectQueryCallbackInfo
  54. {
  55. PhysicsWorld* world;
  56. PhysicsQueryRectCallbackFunc func;
  57. void* data;
  58. }RectQueryCallbackInfo;
  59. typedef struct PointQueryCallbackInfo
  60. {
  61. PhysicsWorld* world;
  62. PhysicsQueryPointCallbackFunc func;
  63. void* data;
  64. }PointQueryCallbackInfo;
  65. }
  66. class PhysicsWorldCallback
  67. {
  68. public:
  69. static cpBool collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace *space, PhysicsWorld *world);
  70. static cpBool collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world);
  71. static void collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world);
  72. static void collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace *space, PhysicsWorld *world);
  73. static void rayCastCallbackFunc(cpShape *shape, cpVect point, cpVect normal, cpFloat alpha, RayCastCallbackInfo *info);
  74. static void queryRectCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info);
  75. static void queryPointFunc(cpShape *shape, cpVect point, cpFloat distance, cpVect gradient, PointQueryCallbackInfo *info);
  76. static void getShapesAtPointFunc(cpShape *shape, cpVect point, cpFloat distance, cpVect gradient, Vector<PhysicsShape*>* arr);
  77. public:
  78. static bool continues;
  79. };
  80. bool PhysicsWorldCallback::continues = true;
  81. cpBool PhysicsWorldCallback::collisionBeginCallbackFunc(cpArbiter *arb, struct cpSpace* /*space*/, PhysicsWorld *world)
  82. {
  83. CP_ARBITER_GET_SHAPES(arb, a, b);
  84. PhysicsShape *shapeA = static_cast<PhysicsShape*>(cpShapeGetUserData(a));
  85. PhysicsShape *shapeB = static_cast<PhysicsShape*>(cpShapeGetUserData(b));
  86. CC_ASSERT(shapeA != nullptr && shapeB != nullptr);
  87. auto contact = PhysicsContact::construct(shapeA, shapeB);
  88. cpArbiterSetUserData(arb, contact);
  89. contact->_contactInfo = arb;
  90. return world->collisionBeginCallback(*contact);
  91. }
  92. cpBool PhysicsWorldCallback::collisionPreSolveCallbackFunc(cpArbiter *arb, cpSpace* /*space*/, PhysicsWorld *world)
  93. {
  94. return world->collisionPreSolveCallback(*static_cast<PhysicsContact*>(cpArbiterGetUserData(arb)));
  95. }
  96. void PhysicsWorldCallback::collisionPostSolveCallbackFunc(cpArbiter *arb, cpSpace* /*space*/, PhysicsWorld *world)
  97. {
  98. world->collisionPostSolveCallback(*static_cast<PhysicsContact*>(cpArbiterGetUserData(arb)));
  99. }
  100. void PhysicsWorldCallback::collisionSeparateCallbackFunc(cpArbiter *arb, cpSpace* /*space*/, PhysicsWorld *world)
  101. {
  102. PhysicsContact* contact = static_cast<PhysicsContact*>(cpArbiterGetUserData(arb));
  103. world->collisionSeparateCallback(*contact);
  104. delete contact;
  105. }
  106. void PhysicsWorldCallback::rayCastCallbackFunc(cpShape *shape, cpVect point, cpVect normal, cpFloat alpha, RayCastCallbackInfo *info)
  107. {
  108. if (!PhysicsWorldCallback::continues)
  109. {
  110. return;
  111. }
  112. PhysicsShape *physicsShape = static_cast<PhysicsShape*>(cpShapeGetUserData(shape));
  113. CC_ASSERT(physicsShape != nullptr);
  114. PhysicsRayCastInfo callbackInfo =
  115. {
  116. physicsShape,
  117. info->p1,
  118. info->p2,
  119. PhysicsHelper::cpv2point(point),
  120. PhysicsHelper::cpv2point(normal),
  121. static_cast<float>(alpha),
  122. };
  123. PhysicsWorldCallback::continues = info->func(*info->world, callbackInfo, info->data);
  124. }
  125. void PhysicsWorldCallback::queryRectCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info)
  126. {
  127. PhysicsShape *physicsShape = static_cast<PhysicsShape*>(cpShapeGetUserData(shape));
  128. CC_ASSERT(physicsShape != nullptr);
  129. if (!PhysicsWorldCallback::continues)
  130. {
  131. return;
  132. }
  133. PhysicsWorldCallback::continues = info->func(*info->world, *physicsShape, info->data);
  134. }
  135. void PhysicsWorldCallback::getShapesAtPointFunc(cpShape *shape, cpVect /*point*/, cpFloat /*distance*/, cpVect /*gradient*/, Vector<PhysicsShape*>* arr)
  136. {
  137. PhysicsShape *physicsShape = static_cast<PhysicsShape*>(cpShapeGetUserData(shape));
  138. CC_ASSERT(physicsShape != nullptr);
  139. arr->pushBack(physicsShape);
  140. }
  141. void PhysicsWorldCallback::queryPointFunc(cpShape *shape, cpVect /*point*/, cpFloat /*distance*/, cpVect /*gradient*/, PointQueryCallbackInfo *info)
  142. {
  143. PhysicsShape *physicsShape = static_cast<PhysicsShape*>(cpShapeGetUserData(shape));
  144. CC_ASSERT(physicsShape != nullptr);
  145. PhysicsWorldCallback::continues = info->func(*info->world, *physicsShape, info->data);
  146. }
  147. static inline cpSpaceDebugColor RGBAColor(float r, float g, float b, float a){
  148. cpSpaceDebugColor color = {r, g, b, a};
  149. return color;
  150. }
  151. static inline cpSpaceDebugColor LAColor(float l, float a){
  152. cpSpaceDebugColor color = {l, l, l, a};
  153. return color;
  154. }
  155. static void DrawCircle(cpVect p, cpFloat /*a*/, cpFloat r, cpSpaceDebugColor outline, cpSpaceDebugColor fill, cpDataPointer data)
  156. {
  157. const Color4F fillColor(fill.r, fill.g, fill.b, fill.a);
  158. const Color4F outlineColor(outline.r, outline.g, outline.b, outline.a);
  159. DrawNode* drawNode = static_cast<DrawNode*>(data);
  160. float radius = PhysicsHelper::cpfloat2float(r);
  161. Vec2 centre = PhysicsHelper::cpv2point(p);
  162. static const int CIRCLE_SEG_NUM = 12;
  163. Vec2 seg[CIRCLE_SEG_NUM] = {};
  164. for (int i = 0; i < CIRCLE_SEG_NUM; ++i)
  165. {
  166. float angle = (float)i * M_PI / (float)CIRCLE_SEG_NUM * 2.0f;
  167. Vec2 d(radius * cosf(angle), radius * sinf(angle));
  168. seg[i] = centre + d;
  169. }
  170. drawNode->drawPolygon(seg, CIRCLE_SEG_NUM, fillColor, 1, outlineColor);
  171. }
  172. static void DrawFatSegment(cpVect a, cpVect b, cpFloat r, cpSpaceDebugColor outline, cpSpaceDebugColor /*fill*/, cpDataPointer data)
  173. {
  174. const Color4F outlineColor(outline.r, outline.g, outline.b, outline.a);
  175. DrawNode* drawNode = static_cast<DrawNode*>(data);
  176. drawNode->drawSegment(PhysicsHelper::cpv2point(a),
  177. PhysicsHelper::cpv2point(b),
  178. PhysicsHelper::cpfloat2float(r==0 ? 1 : r), outlineColor);
  179. }
  180. static void DrawSegment(cpVect a, cpVect b, cpSpaceDebugColor color, cpDataPointer data)
  181. {
  182. DrawFatSegment(a, b, 0.0, color, color, data);
  183. }
  184. static void DrawPolygon(int count, const cpVect *verts, cpFloat /*r*/, cpSpaceDebugColor outline, cpSpaceDebugColor fill, cpDataPointer data)
  185. {
  186. const Color4F fillColor(fill.r, fill.g, fill.b, fill.a);
  187. const Color4F outlineColor(outline.r, outline.g, outline.b, outline.a);
  188. DrawNode* drawNode = static_cast<DrawNode*>(data);
  189. int num = count;
  190. Vec2* seg = new (std::nothrow) Vec2[num];
  191. for(int i=0;i<num;++i)
  192. seg[i] = PhysicsHelper::cpv2point(verts[i]);
  193. drawNode->drawPolygon(seg, num, fillColor, 1.0f, outlineColor);
  194. delete[] seg;
  195. }
  196. static void DrawDot(cpFloat /*size*/, cpVect pos, cpSpaceDebugColor color, cpDataPointer data)
  197. {
  198. const Color4F dotColor(color.r, color.g, color.b, color.a);
  199. DrawNode* drawNode = static_cast<DrawNode*>(data);
  200. drawNode->drawDot(PhysicsHelper::cpv2point(pos), 2, dotColor);
  201. }
  202. static cpSpaceDebugColor ColorForShape(cpShape *shape, cpDataPointer /*data*/)
  203. {
  204. if(cpShapeGetSensor(shape)){
  205. return LAColor(1.0f, 0.3f);
  206. } else {
  207. cpBody *body = cpShapeGetBody(shape);
  208. if(cpBodyIsSleeping(body)){
  209. return LAColor(0.2f, 0.3f);
  210. } else if(body->sleeping.idleTime > shape->space->sleepTimeThreshold) {
  211. return LAColor(0.66f, 0.3f);
  212. } else {
  213. GLfloat intensity = (cpBodyGetType(body) == CP_BODY_TYPE_STATIC ? 0.15f : 0.75f);
  214. return RGBAColor(intensity, 0.0f, 0.0f, 0.3f);
  215. }
  216. }
  217. }
  218. void PhysicsWorld::debugDraw()
  219. {
  220. if (_debugDraw == nullptr)
  221. {
  222. _debugDraw = DrawNode::create();
  223. _debugDraw->retain();
  224. Director::getInstance()->getRunningScene()->addChild(_debugDraw);
  225. }
  226. cpSpaceDebugDrawOptions drawOptions = {
  227. DrawCircle,
  228. DrawSegment,
  229. DrawFatSegment,
  230. DrawPolygon,
  231. DrawDot,
  232. (cpSpaceDebugDrawFlags)(_debugDrawMask),
  233. {1.0f, 0.0f, 0.0f, 1.0f},
  234. ColorForShape,
  235. {0.0f, 0.75f, 0.0f, 1.0f},
  236. {0.0f, 0.0f, 1.0f, 1.0f},
  237. _debugDraw,
  238. };
  239. if (_debugDraw)
  240. {
  241. _debugDraw->clear();
  242. cpSpaceDebugDraw(_cpSpace, &drawOptions);
  243. }
  244. }
  245. bool PhysicsWorld::collisionBeginCallback(PhysicsContact& contact)
  246. {
  247. bool ret = true;
  248. PhysicsShape* shapeA = contact.getShapeA();
  249. PhysicsShape* shapeB = contact.getShapeB();
  250. PhysicsBody* bodyA = shapeA->getBody();
  251. PhysicsBody* bodyB = shapeB->getBody();
  252. std::vector<PhysicsJoint*> jointsA = bodyA->getJoints();
  253. // check the joint is collision enable or not
  254. for (PhysicsJoint* joint : jointsA)
  255. {
  256. if (std::find(_joints.begin(), _joints.end(), joint) == _joints.end())
  257. {
  258. continue;
  259. }
  260. if (!joint->isCollisionEnabled())
  261. {
  262. PhysicsBody* body = joint->getBodyA() == bodyA ? joint->getBodyB() : joint->getBodyA();
  263. if (body == bodyB)
  264. {
  265. contact.setNotificationEnable(false);
  266. return false;
  267. }
  268. }
  269. }
  270. // bitmask check
  271. if ((shapeA->getCategoryBitmask() & shapeB->getContactTestBitmask()) == 0
  272. || (shapeA->getContactTestBitmask() & shapeB->getCategoryBitmask()) == 0)
  273. {
  274. contact.setNotificationEnable(false);
  275. }
  276. if (shapeA->getGroup() != 0 && shapeA->getGroup() == shapeB->getGroup())
  277. {
  278. ret = shapeA->getGroup() > 0;
  279. }
  280. else
  281. {
  282. if ((shapeA->getCategoryBitmask() & shapeB->getCollisionBitmask()) == 0
  283. || (shapeB->getCategoryBitmask() & shapeA->getCollisionBitmask()) == 0)
  284. {
  285. ret = false;
  286. }
  287. }
  288. if (contact.isNotificationEnabled())
  289. {
  290. contact.setEventCode(PhysicsContact::EventCode::BEGIN);
  291. contact.setWorld(this);
  292. _eventDispatcher->dispatchEvent(&contact);
  293. }
  294. return ret ? contact.resetResult() : false;
  295. }
  296. bool PhysicsWorld::collisionPreSolveCallback(PhysicsContact& contact)
  297. {
  298. if (!contact.isNotificationEnabled())
  299. {
  300. return true;
  301. }
  302. contact.setEventCode(PhysicsContact::EventCode::PRESOLVE);
  303. contact.setWorld(this);
  304. _eventDispatcher->dispatchEvent(&contact);
  305. return contact.resetResult();
  306. }
  307. void PhysicsWorld::collisionPostSolveCallback(PhysicsContact& contact)
  308. {
  309. if (!contact.isNotificationEnabled())
  310. {
  311. return;
  312. }
  313. contact.setEventCode(PhysicsContact::EventCode::POSTSOLVE);
  314. contact.setWorld(this);
  315. _eventDispatcher->dispatchEvent(&contact);
  316. }
  317. void PhysicsWorld::collisionSeparateCallback(PhysicsContact& contact)
  318. {
  319. if (!contact.isNotificationEnabled())
  320. {
  321. return;
  322. }
  323. contact.setEventCode(PhysicsContact::EventCode::SEPARATE);
  324. contact.setWorld(this);
  325. _eventDispatcher->dispatchEvent(&contact);
  326. }
  327. void PhysicsWorld::rayCast(PhysicsRayCastCallbackFunc func, const Vec2& point1, const Vec2& point2, void* data)
  328. {
  329. CCASSERT(func != nullptr, "func shouldn't be nullptr");
  330. if (func != nullptr)
  331. {
  332. if (!_delayAddBodies.empty() || !_delayRemoveBodies.empty())
  333. {
  334. updateBodies();
  335. }
  336. RayCastCallbackInfo info = { this, func, point1, point2, data };
  337. PhysicsWorldCallback::continues = true;
  338. cpSpaceSegmentQuery(_cpSpace,
  339. PhysicsHelper::point2cpv(point1),
  340. PhysicsHelper::point2cpv(point2),
  341. 0.0f,
  342. CP_SHAPE_FILTER_ALL,
  343. (cpSpaceSegmentQueryFunc)PhysicsWorldCallback::rayCastCallbackFunc,
  344. &info);
  345. }
  346. }
  347. void PhysicsWorld::queryRect(PhysicsQueryRectCallbackFunc func, const Rect& rect, void* data)
  348. {
  349. CCASSERT(func != nullptr, "func shouldn't be nullptr");
  350. if (func != nullptr)
  351. {
  352. if (!_delayAddBodies.empty() || !_delayRemoveBodies.empty())
  353. {
  354. updateBodies();
  355. }
  356. RectQueryCallbackInfo info = {this, func, data};
  357. PhysicsWorldCallback::continues = true;
  358. cpSpaceBBQuery(_cpSpace,
  359. PhysicsHelper::rect2cpbb(rect),
  360. CP_SHAPE_FILTER_ALL,
  361. (cpSpaceBBQueryFunc)PhysicsWorldCallback::queryRectCallbackFunc,
  362. &info);
  363. }
  364. }
  365. void PhysicsWorld::queryPoint(PhysicsQueryPointCallbackFunc func, const Vec2& point, void* data)
  366. {
  367. CCASSERT(func != nullptr, "func shouldn't be nullptr");
  368. if (func != nullptr)
  369. {
  370. if (!_delayAddBodies.empty() || !_delayRemoveBodies.empty())
  371. {
  372. updateBodies();
  373. }
  374. PointQueryCallbackInfo info = {this, func, data};
  375. PhysicsWorldCallback::continues = true;
  376. cpSpacePointQuery(_cpSpace,
  377. PhysicsHelper::point2cpv(point),
  378. 0,
  379. CP_SHAPE_FILTER_ALL,
  380. (cpSpacePointQueryFunc)PhysicsWorldCallback::queryPointFunc,
  381. &info);
  382. }
  383. }
  384. Vector<PhysicsShape*> PhysicsWorld::getShapes(const Vec2& point) const
  385. {
  386. Vector<PhysicsShape*> arr;
  387. cpSpacePointQuery(_cpSpace,
  388. PhysicsHelper::point2cpv(point),
  389. 0,
  390. CP_SHAPE_FILTER_ALL,
  391. (cpSpacePointQueryFunc)PhysicsWorldCallback::getShapesAtPointFunc,
  392. &arr);
  393. return arr;
  394. }
  395. PhysicsShape* PhysicsWorld::getShape(const Vec2& point) const
  396. {
  397. cpShape* shape = cpSpacePointQueryNearest(_cpSpace,
  398. PhysicsHelper::point2cpv(point),
  399. 0,
  400. CP_SHAPE_FILTER_ALL,
  401. nullptr);
  402. return shape == nullptr ? nullptr : static_cast<PhysicsShape*>(cpShapeGetUserData(shape));
  403. }
  404. bool PhysicsWorld::init()
  405. {
  406. do
  407. {
  408. #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  409. _cpSpace = cpSpaceNew();
  410. #else
  411. _cpSpace = cpHastySpaceNew();
  412. cpHastySpaceSetThreads(_cpSpace, 0);
  413. #endif
  414. CC_BREAK_IF(_cpSpace == nullptr);
  415. cpSpaceSetGravity(_cpSpace, PhysicsHelper::point2cpv(_gravity));
  416. cpCollisionHandler *handler = cpSpaceAddDefaultCollisionHandler(_cpSpace);
  417. handler->userData = this;
  418. handler->beginFunc = (cpCollisionBeginFunc)PhysicsWorldCallback::collisionBeginCallbackFunc;
  419. handler->preSolveFunc = (cpCollisionPreSolveFunc)PhysicsWorldCallback::collisionPreSolveCallbackFunc;
  420. handler->postSolveFunc = (cpCollisionPostSolveFunc)PhysicsWorldCallback::collisionPostSolveCallbackFunc;
  421. handler->separateFunc = (cpCollisionSeparateFunc)PhysicsWorldCallback::collisionSeparateCallbackFunc;
  422. return true;
  423. } while (false);
  424. return false;
  425. }
  426. void PhysicsWorld::addBody(PhysicsBody* body)
  427. {
  428. CCASSERT(body != nullptr, "the body can not be nullptr");
  429. if (body->getWorld() == this)
  430. {
  431. return;
  432. }
  433. if (body->getWorld() != nullptr)
  434. {
  435. body->removeFromWorld();
  436. }
  437. addBodyOrDelay(body);
  438. _bodies.pushBack(body);
  439. body->_world = this;
  440. }
  441. void PhysicsWorld::doAddBody(PhysicsBody* body)
  442. {
  443. if (body->isEnabled())
  444. {
  445. // add body to space
  446. if (!cpSpaceContainsBody(_cpSpace, body->_cpBody))
  447. {
  448. cpSpaceAddBody(_cpSpace, body->_cpBody);
  449. }
  450. // add shapes to space
  451. for (auto& shape : body->getShapes())
  452. {
  453. addShape(dynamic_cast<PhysicsShape*>(shape));
  454. }
  455. }
  456. }
  457. void PhysicsWorld::addBodyOrDelay(PhysicsBody* body)
  458. {
  459. auto removeBodyIter = _delayRemoveBodies.find(body);
  460. if (removeBodyIter != _delayRemoveBodies.end())
  461. {
  462. _delayRemoveBodies.erase(removeBodyIter);
  463. return;
  464. }
  465. if (_delayAddBodies.find(body) == _delayAddBodies.end())
  466. {
  467. _delayAddBodies.pushBack(body);
  468. }
  469. }
  470. void PhysicsWorld::updateBodies()
  471. {
  472. if (cpSpaceIsLocked(_cpSpace))
  473. {
  474. return;
  475. }
  476. // issue #4944, contact callback will be invoked when add/remove body, _delayAddBodies maybe changed, so we need make a copy.
  477. auto addCopy = _delayAddBodies;
  478. _delayAddBodies.clear();
  479. for (auto& body : addCopy)
  480. {
  481. doAddBody(body);
  482. }
  483. auto removeCopy = _delayRemoveBodies;
  484. _delayRemoveBodies.clear();
  485. for (auto& body : removeCopy)
  486. {
  487. doRemoveBody(body);
  488. }
  489. }
  490. void PhysicsWorld::removeBody(int tag)
  491. {
  492. for (auto& body : _bodies)
  493. {
  494. if (body->getTag() == tag)
  495. {
  496. removeBody(body);
  497. return;
  498. }
  499. }
  500. }
  501. void PhysicsWorld::removeBody(PhysicsBody* body)
  502. {
  503. if (body->getWorld() != this)
  504. {
  505. CCLOG("Physics Warning: this body doesn't belong to this world");
  506. return;
  507. }
  508. // destroy the body's joints
  509. auto removeCopy = body->_joints;
  510. for (auto joint : removeCopy)
  511. {
  512. removeJoint(joint, true);
  513. }
  514. body->_joints.clear();
  515. removeBodyOrDelay(body);
  516. _bodies.eraseObject(body);
  517. body->_world = nullptr;
  518. }
  519. void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body)
  520. {
  521. if (_delayAddBodies.getIndex(body) != CC_INVALID_INDEX)
  522. {
  523. _delayAddBodies.eraseObject(body);
  524. return;
  525. }
  526. if (cpSpaceIsLocked(_cpSpace))
  527. {
  528. if (_delayRemoveBodies.getIndex(body) == CC_INVALID_INDEX)
  529. {
  530. _delayRemoveBodies.pushBack(body);
  531. }
  532. }else
  533. {
  534. doRemoveBody(body);
  535. }
  536. }
  537. void PhysicsWorld::removeJoint(PhysicsJoint* joint, bool destroy)
  538. {
  539. if (joint)
  540. {
  541. if (joint->getWorld() != this && destroy)
  542. {
  543. CCLOG("physics warning: the joint is not in this world, it won't be destroyed until the body it connects is destroyed");
  544. return;
  545. }
  546. joint->_destroyMark = destroy;
  547. bool removedFromDelayAdd = false;
  548. auto it = std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint);
  549. if (it != _delayAddJoints.end())
  550. {
  551. _delayAddJoints.erase(it);
  552. removedFromDelayAdd = true;
  553. }
  554. if (cpSpaceIsLocked(_cpSpace))
  555. {
  556. if (removedFromDelayAdd)
  557. return;
  558. if (std::find(_delayRemoveJoints.rbegin(), _delayRemoveJoints.rend(), joint) == _delayRemoveJoints.rend())
  559. {
  560. _delayRemoveJoints.push_back(joint);
  561. }
  562. }
  563. else
  564. {
  565. doRemoveJoint(joint);
  566. }
  567. }
  568. }
  569. void PhysicsWorld::updateJoints()
  570. {
  571. if (cpSpaceIsLocked(_cpSpace))
  572. {
  573. return;
  574. }
  575. for (auto joint : _delayAddJoints)
  576. {
  577. joint->_world = this;
  578. if (joint->initJoint())
  579. {
  580. _joints.push_back(joint);
  581. }
  582. else
  583. {
  584. delete joint;
  585. }
  586. }
  587. _delayAddJoints.clear();
  588. for (auto joint : _delayRemoveJoints)
  589. {
  590. doRemoveJoint(joint);
  591. }
  592. _delayRemoveJoints.clear();
  593. }
  594. void PhysicsWorld::removeShape(PhysicsShape* shape)
  595. {
  596. if (shape)
  597. {
  598. for (auto cps : shape->_cpShapes)
  599. {
  600. if (cpSpaceContainsShape(_cpSpace, cps))
  601. {
  602. cpSpaceRemoveShape(_cpSpace, cps);
  603. }
  604. }
  605. }
  606. }
  607. void PhysicsWorld::addJoint(PhysicsJoint* joint)
  608. {
  609. if (joint)
  610. {
  611. CCASSERT(joint->getWorld() == nullptr, "Can not add joint already add to other world!");
  612. joint->_world = this;
  613. auto it = std::find(_delayRemoveJoints.begin(), _delayRemoveJoints.end(), joint);
  614. if (it != _delayRemoveJoints.end())
  615. {
  616. _delayRemoveJoints.erase(it);
  617. return;
  618. }
  619. if (std::find(_delayAddJoints.begin(), _delayAddJoints.end(), joint) == _delayAddJoints.end())
  620. {
  621. _delayAddJoints.push_back(joint);
  622. }
  623. }
  624. }
  625. void PhysicsWorld::removeAllJoints(bool destroy)
  626. {
  627. auto removeCopy = _joints;
  628. for (auto joint : removeCopy)
  629. {
  630. removeJoint(joint, destroy);
  631. }
  632. }
  633. void PhysicsWorld::addShape(PhysicsShape* physicsShape)
  634. {
  635. if (physicsShape)
  636. {
  637. for (auto shape : physicsShape->_cpShapes)
  638. {
  639. cpSpaceAddShape(_cpSpace, shape);
  640. }
  641. }
  642. }
  643. void PhysicsWorld::doRemoveBody(PhysicsBody* body)
  644. {
  645. CCASSERT(body != nullptr, "the body can not be nullptr");
  646. // remove shapes
  647. for (auto& shape : body->getShapes())
  648. {
  649. removeShape(shape);
  650. }
  651. // remove body
  652. if (cpSpaceContainsBody(_cpSpace, body->_cpBody))
  653. {
  654. cpSpaceRemoveBody(_cpSpace, body->_cpBody);
  655. }
  656. }
  657. void PhysicsWorld::doRemoveJoint(PhysicsJoint* joint)
  658. {
  659. for (auto constraint : joint->_cpConstraints)
  660. {
  661. cpSpaceRemoveConstraint(_cpSpace, constraint);
  662. }
  663. _joints.remove(joint);
  664. joint->_world = nullptr;
  665. if (joint->getBodyA())
  666. {
  667. joint->getBodyA()->removeJoint(joint);
  668. }
  669. if (joint->getBodyB())
  670. {
  671. joint->getBodyB()->removeJoint(joint);
  672. }
  673. if (joint->_destroyMark)
  674. {
  675. delete joint;
  676. }
  677. }
  678. void PhysicsWorld::removeAllBodies()
  679. {
  680. for (auto& child : _bodies)
  681. {
  682. removeBodyOrDelay(child);
  683. child->_world = nullptr;
  684. }
  685. _bodies.clear();
  686. }
  687. void PhysicsWorld::setDebugDrawMask(int mask)
  688. {
  689. if (mask == DEBUGDRAW_NONE)
  690. {
  691. _debugDraw->removeFromParent();
  692. CC_SAFE_RELEASE_NULL(_debugDraw);
  693. }
  694. _debugDrawMask = mask;
  695. }
  696. const Vector<PhysicsBody*>& PhysicsWorld::getAllBodies() const
  697. {
  698. return _bodies;
  699. }
  700. PhysicsBody* PhysicsWorld::getBody(int tag) const
  701. {
  702. for (auto& body : _bodies)
  703. {
  704. if (body->getTag() == tag)
  705. {
  706. return body;
  707. }
  708. }
  709. return nullptr;
  710. }
  711. void PhysicsWorld::setGravity(const Vec2& gravity)
  712. {
  713. _gravity = gravity;
  714. cpSpaceSetGravity(_cpSpace, PhysicsHelper::point2cpv(gravity));
  715. }
  716. void PhysicsWorld::setSubsteps(int steps)
  717. {
  718. if(steps > 0)
  719. {
  720. _substeps = steps;
  721. if (steps > 1)
  722. {
  723. _updateRate = 1;
  724. }
  725. }
  726. }
  727. void PhysicsWorld::step(float delta)
  728. {
  729. if (_autoStep)
  730. {
  731. CCLOG("Physics Warning: You need to close auto step( setAutoStep(false) ) first");
  732. }
  733. else
  734. {
  735. update(delta, true);
  736. }
  737. }
  738. void PhysicsWorld::update(float delta, bool userCall/* = false*/)
  739. {
  740. if(!_delayAddBodies.empty())
  741. {
  742. updateBodies();
  743. }
  744. else if (!_delayRemoveBodies.empty())
  745. {
  746. updateBodies();
  747. }
  748. auto sceneToWorldTransform = _scene->getNodeToParentTransform();
  749. beforeSimulation(_scene, sceneToWorldTransform, 1.f, 1.f, 0.f);
  750. if (!_delayAddJoints.empty() || !_delayRemoveJoints.empty())
  751. {
  752. updateJoints();
  753. }
  754. if (delta < FLT_EPSILON)
  755. {
  756. return;
  757. }
  758. if (userCall)
  759. {
  760. #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  761. cpSpaceStep(_cpSpace, delta);
  762. #else
  763. cpHastySpaceStep(_cpSpace, delta);
  764. #endif
  765. }
  766. else
  767. {
  768. _updateTime += delta;
  769. if(_fixedRate)
  770. {
  771. const float step = 1.0f / _fixedRate;
  772. const float dt = step * _speed;
  773. while(_updateTime>step)
  774. {
  775. _updateTime-=step;
  776. #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  777. cpSpaceStep(_cpSpace, dt);
  778. #else
  779. cpHastySpaceStep(_cpSpace, dt);
  780. #endif
  781. }
  782. }
  783. else
  784. {
  785. if (++_updateRateCount >= _updateRate)
  786. {
  787. const float dt = _updateTime * _speed / _substeps;
  788. for (int i = 0; i < _substeps; ++i)
  789. {
  790. #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  791. cpSpaceStep(_cpSpace, dt);
  792. #else
  793. cpHastySpaceStep(_cpSpace, dt);
  794. #endif
  795. for (auto& body : _bodies)
  796. {
  797. body->update(dt);
  798. }
  799. }
  800. _updateRateCount = 0;
  801. _updateTime = 0.0f;
  802. }
  803. }
  804. }
  805. if (_debugDrawMask != DEBUGDRAW_NONE)
  806. {
  807. debugDraw();
  808. }
  809. // Update physics position, should loop as the same sequence as node tree.
  810. // PhysicsWorld::afterSimulation() will depend on the sequence.
  811. afterSimulation(_scene, sceneToWorldTransform, 0.f);
  812. }
  813. PhysicsWorld* PhysicsWorld::construct(Scene* scene)
  814. {
  815. PhysicsWorld * world = new (std::nothrow) PhysicsWorld();
  816. if (world && world->init())
  817. {
  818. world->_scene = scene;
  819. world->_eventDispatcher = scene->getEventDispatcher();
  820. return world;
  821. }
  822. CC_SAFE_DELETE(world);
  823. return nullptr;
  824. }
  825. PhysicsWorld::PhysicsWorld()
  826. : _gravity(Vec2(0.0f, -98.0f))
  827. , _speed(1.0f)
  828. , _updateRate(1)
  829. , _updateRateCount(0)
  830. , _updateTime(0.0f)
  831. , _substeps(1)
  832. , _fixedRate(0)
  833. , _cpSpace(nullptr)
  834. , _updateBodyTransform(false)
  835. , _scene(nullptr)
  836. , _autoStep(true)
  837. , _debugDraw(nullptr)
  838. , _debugDrawMask(DEBUGDRAW_NONE)
  839. , _eventDispatcher(nullptr)
  840. {
  841. }
  842. PhysicsWorld::~PhysicsWorld()
  843. {
  844. removeAllJoints(true);
  845. removeAllBodies();
  846. if (_cpSpace)
  847. {
  848. #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  849. cpSpaceFree(_cpSpace);
  850. #else
  851. cpHastySpaceFree(_cpSpace);
  852. #endif
  853. }
  854. CC_SAFE_RELEASE_NULL(_debugDraw);
  855. }
  856. void PhysicsWorld::beforeSimulation(Node *node, const Mat4& parentToWorldTransform, float nodeParentScaleX, float nodeParentScaleY, float parentRotation)
  857. {
  858. auto scaleX = nodeParentScaleX * node->getScaleX();
  859. auto scaleY = nodeParentScaleY * node->getScaleY();
  860. auto rotation = parentRotation + node->getRotation();
  861. auto nodeToWorldTransform = parentToWorldTransform * node->getNodeToParentTransform();
  862. auto physicsBody = node->getPhysicsBody();
  863. if (physicsBody)
  864. {
  865. physicsBody->beforeSimulation(parentToWorldTransform, nodeToWorldTransform, scaleX, scaleY, rotation);
  866. }
  867. for (auto child : node->getChildren())
  868. beforeSimulation(child, nodeToWorldTransform, scaleX, scaleY, rotation);
  869. }
  870. void PhysicsWorld::afterSimulation(Node *node, const Mat4& parentToWorldTransform, float parentRotation)
  871. {
  872. auto nodeToWorldTransform = parentToWorldTransform * node->getNodeToParentTransform();
  873. auto nodeRotation = parentRotation + node->getRotation();
  874. auto physicsBody = node->getPhysicsBody();
  875. if (physicsBody)
  876. {
  877. physicsBody->afterSimulation(parentToWorldTransform, parentRotation);
  878. }
  879. for (auto child : node->getChildren())
  880. afterSimulation(child, nodeToWorldTransform, nodeRotation);
  881. }
  882. NS_CC_END
  883. #endif // CC_USE_PHYSICS