RigidBody.cpp 33 KB

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