CCPhysicsWorld.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. #ifndef __CCPHYSICS_WORLD_H__
  22. #define __CCPHYSICS_WORLD_H__
  23. #include "base/ccConfig.h"
  24. #if CC_USE_PHYSICS
  25. #include <list>
  26. #include "base/CCVector.h"
  27. #include "math/CCGeometry.h"
  28. #include "physics/CCPhysicsBody.h"
  29. struct cpSpace;
  30. NS_CC_BEGIN
  31. class PhysicsBody;
  32. class PhysicsJoint;
  33. class PhysicsShape;
  34. class PhysicsContact;
  35. class Director;
  36. class Node;
  37. class Sprite;
  38. class Scene;
  39. class DrawNode;
  40. class PhysicsDebugDraw;
  41. class EventDispatcher;
  42. class PhysicsWorld;
  43. typedef struct PhysicsRayCastInfo
  44. {
  45. PhysicsShape* shape;
  46. Vec2 start;
  47. Vec2 end; ///< in lua, it's name is "ended"
  48. Vec2 contact;
  49. Vec2 normal;
  50. // FIXME: correct thing to do is use `cpFlaot` instead of float.
  51. // but in order to do so, we should include "chipmunk_types.h"
  52. // in Chipmunk v7.0, chipmunk_types includes all the mac types that
  53. // conflicts with cocos2d Size, Point,... etc types. And all the CocosStudio
  54. // lib will need to use the `cocos2d::` namespace prefix. And it is easier to do this
  55. // than change all the cocosstudio library (and also users code)
  56. float fraction;
  57. void* data;
  58. }PhysicsRayCastInfo;
  59. /**
  60. * @brief Called for each fixture found in the query. You control how the ray cast
  61. * proceeds by returning a float:
  62. * return true: continue
  63. * return false: terminate the ray cast
  64. * @param fixture the fixture hit by the ray
  65. * @param point the point of initial intersection
  66. * @param normal the normal vector at the point of intersection
  67. * @return true to continue, false to terminate
  68. */
  69. typedef std::function<bool(PhysicsWorld& world, const PhysicsRayCastInfo& info, void* data)> PhysicsRayCastCallbackFunc;
  70. typedef std::function<bool(PhysicsWorld&, PhysicsShape&, void*)> PhysicsQueryRectCallbackFunc;
  71. typedef PhysicsQueryRectCallbackFunc PhysicsQueryPointCallbackFunc;
  72. /**
  73. * @addtogroup physics
  74. * @{
  75. * @addtogroup physics_2d
  76. * @{
  77. */
  78. /**
  79. * @class PhysicsWorld CCPhysicsWorld.h
  80. * @brief An PhysicsWorld object simulates collisions and other physical properties. You do not create PhysicsWorld objects directly; instead, you can get it from an Scene object.
  81. */
  82. class CC_DLL PhysicsWorld
  83. {
  84. public:
  85. static const int DEBUGDRAW_NONE; ///< draw nothing
  86. static const int DEBUGDRAW_SHAPE; ///< draw shapes
  87. static const int DEBUGDRAW_JOINT; ///< draw joints
  88. static const int DEBUGDRAW_CONTACT; ///< draw contact
  89. static const int DEBUGDRAW_ALL; ///< draw all
  90. public:
  91. /**
  92. * Adds a joint to this physics world.
  93. *
  94. * This joint will be added to this physics world at next frame.
  95. * @attention If this joint is already added to another physics world, it will be removed from that world first and then add to this world.
  96. * @param joint A pointer to an existing PhysicsJoint object.
  97. */
  98. virtual void addJoint(PhysicsJoint* joint);
  99. /**
  100. * Remove a joint from this physics world.
  101. *
  102. * If this world is not locked, the joint is removed immediately, otherwise at next frame.
  103. * If this joint is connected with a body, it will be removed from the body also.
  104. * @param joint A pointer to an existing PhysicsJoint object.
  105. * @param destroy true this joint will be destroyed after remove from this world, false otherwise.
  106. */
  107. virtual void removeJoint(PhysicsJoint* joint, bool destroy = true);
  108. /**
  109. * Remove all joints from this physics world.
  110. *
  111. * @attention This function is invoked in the destructor of this physics world, you do not use this api in common.
  112. * @param destroy true all joints will be destroyed after remove from this world, false otherwise.
  113. */
  114. virtual void removeAllJoints(bool destroy = true);
  115. /**
  116. * Remove a body from this physics world.
  117. *
  118. * If this world is not locked, the body is removed immediately, otherwise at next frame.
  119. * @attention If this body has joints, those joints will be removed also.
  120. * @param body A pointer to an existing PhysicsBody object.
  121. */
  122. virtual void removeBody(PhysicsBody* body);
  123. /**
  124. * Remove body by tag.
  125. *
  126. * If this world is not locked, the object is removed immediately, otherwise at next frame.
  127. * @attention If this body has joints, those joints will be removed also.
  128. * @param tag An integer number that identifies a PhysicsBody object.
  129. */
  130. virtual void removeBody(int tag);
  131. /**
  132. * Remove all bodies from physics world.
  133. *
  134. * If this world is not locked, those body are removed immediately, otherwise at next frame.
  135. */
  136. virtual void removeAllBodies();
  137. /**
  138. * Searches for physics shapes that intersects the ray.
  139. *
  140. * Query this physics world along the line segment from start to end.
  141. * @param func Func is called for each shape found.
  142. * @param start A Vec2 object contains the begin position of the ray.
  143. * @param end A Vec2 object contains the end position of the ray.
  144. * @param data User defined data, it is passed to func.
  145. */
  146. void rayCast(PhysicsRayCastCallbackFunc func, const Vec2& start, const Vec2& end, void* data);
  147. /**
  148. * Searches for physics shapes that contains in the rect.
  149. *
  150. * Query this physics world to find all shapes overlap rect.
  151. * @param func Func is called for each shape whose bounding box overlaps rect.
  152. * @param rect A Rect object contains a rectangle's x, y, width and height.
  153. * @param data User defined data, it is passed to func.
  154. */
  155. void queryRect(PhysicsQueryRectCallbackFunc func, const Rect& rect, void* data);
  156. /**
  157. * Searches for physics shapes that contains the point.
  158. *
  159. * @attention The point must lie inside a shape.
  160. * @param func Func is called for each shape contains the point.
  161. * @param point A Vec2 object contains the position of the point.
  162. * @param data User defined data, it is passed to func.
  163. */
  164. void queryPoint(PhysicsQueryPointCallbackFunc func, const Vec2& point, void* data);
  165. /**
  166. * Get physics shapes that contains the point.
  167. *
  168. * All shapes contains the point will be pushed in a Vector<PhysicsShape*> object.
  169. * @attention The point must lie inside a shape.
  170. * @param point A Vec2 object contains the position of the point.
  171. * @return A Vector<PhysicsShape*> object contains all found PhysicsShape pointer.
  172. */
  173. Vector<PhysicsShape*> getShapes(const Vec2& point) const;
  174. /**
  175. * Get the nearest physics shape that contains the point.
  176. *
  177. * Query this physics world at point and return the closest shape.
  178. * @param point A Vec2 object contains the position of the point.
  179. * @return A PhysicsShape object pointer or nullptr if no shapes were found
  180. */
  181. PhysicsShape* getShape(const Vec2& point) const;
  182. /**
  183. * Get all the bodies that in this physics world.
  184. *
  185. * @return A Vector<PhysicsBody*>& object contains all bodies in this physics world.
  186. */
  187. const Vector<PhysicsBody*>& getAllBodies() const;
  188. /**
  189. * Get a body by tag.
  190. *
  191. * @param tag An integer number that identifies a PhysicsBody object.
  192. * @return A PhysicsBody object pointer or nullptr if no shapes were found.
  193. */
  194. PhysicsBody* getBody(int tag) const;
  195. /**
  196. * Get a scene contain this physics world.
  197. *
  198. * @attention This value is initialized in constructor
  199. * @return A Scene object reference.
  200. */
  201. Scene& getScene() const { return *_scene; }
  202. /**
  203. * Get the gravity value of this physics world.
  204. *
  205. * @return A Vec2 object.
  206. */
  207. Vec2 getGravity() const { return _gravity; }
  208. /**
  209. * set the gravity value of this physics world.
  210. *
  211. * @param gravity A gravity value of this physics world.
  212. */
  213. void setGravity(const Vec2& gravity);
  214. /**
  215. * Set the speed of this physics world.
  216. *
  217. * @attention if you setAutoStep(false), this won't work.
  218. * @param speed A float number. Speed is the rate at which the simulation executes. default value is 1.0.
  219. */
  220. void setSpeed(float speed) { if(speed >= 0.0f) { _speed = speed; } }
  221. /**
  222. * Get the speed of this physics world.
  223. *
  224. * @return A float number.
  225. */
  226. float getSpeed() { return _speed; }
  227. /**
  228. * Set the update rate of this physics world
  229. *
  230. * Update rate is the value of EngineUpdateTimes/PhysicsWorldUpdateTimes.
  231. * Set it higher can improve performance, set it lower can improve accuracy of physics world simulation.
  232. * @attention if you setAutoStep(false), this won't work.
  233. * @param rate An integer number, default value is 1.0.
  234. */
  235. void setUpdateRate(int rate) { if(rate > 0) { _updateRate = rate; } }
  236. /**
  237. * Get the update rate of this physics world.
  238. *
  239. * @return An integer number.
  240. */
  241. int getUpdateRate() { return _updateRate; }
  242. /**
  243. * set the number of substeps in an update of the physics world.
  244. *
  245. * One physics update will be divided into several substeps to increase its accuracy.
  246. * @param steps An integer number, default value is 1.
  247. */
  248. void setSubsteps(int steps);
  249. /**
  250. * Get the number of substeps of this physics world.
  251. *
  252. * @return An integer number.
  253. */
  254. int getSubsteps() const { return _substeps; }
  255. /**
  256. * set the number of update of the physics world in a second.
  257. * 0 - disable fixed step system
  258. * default value is 0
  259. */
  260. void setFixedUpdateRate(int updatesPerSecond) { if(updatesPerSecond > 0) { _fixedRate = updatesPerSecond; } }
  261. /** get the number of substeps */
  262. int getFixedUpdateRate() const { return _fixedRate; }
  263. /**
  264. * Set the debug draw mask of this physics world.
  265. *
  266. * This physics world will draw shapes and joints by DrawNode according to mask.
  267. * @param mask Mask has four value:DEBUGDRAW_NONE, DEBUGDRAW_SHAPE, DEBUGDRAW_JOINT, DEBUGDRAW_CONTACT and DEBUGDRAW_ALL, default is DEBUGDRAW_NONE
  268. */
  269. void setDebugDrawMask(int mask);
  270. /**
  271. * Get the debug draw mask.
  272. *
  273. * @return An integer number.
  274. */
  275. int getDebugDrawMask() { return _debugDrawMask; }
  276. /**
  277. * To control the step of physics.
  278. *
  279. * If you want control it by yourself( fixed-timestep for example ), you can set this to false and call step by yourself.
  280. * @attention If you set auto step to false, setSpeed setSubsteps and setUpdateRate won't work, you need to control the time step by yourself.
  281. * @param autoStep A bool object, default value is true.
  282. */
  283. void setAutoStep(bool autoStep){ _autoStep = autoStep; }
  284. /**
  285. * Get the auto step of this physics world.
  286. *
  287. * @return A bool object.
  288. */
  289. bool isAutoStep() { return _autoStep; }
  290. /**
  291. * The step for physics world.
  292. *
  293. * The times passing for simulate the physics.
  294. * @attention You need to setAutoStep(false) first before it can work.
  295. * @param delta A float number.
  296. */
  297. void step(float delta);
  298. protected:
  299. static PhysicsWorld* construct(Scene* scene);
  300. bool init();
  301. virtual void addBody(PhysicsBody* body);
  302. virtual void addShape(PhysicsShape* shape);
  303. virtual void removeShape(PhysicsShape* shape);
  304. virtual void update(float delta, bool userCall = false);
  305. virtual void debugDraw();
  306. virtual bool collisionBeginCallback(PhysicsContact& contact);
  307. virtual bool collisionPreSolveCallback(PhysicsContact& contact);
  308. virtual void collisionPostSolveCallback(PhysicsContact& contact);
  309. virtual void collisionSeparateCallback(PhysicsContact& contact);
  310. virtual void doAddBody(PhysicsBody* body);
  311. virtual void doRemoveBody(PhysicsBody* body);
  312. virtual void doRemoveJoint(PhysicsJoint* joint);
  313. virtual void addBodyOrDelay(PhysicsBody* body);
  314. virtual void removeBodyOrDelay(PhysicsBody* body);
  315. virtual void updateBodies();
  316. virtual void updateJoints();
  317. protected:
  318. Vec2 _gravity;
  319. float _speed;
  320. int _updateRate;
  321. int _updateRateCount;
  322. float _updateTime;
  323. int _substeps;
  324. int _fixedRate;
  325. cpSpace* _cpSpace;
  326. bool _updateBodyTransform;
  327. Vector<PhysicsBody*> _bodies;
  328. std::list<PhysicsJoint*> _joints;
  329. Scene* _scene;
  330. bool _autoStep;
  331. DrawNode* _debugDraw;
  332. int _debugDrawMask;
  333. EventDispatcher* _eventDispatcher;
  334. Vector<PhysicsBody*> _delayAddBodies;
  335. Vector<PhysicsBody*> _delayRemoveBodies;
  336. std::vector<PhysicsJoint*> _delayAddJoints;
  337. std::vector<PhysicsJoint*> _delayRemoveJoints;
  338. protected:
  339. PhysicsWorld();
  340. virtual ~PhysicsWorld();
  341. void beforeSimulation(Node *node, const Mat4& parentToWorldTransform, float nodeParentScaleX, float nodeParentScaleY, float parentRotation);
  342. void afterSimulation(Node* node, const Mat4& parentToWorldTransform, float parentRotation);
  343. friend class Node;
  344. friend class Sprite;
  345. friend class Scene;
  346. friend class Director;
  347. friend class PhysicsBody;
  348. friend class PhysicsShape;
  349. friend class PhysicsJoint;
  350. friend class PhysicsWorldCallback;
  351. friend class PhysicsDebugDraw;
  352. };
  353. extern const float CC_DLL PHYSICS_INFINITY;
  354. /** @} */
  355. /** @} */
  356. NS_CC_END
  357. #endif // CC_USE_PHYSICS
  358. #endif // __CCPHYSICS_WORLD_H__