PhysicsWorld2D.h 10 KB

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