RigidBody.cpp 32 KB

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