Constraint.cpp 16 KB

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