Constraint.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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. nullptr
  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_EX("Constraint Type", constraintType_, MarkConstraintDirty, typeNames, CONSTRAINT_POINT, AM_DEFAULT);
  77. URHO3D_ATTRIBUTE_EX("Position", Vector3, position_, AdjustOtherBodyPosition, Vector3::ZERO, AM_DEFAULT);
  78. URHO3D_ATTRIBUTE_EX("Rotation", Quaternion, rotation_, MarkFramesDirty, Quaternion::IDENTITY, AM_DEFAULT);
  79. URHO3D_ATTRIBUTE_EX("Other Body Position", Vector3, otherPosition_, MarkFramesDirty, Vector3::ZERO, AM_DEFAULT);
  80. URHO3D_ATTRIBUTE_EX("Other Body Rotation", Quaternion, otherRotation_, MarkFramesDirty, Quaternion::IDENTITY, AM_DEFAULT);
  81. URHO3D_ATTRIBUTE_EX("Other Body NodeID", unsigned, otherBodyNodeID_, MarkConstraintDirty, 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_EX("Disable Collision", bool, disableCollision_, MarkConstraintDirty, false, AM_DEFAULT);
  87. }
  88. void Constraint::ApplyAttributes()
  89. {
  90. if (recreateConstraint_)
  91. {
  92. if (otherBody_)
  93. otherBody_->RemoveConstraint(this);
  94. otherBody_.Reset();
  95. Scene* scene = GetScene();
  96. if (scene && otherBodyNodeID_)
  97. {
  98. Node* otherNode = scene->GetNode(otherBodyNodeID_);
  99. if (otherNode)
  100. otherBody_ = otherNode->GetComponent<RigidBody>();
  101. }
  102. CreateConstraint();
  103. }
  104. else if (framesDirty_)
  105. {
  106. ApplyFrames();
  107. framesDirty_ = false;
  108. }
  109. }
  110. void Constraint::OnSetEnabled()
  111. {
  112. if (constraint_)
  113. constraint_->setEnabled(IsEnabledEffective());
  114. }
  115. void Constraint::GetDependencyNodes(PODVector<Node*>& dest)
  116. {
  117. if (otherBody_ && otherBody_->GetNode())
  118. dest.Push(otherBody_->GetNode());
  119. }
  120. void Constraint::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  121. {
  122. if (debug && physicsWorld_ && constraint_)
  123. {
  124. physicsWorld_->SetDebugRenderer(debug);
  125. physicsWorld_->SetDebugDepthTest(depthTest);
  126. physicsWorld_->GetWorld()->debugDrawConstraint(constraint_.Get());
  127. physicsWorld_->SetDebugRenderer(nullptr);
  128. }
  129. }
  130. void Constraint::SetConstraintType(ConstraintType type)
  131. {
  132. if (type != constraintType_ || !constraint_)
  133. {
  134. constraintType_ = type;
  135. CreateConstraint();
  136. MarkNetworkUpdate();
  137. }
  138. }
  139. void Constraint::SetOtherBody(RigidBody* body)
  140. {
  141. if (otherBody_ != body)
  142. {
  143. if (otherBody_)
  144. otherBody_->RemoveConstraint(this);
  145. otherBody_ = body;
  146. // Update the connected body attribute
  147. Node* otherNode = otherBody_ ? otherBody_->GetNode() : nullptr;
  148. otherBodyNodeID_ = otherNode ? otherNode->GetID() : 0;
  149. CreateConstraint();
  150. MarkNetworkUpdate();
  151. }
  152. }
  153. void Constraint::SetPosition(const Vector3& position)
  154. {
  155. if (position != position_)
  156. {
  157. position_ = position;
  158. ApplyFrames();
  159. MarkNetworkUpdate();
  160. }
  161. }
  162. void Constraint::SetRotation(const Quaternion& rotation)
  163. {
  164. if (rotation != rotation_)
  165. {
  166. rotation_ = rotation;
  167. ApplyFrames();
  168. MarkNetworkUpdate();
  169. }
  170. }
  171. void Constraint::SetAxis(const Vector3& axis)
  172. {
  173. switch (constraintType_)
  174. {
  175. case CONSTRAINT_POINT:
  176. case CONSTRAINT_HINGE:
  177. rotation_ = Quaternion(Vector3::FORWARD, axis);
  178. break;
  179. case CONSTRAINT_SLIDER:
  180. case CONSTRAINT_CONETWIST:
  181. rotation_ = Quaternion(Vector3::RIGHT, axis);
  182. break;
  183. default:
  184. break;
  185. }
  186. ApplyFrames();
  187. MarkNetworkUpdate();
  188. }
  189. void Constraint::SetOtherPosition(const Vector3& position)
  190. {
  191. if (position != otherPosition_)
  192. {
  193. otherPosition_ = position;
  194. ApplyFrames();
  195. MarkNetworkUpdate();
  196. }
  197. }
  198. void Constraint::SetOtherRotation(const Quaternion& rotation)
  199. {
  200. if (rotation != otherRotation_)
  201. {
  202. otherRotation_ = rotation;
  203. ApplyFrames();
  204. MarkNetworkUpdate();
  205. }
  206. }
  207. void Constraint::SetOtherAxis(const Vector3& axis)
  208. {
  209. switch (constraintType_)
  210. {
  211. case CONSTRAINT_POINT:
  212. case CONSTRAINT_HINGE:
  213. otherRotation_ = Quaternion(Vector3::FORWARD, axis);
  214. break;
  215. case CONSTRAINT_SLIDER:
  216. case CONSTRAINT_CONETWIST:
  217. otherRotation_ = Quaternion(Vector3::RIGHT, axis);
  218. break;
  219. default:
  220. break;
  221. }
  222. ApplyFrames();
  223. MarkNetworkUpdate();
  224. }
  225. void Constraint::SetWorldPosition(const Vector3& position)
  226. {
  227. if (constraint_)
  228. {
  229. btTransform ownBodyInverse = constraint_->getRigidBodyA().getWorldTransform().inverse();
  230. btTransform otherBodyInverse = constraint_->getRigidBodyB().getWorldTransform().inverse();
  231. btVector3 worldPos = ToBtVector3(position);
  232. position_ = (ToVector3(ownBodyInverse * worldPos) + ownBody_->GetCenterOfMass()) / cachedWorldScale_;
  233. otherPosition_ = ToVector3(otherBodyInverse * worldPos);
  234. if (otherBody_)
  235. {
  236. otherPosition_ += otherBody_->GetCenterOfMass();
  237. otherPosition_ /= otherBody_->GetNode()->GetWorldScale();
  238. }
  239. ApplyFrames();
  240. MarkNetworkUpdate();
  241. }
  242. else
  243. URHO3D_LOGWARNING("Constraint not created, world position could not be stored");
  244. }
  245. void Constraint::SetHighLimit(const Vector2& limit)
  246. {
  247. if (limit != highLimit_)
  248. {
  249. highLimit_ = limit;
  250. ApplyLimits();
  251. MarkNetworkUpdate();
  252. }
  253. }
  254. void Constraint::SetLowLimit(const Vector2& limit)
  255. {
  256. if (limit != lowLimit_)
  257. {
  258. lowLimit_ = limit;
  259. ApplyLimits();
  260. MarkNetworkUpdate();
  261. }
  262. }
  263. void Constraint::SetERP(float erp)
  264. {
  265. erp = Max(erp, 0.0f);
  266. if (erp != erp_)
  267. {
  268. erp_ = erp;
  269. ApplyLimits();
  270. MarkNetworkUpdate();
  271. }
  272. }
  273. void Constraint::SetCFM(float cfm)
  274. {
  275. cfm = Max(cfm, 0.0f);
  276. if (cfm != cfm_)
  277. {
  278. cfm_ = cfm;
  279. ApplyLimits();
  280. MarkNetworkUpdate();
  281. }
  282. }
  283. void Constraint::SetDisableCollision(bool disable)
  284. {
  285. if (disable != disableCollision_)
  286. {
  287. disableCollision_ = disable;
  288. CreateConstraint();
  289. MarkNetworkUpdate();
  290. }
  291. }
  292. Vector3 Constraint::GetWorldPosition() const
  293. {
  294. if (constraint_)
  295. {
  296. btTransform ownBody = constraint_->getRigidBodyA().getWorldTransform();
  297. return ToVector3(ownBody * ToBtVector3(position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass()));
  298. }
  299. else
  300. return Vector3::ZERO;
  301. }
  302. void Constraint::ReleaseConstraint()
  303. {
  304. if (constraint_)
  305. {
  306. if (ownBody_)
  307. ownBody_->RemoveConstraint(this);
  308. if (otherBody_)
  309. otherBody_->RemoveConstraint(this);
  310. if (physicsWorld_)
  311. physicsWorld_->GetWorld()->removeConstraint(constraint_.Get());
  312. constraint_.Reset();
  313. }
  314. }
  315. void Constraint::ApplyFrames()
  316. {
  317. if (!constraint_ || !node_ || (otherBody_ && !otherBody_->GetNode()))
  318. return;
  319. cachedWorldScale_ = node_->GetWorldScale();
  320. Vector3 ownBodyScaledPosition = position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass();
  321. Vector3 otherBodyScaledPosition =
  322. otherBody_ ? otherPosition_ * otherBody_->GetNode()->GetWorldScale() - otherBody_->GetCenterOfMass() : otherPosition_;
  323. switch (constraint_->getConstraintType())
  324. {
  325. case POINT2POINT_CONSTRAINT_TYPE:
  326. {
  327. btPoint2PointConstraint* pointConstraint = static_cast<btPoint2PointConstraint*>(constraint_.Get());
  328. pointConstraint->setPivotA(ToBtVector3(ownBodyScaledPosition));
  329. pointConstraint->setPivotB(ToBtVector3(otherBodyScaledPosition));
  330. }
  331. break;
  332. case HINGE_CONSTRAINT_TYPE:
  333. {
  334. btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_.Get());
  335. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  336. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  337. hingeConstraint->setFrames(ownFrame, otherFrame);
  338. }
  339. break;
  340. case SLIDER_CONSTRAINT_TYPE:
  341. {
  342. btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_.Get());
  343. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  344. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  345. sliderConstraint->setFrames(ownFrame, otherFrame);
  346. }
  347. break;
  348. case CONETWIST_CONSTRAINT_TYPE:
  349. {
  350. btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_.Get());
  351. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  352. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  353. coneTwistConstraint->setFrames(ownFrame, otherFrame);
  354. }
  355. break;
  356. default:
  357. break;
  358. }
  359. }
  360. void Constraint::OnNodeSet(Node* node)
  361. {
  362. if (node)
  363. {
  364. node->AddListener(this);
  365. cachedWorldScale_ = node->GetWorldScale();
  366. }
  367. }
  368. void Constraint::OnSceneSet(Scene* scene)
  369. {
  370. if (scene)
  371. {
  372. if (scene == node_)
  373. URHO3D_LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  374. physicsWorld_ = scene->GetOrCreateComponent<PhysicsWorld>();
  375. physicsWorld_->AddConstraint(this);
  376. // Create constraint now if necessary (attributes modified before adding to scene)
  377. if (retryCreation_)
  378. CreateConstraint();
  379. }
  380. else
  381. {
  382. ReleaseConstraint();
  383. if (physicsWorld_)
  384. physicsWorld_->RemoveConstraint(this);
  385. // Recreate when moved to a scene again
  386. retryCreation_ = true;
  387. }
  388. }
  389. void Constraint::OnMarkedDirty(Node* node)
  390. {
  391. /// \todo This does not catch the connected body node's scale changing
  392. if (HasWorldScaleChanged(cachedWorldScale_, node->GetWorldScale()))
  393. ApplyFrames();
  394. }
  395. void Constraint::CreateConstraint()
  396. {
  397. URHO3D_PROFILE(CreateConstraint);
  398. cachedWorldScale_ = node_->GetWorldScale();
  399. ReleaseConstraint();
  400. ownBody_ = GetComponent<RigidBody>();
  401. btRigidBody* ownBody = ownBody_ ? ownBody_->GetBody() : nullptr;
  402. btRigidBody* otherBody = otherBody_ ? otherBody_->GetBody() : nullptr;
  403. // If no physics world available now mark for retry later
  404. if (!physicsWorld_ || !ownBody)
  405. {
  406. retryCreation_ = true;
  407. return;
  408. }
  409. if (!otherBody)
  410. otherBody = &btTypedConstraint::getFixedBody();
  411. Vector3 ownBodyScaledPosition = position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass();
  412. Vector3 otherBodyScaledPosition = otherBody_ ? otherPosition_ * otherBody_->GetNode()->GetWorldScale() -
  413. otherBody_->GetCenterOfMass() : otherPosition_;
  414. switch (constraintType_)
  415. {
  416. case CONSTRAINT_POINT:
  417. {
  418. constraint_ = new btPoint2PointConstraint(*ownBody, *otherBody, ToBtVector3(ownBodyScaledPosition),
  419. ToBtVector3(otherBodyScaledPosition));
  420. }
  421. break;
  422. case CONSTRAINT_HINGE:
  423. {
  424. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  425. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  426. constraint_ = new btHingeConstraint(*ownBody, *otherBody, ownFrame, otherFrame);
  427. }
  428. break;
  429. case CONSTRAINT_SLIDER:
  430. {
  431. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  432. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  433. constraint_ = new btSliderConstraint(*ownBody, *otherBody, ownFrame, otherFrame, false);
  434. }
  435. break;
  436. case CONSTRAINT_CONETWIST:
  437. {
  438. btTransform ownFrame(ToBtQuaternion(rotation_), ToBtVector3(ownBodyScaledPosition));
  439. btTransform otherFrame(ToBtQuaternion(otherRotation_), ToBtVector3(otherBodyScaledPosition));
  440. constraint_ = new btConeTwistConstraint(*ownBody, *otherBody, ownFrame, otherFrame);
  441. }
  442. break;
  443. default:
  444. break;
  445. }
  446. if (constraint_)
  447. {
  448. constraint_->setUserConstraintPtr(this);
  449. constraint_->setEnabled(IsEnabledEffective());
  450. ownBody_->AddConstraint(this);
  451. if (otherBody_)
  452. otherBody_->AddConstraint(this);
  453. ApplyLimits();
  454. physicsWorld_->GetWorld()->addConstraint(constraint_.Get(), disableCollision_);
  455. }
  456. recreateConstraint_ = false;
  457. framesDirty_ = false;
  458. retryCreation_ = false;
  459. }
  460. void Constraint::ApplyLimits()
  461. {
  462. if (!constraint_)
  463. return;
  464. switch (constraint_->getConstraintType())
  465. {
  466. case HINGE_CONSTRAINT_TYPE:
  467. {
  468. btHingeConstraint* hingeConstraint = static_cast<btHingeConstraint*>(constraint_.Get());
  469. hingeConstraint->setLimit(lowLimit_.x_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
  470. }
  471. break;
  472. case SLIDER_CONSTRAINT_TYPE:
  473. {
  474. btSliderConstraint* sliderConstraint = static_cast<btSliderConstraint*>(constraint_.Get());
  475. sliderConstraint->setUpperLinLimit(highLimit_.x_);
  476. sliderConstraint->setUpperAngLimit(highLimit_.y_ * M_DEGTORAD);
  477. sliderConstraint->setLowerLinLimit(lowLimit_.x_);
  478. sliderConstraint->setLowerAngLimit(lowLimit_.y_ * M_DEGTORAD);
  479. }
  480. break;
  481. case CONETWIST_CONSTRAINT_TYPE:
  482. {
  483. btConeTwistConstraint* coneTwistConstraint = static_cast<btConeTwistConstraint*>(constraint_.Get());
  484. coneTwistConstraint->setLimit(highLimit_.y_ * M_DEGTORAD, highLimit_.y_ * M_DEGTORAD, highLimit_.x_ * M_DEGTORAD);
  485. }
  486. break;
  487. default:
  488. break;
  489. }
  490. if (erp_ != 0.0f)
  491. constraint_->setParam(BT_CONSTRAINT_STOP_ERP, erp_);
  492. if (cfm_ != 0.0f)
  493. constraint_->setParam(BT_CONSTRAINT_STOP_CFM, cfm_);
  494. }
  495. void Constraint::AdjustOtherBodyPosition()
  496. {
  497. // Convenience for editing static constraints: if not connected to another body, adjust world position to match local
  498. // (when deserializing, the proper other body position will be read after own position, so this calculation is safely
  499. // overridden and does not accumulate constraint error
  500. if (constraint_ && !otherBody_)
  501. {
  502. btTransform ownBody = constraint_->getRigidBodyA().getWorldTransform();
  503. btVector3 worldPos = ownBody * ToBtVector3(position_ * cachedWorldScale_ - ownBody_->GetCenterOfMass());
  504. otherPosition_ = ToVector3(worldPos);
  505. }
  506. MarkFramesDirty();
  507. }
  508. }