RigidBody.cpp 32 KB

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