Constraint.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/Log.h"
  27. #include "../Physics/Constraint.h"
  28. #include "../Physics/PhysicsUtils.h"
  29. #include "../Physics/PhysicsWorld.h"
  30. #include "../Physics/RigidBody.h"
  31. #include "../Scene/Scene.h"
  32. #include <Bullet/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h>
  33. #include <Bullet/BulletDynamics/ConstraintSolver/btHingeConstraint.h>
  34. #include <Bullet/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h>
  35. #include <Bullet/BulletDynamics/ConstraintSolver/btSliderConstraint.h>
  36. #include <Bullet/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
  37. namespace Urho3D
  38. {
  39. static const char* typeNames[] =
  40. {
  41. "Point",
  42. "Hinge",
  43. "Slider",
  44. "ConeTwist",
  45. 0
  46. };
  47. extern const char* PHYSICS_CATEGORY;
  48. Constraint::Constraint(Context* context) :
  49. Component(context),
  50. constraintType_(CONSTRAINT_POINT),
  51. position_(Vector3::ZERO),
  52. rotation_(Quaternion::IDENTITY),
  53. otherPosition_(Vector3::ZERO),
  54. otherRotation_(Quaternion::IDENTITY),
  55. highLimit_(Vector2::ZERO),
  56. lowLimit_(Vector2::ZERO),
  57. erp_(0.0f),
  58. cfm_(0.0f),
  59. otherBodyNodeID_(0),
  60. disableCollision_(false),
  61. recreateConstraint_(true),
  62. framesDirty_(false),
  63. retryCreation_(false)
  64. {
  65. }
  66. Constraint::~Constraint()
  67. {
  68. ReleaseConstraint();
  69. if (physicsWorld_)
  70. physicsWorld_->RemoveConstraint(this);
  71. }
  72. void Constraint::RegisterObject(Context* context)
  73. {
  74. context->RegisterFactory<Constraint>(PHYSICS_CATEGORY);
  75. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  76. URHO3D_ENUM_ATTRIBUTE("Constraint Type", constraintType_, typeNames, CONSTRAINT_POINT, AM_DEFAULT);
  77. URHO3D_ATTRIBUTE("Position", Vector3, position_, Vector3::ZERO, AM_DEFAULT);
  78. URHO3D_ATTRIBUTE("Rotation", Quaternion, rotation_, Quaternion::IDENTITY, AM_DEFAULT);
  79. URHO3D_ATTRIBUTE("Other Body Position", Vector3, otherPosition_, Vector3::ZERO, AM_DEFAULT);
  80. URHO3D_ATTRIBUTE("Other Body Rotation", Quaternion, otherRotation_, Quaternion::IDENTITY, AM_DEFAULT);
  81. URHO3D_ATTRIBUTE("Other Body NodeID", unsigned, otherBodyNodeID_, 0, AM_DEFAULT | AM_NODEID);
  82. URHO3D_ACCESSOR_ATTRIBUTE("High Limit", GetHighLimit, SetHighLimit, Vector2, Vector2::ZERO, AM_DEFAULT);
  83. URHO3D_ACCESSOR_ATTRIBUTE("Low Limit", GetLowLimit, SetLowLimit, Vector2, Vector2::ZERO, AM_DEFAULT);
  84. URHO3D_ACCESSOR_ATTRIBUTE("ERP Parameter", GetERP, SetERP, float, 0.0f, AM_DEFAULT);
  85. URHO3D_ACCESSOR_ATTRIBUTE("CFM Parameter", GetCFM, SetCFM, float, 0.0f, AM_DEFAULT);
  86. URHO3D_ATTRIBUTE("Disable Collision", bool, disableCollision_, false, AM_DEFAULT);
  87. }
  88. void Constraint::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  89. {
  90. Serializable::OnSetAttribute(attr, src);
  91. if (!attr.accessor_)
  92. {
  93. // Convenience for editing static constraints: if not connected to another body, adjust world position to match local
  94. // (when deserializing, the proper other body position will be read after own position, so this calculation is safely
  95. // overridden and does not accumulate constraint error
  96. if (attr.offset_ == offsetof(Constraint, position_) && constraint_ && !otherBody_)
  97. {
  98. btTransform ownBody = constraint_->getRigidBodyA().getWorldTransform();
  99. btVector3 worldPos = ownBody * ToBtVector3(position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass());
  100. otherPosition_ = ToVector3(worldPos);
  101. }
  102. // Certain attribute changes require recreation of the constraint
  103. if (attr.offset_ == offsetof(Constraint, constraintType_) || attr.offset_ == offsetof(Constraint, otherBodyNodeID_) ||
  104. attr.offset_ == offsetof(Constraint, disableCollision_))
  105. recreateConstraint_ = true;
  106. else
  107. framesDirty_ = true;
  108. }
  109. }
  110. void Constraint::ApplyAttributes()
  111. {
  112. if (recreateConstraint_)
  113. {
  114. if (otherBody_)
  115. otherBody_->RemoveConstraint(this);
  116. otherBody_.Reset();
  117. Scene* scene = GetScene();
  118. if (scene && otherBodyNodeID_)
  119. {
  120. Node* otherNode = scene->GetNode(otherBodyNodeID_);
  121. if (otherNode)
  122. otherBody_ = otherNode->GetComponent<RigidBody>();
  123. }
  124. CreateConstraint();
  125. }
  126. else if (framesDirty_)
  127. {
  128. ApplyFrames();
  129. framesDirty_ = false;
  130. }
  131. }
  132. void Constraint::OnSetEnabled()
  133. {
  134. if (constraint_)
  135. constraint_->setEnabled(IsEnabledEffective());
  136. }
  137. void Constraint::GetDependencyNodes(PODVector<Node*>& dest)
  138. {
  139. if (otherBody_ && otherBody_->GetNode())
  140. dest.Push(otherBody_->GetNode());
  141. }
  142. void Constraint::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  143. {
  144. if (debug && physicsWorld_ && constraint_)
  145. {
  146. physicsWorld_->SetDebugRenderer(debug);
  147. physicsWorld_->SetDebugDepthTest(depthTest);
  148. physicsWorld_->GetWorld()->debugDrawConstraint(constraint_.Get());
  149. physicsWorld_->SetDebugRenderer(0);
  150. }
  151. }
  152. void Constraint::SetConstraintType(ConstraintType type)
  153. {
  154. if (type != constraintType_)
  155. {
  156. constraintType_ = type;
  157. CreateConstraint();
  158. MarkNetworkUpdate();
  159. }
  160. }
  161. void Constraint::SetOtherBody(RigidBody* body)
  162. {
  163. if (otherBody_ != body)
  164. {
  165. if (otherBody_)
  166. otherBody_->RemoveConstraint(this);
  167. otherBody_ = body;
  168. // Update the connected body attribute
  169. Node* otherNode = otherBody_ ? otherBody_->GetNode() : 0;
  170. otherBodyNodeID_ = otherNode ? otherNode->GetID() : 0;
  171. CreateConstraint();
  172. MarkNetworkUpdate();
  173. }
  174. }
  175. void Constraint::SetPosition(const Vector3& position)
  176. {
  177. if (position != position_)
  178. {
  179. position_ = position;
  180. ApplyFrames();
  181. MarkNetworkUpdate();
  182. }
  183. }
  184. void Constraint::SetRotation(const Quaternion& rotation)
  185. {
  186. if (rotation != rotation_)
  187. {
  188. rotation_ = rotation;
  189. ApplyFrames();
  190. MarkNetworkUpdate();
  191. }
  192. }
  193. void Constraint::SetAxis(const Vector3& axis)
  194. {
  195. switch (constraintType_)
  196. {
  197. case CONSTRAINT_POINT:
  198. case CONSTRAINT_HINGE:
  199. rotation_ = Quaternion(Vector3::FORWARD, axis);
  200. break;
  201. case CONSTRAINT_SLIDER:
  202. case CONSTRAINT_CONETWIST:
  203. rotation_ = Quaternion(Vector3::RIGHT, axis);
  204. break;
  205. default:
  206. break;
  207. }
  208. ApplyFrames();
  209. MarkNetworkUpdate();
  210. }
  211. void Constraint::SetOtherPosition(const Vector3& position)
  212. {
  213. if (position != otherPosition_)
  214. {
  215. otherPosition_ = position;
  216. ApplyFrames();
  217. MarkNetworkUpdate();
  218. }
  219. }
  220. void Constraint::SetOtherRotation(const Quaternion& rotation)
  221. {
  222. if (rotation != otherRotation_)
  223. {
  224. otherRotation_ = rotation;
  225. ApplyFrames();
  226. MarkNetworkUpdate();
  227. }
  228. }
  229. void Constraint::SetOtherAxis(const Vector3& axis)
  230. {
  231. switch (constraintType_)
  232. {
  233. case CONSTRAINT_POINT:
  234. case CONSTRAINT_HINGE:
  235. otherRotation_ = Quaternion(Vector3::FORWARD, axis);
  236. break;
  237. case CONSTRAINT_SLIDER:
  238. case CONSTRAINT_CONETWIST:
  239. otherRotation_ = Quaternion(Vector3::RIGHT, axis);
  240. break;
  241. default:
  242. break;
  243. }
  244. ApplyFrames();
  245. MarkNetworkUpdate();
  246. }
  247. void Constraint::SetWorldPosition(const Vector3& position)
  248. {
  249. if (constraint_)
  250. {
  251. btTransform ownBodyInverse = constraint_->getRigidBodyA().getWorldTransform().inverse();
  252. btTransform otherBodyInverse = constraint_->getRigidBodyB().getWorldTransform().inverse();
  253. btVector3 worldPos = ToBtVector3(position);
  254. position_ = (ToVector3(ownBodyInverse * worldPos) + ownBody_->GetCenterOfMass()) / cachedWorldScale_;
  255. otherPosition_ = ToVector3(otherBodyInverse * worldPos);
  256. if (otherBody_)
  257. {
  258. otherPosition_ += otherBody_->GetCenterOfMass();
  259. otherPosition_ /= otherBody_->GetNode()->GetWorldScale();
  260. }
  261. ApplyFrames();
  262. MarkNetworkUpdate();
  263. }
  264. else
  265. URHO3D_LOGWARNING("Constraint not created, world position could not be stored");
  266. }
  267. void Constraint::SetHighLimit(const Vector2& limit)
  268. {
  269. if (limit != highLimit_)
  270. {
  271. highLimit_ = limit;
  272. ApplyLimits();
  273. MarkNetworkUpdate();
  274. }
  275. }
  276. void Constraint::SetLowLimit(const Vector2& limit)
  277. {
  278. if (limit != lowLimit_)
  279. {
  280. lowLimit_ = limit;
  281. ApplyLimits();
  282. MarkNetworkUpdate();
  283. }
  284. }
  285. void Constraint::SetERP(float erp)
  286. {
  287. erp = Max(erp, 0.0f);
  288. if (erp != erp_)
  289. {
  290. erp_ = erp;
  291. ApplyLimits();
  292. MarkNetworkUpdate();
  293. }
  294. }
  295. void Constraint::SetCFM(float cfm)
  296. {
  297. cfm = Max(cfm, 0.0f);
  298. if (cfm != cfm_)
  299. {
  300. cfm_ = cfm;
  301. ApplyLimits();
  302. MarkNetworkUpdate();
  303. }
  304. }
  305. void Constraint::SetDisableCollision(bool disable)
  306. {
  307. if (disable != disableCollision_)
  308. {
  309. disableCollision_ = disable;
  310. CreateConstraint();
  311. MarkNetworkUpdate();
  312. }
  313. }
  314. Vector3 Constraint::GetWorldPosition() const
  315. {
  316. if (constraint_)
  317. {
  318. btTransform ownBody = constraint_->getRigidBodyA().getWorldTransform();
  319. return ToVector3(ownBody * ToBtVector3(position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass()));
  320. }
  321. else
  322. return Vector3::ZERO;
  323. }
  324. void Constraint::ReleaseConstraint()
  325. {
  326. if (constraint_)
  327. {
  328. if (ownBody_)
  329. ownBody_->RemoveConstraint(this);
  330. if (otherBody_)
  331. otherBody_->RemoveConstraint(this);
  332. if (physicsWorld_)
  333. physicsWorld_->GetWorld()->removeConstraint(constraint_.Get());
  334. constraint_.Reset();
  335. }
  336. }
  337. void Constraint::ApplyFrames()
  338. {
  339. if (!constraint_ || !node_ || (otherBody_ && !otherBody_->GetNode()))
  340. return;
  341. cachedWorldScale_ = node_->GetWorldScale();
  342. Vector3 ownBodyScaledPosition = position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass();
  343. Vector3 otherBodyScaledPosition =
  344. otherBody_ ? otherPosition_ * otherBody_->GetNode()->GetWorldScale() - otherBody_->GetCenterOfMass() : otherPosition_;
  345. switch (constraint_->getConstraintType())
  346. {
  347. case POINT2POINT_CONSTRAINT_TYPE:
  348. {
  349. btPoint2PointConstraint* pointConstraint = static_cast<btPoint2PointConstraint*>(constraint_.Get());
  350. pointConstraint->setPivotA(ToBtVector3(ownBodyScaledPosition));
  351. pointConstraint->setPivotB(ToBtVector3(otherBodyScaledPosition));
  352. }
  353. break;
  354. case HINGE_CONSTRAINT_TYPE:
  355. {
  356. btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_.Get());
  357. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  358. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  359. hingeConstraint->setFrames(ownFrame, otherFrame);
  360. }
  361. break;
  362. case SLIDER_CONSTRAINT_TYPE:
  363. {
  364. btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_.Get());
  365. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  366. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  367. sliderConstraint->setFrames(ownFrame, otherFrame);
  368. }
  369. break;
  370. case CONETWIST_CONSTRAINT_TYPE:
  371. {
  372. btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_.Get());
  373. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  374. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  375. coneTwistConstraint->setFrames(ownFrame, otherFrame);
  376. }
  377. break;
  378. default:
  379. break;
  380. }
  381. }
  382. void Constraint::OnNodeSet(Node* node)
  383. {
  384. if (node)
  385. {
  386. node->AddListener(this);
  387. cachedWorldScale_ = node->GetWorldScale();
  388. }
  389. }
  390. void Constraint::OnSceneSet(Scene* scene)
  391. {
  392. if (scene)
  393. {
  394. if (scene == node_)
  395. URHO3D_LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  396. physicsWorld_ = scene->GetOrCreateComponent<PhysicsWorld>();
  397. physicsWorld_->AddConstraint(this);
  398. // Create constraint now if necessary (attributes modified before adding to scene)
  399. if (retryCreation_)
  400. CreateConstraint();
  401. }
  402. else
  403. {
  404. ReleaseConstraint();
  405. if (physicsWorld_)
  406. physicsWorld_->RemoveConstraint(this);
  407. // Recreate when moved to a scene again
  408. retryCreation_ = true;
  409. }
  410. }
  411. void Constraint::OnMarkedDirty(Node* node)
  412. {
  413. /// \todo This does not catch the connected body node's scale changing
  414. if (HasWorldScaleChanged(cachedWorldScale_, node->GetWorldScale()))
  415. ApplyFrames();
  416. }
  417. void Constraint::CreateConstraint()
  418. {
  419. URHO3D_PROFILE(CreateConstraint);
  420. cachedWorldScale_ = node_->GetWorldScale();
  421. ReleaseConstraint();
  422. ownBody_ = GetComponent<RigidBody>();
  423. btRigidBody* ownBody = ownBody_ ? ownBody_->GetBody() : 0;
  424. btRigidBody* otherBody = otherBody_ ? otherBody_->GetBody() : 0;
  425. // If no physics world available now mark for retry later
  426. if (!physicsWorld_ || !ownBody)
  427. {
  428. retryCreation_ = true;
  429. return;
  430. }
  431. if (!otherBody)
  432. otherBody = &btTypedConstraint::getFixedBody();
  433. Vector3 ownBodyScaledPosition = position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass();
  434. Vector3 otherBodyScaledPosition = otherBody_ ? otherPosition_ * otherBody_->GetNode()->GetWorldScale() -
  435. otherBody_->GetCenterOfMass() : otherPosition_;
  436. switch (constraintType_)
  437. {
  438. case CONSTRAINT_POINT:
  439. {
  440. constraint_ = new btPoint2PointConstraint(*ownBody, *otherBody, ToBtVector3(ownBodyScaledPosition),
  441. ToBtVector3(otherBodyScaledPosition));
  442. }
  443. break;
  444. case CONSTRAINT_HINGE:
  445. {
  446. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  447. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  448. constraint_ = new btHingeConstraint(*ownBody, *otherBody, ownFrame, otherFrame);
  449. }
  450. break;
  451. case CONSTRAINT_SLIDER:
  452. {
  453. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  454. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  455. constraint_ = new btSliderConstraint(*ownBody, *otherBody, ownFrame, otherFrame, false);
  456. }
  457. break;
  458. case CONSTRAINT_CONETWIST:
  459. {
  460. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  461. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  462. constraint_ = new btConeTwistConstraint(*ownBody, *otherBody, ownFrame, otherFrame);
  463. }
  464. break;
  465. default:
  466. break;
  467. }
  468. if (constraint_)
  469. {
  470. constraint_->setUserConstraintPtr(this);
  471. constraint_->setEnabled(IsEnabledEffective());
  472. ownBody_->AddConstraint(this);
  473. if (otherBody_)
  474. otherBody_->AddConstraint(this);
  475. ApplyLimits();
  476. physicsWorld_->GetWorld()->addConstraint(constraint_.Get(), disableCollision_);
  477. }
  478. recreateConstraint_ = false;
  479. framesDirty_ = false;
  480. retryCreation_ = false;
  481. }
  482. void Constraint::ApplyLimits()
  483. {
  484. if (!constraint_)
  485. return;
  486. switch (constraint_->getConstraintType())
  487. {
  488. case HINGE_CONSTRAINT_TYPE:
  489. {
  490. btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_.Get());
  491. hingeConstraint->setLimit(lowLimit_.x_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
  492. }
  493. break;
  494. case SLIDER_CONSTRAINT_TYPE:
  495. {
  496. btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_.Get());
  497. sliderConstraint->setUpperLinLimit(highLimit_.x_);
  498. sliderConstraint->setUpperAngLimit(highLimit_.y_ * M_DEGTORAD);
  499. sliderConstraint->setLowerLinLimit(lowLimit_.x_);
  500. sliderConstraint->setLowerAngLimit(lowLimit_.y_ * M_DEGTORAD);
  501. }
  502. break;
  503. case CONETWIST_CONSTRAINT_TYPE:
  504. {
  505. btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_.Get());
  506. coneTwistConstraint->setLimit(highLimit_.y_ * M_DEGTORAD, highLimit_.y_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
  507. }
  508. break;
  509. default:
  510. break;
  511. }
  512. if (erp_ != 0.0f)
  513. constraint_->setParam(BT_CONSTRAINT_STOP_ERP, erp_);
  514. if (cfm_ != 0.0f)
  515. constraint_->setParam(BT_CONSTRAINT_STOP_CFM, cfm_);
  516. }
  517. }