Constraint.cpp 18 KB

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