PhysicsWorld2D.h 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. //
  2. // Copyright (c) 2008-2015 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 <Box2D/Box2D.h>
  25. namespace Atomic
  26. {
  27. class Camera;
  28. class RigidBody2D;
  29. /// 2D Physics raycast hit.
  30. struct ATOMIC_API PhysicsRaycastResult2D
  31. {
  32. /// Construct with defaults.
  33. PhysicsRaycastResult2D() :
  34. body_(0)
  35. {
  36. }
  37. /// Test for inequality, added to prevent GCC from complaining.
  38. bool operator !=(const PhysicsRaycastResult2D& rhs) const
  39. {
  40. return position_ != rhs.position_ || normal_ != rhs.normal_ || distance_ != rhs.distance_ || body_ != rhs.body_;
  41. }
  42. /// Hit worldspace position.
  43. Vector2 position_;
  44. /// Hit worldspace normal.
  45. Vector2 normal_;
  46. /// Hit distance from ray origin.
  47. float distance_;
  48. /// Rigid body that was hit.
  49. RigidBody2D* body_;
  50. };
  51. /// 2D physics simulation world component. Should be added only to the root scene node.
  52. class ATOMIC_API PhysicsWorld2D : public Component, public b2ContactListener, public b2Draw
  53. {
  54. OBJECT(PhysicsWorld2D);
  55. public:
  56. /// Construct.
  57. PhysicsWorld2D(Context* context);
  58. /// Destruct.
  59. virtual ~PhysicsWorld2D();
  60. /// Register object factory.
  61. static void RegisterObject(Context* context);
  62. /// Visualize the component as debug geometry.
  63. virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
  64. // Implement b2ContactListener.
  65. /// Called when two fixtures begin to touch.
  66. virtual void BeginContact(b2Contact* contact);
  67. /// Called when two fixtures cease to touch.
  68. virtual void EndContact(b2Contact* contact);
  69. // Implement b2Draw.
  70. /// Draw a closed polygon provided in CCW order.
  71. virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
  72. /// Draw a solid closed polygon provided in CCW order.
  73. virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
  74. /// Draw a circle.
  75. virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color);
  76. /// Draw a solid circle.
  77. virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color);
  78. /// Draw a line segment.
  79. virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);
  80. /// Draw a transform. Choose your own length scale.
  81. virtual void DrawTransform(const b2Transform& xf);
  82. /// Step the simulation forward.
  83. void Update(float timeStep);
  84. /// Add debug geometry to the debug renderer.
  85. void DrawDebugGeometry();
  86. /// Set draw shape.
  87. void SetDrawShape(bool drawShape);
  88. /// Set draw joint.
  89. void SetDrawJoint(bool drawJoint);
  90. /// Set draw aabb.
  91. void SetDrawAabb(bool drawAabb);
  92. /// Set draw pair.
  93. void SetDrawPair(bool drawPair);
  94. /// Set draw center of mass.
  95. void SetDrawCenterOfMass(bool drawCenterOfMass);
  96. /// Set allow sleeping.
  97. void SetAllowSleeping(bool enable);
  98. /// Set warm starting.
  99. void SetWarmStarting(bool enable);
  100. /// Set continuous physics.
  101. void SetContinuousPhysics(bool enable);
  102. /// Set sub stepping.
  103. void SetSubStepping(bool enable);
  104. /// Set gravity.
  105. void SetGravity(const Vector2& gravity);
  106. /// Set auto clear forces.
  107. void SetAutoClearForces(bool enable);
  108. /// Set velocity iterations.
  109. void SetVelocityIterations(int velocityIterations);
  110. /// Set position iterations.
  111. void SetPositionIterations(int positionIterations);
  112. /// Add rigid body.
  113. void AddRigidBody(RigidBody2D* rigidBody);
  114. /// Remove rigid body.
  115. void RemoveRigidBody(RigidBody2D* rigidBody);
  116. /// Perform a physics world raycast and return all hits.
  117. void Raycast(PODVector<PhysicsRaycastResult2D>& results, const Vector2& startPoint, const Vector2& endPoint,
  118. unsigned collisionMask = M_MAX_UNSIGNED);
  119. /// Perform a physics world raycast and return the closest hit.
  120. void RaycastSingle(PhysicsRaycastResult2D& result, const Vector2& startPoint, const Vector2& endPoint,
  121. unsigned collisionMask = M_MAX_UNSIGNED);
  122. /// Return rigid body at point.
  123. RigidBody2D* GetRigidBody(const Vector2& point, unsigned collisionMask = M_MAX_UNSIGNED);
  124. /// Return rigid body at screen point.
  125. RigidBody2D* GetRigidBody(int screenX, int screenY, unsigned collisionMask = M_MAX_UNSIGNED);
  126. /// Return rigid bodies by a box query.
  127. void GetRigidBodies(PODVector<RigidBody2D*>& result, const Rect& aabb, unsigned collisionMask = M_MAX_UNSIGNED);
  128. /// Return draw shape.
  129. bool GetDrawShape() const { return (m_drawFlags & e_shapeBit) != 0; }
  130. /// Return draw joint.
  131. bool GetDrawJoint() const { return (m_drawFlags & e_jointBit) != 0; }
  132. /// Return draw aabb.
  133. bool GetDrawAabb() const { return (m_drawFlags & e_aabbBit) != 0; }
  134. /// Return draw pair.
  135. bool GetDrawPair() const { return (m_drawFlags & e_pairBit) != 0; }
  136. /// Return draw center of mass.
  137. bool GetDrawCenterOfMass() const { return (m_drawFlags & e_centerOfMassBit) != 0; }
  138. /// Return allow sleeping.
  139. bool GetAllowSleeping() const;
  140. /// Return warm starting.
  141. bool GetWarmStarting() const;
  142. /// Return continuous physics.
  143. bool GetContinuousPhysics() const;
  144. /// Return sub stepping.
  145. bool GetSubStepping() const;
  146. /// Return auto clear forces.
  147. bool GetAutoClearForces() const;
  148. /// Return gravity.
  149. const Vector2& GetGravity() const { return gravity_; }
  150. /// Return velocity iterations.
  151. int GetVelocityIterations() const { return velocityIterations_; }
  152. /// Return position iterations.
  153. int GetPositionIterations() const { return positionIterations_; }
  154. /// Return the Box2D physics world.
  155. b2World* GetWorld() { return world_; }
  156. /// Set node dirtying to be disregarded.
  157. void SetApplyingTransforms(bool enable) { applyingTransforms_ = enable; }
  158. /// Return whether node dirtying should be disregarded.
  159. bool IsApplyingTransforms() const { return applyingTransforms_; }
  160. protected:
  161. /// Handle scene being assigned.
  162. virtual void OnSceneSet(Scene* scene);
  163. private:
  164. /// Handle the scene subsystem update event, step simulation here.
  165. void HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData);
  166. /// Send begin contact events.
  167. void SendBeginContactEvents();
  168. /// Send end contact events.
  169. void SendEndContactEvents();
  170. /// Box2D physics world.
  171. b2World* world_;
  172. /// Gravity.
  173. Vector2 gravity_;
  174. /// Velocity iterations.
  175. int velocityIterations_;
  176. /// Position iterations.
  177. int positionIterations_;
  178. /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
  179. WeakPtr<Scene> scene_;
  180. /// Debug renderer.
  181. DebugRenderer* debugRenderer_;
  182. /// Debug draw depth test mode.
  183. bool debugDepthTest_;
  184. /// Physics steping.
  185. bool physicsSteping_;
  186. /// Applying transforms.
  187. bool applyingTransforms_;
  188. /// Rigid bodies.
  189. Vector<WeakPtr<RigidBody2D> > rigidBodies_;
  190. /// Contact info.
  191. struct ContactInfo
  192. {
  193. /// Construct.
  194. ContactInfo();
  195. /// Construct.
  196. ContactInfo(b2Contact* contract);
  197. /// Copy construct.
  198. ContactInfo(const ContactInfo& other);
  199. /// Rigid body A.
  200. SharedPtr<RigidBody2D> bodyA_;
  201. /// Rigid body B.
  202. SharedPtr<RigidBody2D> bodyB_;
  203. /// Node A.
  204. SharedPtr<Node> nodeA_;
  205. /// Node B.
  206. SharedPtr<Node> nodeB_;
  207. };
  208. /// Begin contact infos.
  209. Vector<ContactInfo> beginContactInfos_;
  210. /// End contact infos.
  211. Vector<ContactInfo> endContactInfos_;
  212. };
  213. }