CCPhysicsWorld.cpp 29 KB

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