PhysicsWorld.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. //
  2. // Copyright (c) 2008-2013 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 "BoundingBox.h"
  24. #include "Component.h"
  25. #include "HashSet.h"
  26. #include "Sphere.h"
  27. #include "Vector3.h"
  28. #include <LinearMath/btIDebugDraw.h>
  29. class btCollisionConfiguration;
  30. class btBroadphaseInterface;
  31. class btConstraintSolver;
  32. class btDiscreteDynamicsWorld;
  33. class btDispatcher;
  34. class btDynamicsWorld;
  35. class btPersistentManifold;
  36. namespace Urho3D
  37. {
  38. class CollisionShape;
  39. class Deserializer;
  40. class Constraint;
  41. class Node;
  42. class Ray;
  43. class RigidBody;
  44. class Scene;
  45. class Serializer;
  46. class XMLElement;
  47. struct CollisionGeometryData;
  48. /// Physics raycast hit.
  49. struct PhysicsRaycastResult
  50. {
  51. PhysicsRaycastResult() :
  52. body_(0)
  53. {
  54. }
  55. /// Hit worldspace position.
  56. Vector3 position_;
  57. /// Hit worldspace normal.
  58. Vector3 normal_;
  59. /// Hit distance from ray origin.
  60. float distance_;
  61. /// Rigid body that was hit.
  62. RigidBody* body_;
  63. };
  64. /// Delayed world transform assignment for parented rigidbodies.
  65. struct DelayedWorldTransform
  66. {
  67. /// Rigid body.
  68. RigidBody* rigidBody_;
  69. /// Parent rigid body.
  70. RigidBody* parentRigidBody_;
  71. /// New world position.
  72. Vector3 worldPosition_;
  73. /// New world rotation.
  74. Quaternion worldRotation_;
  75. };
  76. static const float DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY = 100.0f;
  77. /// Physics simulation world component. Should be added only to the root scene node.
  78. class URHO3D_API PhysicsWorld : public Component, public btIDebugDraw
  79. {
  80. OBJECT(PhysicsWorld);
  81. friend void InternalPreTickCallback(btDynamicsWorld *world, btScalar timeStep);
  82. friend void InternalTickCallback(btDynamicsWorld *world, btScalar timeStep);
  83. public:
  84. /// Construct.
  85. PhysicsWorld(Context* scontext);
  86. /// Destruct.
  87. virtual ~PhysicsWorld();
  88. /// Register object factory.
  89. static void RegisterObject(Context* context);
  90. /// Check if an AABB is visible for debug drawing.
  91. virtual bool isVisible(const btVector3& aabbMin, const btVector3& aabbMax);
  92. /// Draw a physics debug line.
  93. virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& color);
  94. /// Log warning from the physics engine.
  95. virtual void reportErrorWarning(const char* warningString);
  96. /// Draw a physics debug contact point. Not implemented.
  97. virtual void drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color) {}
  98. /// Draw physics debug 3D text. Not implemented.
  99. virtual void draw3dText(const btVector3& location,const char* textString) {}
  100. /// Set debug draw flags.
  101. virtual void setDebugMode(int debugMode) { debugMode_ = debugMode; }
  102. /// Return debug draw flags.
  103. virtual int getDebugMode() const { return debugMode_; }
  104. /// Visualize the component as debug geometry.
  105. virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
  106. /// Step the simulation forward.
  107. void Update(float timeStep);
  108. /// Refresh collisions only without updating dynamics.
  109. void UpdateCollisions();
  110. /// Set simulation steps per second.
  111. void SetFps(int fps);
  112. /// Set gravity.
  113. void SetGravity(Vector3 gravity);
  114. /// Set number of constraint solver iterations.
  115. void SetNumIterations(int num);
  116. /// Set whether to interpolate between simulation steps.
  117. void SetInterpolation(bool enable);
  118. /// Set whether to use Bullet's internal edge utility for trimesh collisions. Disabled by default.
  119. void SetInternalEdge(bool enable);
  120. /// Set split impulse collision mode. This is more accurate, but slower. Disabled by default.
  121. void SetSplitImpulse(bool enable);
  122. /// Set maximum angular velocity for network replication.
  123. void SetMaxNetworkAngularVelocity(float velocity);
  124. /// Perform a physics world raycast and return all hits.
  125. void Raycast(PODVector<PhysicsRaycastResult>& result, const Ray& ray, float maxDistance, unsigned collisionMask = M_MAX_UNSIGNED);
  126. /// Perform a physics world raycast and return the closest hit.
  127. void RaycastSingle(PhysicsRaycastResult& result, const Ray& ray, float maxDistance, unsigned collisionMask = M_MAX_UNSIGNED);
  128. /// Perform a physics world swept sphere test and return the closest hit.
  129. void SphereCast(PhysicsRaycastResult& result, const Ray& ray, float radius, float maxDistance, unsigned collisionMask = M_MAX_UNSIGNED);
  130. /// Return rigid bodies by a sphere query.
  131. void GetRigidBodies(PODVector<RigidBody*>& result, const Sphere& sphere, unsigned collisionMask = M_MAX_UNSIGNED);
  132. /// Return rigid bodies by a box query.
  133. void GetRigidBodies(PODVector<RigidBody*>& result, const BoundingBox& box, unsigned collisionMask = M_MAX_UNSIGNED);
  134. /// Return rigid bodies that have been in collision with a specific body on the last simulation step.
  135. void GetRigidBodies(PODVector<RigidBody*>& result, const RigidBody* body);
  136. /// Return gravity.
  137. Vector3 GetGravity() const;
  138. /// Return number of constraint solver iterations.
  139. int GetNumIterations() const;
  140. /// Return whether interpolation between simulation steps is enabled.
  141. bool GetInterpolation() const { return interpolation_; }
  142. /// Return whether Bullet's internal edge utility for trimesh collisions is enabled.
  143. bool GetInternalEdge() const { return internalEdge_; }
  144. /// Return whether split impulse collision mode is enabled.
  145. bool GetSplitImpulse() const;
  146. /// Return simulation steps per second.
  147. int GetFps() const { return fps_; }
  148. /// Return maximum angular velocity for network replication.
  149. float GetMaxNetworkAngularVelocity() const { return maxNetworkAngularVelocity_; }
  150. /// Add a rigid body to keep track of. Called by RigidBody.
  151. void AddRigidBody(RigidBody* body);
  152. /// Remove a rigid body. Called by RigidBody.
  153. void RemoveRigidBody(RigidBody* body);
  154. /// Add a collision shape to keep track of. Called by CollisionShape.
  155. void AddCollisionShape(CollisionShape* shape);
  156. /// Remove a collision shape. Called by CollisionShape.
  157. void RemoveCollisionShape(CollisionShape* shape);
  158. /// Add a constraint to keep track of. Called by Constraint.
  159. void AddConstraint(Constraint* joint);
  160. /// Remove a constraint. Called by Constraint.
  161. void RemoveConstraint(Constraint* joint);
  162. /// Add a delayed world transform assignment. Called by RigidBody.
  163. void AddDelayedWorldTransform(const DelayedWorldTransform& transform);
  164. /// Add debug geometry to the debug renderer.
  165. void DrawDebugGeometry(bool depthTest);
  166. /// Set debug renderer to use. Called both by PhysicsWorld itself and physics components.
  167. void SetDebugRenderer(DebugRenderer* debug);
  168. /// Set debug geometry depth test mode. Called both by PhysicsWorld itself and physics components.
  169. void SetDebugDepthTest(bool enable);
  170. /// Return the Bullet physics world.
  171. btDiscreteDynamicsWorld* GetWorld() { return world_; }
  172. /// Clean up the geometry cache.
  173. void CleanupGeometryCache();
  174. /// Return the collision geometry cache.
  175. HashMap<String, SharedPtr<CollisionGeometryData> >& GetGeometryCache() { return geometryCache_; }
  176. /// Set node dirtying to be disregarded.
  177. void SetApplyingTransforms(bool enable) { applyingTransforms_ = enable; }
  178. /// Return whether node dirtying should be disregarded.
  179. bool IsApplyingTransforms() const { return applyingTransforms_; }
  180. protected:
  181. /// Handle node being assigned.
  182. virtual void OnNodeSet(Node* node);
  183. private:
  184. /// Handle the scene subsystem update event, step simulation here.
  185. void HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData);
  186. /// Trigger update before each physics simulation step.
  187. void PreStep(float timeStep);
  188. /// Trigger update after ecah physics simulation step.
  189. void PostStep(float timeStep);
  190. /// Send accumulated collision events.
  191. void SendCollisionEvents();
  192. /// Bullet collision configuration.
  193. btCollisionConfiguration* collisionConfiguration_;
  194. /// Bullet collision dispatcher.
  195. btDispatcher* collisionDispatcher_;
  196. /// Bullet collision broadphase.
  197. btBroadphaseInterface* broadphase_;
  198. /// Bullet constraint solver.
  199. btConstraintSolver* solver_;
  200. /// Bullet physics world.
  201. btDiscreteDynamicsWorld* world_;
  202. /// Extra weak pointer to scene to allow for cleanup in case the world is destroyed before other components.
  203. WeakPtr<Scene> scene_;
  204. /// Rigid bodies in the world.
  205. PODVector<RigidBody*> rigidBodies_;
  206. /// Collision shapes in the world.
  207. PODVector<CollisionShape*> collisionShapes_;
  208. /// Constraints in the world.
  209. PODVector<Constraint*> constraints_;
  210. /// Collision pairs on this frame.
  211. HashMap<Pair<WeakPtr<RigidBody>, WeakPtr<RigidBody> >, btPersistentManifold* > currentCollisions_;
  212. /// Collision pairs on the previous frame. Used to check if a collision is "new." Manifolds are not guaranteed to exist anymore.
  213. HashMap<Pair<WeakPtr<RigidBody>, WeakPtr<RigidBody> >, btPersistentManifold* > previousCollisions_;
  214. /// Delayed (parented) world transform assignments.
  215. HashMap<RigidBody*, DelayedWorldTransform> delayedWorldTransforms_;
  216. /// Cache for collision geometry data.
  217. HashMap<String, SharedPtr<CollisionGeometryData> > geometryCache_;
  218. /// Simulation steps per second.
  219. unsigned fps_;
  220. /// Time accumulator for non-interpolated mode.
  221. float timeAcc_;
  222. /// Maximum angular velocity for network replication.
  223. float maxNetworkAngularVelocity_;
  224. /// Interpolation flag.
  225. bool interpolation_;
  226. /// Use internal edge utility flag.
  227. bool internalEdge_;
  228. /// Applying transforms flag.
  229. bool applyingTransforms_;
  230. /// Debug renderer.
  231. DebugRenderer* debugRenderer_;
  232. /// Debug draw flags.
  233. int debugMode_;
  234. /// Debug draw depth test mode.
  235. bool debugDepthTest_;
  236. };
  237. /// Register Physics library objects.
  238. void URHO3D_API RegisterPhysicsLibrary(Context* context);
  239. }