RigidBody.cpp 31 KB

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