RigidBody.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 "../IO/VectorBuffer.h"
  24. #include "../Scene/Component.h"
  25. // ATOMIC BEGIN
  26. #include <Bullet/src/LinearMath/btMotionState.h>
  27. // ATOMIC END
  28. class btCompoundShape;
  29. class btRigidBody;
  30. namespace Atomic
  31. {
  32. class CollisionShape;
  33. class Constraint;
  34. class PhysicsWorld;
  35. class SmoothedTransform;
  36. /// Rigid body collision event signaling mode.
  37. enum CollisionEventMode
  38. {
  39. COLLISION_NEVER = 0,
  40. COLLISION_ACTIVE,
  41. COLLISION_ALWAYS
  42. };
  43. /// Physics rigid body component.
  44. class ATOMIC_API RigidBody : public Component, public btMotionState
  45. {
  46. ATOMIC_OBJECT(RigidBody, Component);
  47. public:
  48. /// Construct.
  49. RigidBody(Context* context);
  50. /// Destruct. Free the rigid body and geometries.
  51. virtual ~RigidBody();
  52. /// Register object factory.
  53. static void RegisterObject(Context* context);
  54. /// Handle attribute write access.
  55. virtual void OnSetAttribute(const AttributeInfo& attr, const Variant& src);
  56. /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update.
  57. virtual void ApplyAttributes();
  58. /// Handle enabled/disabled state change.
  59. virtual void OnSetEnabled();
  60. /// Return initial world transform to Bullet.
  61. virtual void getWorldTransform(btTransform& worldTrans) const;
  62. /// Update world transform from Bullet.
  63. virtual void setWorldTransform(const btTransform& worldTrans);
  64. /// Visualize the component as debug geometry.
  65. virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
  66. /// Set mass. Zero mass makes the body static.
  67. void SetMass(float mass);
  68. /// Set rigid body position in world space.
  69. void SetPosition(const Vector3& position);
  70. /// Set rigid body rotation in world space.
  71. void SetRotation(const Quaternion& rotation);
  72. /// Set rigid body position and rotation in world space as an atomic operation.
  73. void SetTransform(const Vector3& position, const Quaternion& rotation);
  74. /// Set linear velocity.
  75. void SetLinearVelocity(const Vector3& velocity);
  76. /// Set linear degrees of freedom. Use 1 to enable an axis or 0 to disable. Default is all axes enabled (1, 1, 1).
  77. void SetLinearFactor(const Vector3& factor);
  78. /// Set linear velocity deactivation threshold.
  79. void SetLinearRestThreshold(float threshold);
  80. /// Set linear velocity damping factor.
  81. void SetLinearDamping(float damping);
  82. /// Set angular velocity.
  83. void SetAngularVelocity(const Vector3& angularVelocity);
  84. /// Set angular degrees of freedom. Use 1 to enable an axis or 0 to disable. Default is all axes enabled (1, 1, 1).
  85. void SetAngularFactor(const Vector3& factor);
  86. /// Set angular velocity deactivation threshold.
  87. void SetAngularRestThreshold(float threshold);
  88. /// Set angular velocity damping factor.
  89. void SetAngularDamping(float factor);
  90. /// Set friction coefficient.
  91. void SetFriction(float friction);
  92. /// Set anisotropic friction.
  93. void SetAnisotropicFriction(const Vector3& friction);
  94. /// Set rolling friction coefficient.
  95. void SetRollingFriction(float friction);
  96. /// Set restitution coefficient.
  97. void SetRestitution(float restitution);
  98. /// Set contact processing threshold.
  99. void SetContactProcessingThreshold(float threshold);
  100. /// Set continuous collision detection swept sphere radius.
  101. void SetCcdRadius(float radius);
  102. /// Set continuous collision detection motion-per-simulation-step threshold. 0 disables, which is the default.
  103. void SetCcdMotionThreshold(float threshold);
  104. /// Set whether gravity is applied to rigid body.
  105. void SetUseGravity(bool enable);
  106. /// Set gravity override. If zero, uses physics world's gravity.
  107. void SetGravityOverride(const Vector3& gravity);
  108. /// Set rigid body kinematic mode. In kinematic mode forces are not applied to the rigid body.
  109. void SetKinematic(bool enable);
  110. /// Set rigid body trigger mode. In trigger mode collisions are reported but do not apply forces.
  111. void SetTrigger(bool enable);
  112. /// Set collision layer.
  113. void SetCollisionLayer(unsigned layer);
  114. /// Set collision mask.
  115. void SetCollisionMask(unsigned mask);
  116. /// Set collision group and mask.
  117. void SetCollisionLayerAndMask(unsigned layer, unsigned mask);
  118. /// Set collision event signaling mode. Default is to signal when rigid bodies are active.
  119. void SetCollisionEventMode(CollisionEventMode mode);
  120. /// Apply force to center of mass.
  121. void ApplyForce(const Vector3& force);
  122. /// Apply force at local position.
  123. void ApplyForce(const Vector3& force, const Vector3& position);
  124. /// Apply torque.
  125. void ApplyTorque(const Vector3& torque);
  126. /// Apply impulse to center of mass.
  127. void ApplyImpulse(const Vector3& impulse);
  128. /// Apply impulse at local position.
  129. void ApplyImpulse(const Vector3& impulse, const Vector3& position);
  130. /// Apply torque impulse.
  131. void ApplyTorqueImpulse(const Vector3& torque);
  132. /// Reset accumulated forces.
  133. void ResetForces();
  134. /// Activate rigid body if it was resting.
  135. void Activate();
  136. /// Readd rigid body to the physics world to clean up internal state like stale contacts.
  137. void ReAddBodyToWorld();
  138. /// Disable mass update. Call this to optimize performance when adding or editing multiple collision shapes in the same node.
  139. void DisableMassUpdate();
  140. /// Re-enable mass update and recalculate the mass/inertia by calling UpdateMass(). Call when collision shape changes are finished.
  141. void EnableMassUpdate();
  142. /// Return physics world.
  143. PhysicsWorld* GetPhysicsWorld() const { return physicsWorld_; }
  144. /// Return Bullet rigid body.
  145. btRigidBody* GetBody() const { return body_.Get(); }
  146. /// Return Bullet compound collision shape.
  147. btCompoundShape* GetCompoundShape() const { return compoundShape_.Get(); }
  148. /// Return mass.
  149. float GetMass() const { return mass_; }
  150. /// Return rigid body position in world space.
  151. Vector3 GetPosition() const;
  152. /// Return rigid body rotation in world space.
  153. Quaternion GetRotation() const;
  154. /// Return linear velocity.
  155. Vector3 GetLinearVelocity() const;
  156. /// Return linear degrees of freedom.
  157. Vector3 GetLinearFactor() const;
  158. /// Return linear velocity at local point.
  159. Vector3 GetVelocityAtPoint(const Vector3& position) const;
  160. /// Return linear velocity deactivation threshold.
  161. float GetLinearRestThreshold() const;
  162. /// Return linear velocity damping factor.
  163. float GetLinearDamping() const;
  164. /// Return angular velocity.
  165. Vector3 GetAngularVelocity() const;
  166. /// Return angular degrees of freedom.
  167. Vector3 GetAngularFactor() const;
  168. /// Return angular velocity deactivation threshold.
  169. float GetAngularRestThreshold() const;
  170. /// Return angular velocity damping factor.
  171. float GetAngularDamping() const;
  172. /// Return friction coefficient.
  173. float GetFriction() const;
  174. /// Return anisotropic friction.
  175. Vector3 GetAnisotropicFriction() const;
  176. /// Return rolling friction coefficient.
  177. float GetRollingFriction() const;
  178. /// Return restitution coefficient.
  179. float GetRestitution() const;
  180. /// Return contact processing threshold.
  181. float GetContactProcessingThreshold() const;
  182. /// Return continuous collision detection swept sphere radius.
  183. float GetCcdRadius() const;
  184. /// Return continuous collision detection motion-per-simulation-step threshold.
  185. float GetCcdMotionThreshold() const;
  186. /// Return whether rigid body uses gravity.
  187. bool GetUseGravity() const { return useGravity_; }
  188. /// Return gravity override. If zero (default), uses the physics world's gravity.
  189. const Vector3& GetGravityOverride() const { return gravityOverride_; }
  190. /// Return center of mass offset.
  191. const Vector3& GetCenterOfMass() const { return centerOfMass_; }
  192. /// Return kinematic mode flag.
  193. bool IsKinematic() const { return kinematic_; }
  194. /// Return whether this RigidBody is acting as a trigger.
  195. bool IsTrigger() const { return trigger_; }
  196. /// Return whether rigid body is active (not sleeping.)
  197. bool IsActive() const;
  198. /// Return collision layer.
  199. unsigned GetCollisionLayer() const { return collisionLayer_; }
  200. /// Return collision mask.
  201. unsigned GetCollisionMask() const { return collisionMask_; }
  202. /// Return collision event signaling mode.
  203. CollisionEventMode GetCollisionEventMode() const { return collisionEventMode_; }
  204. /// Return colliding rigid bodies from the last simulation step. Only returns collisions that were sent as events (depends on collision event mode) and excludes e.g. static-static collisions.
  205. void GetCollidingBodies(PODVector<RigidBody*>& result) const;
  206. /// Apply new world transform after a simulation step. Called internally.
  207. void ApplyWorldTransform(const Vector3& newWorldPosition, const Quaternion& newWorldRotation);
  208. /// Update mass and inertia to the Bullet rigid body. Readd body to world if necessary: if was in world and the Bullet collision shape to use changed.
  209. void UpdateMass();
  210. /// Update gravity parameters to the Bullet rigid body.
  211. void UpdateGravity();
  212. /// Set network angular velocity attribute.
  213. void SetNetAngularVelocityAttr(const PODVector<unsigned char>& value);
  214. /// Return network angular velocity attribute.
  215. const PODVector<unsigned char>& GetNetAngularVelocityAttr() const;
  216. /// Add a constraint that refers to this rigid body.
  217. void AddConstraint(Constraint* constraint);
  218. /// Remove a constraint that refers to this rigid body.
  219. void RemoveConstraint(Constraint* constraint);
  220. /// Remove the rigid body.
  221. void ReleaseBody();
  222. protected:
  223. /// Handle node being assigned.
  224. virtual void OnNodeSet(Node* node);
  225. /// Handle scene being assigned.
  226. virtual void OnSceneSet(Scene* scene);
  227. /// Handle node transform being dirtied.
  228. virtual void OnMarkedDirty(Node* node);
  229. private:
  230. /// Create the rigid body, or re-add to the physics world with changed flags. Calls UpdateMass().
  231. void AddBodyToWorld();
  232. /// Remove the rigid body from the physics world.
  233. void RemoveBodyFromWorld();
  234. /// Handle SmoothedTransform target position update.
  235. void HandleTargetPosition(StringHash eventType, VariantMap& eventData);
  236. /// Handle SmoothedTransform target rotation update.
  237. void HandleTargetRotation(StringHash eventType, VariantMap& eventData);
  238. /// Bullet rigid body.
  239. UniquePtr<btRigidBody> body_;
  240. /// Bullet compound collision shape.
  241. UniquePtr<btCompoundShape> compoundShape_;
  242. /// Compound collision shape with center of mass offset applied.
  243. UniquePtr<btCompoundShape> shiftedCompoundShape_;
  244. /// Physics world.
  245. WeakPtr<PhysicsWorld> physicsWorld_;
  246. /// Smoothed transform, if has one.
  247. WeakPtr<SmoothedTransform> smoothedTransform_;
  248. /// Constraints that refer to this rigid body.
  249. PODVector<Constraint*> constraints_;
  250. /// Gravity override vector.
  251. Vector3 gravityOverride_;
  252. /// Center of mass offset.
  253. Vector3 centerOfMass_;
  254. /// Mass.
  255. float mass_;
  256. /// Attribute buffer for network replication.
  257. mutable VectorBuffer attrBuffer_;
  258. /// Collision layer.
  259. unsigned collisionLayer_;
  260. /// Collision mask.
  261. unsigned collisionMask_;
  262. /// Collision event signaling mode.
  263. CollisionEventMode collisionEventMode_;
  264. /// Last interpolated position from the simulation.
  265. mutable Vector3 lastPosition_;
  266. /// Last interpolated rotation from the simulation.
  267. mutable Quaternion lastRotation_;
  268. /// Kinematic flag.
  269. bool kinematic_;
  270. /// Trigger flag.
  271. bool trigger_;
  272. /// Use gravity flag.
  273. bool useGravity_;
  274. /// Readd body to world flag.
  275. bool readdBody_;
  276. /// Body exists in world flag.
  277. bool inWorld_;
  278. /// Mass update enable flag.
  279. bool enableMassUpdate_;
  280. /// Internal flag whether has simulated at least once.
  281. mutable bool hasSimulated_;
  282. };
  283. }