PhysicsWorld2D.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  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. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Scene/Component.h"
  24. #include "../IO/VectorBuffer.h"
  25. #include <Box2D/Box2D.h>
  26. namespace Atomic
  27. {
  28. class Camera;
  29. class CollisionShape2D;
  30. class RigidBody2D;
  31. /// 2D Physics raycast hit.
  32. struct ATOMIC_API PhysicsRaycastResult2D
  33. {
  34. /// Construct with defaults.
  35. PhysicsRaycastResult2D() :
  36. body_(0)
  37. {
  38. }
  39. /// Test for inequality, added to prevent GCC from complaining.
  40. bool operator !=(const PhysicsRaycastResult2D& rhs) const
  41. {
  42. return position_ != rhs.position_ || normal_ != rhs.normal_ || distance_ != rhs.distance_ || body_ != rhs.body_;
  43. }
  44. /// Hit worldspace position.
  45. Vector2 position_;
  46. /// Hit worldspace normal.
  47. Vector2 normal_;
  48. /// Hit distance from ray origin.
  49. float distance_;
  50. /// Rigid body that was hit.
  51. RigidBody2D* body_;
  52. };
  53. /// Delayed world transform assignment for parented 2D rigidbodies.
  54. struct DelayedWorldTransform2D
  55. {
  56. /// Rigid body.
  57. RigidBody2D* rigidBody_;
  58. /// Parent rigid body.
  59. RigidBody2D* parentRigidBody_;
  60. /// New world position.
  61. Vector3 worldPosition_;
  62. /// New world rotation.
  63. Quaternion worldRotation_;
  64. };
  65. /// 2D physics simulation world component. Should be added only to the root scene node.
  66. class ATOMIC_API PhysicsWorld2D : public Component, public b2ContactListener, public b2Draw
  67. {
  68. ATOMIC_OBJECT(PhysicsWorld2D, Component);
  69. public:
  70. /// Construct.
  71. PhysicsWorld2D(Context* context);
  72. /// Destruct.
  73. virtual ~PhysicsWorld2D();
  74. /// Register object factory.
  75. static void RegisterObject(Context* context);
  76. /// Visualize the component as debug geometry.
  77. virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
  78. // Implement b2ContactListener
  79. /// Called when two fixtures begin to touch.
  80. virtual void BeginContact(b2Contact* contact);
  81. /// Called when two fixtures cease to touch.
  82. virtual void EndContact(b2Contact* contact);
  83. /// Called when contact is updated.
  84. virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold);
  85. // Implement b2Draw
  86. /// Draw a closed polygon provided in CCW order.
  87. virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
  88. /// Draw a solid closed polygon provided in CCW order.
  89. virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
  90. /// Draw a circle.
  91. virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color);
  92. /// Draw a solid circle.
  93. virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color);
  94. /// Draw a line segment.
  95. virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);
  96. /// Draw a transform. Choose your own length scale.
  97. virtual void DrawTransform(const b2Transform& xf);
  98. /// Draw a point.
  99. virtual void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color);
  100. /// Step the simulation forward.
  101. void Update(float timeStep);
  102. /// Add debug geometry to the debug renderer.
  103. void DrawDebugGeometry();
  104. /// Enable or disable automatic physics simulation during scene update. Enabled by default.
  105. void SetUpdateEnabled(bool enable);
  106. /// Set draw shape.
  107. void SetDrawShape(bool drawShape);
  108. /// Set draw joint.
  109. void SetDrawJoint(bool drawJoint);
  110. /// Set draw aabb.
  111. void SetDrawAabb(bool drawAabb);
  112. /// Set draw pair.
  113. void SetDrawPair(bool drawPair);
  114. /// Set draw center of mass.
  115. void SetDrawCenterOfMass(bool drawCenterOfMass);
  116. /// Set allow sleeping.
  117. void SetAllowSleeping(bool enable);
  118. /// Set warm starting.
  119. void SetWarmStarting(bool enable);
  120. /// Set continuous physics.
  121. void SetContinuousPhysics(bool enable);
  122. /// Set sub stepping.
  123. void SetSubStepping(bool enable);
  124. /// Set gravity.
  125. void SetGravity(const Vector2& gravity);
  126. /// Set auto clear forces.
  127. void SetAutoClearForces(bool enable);
  128. /// Set velocity iterations.
  129. void SetVelocityIterations(int velocityIterations);
  130. /// Set position iterations.
  131. void SetPositionIterations(int positionIterations);
  132. /// Add rigid body.
  133. void AddRigidBody(RigidBody2D* rigidBody);
  134. /// Remove rigid body.
  135. void RemoveRigidBody(RigidBody2D* rigidBody);
  136. /// Add a delayed world transform assignment. Called by RigidBody2D.
  137. void AddDelayedWorldTransform(const DelayedWorldTransform2D& transform);
  138. /// Perform a physics world raycast and return all hits.
  139. void Raycast(PODVector<PhysicsRaycastResult2D>& results, const Vector2& startPoint, const Vector2& endPoint,
  140. unsigned collisionMask = M_MAX_UNSIGNED);
  141. /// Perform a physics world raycast and return the closest hit.
  142. void RaycastSingle(PhysicsRaycastResult2D& result, const Vector2& startPoint, const Vector2& endPoint,
  143. unsigned collisionMask = M_MAX_UNSIGNED);
  144. /// Return rigid body at point.
  145. RigidBody2D* GetRigidBody(const Vector2& point, unsigned collisionMask = M_MAX_UNSIGNED);
  146. /// Return rigid body at screen point.
  147. RigidBody2D* GetRigidBody(int screenX, int screenY, unsigned collisionMask = M_MAX_UNSIGNED);
  148. /// Return rigid bodies by a box query.
  149. void GetRigidBodies(PODVector<RigidBody2D*>& result, const Rect& aabb, unsigned collisionMask = M_MAX_UNSIGNED);
  150. /// Return whether physics world will automatically simulate during scene update.
  151. bool IsUpdateEnabled() const { return updateEnabled_; }
  152. /// Return draw shape.
  153. bool GetDrawShape() const { return (m_drawFlags & e_shapeBit) != 0; }
  154. /// Return draw joint.
  155. bool GetDrawJoint() const { return (m_drawFlags & e_jointBit) != 0; }
  156. /// Return draw aabb.
  157. bool GetDrawAabb() const { return (m_drawFlags & e_aabbBit) != 0; }
  158. /// Return draw pair.
  159. bool GetDrawPair() const { return (m_drawFlags & e_pairBit) != 0; }
  160. /// Return draw center of mass.
  161. bool GetDrawCenterOfMass() const { return (m_drawFlags & e_centerOfMassBit) != 0; }
  162. /// Return allow sleeping.
  163. bool GetAllowSleeping() const;
  164. /// Return warm starting.
  165. bool GetWarmStarting() const;
  166. /// Return continuous physics.
  167. bool GetContinuousPhysics() const;
  168. /// Return sub stepping.
  169. bool GetSubStepping() const;
  170. /// Return auto clear forces.
  171. bool GetAutoClearForces() const;
  172. /// Return gravity.
  173. const Vector2& GetGravity() const { return gravity_; }
  174. /// Return velocity iterations.
  175. int GetVelocityIterations() const { return velocityIterations_; }
  176. /// Return position iterations.
  177. int GetPositionIterations() const { return positionIterations_; }
  178. /// Return the Box2D physics world.
  179. b2World* GetWorld() { return world_.Get(); }
  180. /// Set node dirtying to be disregarded.
  181. void SetApplyingTransforms(bool enable) { applyingTransforms_ = enable; }
  182. /// Return whether node dirtying should be disregarded.
  183. bool IsApplyingTransforms() const { return applyingTransforms_; }
  184. protected:
  185. /// Handle scene being assigned.
  186. virtual void OnSceneSet(Scene* scene);
  187. /// Handle the scene subsystem update event, step simulation here.
  188. void HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData);
  189. /// Send begin contact events.
  190. void SendBeginContactEvents();
  191. /// Send end contact events.
  192. void SendEndContactEvents();
  193. /// Box2D physics world.
  194. UniquePtr<b2World> world_;
  195. /// Gravity.
  196. Vector2 gravity_;
  197. /// Velocity iterations.
  198. int velocityIterations_;
  199. /// Position iterations.
  200. int positionIterations_;
  201. /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
  202. WeakPtr<Scene> scene_;
  203. /// Debug renderer.
  204. DebugRenderer* debugRenderer_;
  205. /// Debug draw depth test mode.
  206. bool debugDepthTest_;
  207. /// Automatic simulation update enabled flag.
  208. bool updateEnabled_;
  209. /// Whether is currently stepping the world. Used internally.
  210. bool physicsStepping_;
  211. /// Applying transforms.
  212. bool applyingTransforms_;
  213. /// Rigid bodies.
  214. Vector<WeakPtr<RigidBody2D> > rigidBodies_;
  215. /// Delayed (parented) world transform assignments.
  216. HashMap<RigidBody2D*, DelayedWorldTransform2D> delayedWorldTransforms_;
  217. /// Contact info.
  218. struct ContactInfo
  219. {
  220. /// Construct.
  221. ContactInfo();
  222. /// Construct.
  223. ContactInfo(b2Contact* contract);
  224. /// Write contact info to buffer.
  225. const PODVector<unsigned char>& Serialize(VectorBuffer& buffer) const;
  226. /// Rigid body A.
  227. SharedPtr<RigidBody2D> bodyA_;
  228. /// Rigid body B.
  229. SharedPtr<RigidBody2D> bodyB_;
  230. /// Node A.
  231. SharedPtr<Node> nodeA_;
  232. /// Node B.
  233. SharedPtr<Node> nodeB_;
  234. /// Shape A.
  235. SharedPtr<CollisionShape2D> shapeA_;
  236. /// Shape B.
  237. SharedPtr<CollisionShape2D> shapeB_;
  238. /// Number of contact points.
  239. int numPoints_;
  240. /// Contact normal in world space.
  241. Vector2 worldNormal_;
  242. /// Contact positions in world space.
  243. Vector2 worldPositions_[b2_maxManifoldPoints];
  244. /// Contact overlap values.
  245. float separations_[b2_maxManifoldPoints];
  246. };
  247. /// Begin contact infos.
  248. Vector<ContactInfo> beginContactInfos_;
  249. /// End contact infos.
  250. Vector<ContactInfo> endContactInfos_;
  251. /// Temporary buffer with contact data.
  252. VectorBuffer contacts_;
  253. };
  254. }