PhysicsWorld.h 12 KB

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