RigidBody.cpp 32 KB

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