RigidBody.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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. #include "Precompiled.h"
  23. #include "CollisionShape.h"
  24. #include "Constraint.h"
  25. #include "Context.h"
  26. #include "Log.h"
  27. #include "MemoryBuffer.h"
  28. #include "PhysicsUtils.h"
  29. #include "PhysicsWorld.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "ResourceEvents.h"
  33. #include "RigidBody.h"
  34. #include "Scene.h"
  35. #include "SceneEvents.h"
  36. #include "SmoothedTransform.h"
  37. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  38. #include <BulletDynamics/Dynamics/btRigidBody.h>
  39. #include <BulletCollision/CollisionShapes/btCompoundShape.h>
  40. namespace Urho3D
  41. {
  42. static const float DEFAULT_MASS = 0.0f;
  43. static const float DEFAULT_FRICTION = 0.5f;
  44. static const float DEFAULT_RESTITUTION = 0.0f;
  45. static const float DEFAULT_ROLLING_FRICTION = 0.0f;
  46. static const unsigned DEFAULT_COLLISION_LAYER = 0x1;
  47. static const unsigned DEFAULT_COLLISION_MASK = M_MAX_UNSIGNED;
  48. static const char* collisionEventModeNames[] =
  49. {
  50. "Never",
  51. "When Active",
  52. "Always",
  53. 0
  54. };
  55. extern const char* PHYSICS_CATEGORY;
  56. RigidBody::RigidBody(Context* context) :
  57. Component(context),
  58. body_(0),
  59. compoundShape_(0),
  60. shiftedCompoundShape_(0),
  61. gravityOverride_(Vector3::ZERO),
  62. centerOfMass_(Vector3::ZERO),
  63. mass_(DEFAULT_MASS),
  64. collisionLayer_(DEFAULT_COLLISION_LAYER),
  65. collisionMask_(DEFAULT_COLLISION_MASK),
  66. collisionEventMode_(COLLISION_ACTIVE),
  67. lastPosition_(Vector3::ZERO),
  68. lastRotation_(Quaternion::IDENTITY),
  69. kinematic_(false),
  70. phantom_(false),
  71. useGravity_(true),
  72. hasSmoothedTransform_(false),
  73. readdBody_(false),
  74. inWorld_(false)
  75. {
  76. compoundShape_ = new btCompoundShape();
  77. shiftedCompoundShape_ = new btCompoundShape();
  78. }
  79. RigidBody::~RigidBody()
  80. {
  81. ReleaseBody();
  82. if (physicsWorld_)
  83. physicsWorld_->RemoveRigidBody(this);
  84. delete compoundShape_;
  85. compoundShape_ = 0;
  86. delete shiftedCompoundShape_;
  87. shiftedCompoundShape_ = 0;
  88. }
  89. void RigidBody::RegisterObject(Context* context)
  90. {
  91. context->RegisterFactory<RigidBody>(PHYSICS_CATEGORY);
  92. ACCESSOR_ATTRIBUTE(RigidBody, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  93. ACCESSOR_ATTRIBUTE(RigidBody, VAR_QUATERNION, "Physics Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE | AM_NOEDIT);
  94. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Physics Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE | AM_NOEDIT);
  95. ATTRIBUTE(RigidBody, VAR_FLOAT, "Mass", mass_, DEFAULT_MASS, AM_DEFAULT);
  96. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Friction", GetFriction, SetFriction, float, DEFAULT_FRICTION, AM_DEFAULT);
  97. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Anisotropic Friction", GetAnisotropicFriction, SetAnisotropicFriction, Vector3, Vector3::ONE, AM_DEFAULT);
  98. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Rolling Friction", GetRollingFriction, SetRollingFriction, float, DEFAULT_ROLLING_FRICTION, AM_DEFAULT);
  99. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Restitution", GetRestitution, SetRestitution, float, DEFAULT_RESTITUTION, AM_DEFAULT);
  100. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Linear Velocity", GetLinearVelocity, SetLinearVelocity, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  101. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Angular Velocity", GetAngularVelocity, SetAngularVelocity, Vector3, Vector3::ZERO, AM_FILE);
  102. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Linear Factor", GetLinearFactor, SetLinearFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  103. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Angular Factor", GetAngularFactor, SetAngularFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  104. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Linear Damping", GetLinearDamping, SetLinearDamping, float, 0.0f, AM_DEFAULT);
  105. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Angular Damping", GetAngularDamping, SetAngularDamping, float, 0.0f, AM_DEFAULT);
  106. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Linear Rest Threshold", GetLinearRestThreshold, SetLinearRestThreshold, float, 0.8f, AM_DEFAULT);
  107. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Angular Rest Threshold", GetAngularRestThreshold, SetAngularRestThreshold, float, 1.0f, AM_DEFAULT);
  108. ATTRIBUTE(RigidBody, VAR_INT, "Collision Layer", collisionLayer_, DEFAULT_COLLISION_LAYER, AM_DEFAULT);
  109. ATTRIBUTE(RigidBody, VAR_INT, "Collision Mask", collisionMask_, DEFAULT_COLLISION_MASK, AM_DEFAULT);
  110. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Contact Threshold", GetContactProcessingThreshold, SetContactProcessingThreshold, float, BT_LARGE_FLOAT, AM_DEFAULT);
  111. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "CCD Radius", GetCcdRadius, SetCcdRadius, float, 0.0f, AM_DEFAULT);
  112. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "CCD Motion Threshold", GetCcdMotionThreshold, SetCcdMotionThreshold, float, 0.0f, AM_DEFAULT);
  113. REF_ACCESSOR_ATTRIBUTE(RigidBody, VAR_BUFFER, "Network Angular Velocity", GetNetAngularVelocityAttr, SetNetAngularVelocityAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  114. ENUM_ATTRIBUTE(RigidBody, "Collision Event Mode", collisionEventMode_, collisionEventModeNames, COLLISION_ACTIVE, AM_DEFAULT);
  115. ACCESSOR_ATTRIBUTE(RigidBody, VAR_BOOL, "Use Gravity", GetUseGravity, SetUseGravity, bool, true, AM_DEFAULT);
  116. ATTRIBUTE(RigidBody, VAR_BOOL, "Is Kinematic", kinematic_, false, AM_DEFAULT);
  117. ATTRIBUTE(RigidBody, VAR_BOOL, "Is Phantom", phantom_, false, AM_DEFAULT);
  118. REF_ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Gravity Override", GetGravityOverride, SetGravityOverride, Vector3, Vector3::ZERO, AM_DEFAULT);
  119. }
  120. void RigidBody::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  121. {
  122. Component::OnSetAttribute(attr, src);
  123. // Change of any non-accessor attribute requires the rigid body to be re-added to the physics world
  124. if (!attr.accessor_)
  125. readdBody_ = true;
  126. }
  127. void RigidBody::ApplyAttributes()
  128. {
  129. if (readdBody_)
  130. AddBodyToWorld();
  131. }
  132. void RigidBody::OnSetEnabled()
  133. {
  134. bool enabled = IsEnabledEffective();
  135. if (enabled && !inWorld_)
  136. AddBodyToWorld();
  137. else if (!enabled && inWorld_)
  138. RemoveBodyFromWorld();
  139. }
  140. void RigidBody::getWorldTransform(btTransform &worldTrans) const
  141. {
  142. // We may be in a pathological state where a RigidBody exists without a scene node when this callback is fired,
  143. // so check to be sure
  144. if (node_)
  145. {
  146. lastPosition_ = node_->GetWorldPosition();
  147. lastRotation_ = node_->GetWorldRotation();
  148. worldTrans.setOrigin(ToBtVector3(lastPosition_ + lastRotation_ * centerOfMass_));
  149. worldTrans.setRotation(ToBtQuaternion(lastRotation_));
  150. }
  151. }
  152. void RigidBody::setWorldTransform(const btTransform &worldTrans)
  153. {
  154. Quaternion newWorldRotation = ToQuaternion(worldTrans.getRotation());
  155. Vector3 newWorldPosition = ToVector3(worldTrans.getOrigin()) - newWorldRotation * centerOfMass_;
  156. RigidBody* parentRigidBody = 0;
  157. // It is possible that the RigidBody component has been kept alive via a shared pointer,
  158. // while its scene node has already been destroyed
  159. if (node_)
  160. {
  161. // If the rigid body is parented to another rigid body, can not set the transform immediately.
  162. // In that case store it to PhysicsWorld for delayed assignment
  163. Node* parent = node_->GetParent();
  164. if (parent != GetScene() && parent)
  165. parentRigidBody = parent->GetComponent<RigidBody>();
  166. if (!parentRigidBody)
  167. ApplyWorldTransform(newWorldPosition, newWorldRotation);
  168. else
  169. {
  170. DelayedWorldTransform delayed;
  171. delayed.rigidBody_ = this;
  172. delayed.parentRigidBody_ = parentRigidBody;
  173. delayed.worldPosition_ = newWorldPosition;
  174. delayed.worldRotation_ = newWorldRotation;
  175. physicsWorld_->AddDelayedWorldTransform(delayed);
  176. }
  177. MarkNetworkUpdate();
  178. }
  179. }
  180. void RigidBody::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  181. {
  182. if (debug && physicsWorld_ && body_ && IsEnabledEffective())
  183. {
  184. physicsWorld_->SetDebugRenderer(debug);
  185. physicsWorld_->SetDebugDepthTest(depthTest);
  186. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  187. world->debugDrawObject(body_->getWorldTransform(), shiftedCompoundShape_, IsActive() ? btVector3(1.0f, 1.0f, 1.0f) :
  188. btVector3(0.0f, 1.0f, 0.0f));
  189. physicsWorld_->SetDebugRenderer(0);
  190. }
  191. }
  192. void RigidBody::SetMass(float mass)
  193. {
  194. mass = Max(mass, 0.0f);
  195. if (mass != mass_)
  196. {
  197. mass_ = mass;
  198. AddBodyToWorld();
  199. MarkNetworkUpdate();
  200. }
  201. }
  202. void RigidBody::SetPosition(Vector3 position)
  203. {
  204. if (body_)
  205. {
  206. btTransform& worldTrans = body_->getWorldTransform();
  207. worldTrans.setOrigin(ToBtVector3(position + ToQuaternion(worldTrans.getRotation()) * centerOfMass_));
  208. // When forcing the physics position, set also interpolated position so that there is no jitter
  209. // Do not reset for kinematic objects, so that they can estimate velocity properly
  210. if (!kinematic_)
  211. {
  212. btTransform interpTrans = body_->getInterpolationWorldTransform();
  213. interpTrans.setOrigin(worldTrans.getOrigin());
  214. body_->setInterpolationWorldTransform(interpTrans);
  215. }
  216. body_->updateInertiaTensor();
  217. Activate();
  218. MarkNetworkUpdate();
  219. }
  220. }
  221. void RigidBody::SetRotation(Quaternion rotation)
  222. {
  223. if (body_)
  224. {
  225. // Due to center of mass offset, we may need to adjust position also
  226. Vector3 oldPosition = GetPosition();
  227. btTransform& worldTrans = body_->getWorldTransform();
  228. worldTrans.setRotation(ToBtQuaternion(rotation));
  229. if (!centerOfMass_.Equals(Vector3::ZERO))
  230. worldTrans.setOrigin(ToBtVector3(oldPosition + rotation * centerOfMass_));
  231. if (!kinematic_)
  232. {
  233. btTransform interpTrans = body_->getInterpolationWorldTransform();
  234. interpTrans.setRotation(worldTrans.getRotation());
  235. if (!centerOfMass_.Equals(Vector3::ZERO))
  236. interpTrans.setOrigin(worldTrans.getOrigin());
  237. body_->setInterpolationWorldTransform(interpTrans);
  238. }
  239. body_->updateInertiaTensor();
  240. Activate();
  241. MarkNetworkUpdate();
  242. }
  243. }
  244. void RigidBody::SetTransform(const Vector3& position, const Quaternion& rotation)
  245. {
  246. if (body_)
  247. {
  248. btTransform& worldTrans = body_->getWorldTransform();
  249. worldTrans.setRotation(ToBtQuaternion(rotation));
  250. worldTrans.setOrigin(ToBtVector3(position + rotation * centerOfMass_));
  251. if (!kinematic_)
  252. {
  253. btTransform interpTrans = body_->getInterpolationWorldTransform();
  254. interpTrans.setOrigin(worldTrans.getOrigin());
  255. interpTrans.setRotation(worldTrans.getRotation());
  256. body_->setInterpolationWorldTransform(interpTrans);
  257. }
  258. body_->updateInertiaTensor();
  259. Activate();
  260. MarkNetworkUpdate();
  261. }
  262. }
  263. void RigidBody::SetLinearVelocity(Vector3 velocity)
  264. {
  265. if (body_)
  266. {
  267. body_->setLinearVelocity(ToBtVector3(velocity));
  268. if (velocity != Vector3::ZERO)
  269. Activate();
  270. MarkNetworkUpdate();
  271. }
  272. }
  273. void RigidBody::SetLinearFactor(Vector3 factor)
  274. {
  275. if (body_)
  276. {
  277. body_->setLinearFactor(ToBtVector3(factor));
  278. MarkNetworkUpdate();
  279. }
  280. }
  281. void RigidBody::SetLinearRestThreshold(float threshold)
  282. {
  283. if (body_)
  284. {
  285. body_->setSleepingThresholds(threshold, body_->getAngularSleepingThreshold());
  286. MarkNetworkUpdate();
  287. }
  288. }
  289. void RigidBody::SetLinearDamping(float damping)
  290. {
  291. if (body_)
  292. {
  293. body_->setDamping(damping, body_->getAngularDamping());
  294. MarkNetworkUpdate();
  295. }
  296. }
  297. void RigidBody::SetAngularVelocity(Vector3 velocity)
  298. {
  299. if (body_)
  300. {
  301. body_->setAngularVelocity(ToBtVector3(velocity));
  302. if (velocity != Vector3::ZERO)
  303. Activate();
  304. MarkNetworkUpdate();
  305. }
  306. }
  307. void RigidBody::SetAngularFactor(Vector3 factor)
  308. {
  309. if (body_)
  310. {
  311. body_->setAngularFactor(ToBtVector3(factor));
  312. MarkNetworkUpdate();
  313. }
  314. }
  315. void RigidBody::SetAngularRestThreshold(float threshold)
  316. {
  317. if (body_)
  318. {
  319. body_->setSleepingThresholds(body_->getLinearSleepingThreshold(), threshold);
  320. MarkNetworkUpdate();
  321. }
  322. }
  323. void RigidBody::SetAngularDamping(float damping)
  324. {
  325. if (body_)
  326. {
  327. body_->setDamping(body_->getLinearDamping(), damping);
  328. MarkNetworkUpdate();
  329. }
  330. }
  331. void RigidBody::SetFriction(float friction)
  332. {
  333. if (body_)
  334. {
  335. body_->setFriction(friction);
  336. MarkNetworkUpdate();
  337. }
  338. }
  339. void RigidBody::SetAnisotropicFriction(Vector3 friction)
  340. {
  341. if (body_)
  342. {
  343. body_->setAnisotropicFriction(ToBtVector3(friction));
  344. MarkNetworkUpdate();
  345. }
  346. }
  347. void RigidBody::SetRollingFriction(float friction)
  348. {
  349. if (body_)
  350. {
  351. body_->setRollingFriction(friction);
  352. MarkNetworkUpdate();
  353. }
  354. }
  355. void RigidBody::SetRestitution(float restitution)
  356. {
  357. if (body_)
  358. {
  359. body_->setRestitution(restitution);
  360. MarkNetworkUpdate();
  361. }
  362. }
  363. void RigidBody::SetContactProcessingThreshold(float threshold)
  364. {
  365. if (body_)
  366. {
  367. body_->setContactProcessingThreshold(threshold);
  368. MarkNetworkUpdate();
  369. }
  370. }
  371. void RigidBody::SetCcdRadius(float radius)
  372. {
  373. radius = Max(radius, 0.0f);
  374. if (body_)
  375. {
  376. body_->setCcdSweptSphereRadius(radius);
  377. MarkNetworkUpdate();
  378. }
  379. }
  380. void RigidBody::SetCcdMotionThreshold(float threshold)
  381. {
  382. threshold = Max(threshold, 0.0f);
  383. if (body_)
  384. {
  385. body_->setCcdMotionThreshold(threshold);
  386. MarkNetworkUpdate();
  387. }
  388. }
  389. void RigidBody::SetUseGravity(bool enable)
  390. {
  391. if (enable != useGravity_)
  392. {
  393. useGravity_ = enable;
  394. UpdateGravity();
  395. MarkNetworkUpdate();
  396. }
  397. }
  398. void RigidBody::SetGravityOverride(const Vector3& gravity)
  399. {
  400. if (gravity != gravityOverride_)
  401. {
  402. gravityOverride_ = gravity;
  403. UpdateGravity();
  404. MarkNetworkUpdate();
  405. }
  406. }
  407. void RigidBody::SetKinematic(bool enable)
  408. {
  409. if (enable != kinematic_)
  410. {
  411. kinematic_ = enable;
  412. AddBodyToWorld();
  413. MarkNetworkUpdate();
  414. }
  415. }
  416. void RigidBody::SetPhantom(bool enable)
  417. {
  418. if (enable != phantom_)
  419. {
  420. phantom_ = enable;
  421. AddBodyToWorld();
  422. MarkNetworkUpdate();
  423. }
  424. }
  425. void RigidBody::SetCollisionLayer(unsigned layer)
  426. {
  427. if (layer != collisionLayer_)
  428. {
  429. collisionLayer_ = layer;
  430. AddBodyToWorld();
  431. MarkNetworkUpdate();
  432. }
  433. }
  434. void RigidBody::SetCollisionMask(unsigned mask)
  435. {
  436. if (mask != collisionMask_)
  437. {
  438. collisionMask_ = mask;
  439. AddBodyToWorld();
  440. MarkNetworkUpdate();
  441. }
  442. }
  443. void RigidBody::SetCollisionLayerAndMask(unsigned layer, unsigned mask)
  444. {
  445. if (layer != collisionLayer_ || mask != collisionMask_)
  446. {
  447. collisionLayer_ = layer;
  448. collisionMask_ = mask;
  449. AddBodyToWorld();
  450. MarkNetworkUpdate();
  451. }
  452. }
  453. void RigidBody::SetCollisionEventMode(CollisionEventMode mode)
  454. {
  455. collisionEventMode_ = mode;
  456. MarkNetworkUpdate();
  457. }
  458. void RigidBody::ApplyForce(const Vector3& force)
  459. {
  460. if (body_ && force != Vector3::ZERO)
  461. {
  462. Activate();
  463. body_->applyCentralForce(ToBtVector3(force));
  464. }
  465. }
  466. void RigidBody::ApplyForce(const Vector3& force, const Vector3& position)
  467. {
  468. if (body_ && force != Vector3::ZERO)
  469. {
  470. Activate();
  471. body_->applyForce(ToBtVector3(force), ToBtVector3(position - centerOfMass_));
  472. }
  473. }
  474. void RigidBody::ApplyTorque(const Vector3& torque)
  475. {
  476. if (body_ && torque != Vector3::ZERO)
  477. {
  478. Activate();
  479. body_->applyTorque(ToBtVector3(torque));
  480. }
  481. }
  482. void RigidBody::ApplyImpulse(const Vector3& impulse)
  483. {
  484. if (body_ && impulse != Vector3::ZERO)
  485. {
  486. Activate();
  487. body_->applyCentralImpulse(ToBtVector3(impulse));
  488. }
  489. }
  490. void RigidBody::ApplyImpulse(const Vector3& impulse, const Vector3& position)
  491. {
  492. if (body_ && impulse != Vector3::ZERO)
  493. {
  494. Activate();
  495. body_->applyImpulse(ToBtVector3(impulse), ToBtVector3(position - centerOfMass_));
  496. }
  497. }
  498. void RigidBody::ApplyTorqueImpulse(const Vector3& torque)
  499. {
  500. if (body_ && torque != Vector3::ZERO)
  501. {
  502. Activate();
  503. body_->applyTorqueImpulse(ToBtVector3(torque));
  504. }
  505. }
  506. void RigidBody::ResetForces()
  507. {
  508. if (body_)
  509. body_->clearForces();
  510. }
  511. void RigidBody::Activate()
  512. {
  513. if (body_ && mass_ > 0.0f)
  514. body_->activate(true);
  515. }
  516. void RigidBody::ReAddBodyToWorld()
  517. {
  518. if (body_ && inWorld_)
  519. AddBodyToWorld();
  520. }
  521. Vector3 RigidBody::GetPosition() const
  522. {
  523. if (body_)
  524. {
  525. const btTransform& transform = body_->getWorldTransform();
  526. return ToVector3(transform.getOrigin()) - ToQuaternion(transform.getRotation()) * centerOfMass_;
  527. }
  528. else
  529. return Vector3::ZERO;
  530. }
  531. Quaternion RigidBody::GetRotation() const
  532. {
  533. return body_ ? ToQuaternion(body_->getWorldTransform().getRotation()) : Quaternion::IDENTITY;
  534. }
  535. Vector3 RigidBody::GetLinearVelocity() const
  536. {
  537. return body_ ? ToVector3(body_->getLinearVelocity()) : Vector3::ZERO;
  538. }
  539. Vector3 RigidBody::GetLinearFactor() const
  540. {
  541. return body_ ? ToVector3(body_->getLinearFactor()) : Vector3::ZERO;
  542. }
  543. Vector3 RigidBody::GetVelocityAtPoint(const Vector3& position) const
  544. {
  545. return body_ ? ToVector3(body_->getVelocityInLocalPoint(ToBtVector3(position - centerOfMass_))) : Vector3::ZERO;
  546. }
  547. float RigidBody::GetLinearRestThreshold() const
  548. {
  549. return body_ ? body_->getLinearSleepingThreshold() : 0.0f;
  550. }
  551. float RigidBody::GetLinearDamping() const
  552. {
  553. return body_ ? body_->getLinearDamping() : 0.0f;
  554. }
  555. Vector3 RigidBody::GetAngularVelocity() const
  556. {
  557. return body_ ? ToVector3(body_->getAngularVelocity()) : Vector3::ZERO;
  558. }
  559. Vector3 RigidBody::GetAngularFactor() const
  560. {
  561. return body_ ? ToVector3(body_->getAngularFactor()) : Vector3::ZERO;
  562. }
  563. float RigidBody::GetAngularRestThreshold() const
  564. {
  565. return body_ ? body_->getAngularSleepingThreshold() : 0.0f;
  566. }
  567. float RigidBody::GetAngularDamping() const
  568. {
  569. return body_ ? body_->getAngularDamping() : 0.0f;
  570. }
  571. float RigidBody::GetFriction() const
  572. {
  573. return body_ ? body_->getFriction() : 0.0f;
  574. }
  575. Vector3 RigidBody::GetAnisotropicFriction() const
  576. {
  577. return body_ ? ToVector3(body_->getAnisotropicFriction()) : Vector3::ZERO;
  578. }
  579. float RigidBody::GetRollingFriction() const
  580. {
  581. return body_ ? body_->getRollingFriction() : 0.0f;
  582. }
  583. float RigidBody::GetRestitution() const
  584. {
  585. return body_ ? body_->getRestitution() : 0.0f;
  586. }
  587. float RigidBody::GetContactProcessingThreshold() const
  588. {
  589. return body_ ? body_->getContactProcessingThreshold() : 0.0f;
  590. }
  591. float RigidBody::GetCcdRadius() const
  592. {
  593. return body_ ? body_->getCcdSweptSphereRadius() : 0.0f;
  594. }
  595. float RigidBody::GetCcdMotionThreshold() const
  596. {
  597. return body_ ? body_->getCcdMotionThreshold() : 0.0f;
  598. }
  599. bool RigidBody::IsActive() const
  600. {
  601. return body_ ? body_->isActive() : false;
  602. }
  603. void RigidBody::GetCollidingBodies(PODVector<RigidBody*>& result) const
  604. {
  605. if (physicsWorld_)
  606. physicsWorld_->GetRigidBodies(result, this);
  607. else
  608. result.Clear();
  609. }
  610. void RigidBody::ApplyWorldTransform(const Vector3& newWorldPosition, const Quaternion& newWorldRotation)
  611. {
  612. physicsWorld_->SetApplyingTransforms(true);
  613. // Apply transform to the SmoothedTransform component instead of node transform if available
  614. SmoothedTransform* transform = 0;
  615. if (hasSmoothedTransform_)
  616. transform = GetComponent<SmoothedTransform>();
  617. if (transform)
  618. {
  619. transform->SetTargetWorldPosition(newWorldPosition);
  620. transform->SetTargetWorldRotation(newWorldRotation);
  621. lastPosition_ = newWorldPosition;
  622. lastRotation_ = newWorldRotation;
  623. }
  624. else
  625. {
  626. node_->SetWorldPosition(newWorldPosition);
  627. node_->SetWorldRotation(newWorldRotation);
  628. lastPosition_ = node_->GetWorldPosition();
  629. lastRotation_ = node_->GetWorldRotation();
  630. }
  631. physicsWorld_->SetApplyingTransforms(false);
  632. }
  633. void RigidBody::UpdateMass()
  634. {
  635. if (!body_)
  636. return;
  637. btTransform principal;
  638. principal.setRotation(btQuaternion::getIdentity());
  639. principal.setOrigin(btVector3(0.0f, 0.0f, 0.0f));
  640. // Calculate center of mass shift from all the collision shapes
  641. unsigned numShapes = compoundShape_->getNumChildShapes();
  642. if (numShapes)
  643. {
  644. PODVector<float> masses(numShapes);
  645. for (unsigned i = 0; i < numShapes; ++i)
  646. {
  647. // The actual mass does not matter, divide evenly between child shapes
  648. masses[i] = 1.0f;
  649. }
  650. btVector3 inertia(0.0f, 0.0f, 0.0f);
  651. compoundShape_->calculatePrincipalAxisTransform(&masses[0], principal, inertia);
  652. }
  653. // Add child shapes to shifted compound shape with adjusted offset
  654. while (shiftedCompoundShape_->getNumChildShapes())
  655. shiftedCompoundShape_->removeChildShapeByIndex(shiftedCompoundShape_->getNumChildShapes() - 1);
  656. for (unsigned i = 0; i < numShapes; ++i)
  657. {
  658. btTransform adjusted = compoundShape_->getChildTransform(i);
  659. adjusted.setOrigin(adjusted.getOrigin() - principal.getOrigin());
  660. shiftedCompoundShape_->addChildShape(adjusted, compoundShape_->getChildShape(i));
  661. }
  662. // If shifted compound shape has only one child with no offset/rotation, use the child shape
  663. // directly as the rigid body collision shape for better collision detection performance
  664. bool useCompound = !numShapes || numShapes > 1;
  665. if (!useCompound)
  666. {
  667. const btTransform& childTransform = shiftedCompoundShape_->getChildTransform(0);
  668. if (!ToVector3(childTransform.getOrigin()).Equals(Vector3::ZERO) ||
  669. !ToQuaternion(childTransform.getRotation()).Equals(Quaternion::IDENTITY))
  670. useCompound = true;
  671. }
  672. body_->setCollisionShape(useCompound ? shiftedCompoundShape_ : shiftedCompoundShape_->getChildShape(0));
  673. // If we have one shape and this is a triangle mesh, we use a custom material callback in order to adjust internal edges
  674. if (!useCompound && body_->getCollisionShape()->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE &&
  675. physicsWorld_->GetInternalEdge())
  676. body_->setCollisionFlags(body_->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
  677. else
  678. body_->setCollisionFlags(body_->getCollisionFlags() & ~btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
  679. // Reapply rigid body position with new center of mass shift
  680. Vector3 oldPosition = GetPosition();
  681. centerOfMass_ = ToVector3(principal.getOrigin());
  682. SetPosition(oldPosition);
  683. // Calculate final inertia
  684. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  685. if (mass_ > 0.0f)
  686. shiftedCompoundShape_->calculateLocalInertia(mass_, localInertia);
  687. body_->setMassProps(mass_, localInertia);
  688. body_->updateInertiaTensor();
  689. // Reapply constraint positions for new center of mass shift
  690. if (node_)
  691. {
  692. for (PODVector<Constraint*>::Iterator i = constraints_.Begin(); i != constraints_.End(); ++i)
  693. (*i)->ApplyFrames();
  694. }
  695. }
  696. void RigidBody::UpdateGravity()
  697. {
  698. if (physicsWorld_ && body_)
  699. {
  700. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  701. int flags = body_->getFlags();
  702. if (useGravity_ && gravityOverride_ == Vector3::ZERO)
  703. flags &= ~BT_DISABLE_WORLD_GRAVITY;
  704. else
  705. flags |= BT_DISABLE_WORLD_GRAVITY;
  706. body_->setFlags(flags);
  707. if (useGravity_)
  708. {
  709. // If override vector is zero, use world's gravity
  710. if (gravityOverride_ == Vector3::ZERO)
  711. body_->setGravity(world->getGravity());
  712. else
  713. body_->setGravity(ToBtVector3(gravityOverride_));
  714. }
  715. else
  716. body_->setGravity(btVector3(0.0f, 0.0f, 0.0f));
  717. }
  718. }
  719. void RigidBody::SetNetAngularVelocityAttr(const PODVector<unsigned char>& value)
  720. {
  721. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  722. MemoryBuffer buf(value);
  723. SetAngularVelocity(buf.ReadPackedVector3(maxVelocity));
  724. }
  725. const PODVector<unsigned char>& RigidBody::GetNetAngularVelocityAttr() const
  726. {
  727. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  728. attrBuffer_.Clear();
  729. attrBuffer_.WritePackedVector3(GetAngularVelocity(), maxVelocity);
  730. return attrBuffer_.GetBuffer();
  731. }
  732. void RigidBody::AddConstraint(Constraint* constraint)
  733. {
  734. constraints_.Push(constraint);
  735. }
  736. void RigidBody::RemoveConstraint(Constraint* constraint)
  737. {
  738. constraints_.Remove(constraint);
  739. // A constraint being removed should possibly cause the object to eg. start falling, so activate
  740. Activate();
  741. }
  742. void RigidBody::ReleaseBody()
  743. {
  744. if (body_)
  745. {
  746. // Release all constraints which refer to this body
  747. // Make a copy for iteration
  748. PODVector<Constraint*> constraints = constraints_;
  749. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  750. (*i)->ReleaseConstraint();
  751. RemoveBodyFromWorld();
  752. delete body_;
  753. body_ = 0;
  754. }
  755. }
  756. void RigidBody::OnMarkedDirty(Node* node)
  757. {
  758. // If node transform changes, apply it back to the physics transform. However, do not do this when a SmoothedTransform
  759. // is in use, because in that case the node transform will be constantly updated into smoothed, possibly non-physical
  760. // states; rather follow the SmoothedTransform target transform directly
  761. if ((!physicsWorld_ || !physicsWorld_->IsApplyingTransforms()) && !hasSmoothedTransform_)
  762. {
  763. // Physics operations are not safe from worker threads
  764. Scene* scene = GetScene();
  765. if (scene && scene->IsThreadedUpdate())
  766. {
  767. scene->DelayedMarkedDirty(this);
  768. return;
  769. }
  770. // Check if transform has changed from the last one set in ApplyWorldTransform()
  771. Vector3 newPosition = node_->GetWorldPosition();
  772. Quaternion newRotation = node_->GetWorldRotation();
  773. if (!newRotation.Equals(lastRotation_))
  774. {
  775. lastRotation_ = newRotation;
  776. SetRotation(newRotation);
  777. }
  778. if (!newPosition.Equals(lastPosition_))
  779. {
  780. lastPosition_ = newPosition;
  781. SetPosition(newPosition);
  782. }
  783. }
  784. }
  785. void RigidBody::OnNodeSet(Node* node)
  786. {
  787. if (node)
  788. {
  789. Scene* scene = GetScene();
  790. if (scene)
  791. {
  792. if (scene == node)
  793. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  794. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  795. if (physicsWorld_)
  796. physicsWorld_->AddRigidBody(this);
  797. else
  798. LOGERROR("No physics world component in scene, can not create rigid body");
  799. AddBodyToWorld();
  800. }
  801. else
  802. LOGERROR("Node is detached from scene, can not create rigid body");
  803. node->AddListener(this);
  804. }
  805. }
  806. void RigidBody::AddBodyToWorld()
  807. {
  808. if (!physicsWorld_)
  809. return;
  810. PROFILE(AddBodyToWorld);
  811. if (mass_ < 0.0f)
  812. mass_ = 0.0f;
  813. if (body_)
  814. RemoveBodyFromWorld();
  815. else
  816. {
  817. // Correct inertia will be calculated below
  818. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  819. body_ = new btRigidBody(mass_, this, shiftedCompoundShape_, localInertia);
  820. body_->setUserPointer(this);
  821. // Check for existence of the SmoothedTransform component, which should be created by now in network client mode.
  822. // If it exists, subscribe to its change events
  823. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  824. if (transform)
  825. {
  826. hasSmoothedTransform_ = true;
  827. SubscribeToEvent(transform, E_TARGETPOSITION, HANDLER(RigidBody, HandleTargetPosition));
  828. SubscribeToEvent(transform, E_TARGETROTATION, HANDLER(RigidBody, HandleTargetRotation));
  829. }
  830. // Check if CollisionShapes already exist in the node and add them to the compound shape.
  831. // Do not update mass yet, but do it once all shapes have been added
  832. PODVector<CollisionShape*> shapes;
  833. node_->GetComponents<CollisionShape>(shapes);
  834. for (PODVector<CollisionShape*>::Iterator i = shapes.Begin(); i != shapes.End(); ++i)
  835. (*i)->NotifyRigidBody(false);
  836. // Check if this node contains Constraint components that were waiting for the rigid body to be created, and signal them
  837. // to create themselves now
  838. PODVector<Constraint*> constraints;
  839. node_->GetComponents<Constraint>(constraints);
  840. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  841. (*i)->CreateConstraint();
  842. }
  843. UpdateMass();
  844. UpdateGravity();
  845. int flags = body_->getCollisionFlags();
  846. if (phantom_)
  847. flags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
  848. else
  849. flags &= ~btCollisionObject::CF_NO_CONTACT_RESPONSE;
  850. if (kinematic_)
  851. flags |= btCollisionObject::CF_KINEMATIC_OBJECT;
  852. else
  853. flags &= ~btCollisionObject::CF_KINEMATIC_OBJECT;
  854. body_->setCollisionFlags(flags);
  855. body_->forceActivationState(kinematic_ ? DISABLE_DEACTIVATION : ISLAND_SLEEPING);
  856. if (!IsEnabledEffective())
  857. return;
  858. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  859. world->addRigidBody(body_, collisionLayer_, collisionMask_);
  860. inWorld_ = true;
  861. readdBody_ = false;
  862. if (mass_ > 0.0f)
  863. Activate();
  864. else
  865. {
  866. SetLinearVelocity(Vector3::ZERO);
  867. SetAngularVelocity(Vector3::ZERO);
  868. }
  869. }
  870. void RigidBody::RemoveBodyFromWorld()
  871. {
  872. if (physicsWorld_ && body_ && inWorld_)
  873. {
  874. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  875. world->removeRigidBody(body_);
  876. inWorld_ = false;
  877. }
  878. }
  879. void RigidBody::HandleTargetPosition(StringHash eventType, VariantMap& eventData)
  880. {
  881. // Copy the smoothing target position to the rigid body
  882. if (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms())
  883. SetPosition(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldPosition());
  884. }
  885. void RigidBody::HandleTargetRotation(StringHash eventType, VariantMap& eventData)
  886. {
  887. // Copy the smoothing target rotation to the rigid body
  888. if (!physicsWorld_ || !physicsWorld_->IsApplyingTransforms())
  889. SetRotation(static_cast<SmoothedTransform*>(GetEventSender())->GetTargetWorldRotation());
  890. }
  891. }