RigidBody.cpp 32 KB

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