RigidBody.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "CollisionShape.h"
  24. #include "Constraint.h"
  25. #include "Context.h"
  26. #include "Log.h"
  27. #include "MemoryBuffer.h"
  28. #include "PhysicsUtils.h"
  29. #include "PhysicsWorld.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "ResourceEvents.h"
  33. #include "RigidBody.h"
  34. #include "Scene.h"
  35. #include "SceneEvents.h"
  36. #include "SmoothedTransform.h"
  37. #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  38. #include <BulletDynamics/Dynamics/btRigidBody.h>
  39. #include <BulletCollision/CollisionShapes/btCompoundShape.h>
  40. namespace Urho3D
  41. {
  42. static const float DEFAULT_MASS = 0.0f;
  43. static const float DEFAULT_FRICTION = 0.5f;
  44. static const float DEFAULT_RESTITUTION = 0.0f;
  45. static const unsigned DEFAULT_COLLISION_LAYER = 0x1;
  46. static const unsigned DEFAULT_COLLISION_MASK = M_MAX_UNSIGNED;
  47. static const char* collisionEventModeNames[] =
  48. {
  49. "Never",
  50. "When Active",
  51. "Always",
  52. 0
  53. };
  54. extern const char* PHYSICS_CATEGORY;
  55. RigidBody::RigidBody(Context* context) :
  56. Component(context),
  57. body_(0),
  58. compoundShape_(0),
  59. shiftedCompoundShape_(0),
  60. gravityOverride_(Vector3::ZERO),
  61. centerOfMass_(Vector3::ZERO),
  62. mass_(DEFAULT_MASS),
  63. collisionLayer_(DEFAULT_COLLISION_LAYER),
  64. collisionMask_(DEFAULT_COLLISION_MASK),
  65. collisionEventMode_(COLLISION_ACTIVE),
  66. lastPosition_(Vector3::ZERO),
  67. lastRotation_(Quaternion::IDENTITY),
  68. kinematic_(false),
  69. phantom_(false),
  70. useGravity_(true),
  71. hasSmoothedTransform_(false),
  72. readdBody_(false),
  73. inWorld_(false)
  74. {
  75. compoundShape_ = new btCompoundShape();
  76. shiftedCompoundShape_ = new btCompoundShape();
  77. }
  78. RigidBody::~RigidBody()
  79. {
  80. ReleaseBody();
  81. if (physicsWorld_)
  82. physicsWorld_->RemoveRigidBody(this);
  83. delete compoundShape_;
  84. compoundShape_ = 0;
  85. delete shiftedCompoundShape_;
  86. shiftedCompoundShape_ = 0;
  87. }
  88. void RigidBody::RegisterObject(Context* context)
  89. {
  90. context->RegisterFactory<RigidBody>(PHYSICS_CATEGORY);
  91. ACCESSOR_ATTRIBUTE(RigidBody, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  92. ACCESSOR_ATTRIBUTE(RigidBody, VAR_QUATERNION, "Physics Rotation", GetRotation, SetRotation, Quaternion, Quaternion::IDENTITY, AM_FILE | AM_NOEDIT);
  93. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Physics Position", GetPosition, SetPosition, Vector3, Vector3::ZERO, AM_FILE | AM_NOEDIT);
  94. ATTRIBUTE(RigidBody, VAR_FLOAT, "Mass", mass_, DEFAULT_MASS, AM_DEFAULT);
  95. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Friction", GetFriction, SetFriction, float, DEFAULT_FRICTION, AM_DEFAULT);
  96. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Restitution", GetRestitution, SetRestitution, float, DEFAULT_RESTITUTION, AM_DEFAULT);
  97. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Linear Velocity", GetLinearVelocity, SetLinearVelocity, Vector3, Vector3::ZERO, AM_DEFAULT | AM_LATESTDATA);
  98. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Angular Velocity", GetAngularVelocity, SetAngularVelocity, Vector3, Vector3::ZERO, AM_FILE);
  99. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Linear Factor", GetLinearFactor, SetLinearFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  100. ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Angular Factor", GetAngularFactor, SetAngularFactor, Vector3, Vector3::ONE, AM_DEFAULT);
  101. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Linear Damping", GetLinearDamping, SetLinearDamping, float, 0.0f, AM_DEFAULT);
  102. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Angular Damping", GetAngularDamping, SetAngularDamping, float, 0.0f, AM_DEFAULT);
  103. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Linear Rest Threshold", GetLinearRestThreshold, SetLinearRestThreshold, float, 0.8f, AM_DEFAULT);
  104. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Angular Rest Threshold", GetAngularRestThreshold, SetAngularRestThreshold, float, 1.0f, AM_DEFAULT);
  105. ATTRIBUTE(RigidBody, VAR_INT, "Collision Layer", collisionLayer_, DEFAULT_COLLISION_LAYER, AM_DEFAULT);
  106. ATTRIBUTE(RigidBody, VAR_INT, "Collision Mask", collisionMask_, DEFAULT_COLLISION_MASK, AM_DEFAULT);
  107. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "Contact Threshold", GetContactProcessingThreshold, SetContactProcessingThreshold, float, BT_LARGE_FLOAT, AM_DEFAULT);
  108. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "CCD Radius", GetCcdRadius, SetCcdRadius, float, 0.0f, AM_DEFAULT);
  109. ACCESSOR_ATTRIBUTE(RigidBody, VAR_FLOAT, "CCD Motion Threshold", GetCcdMotionThreshold, SetCcdMotionThreshold, float, 0.0f, AM_DEFAULT);
  110. REF_ACCESSOR_ATTRIBUTE(RigidBody, VAR_BUFFER, "Network Angular Velocity", GetNetAngularVelocityAttr, SetNetAngularVelocityAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  111. ENUM_ATTRIBUTE(RigidBody, "Collision Event Mode", collisionEventMode_, collisionEventModeNames, COLLISION_ACTIVE, AM_DEFAULT);
  112. ACCESSOR_ATTRIBUTE(RigidBody, VAR_BOOL, "Use Gravity", GetUseGravity, SetUseGravity, bool, true, AM_DEFAULT);
  113. ATTRIBUTE(RigidBody, VAR_BOOL, "Is Kinematic", kinematic_, false, AM_DEFAULT);
  114. ATTRIBUTE(RigidBody, VAR_BOOL, "Is Phantom", phantom_, false, AM_DEFAULT);
  115. REF_ACCESSOR_ATTRIBUTE(RigidBody, VAR_VECTOR3, "Gravity Override", GetGravityOverride, SetGravityOverride, Vector3, Vector3::ZERO, AM_DEFAULT);
  116. }
  117. void RigidBody::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  118. {
  119. Component::OnSetAttribute(attr, src);
  120. // Change of any non-accessor attribute requires the rigid body to be re-added to the physics world
  121. if (!attr.accessor_)
  122. readdBody_ = true;
  123. }
  124. void RigidBody::ApplyAttributes()
  125. {
  126. if (readdBody_)
  127. AddBodyToWorld();
  128. }
  129. void RigidBody::OnSetEnabled()
  130. {
  131. bool enabled = IsEnabledEffective();
  132. if (enabled && !inWorld_)
  133. AddBodyToWorld();
  134. else if (!enabled && inWorld_)
  135. RemoveBodyFromWorld();
  136. }
  137. void RigidBody::getWorldTransform(btTransform &worldTrans) const
  138. {
  139. // We may be in a pathological state where a RigidBody exists without a scene node when this callback is fired,
  140. // so check to be sure
  141. if (node_)
  142. {
  143. lastPosition_ = node_->GetWorldPosition();
  144. lastRotation_ = node_->GetWorldRotation();
  145. worldTrans.setOrigin(ToBtVector3(lastPosition_ + lastRotation_ * centerOfMass_));
  146. worldTrans.setRotation(ToBtQuaternion(lastRotation_));
  147. }
  148. }
  149. void RigidBody::setWorldTransform(const btTransform &worldTrans)
  150. {
  151. Quaternion newWorldRotation = ToQuaternion(worldTrans.getRotation());
  152. Vector3 newWorldPosition = ToVector3(worldTrans.getOrigin()) - newWorldRotation * centerOfMass_;
  153. RigidBody* parentRigidBody = 0;
  154. // It is possible that the RigidBody component has been kept alive via a shared pointer,
  155. // while its scene node has already been destroyed
  156. if (node_)
  157. {
  158. // If the rigid body is parented to another rigid body, can not set the transform immediately.
  159. // In that case store it to PhysicsWorld for delayed assignment
  160. Node* parent = node_->GetParent();
  161. if (parent && parent != GetScene())
  162. parentRigidBody = parent->GetComponent<RigidBody>();
  163. if (!parentRigidBody)
  164. ApplyWorldTransform(newWorldPosition, newWorldRotation);
  165. else
  166. {
  167. DelayedWorldTransform delayed;
  168. delayed.rigidBody_ = this;
  169. delayed.parentRigidBody_ = parentRigidBody;
  170. delayed.worldPosition_ = newWorldPosition;
  171. delayed.worldRotation_ = newWorldRotation;
  172. physicsWorld_->AddDelayedWorldTransform(delayed);
  173. }
  174. MarkNetworkUpdate();
  175. }
  176. }
  177. void RigidBody::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  178. {
  179. if (debug && physicsWorld_ && body_ && IsEnabledEffective())
  180. {
  181. physicsWorld_->SetDebugRenderer(debug);
  182. physicsWorld_->SetDebugDepthTest(depthTest);
  183. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  184. world->debugDrawObject(body_->getWorldTransform(), shiftedCompoundShape_, IsActive() ? btVector3(1.0f, 1.0f, 1.0f) :
  185. btVector3(0.0f, 1.0f, 0.0f));
  186. physicsWorld_->SetDebugRenderer(0);
  187. }
  188. }
  189. void RigidBody::SetMass(float mass)
  190. {
  191. mass = Max(mass, 0.0f);
  192. if (mass != mass_)
  193. {
  194. mass_ = mass;
  195. AddBodyToWorld();
  196. MarkNetworkUpdate();
  197. }
  198. }
  199. void RigidBody::SetPosition(Vector3 position)
  200. {
  201. if (body_)
  202. {
  203. btTransform& worldTrans = body_->getWorldTransform();
  204. worldTrans.setOrigin(ToBtVector3(position + ToQuaternion(worldTrans.getRotation()) * centerOfMass_));
  205. // When forcing the physics position, set also interpolated position so that there is no jitter
  206. btTransform interpTrans = body_->getInterpolationWorldTransform();
  207. interpTrans.setOrigin(worldTrans.getOrigin());
  208. body_->setInterpolationWorldTransform(interpTrans);
  209. body_->updateInertiaTensor();
  210. Activate();
  211. MarkNetworkUpdate();
  212. }
  213. }
  214. void RigidBody::SetRotation(Quaternion rotation)
  215. {
  216. if (body_)
  217. {
  218. // Due to center of mass offset, we need to adjust position also
  219. Vector3 oldPosition = GetPosition();
  220. btTransform& worldTrans = body_->getWorldTransform();
  221. worldTrans.setRotation(ToBtQuaternion(rotation));
  222. worldTrans.setOrigin(ToBtVector3(oldPosition + rotation * centerOfMass_));
  223. btTransform interpTrans = body_->getInterpolationWorldTransform();
  224. interpTrans.setRotation(worldTrans.getRotation());
  225. interpTrans.setOrigin(worldTrans.getOrigin());
  226. body_->setInterpolationWorldTransform(interpTrans);
  227. body_->updateInertiaTensor();
  228. Activate();
  229. MarkNetworkUpdate();
  230. }
  231. }
  232. void RigidBody::SetTransform(const Vector3& position, const Quaternion& rotation)
  233. {
  234. if (body_)
  235. {
  236. btTransform& worldTrans = body_->getWorldTransform();
  237. worldTrans.setRotation(ToBtQuaternion(rotation));
  238. worldTrans.setOrigin(ToBtVector3(position + rotation * centerOfMass_));
  239. btTransform interpTrans = body_->getInterpolationWorldTransform();
  240. interpTrans.setOrigin(worldTrans.getOrigin());
  241. interpTrans.setRotation(worldTrans.getRotation());
  242. body_->setInterpolationWorldTransform(interpTrans);
  243. body_->updateInertiaTensor();
  244. Activate();
  245. MarkNetworkUpdate();
  246. }
  247. }
  248. void RigidBody::SetLinearVelocity(Vector3 velocity)
  249. {
  250. if (body_)
  251. {
  252. body_->setLinearVelocity(ToBtVector3(velocity));
  253. if (velocity != Vector3::ZERO)
  254. Activate();
  255. MarkNetworkUpdate();
  256. }
  257. }
  258. void RigidBody::SetLinearFactor(Vector3 factor)
  259. {
  260. if (body_)
  261. {
  262. body_->setLinearFactor(ToBtVector3(factor));
  263. MarkNetworkUpdate();
  264. }
  265. }
  266. void RigidBody::SetLinearRestThreshold(float threshold)
  267. {
  268. if (body_)
  269. {
  270. body_->setSleepingThresholds(threshold, body_->getAngularSleepingThreshold());
  271. MarkNetworkUpdate();
  272. }
  273. }
  274. void RigidBody::SetLinearDamping(float damping)
  275. {
  276. if (body_)
  277. {
  278. body_->setDamping(damping, body_->getAngularDamping());
  279. MarkNetworkUpdate();
  280. }
  281. }
  282. void RigidBody::SetAngularVelocity(Vector3 velocity)
  283. {
  284. if (body_)
  285. {
  286. body_->setAngularVelocity(ToBtVector3(velocity));
  287. if (velocity != Vector3::ZERO)
  288. Activate();
  289. MarkNetworkUpdate();
  290. }
  291. }
  292. void RigidBody::SetAngularFactor(Vector3 factor)
  293. {
  294. if (body_)
  295. {
  296. body_->setAngularFactor(ToBtVector3(factor));
  297. MarkNetworkUpdate();
  298. }
  299. }
  300. void RigidBody::SetAngularRestThreshold(float threshold)
  301. {
  302. if (body_)
  303. {
  304. body_->setSleepingThresholds(body_->getLinearSleepingThreshold(), threshold);
  305. MarkNetworkUpdate();
  306. }
  307. }
  308. void RigidBody::SetAngularDamping(float damping)
  309. {
  310. if (body_)
  311. {
  312. body_->setDamping(body_->getLinearDamping(), damping);
  313. MarkNetworkUpdate();
  314. }
  315. }
  316. void RigidBody::SetFriction(float friction)
  317. {
  318. if (body_)
  319. {
  320. body_->setFriction(friction);
  321. MarkNetworkUpdate();
  322. }
  323. }
  324. void RigidBody::SetRestitution(float restitution)
  325. {
  326. if (body_)
  327. {
  328. body_->setRestitution(restitution);
  329. MarkNetworkUpdate();
  330. }
  331. }
  332. void RigidBody::SetContactProcessingThreshold(float threshold)
  333. {
  334. if (body_)
  335. {
  336. body_->setContactProcessingThreshold(threshold);
  337. MarkNetworkUpdate();
  338. }
  339. }
  340. void RigidBody::SetCcdRadius(float radius)
  341. {
  342. radius = Max(radius, 0.0f);
  343. if (body_)
  344. {
  345. body_->setCcdSweptSphereRadius(radius);
  346. MarkNetworkUpdate();
  347. }
  348. }
  349. void RigidBody::SetCcdMotionThreshold(float threshold)
  350. {
  351. threshold = Max(threshold, 0.0f);
  352. if (body_)
  353. {
  354. body_->setCcdMotionThreshold(threshold);
  355. MarkNetworkUpdate();
  356. }
  357. }
  358. void RigidBody::SetUseGravity(bool enable)
  359. {
  360. if (enable != useGravity_)
  361. {
  362. useGravity_ = enable;
  363. UpdateGravity();
  364. MarkNetworkUpdate();
  365. }
  366. }
  367. void RigidBody::SetGravityOverride(const Vector3& gravity)
  368. {
  369. if (gravity != gravityOverride_)
  370. {
  371. gravityOverride_ = gravity;
  372. UpdateGravity();
  373. MarkNetworkUpdate();
  374. }
  375. }
  376. void RigidBody::SetKinematic(bool enable)
  377. {
  378. if (enable != kinematic_)
  379. {
  380. kinematic_ = enable;
  381. AddBodyToWorld();
  382. MarkNetworkUpdate();
  383. }
  384. }
  385. void RigidBody::SetPhantom(bool enable)
  386. {
  387. if (enable != phantom_)
  388. {
  389. phantom_ = enable;
  390. AddBodyToWorld();
  391. MarkNetworkUpdate();
  392. }
  393. }
  394. void RigidBody::SetCollisionLayer(unsigned layer)
  395. {
  396. if (layer != collisionLayer_)
  397. {
  398. collisionLayer_ = layer;
  399. AddBodyToWorld();
  400. MarkNetworkUpdate();
  401. }
  402. }
  403. void RigidBody::SetCollisionMask(unsigned mask)
  404. {
  405. if (mask != collisionMask_)
  406. {
  407. collisionMask_ = mask;
  408. AddBodyToWorld();
  409. MarkNetworkUpdate();
  410. }
  411. }
  412. void RigidBody::SetCollisionLayerAndMask(unsigned layer, unsigned mask)
  413. {
  414. if (layer != collisionLayer_ || mask != collisionMask_)
  415. {
  416. collisionLayer_ = layer;
  417. collisionMask_ = mask;
  418. AddBodyToWorld();
  419. MarkNetworkUpdate();
  420. }
  421. }
  422. void RigidBody::SetCollisionEventMode(CollisionEventMode mode)
  423. {
  424. collisionEventMode_ = mode;
  425. MarkNetworkUpdate();
  426. }
  427. void RigidBody::ApplyForce(const Vector3& force)
  428. {
  429. if (body_ && force != Vector3::ZERO)
  430. {
  431. Activate();
  432. body_->applyCentralForce(ToBtVector3(force));
  433. }
  434. }
  435. void RigidBody::ApplyForce(const Vector3& force, const Vector3& position)
  436. {
  437. if (body_ && force != Vector3::ZERO)
  438. {
  439. Activate();
  440. body_->applyForce(ToBtVector3(force), ToBtVector3(position - centerOfMass_));
  441. }
  442. }
  443. void RigidBody::ApplyTorque(const Vector3& torque)
  444. {
  445. if (body_ && torque != Vector3::ZERO)
  446. {
  447. Activate();
  448. body_->applyTorque(ToBtVector3(torque));
  449. }
  450. }
  451. void RigidBody::ApplyImpulse(const Vector3& impulse)
  452. {
  453. if (body_ && impulse != Vector3::ZERO)
  454. {
  455. Activate();
  456. body_->applyCentralImpulse(ToBtVector3(impulse));
  457. }
  458. }
  459. void RigidBody::ApplyImpulse(const Vector3& impulse, const Vector3& position)
  460. {
  461. if (body_ && impulse != Vector3::ZERO)
  462. {
  463. Activate();
  464. body_->applyImpulse(ToBtVector3(impulse), ToBtVector3(position - centerOfMass_));
  465. }
  466. }
  467. void RigidBody::ApplyTorqueImpulse(const Vector3& torque)
  468. {
  469. if (body_ && torque != Vector3::ZERO)
  470. {
  471. Activate();
  472. body_->applyTorqueImpulse(ToBtVector3(torque));
  473. }
  474. }
  475. void RigidBody::ResetForces()
  476. {
  477. if (body_)
  478. body_->clearForces();
  479. }
  480. void RigidBody::Activate()
  481. {
  482. if (body_ && mass_ > 0.0f)
  483. body_->activate(true);
  484. }
  485. void RigidBody::ReAddBodyToWorld()
  486. {
  487. if (body_ && inWorld_)
  488. AddBodyToWorld();
  489. }
  490. Vector3 RigidBody::GetPosition() const
  491. {
  492. if (body_)
  493. {
  494. const btTransform& transform = body_->getWorldTransform();
  495. return ToVector3(transform.getOrigin()) - ToQuaternion(transform.getRotation()) * centerOfMass_;
  496. }
  497. else
  498. return Vector3::ZERO;
  499. }
  500. Quaternion RigidBody::GetRotation() const
  501. {
  502. if (body_)
  503. return ToQuaternion(body_->getWorldTransform().getRotation());
  504. else
  505. return Quaternion::IDENTITY;
  506. }
  507. Vector3 RigidBody::GetLinearVelocity() const
  508. {
  509. if (body_)
  510. return ToVector3(body_->getLinearVelocity());
  511. else
  512. return Vector3::ZERO;
  513. }
  514. Vector3 RigidBody::GetLinearFactor() const
  515. {
  516. if (body_)
  517. return ToVector3(body_->getLinearFactor());
  518. else
  519. return Vector3::ZERO;
  520. }
  521. Vector3 RigidBody::GetVelocityAtPoint(const Vector3& position) const
  522. {
  523. if (body_)
  524. return ToVector3(body_->getVelocityInLocalPoint(ToBtVector3(position - centerOfMass_)));
  525. else
  526. return Vector3::ZERO;
  527. }
  528. float RigidBody::GetLinearRestThreshold() const
  529. {
  530. if (body_)
  531. return body_->getLinearSleepingThreshold();
  532. else
  533. return 0.0f;
  534. }
  535. float RigidBody::GetLinearDamping() const
  536. {
  537. if (body_)
  538. return body_->getLinearDamping();
  539. else
  540. return 0.0f;
  541. }
  542. Vector3 RigidBody::GetAngularVelocity() const
  543. {
  544. if (body_)
  545. return ToVector3(body_->getAngularVelocity());
  546. else
  547. return Vector3::ZERO;
  548. }
  549. Vector3 RigidBody::GetAngularFactor() const
  550. {
  551. if (body_)
  552. return ToVector3(body_->getAngularFactor());
  553. else
  554. return Vector3::ZERO;
  555. }
  556. float RigidBody::GetAngularRestThreshold() const
  557. {
  558. if (body_)
  559. return body_->getAngularSleepingThreshold();
  560. else
  561. return 0.0f;
  562. }
  563. float RigidBody::GetAngularDamping() const
  564. {
  565. if (body_)
  566. return body_->getAngularDamping();
  567. else
  568. return 0.0f;
  569. }
  570. float RigidBody::GetFriction() const
  571. {
  572. if (body_)
  573. return body_->getFriction();
  574. else
  575. return 0.0f;
  576. }
  577. float RigidBody::GetRestitution() const
  578. {
  579. if (body_)
  580. return body_->getRestitution();
  581. else
  582. return 0.0f;
  583. }
  584. float RigidBody::GetContactProcessingThreshold() const
  585. {
  586. if (body_)
  587. return body_->getContactProcessingThreshold();
  588. else
  589. return 0.0f;
  590. }
  591. float RigidBody::GetCcdRadius() const
  592. {
  593. if (body_)
  594. return body_->getCcdSweptSphereRadius();
  595. else
  596. return 0.0f;
  597. }
  598. float RigidBody::GetCcdMotionThreshold() const
  599. {
  600. if (body_)
  601. return body_->getCcdMotionThreshold();
  602. else
  603. return 0.0f;
  604. }
  605. bool RigidBody::IsActive() const
  606. {
  607. if (body_)
  608. return body_->isActive();
  609. else
  610. return false;
  611. }
  612. void RigidBody::GetCollidingBodies(PODVector<RigidBody*>& result) const
  613. {
  614. if (physicsWorld_)
  615. physicsWorld_->GetRigidBodies(result, this);
  616. else
  617. result.Clear();
  618. }
  619. void RigidBody::ApplyWorldTransform(const Vector3& newWorldPosition, const Quaternion& newWorldRotation)
  620. {
  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_)
  645. {
  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 = 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. }
  706. void RigidBody::UpdateGravity()
  707. {
  708. if (physicsWorld_ && body_)
  709. {
  710. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  711. int flags = body_->getFlags();
  712. if (useGravity_ && gravityOverride_ == Vector3::ZERO)
  713. flags &= ~BT_DISABLE_WORLD_GRAVITY;
  714. else
  715. flags |= BT_DISABLE_WORLD_GRAVITY;
  716. body_->setFlags(flags);
  717. if (useGravity_)
  718. {
  719. // If override vector is zero, use world's gravity
  720. if (gravityOverride_ == Vector3::ZERO)
  721. body_->setGravity(world->getGravity());
  722. else
  723. body_->setGravity(ToBtVector3(gravityOverride_));
  724. }
  725. else
  726. body_->setGravity(btVector3(0.0f, 0.0f, 0.0f));
  727. }
  728. }
  729. void RigidBody::SetNetAngularVelocityAttr(const PODVector<unsigned char>& value)
  730. {
  731. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  732. MemoryBuffer buf(value);
  733. SetAngularVelocity(buf.ReadPackedVector3(maxVelocity));
  734. }
  735. const PODVector<unsigned char>& RigidBody::GetNetAngularVelocityAttr() const
  736. {
  737. float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
  738. attrBuffer_.Clear();
  739. attrBuffer_.WritePackedVector3(GetAngularVelocity(), maxVelocity);
  740. return attrBuffer_.GetBuffer();
  741. }
  742. void RigidBody::AddConstraint(Constraint* constraint)
  743. {
  744. constraints_.Push(constraint);
  745. }
  746. void RigidBody::RemoveConstraint(Constraint* constraint)
  747. {
  748. constraints_.Remove(constraint);
  749. // A constraint being removed should possibly cause the object to eg. start falling, so activate
  750. Activate();
  751. }
  752. void RigidBody::ReleaseBody()
  753. {
  754. if (body_)
  755. {
  756. // Release all constraints which refer to this body
  757. // Make a copy for iteration
  758. PODVector<Constraint*> constraints = constraints_;
  759. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  760. (*i)->ReleaseConstraint();
  761. RemoveBodyFromWorld();
  762. delete body_;
  763. body_ = 0;
  764. }
  765. }
  766. void RigidBody::OnMarkedDirty(Node* node)
  767. {
  768. // If node transform changes, apply it back to the physics transform. However, do not do this when a SmoothedTransform
  769. // is in use, because in that case the node transform will be constantly updated into smoothed, possibly non-physical
  770. // states; rather follow the SmoothedTransform target transform directly
  771. if ((!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. // Due to possible center of mass offset, if rotation changes, update position also
  786. lastRotation_ = newRotation;
  787. lastPosition_ = newPosition;
  788. SetTransform(newPosition, newRotation);
  789. }
  790. else if (!newPosition.Equals(lastPosition_))
  791. {
  792. lastPosition_ = newPosition;
  793. SetPosition(newPosition);
  794. }
  795. }
  796. }
  797. void RigidBody::OnNodeSet(Node* node)
  798. {
  799. if (node)
  800. {
  801. Scene* scene = GetScene();
  802. if (scene)
  803. {
  804. if (scene == node)
  805. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  806. physicsWorld_ = scene->GetComponent<PhysicsWorld>();
  807. if (physicsWorld_)
  808. physicsWorld_->AddRigidBody(this);
  809. else
  810. LOGERROR("No physics world component in scene, can not create rigid body");
  811. AddBodyToWorld();
  812. }
  813. else
  814. LOGERROR("Node is detached from scene, can not create rigid body");
  815. node->AddListener(this);
  816. }
  817. }
  818. void RigidBody::AddBodyToWorld()
  819. {
  820. if (!physicsWorld_)
  821. return;
  822. PROFILE(AddBodyToWorld);
  823. if (mass_ < 0.0f)
  824. mass_ = 0.0f;
  825. if (body_)
  826. RemoveBodyFromWorld();
  827. else
  828. {
  829. // Correct inertia will be calculated below
  830. btVector3 localInertia(0.0f, 0.0f, 0.0f);
  831. body_ = new btRigidBody(mass_, this, shiftedCompoundShape_, localInertia);
  832. body_->setUserPointer(this);
  833. // Check for existence of the SmoothedTransform component, which should be created by now in network client mode.
  834. // If it exists, subscribe to its change events
  835. SmoothedTransform* transform = GetComponent<SmoothedTransform>();
  836. if (transform)
  837. {
  838. hasSmoothedTransform_ = true;
  839. SubscribeToEvent(transform, E_TARGETPOSITION, HANDLER(RigidBody, HandleTargetPosition));
  840. SubscribeToEvent(transform, E_TARGETROTATION, HANDLER(RigidBody, HandleTargetRotation));
  841. }
  842. // Check if CollisionShapes already exist in the node and add them to the compound shape.
  843. // Do not update mass yet, but do it once all shapes have been added
  844. PODVector<CollisionShape*> shapes;
  845. node_->GetComponents<CollisionShape>(shapes);
  846. for (PODVector<CollisionShape*>::Iterator i = shapes.Begin(); i != shapes.End(); ++i)
  847. (*i)->NotifyRigidBody(false);
  848. // Check if this node contains Constraint components that were waiting for the rigid body to be created, and signal them
  849. // to create themselves now
  850. PODVector<Constraint*> constraints;
  851. node_->GetComponents<Constraint>(constraints);
  852. for (PODVector<Constraint*>::Iterator i = constraints.Begin(); i != constraints.End(); ++i)
  853. (*i)->CreateConstraint();
  854. }
  855. UpdateMass();
  856. UpdateGravity();
  857. int flags = body_->getCollisionFlags();
  858. if (phantom_)
  859. flags |= btCollisionObject::CF_NO_CONTACT_RESPONSE;
  860. else
  861. flags &= ~btCollisionObject::CF_NO_CONTACT_RESPONSE;
  862. if (kinematic_)
  863. flags |= btCollisionObject::CF_KINEMATIC_OBJECT;
  864. else
  865. flags &= ~btCollisionObject::CF_KINEMATIC_OBJECT;
  866. body_->setCollisionFlags(flags);
  867. if (!IsEnabledEffective())
  868. return;
  869. btDiscreteDynamicsWorld* world = physicsWorld_->GetWorld();
  870. world->addRigidBody(body_, collisionLayer_, 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. }