IKSolver.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. //
  2. // Copyright (c) 2008-2016 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 "../IK/IKSolver.h"
  23. #include "../IK/IKConstraint.h"
  24. #include "../IK/IKEvents.h"
  25. #include "../IK/IKEffector.h"
  26. #include "../IK/IKConverters.h"
  27. #include "../Core/Context.h"
  28. #include "../Core/Profiler.h"
  29. #include "../Graphics/Animation.h"
  30. #include "../Graphics/AnimationState.h"
  31. #include "../Graphics/DebugRenderer.h"
  32. #include "../IO/Log.h"
  33. #include "../Scene/SceneEvents.h"
  34. #include <ik/effector.h>
  35. #include <ik/node.h>
  36. #include <ik/solver.h>
  37. #include <ik/util.h>
  38. namespace Atomic
  39. {
  40. extern const char* IK_CATEGORY;
  41. // ----------------------------------------------------------------------------
  42. IKSolver::IKSolver(Context* context) :
  43. Component(context),
  44. solver_(NULL),
  45. algorithm_(FABRIK),
  46. features_(AUTO_SOLVE | JOINT_ROTATIONS | UPDATE_ACTIVE_POSE),
  47. chainTreesNeedUpdating_(false),
  48. treeNeedsRebuild(true),
  49. solverTreeValid_(false)
  50. {
  51. context_->RequireIK();
  52. SetAlgorithm(FABRIK);
  53. SubscribeToEvent(E_COMPONENTADDED, ATOMIC_HANDLER(IKSolver, HandleComponentAdded));
  54. SubscribeToEvent(E_COMPONENTREMOVED, ATOMIC_HANDLER(IKSolver, HandleComponentRemoved));
  55. SubscribeToEvent(E_NODEADDED, ATOMIC_HANDLER(IKSolver, HandleNodeAdded));
  56. SubscribeToEvent(E_NODEREMOVED, ATOMIC_HANDLER(IKSolver, HandleNodeRemoved));
  57. }
  58. // ----------------------------------------------------------------------------
  59. IKSolver::~IKSolver()
  60. {
  61. // Destroying the solver tree will destroy the effector objects, so remove
  62. // any references any of the IKEffector objects could be holding
  63. for (PODVector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it)
  64. (*it)->SetIKEffectorNode(NULL);
  65. ik_solver_destroy(solver_);
  66. context_->ReleaseIK();
  67. }
  68. // ----------------------------------------------------------------------------
  69. void IKSolver::RegisterObject(Context* context)
  70. {
  71. context->RegisterFactory<IKSolver>(IK_CATEGORY);
  72. static const char* algorithmNames[] = {
  73. "1 Bone",
  74. "2 Bone",
  75. "FABRIK",
  76. /* not implemented,
  77. "MSD (Mass/Spring/Damper)",
  78. "Jacobian Inverse",
  79. "Jacobian Transpose",*/
  80. NULL
  81. };
  82. ATOMIC_ENUM_ACCESSOR_ATTRIBUTE("Algorithm", GetAlgorithm, SetAlgorithm, Algorithm, algorithmNames, SOLVER_FABRIK, AM_DEFAULT);
  83. ATOMIC_ACCESSOR_ATTRIBUTE("Max Iterations", GetMaximumIterations, SetMaximumIterations, unsigned, 20, AM_DEFAULT);
  84. ATOMIC_ACCESSOR_ATTRIBUTE("Convergence Tolerance", GetTolerance, SetTolerance, float, 0.001, AM_DEFAULT);
  85. ATOMIC_ACCESSOR_ATTRIBUTE("Bone Rotations", BoneRotationsEnabled, EnableBoneRotations, bool, true, AM_DEFAULT);
  86. ATOMIC_ACCESSOR_ATTRIBUTE("Target Rotation", TargetRotationEnabled, EnableTargetRotation, bool, false, AM_DEFAULT);
  87. ATOMIC_ACCESSOR_ATTRIBUTE("Continuous Solving", ContinuousSolvingEnabled, EnableContinuousSolving, bool, false, AM_DEFAULT);
  88. ATOMIC_ACCESSOR_ATTRIBUTE("Update Active Pose", GetUPDATE_ACTIVE_POSE, SetUPDATE_ACTIVE_POSE, bool, true, AM_DEFAULT);
  89. ATOMIC_ACCESSOR_ATTRIBUTE("Update Pose", UpdatePoseEnabled, EnableUpdatePose, bool, false, AM_DEFAULT);
  90. ATOMIC_ACCESSOR_ATTRIBUTE("Enable Constraints", GetCONSTRAINTS, SetCONSTRAINTS, bool, false, AM_DEFAULT);
  91. ATOMIC_ACCESSOR_ATTRIBUTE("Auto Solve", AutoSolveEnabled, EnableAutoSolve, bool, true, AM_DEFAULT);
  92. }
  93. // ----------------------------------------------------------------------------
  94. IKSolver::Algorithm IKSolver::GetAlgorithm() const
  95. {
  96. return algorithm_;
  97. }
  98. // ----------------------------------------------------------------------------
  99. void IKSolver::SetAlgorithm(IKSolver::Algorithm algorithm)
  100. {
  101. algorithm_ = algorithm;
  102. /* We need to rebuild the tree so make sure that the scene is in the
  103. * initial pose when this occurs.*/
  104. if (node_ != NULL)
  105. ApplyOriginalPoseToScene();
  106. // Initial flags for when there is no solver to destroy
  107. uint8_t initialFlags = 0;
  108. // Destroys the tree and the solver
  109. if (solver_ != NULL)
  110. {
  111. initialFlags = solver_->flags;
  112. DestroyTree();
  113. ik_solver_destroy(solver_);
  114. }
  115. switch (algorithm_)
  116. {
  117. case ONE_BONE : solver_ = ik_solver_create(SOLVER_ONE_BONE); break;
  118. case TWO_BONE : solver_ = ik_solver_create(SOLVER_TWO_BONE); break;
  119. case FABRIK : solver_ = ik_solver_create(SOLVER_FABRIK); break;
  120. /*case MSD : solver_ = ik_solver_create(SOLVER_MSD); break;*/
  121. }
  122. solver_->flags = initialFlags;
  123. if (node_ != NULL)
  124. RebuildTree();
  125. }
  126. // ----------------------------------------------------------------------------
  127. bool IKSolver::GetFeature(Feature feature) const
  128. {
  129. return (features_ & feature) != 0;
  130. }
  131. // ----------------------------------------------------------------------------
  132. void IKSolver::SetFeature(Feature feature, bool enable)
  133. {
  134. switch (feature)
  135. {
  136. case CONSTRAINTS:
  137. {
  138. solver_->flags &= ~SOLVER_ENABLE_CONSTRAINTS;
  139. if (enable)
  140. solver_->flags |= SOLVER_ENABLE_CONSTRAINTS;
  141. } break;
  142. case TARGET_ROTATIONS:
  143. {
  144. solver_->flags &= ~SOLVER_CALCULATE_TARGET_ROTATIONS;
  145. if (enable)
  146. solver_->flags |= SOLVER_CALCULATE_TARGET_ROTATIONS;
  147. } break;
  148. case AUTO_SOLVE:
  149. {
  150. if (((features_ & AUTO_SOLVE) != 0) == enable)
  151. break;
  152. if (enable)
  153. SubscribeToEvent(GetScene(), E_SCENEDRAWABLEUPDATEFINISHED, ATOMIC_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished));
  154. else
  155. UnsubscribeFromEvent(GetScene(), E_SCENEDRAWABLEUPDATEFINISHED);
  156. } break;
  157. default: break;
  158. }
  159. features_ &= ~feature;
  160. if (enable)
  161. features_ |= feature;
  162. }
  163. // ----------------------------------------------------------------------------
  164. unsigned IKSolver::GetMaximumIterations() const
  165. {
  166. return solver_->max_iterations;
  167. }
  168. // ----------------------------------------------------------------------------
  169. void IKSolver::SetMaximumIterations(unsigned iterations)
  170. {
  171. solver_->max_iterations = iterations;
  172. }
  173. // ----------------------------------------------------------------------------
  174. float IKSolver::GetTolerance() const
  175. {
  176. return solver_->tolerance;
  177. }
  178. // ----------------------------------------------------------------------------
  179. void IKSolver::SetTolerance(float tolerance)
  180. {
  181. if (tolerance < M_EPSILON)
  182. tolerance = M_EPSILON;
  183. solver_->tolerance = tolerance;
  184. }
  185. // ----------------------------------------------------------------------------
  186. ik_node_t* IKSolver::CreateIKNodeFromUrhoNode(const Node* node)
  187. {
  188. ik_node_t* ikNode = ik_node_create(node->GetID());
  189. // Set initial position/rotation and pass in Node* as user data for later
  190. ikNode->original_position = Vec3Urho2IK(node->GetWorldPosition());
  191. ikNode->original_rotation = QuatUrho2IK(node->GetWorldRotation());
  192. ikNode->user_data = (void*)node;
  193. /*
  194. * If Urho's node has an effector, also create and attach one to the
  195. * library's node. At this point, the IKEffector component shouldn't be
  196. * holding a reference to any internal effector. Check this for debugging
  197. * purposes and log if it does.
  198. */
  199. IKEffector* effector = node->GetComponent<IKEffector>();
  200. if (effector != NULL)
  201. {
  202. #ifdef DEBUG
  203. if (effector->ikEffectorNode_ != NULL)
  204. ATOMIC_LOGWARNINGF("[ik] IKEffector (attached to node \"%s\") has a reference to a possibly invalid internal effector. Should be NULL.", effector->GetNode()->GetName().CString());
  205. #endif
  206. ik_effector_t* ikEffector = ik_effector_create();
  207. ik_node_attach_effector(ikNode, ikEffector); // ownership of effector
  208. effector->SetIKSolver(this);
  209. effector->SetIKEffectorNode(ikNode);
  210. }
  211. // Exact same deal with the constraint
  212. IKConstraint* constraint = node->GetComponent<IKConstraint>();
  213. if (constraint != NULL)
  214. {
  215. #ifdef DEBUG
  216. if (constraint->ikConstraintNode_ != NULL)
  217. ATOMIC_LOGWARNINGF("[ik] IKConstraint (attached to node \"%s\") has a reference to a possibly invalid internal constraint. Should be NULL.", constraint->GetNode()->GetName().CString());
  218. #endif
  219. constraint->SetIKConstraintNode(ikNode);
  220. }
  221. return ikNode;
  222. }
  223. // ----------------------------------------------------------------------------
  224. void IKSolver::DestroyTree()
  225. {
  226. ik_solver_destroy_tree(solver_);
  227. effectorList_.Clear();
  228. constraintList_.Clear();
  229. }
  230. // ----------------------------------------------------------------------------
  231. void IKSolver::RebuildTree()
  232. {
  233. assert (node_ != NULL);
  234. // Destroy current tree and set a new root node
  235. DestroyTree();
  236. ik_node_t* ikRoot = CreateIKNodeFromUrhoNode(node_);
  237. ik_solver_set_tree(solver_, ikRoot);
  238. /*
  239. * Collect all effectors and constraints from children, and filter them to
  240. * make sure they are in our subtree.
  241. */
  242. node_->GetComponents<IKEffector>(effectorList_, true);
  243. node_->GetComponents<IKConstraint>(constraintList_, true);
  244. for (PODVector<IKEffector*>::Iterator it = effectorList_.Begin(); it != effectorList_.End();)
  245. {
  246. if (ComponentIsInOurSubtree(*it))
  247. {
  248. BuildTreeToEffector((*it));
  249. ++it;
  250. }
  251. else
  252. {
  253. it = effectorList_.Erase(it);
  254. }
  255. }
  256. for (PODVector<IKConstraint*>::Iterator it = constraintList_.Begin(); it != constraintList_.End();)
  257. {
  258. if (ComponentIsInOurSubtree(*it))
  259. ++it;
  260. else
  261. it = constraintList_.Erase(it);
  262. }
  263. treeNeedsRebuild = false;
  264. MarkChainsNeedUpdating();
  265. }
  266. // ----------------------------------------------------------------------------
  267. bool IKSolver::BuildTreeToEffector(IKEffector* effector)
  268. {
  269. /*
  270. * NOTE: This function makes the assumption that the node the effector is
  271. * attached to is -- without a doubt -- in our subtree (by using
  272. * ComponentIsInOurSubtree() first). If this is not the case, the program
  273. * will abort.
  274. */
  275. /*
  276. * we need to build tree up to the node where this effector was added. Do
  277. * this by following the chain of parent nodes until we hit a node that
  278. * exists in the solver's subtree. Then iterate backwards again and add each
  279. * missing node to the solver's tree.
  280. */
  281. const Node* iterNode = effector->GetNode();
  282. ik_node_t* ikNode;
  283. PODVector<const Node*> missingNodes;
  284. while ((ikNode = ik_node_find_child(solver_->tree, iterNode->GetID())) == NULL)
  285. {
  286. missingNodes.Push(iterNode);
  287. iterNode = iterNode->GetParent();
  288. // Assert the assumptions made (described in the beginning of this function)
  289. assert(iterNode != NULL);
  290. assert (iterNode->HasComponent<IKSolver>() == false || iterNode == node_);
  291. }
  292. while (missingNodes.Size() > 0)
  293. {
  294. iterNode = missingNodes.Back();
  295. missingNodes.Pop();
  296. ik_node_t* ikChildNode = CreateIKNodeFromUrhoNode(iterNode);
  297. ik_node_add_child(ikNode, ikChildNode);
  298. ikNode = ikChildNode;
  299. }
  300. return true;
  301. }
  302. // ----------------------------------------------------------------------------
  303. bool IKSolver::ComponentIsInOurSubtree(Component* component) const
  304. {
  305. const Node* iterNode = component->GetNode();
  306. while (true)
  307. {
  308. // Note part of our subtree
  309. if (iterNode == NULL)
  310. return false;
  311. // Reached the root node, it's part of our subtree!
  312. if (iterNode == node_)
  313. return true;
  314. // Path to us is being blocked by another solver
  315. Component* otherSolver = iterNode->GetComponent<IKSolver>();
  316. if (otherSolver != NULL && otherSolver != component)
  317. return false;
  318. iterNode = iterNode->GetParent();
  319. }
  320. return true;
  321. }
  322. // ----------------------------------------------------------------------------
  323. void IKSolver::RebuildChainTrees()
  324. {
  325. solverTreeValid_ = (ik_solver_rebuild_chain_trees(solver_) == 0);
  326. ik_calculate_rotation_weight_decays(&solver_->chain_tree);
  327. chainTreesNeedUpdating_ = false;
  328. }
  329. // ----------------------------------------------------------------------------
  330. void IKSolver::RecalculateSegmentLengths()
  331. {
  332. ik_solver_recalculate_segment_lengths(solver_);
  333. SubscribeToEvent(GetScene(), E_SCENEDRAWABLEUPDATEFINISHED, ATOMIC_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished));
  334. }
  335. // ----------------------------------------------------------------------------
  336. void IKSolver::CalculateJointRotations()
  337. {
  338. ik_solver_calculate_joint_rotations(solver_);
  339. }
  340. // ----------------------------------------------------------------------------
  341. void IKSolver::Solve()
  342. {
  343. ATOMIC_PROFILE(IKSolve);
  344. if (treeNeedsRebuild)
  345. RebuildTree();
  346. if (chainTreesNeedUpdating_)
  347. RebuildChainTrees();
  348. if (IsSolverTreeValid() == false)
  349. return;
  350. if (features_ & UPDATE_ORIGINAL_POSE)
  351. ApplySceneToOriginalPose();
  352. if (features_ & UPDATE_ACTIVE_POSE)
  353. ApplySceneToActivePose();
  354. if (features_ & USE_ORIGINAL_POSE)
  355. ApplyOriginalPoseToActivePose();
  356. for (PODVector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it)
  357. {
  358. (*it)->UpdateTargetNodePosition();
  359. }
  360. ik_solver_solve(solver_);
  361. if (features_ & JOINT_ROTATIONS)
  362. ik_solver_calculate_joint_rotations(solver_);
  363. ApplyActivePoseToScene();
  364. }
  365. // ----------------------------------------------------------------------------
  366. static void ApplyInitialPoseToSceneCallback(ik_node_t* ikNode)
  367. {
  368. Node* node = (Node*)ikNode->user_data;
  369. node->SetWorldRotation(QuatIK2Urho(&ikNode->original_rotation));
  370. node->SetWorldPosition(Vec3IK2Urho(&ikNode->original_position));
  371. }
  372. void IKSolver::ApplyOriginalPoseToScene()
  373. {
  374. ik_solver_iterate_tree(solver_, ApplyInitialPoseToSceneCallback);
  375. }
  376. // ----------------------------------------------------------------------------
  377. static void ApplySceneToInitialPoseCallback(ik_node_t* ikNode)
  378. {
  379. Node* node = (Node*)ikNode->user_data;
  380. ikNode->original_rotation = QuatUrho2IK(node->GetWorldRotation());
  381. ikNode->original_position = Vec3Urho2IK(node->GetWorldPosition());
  382. }
  383. void IKSolver::ApplySceneToOriginalPose()
  384. {
  385. ik_solver_iterate_tree(solver_, ApplySceneToInitialPoseCallback);
  386. }
  387. // ----------------------------------------------------------------------------
  388. static void ApplyActivePoseToSceneCallback(ik_node_t* ikNode)
  389. {
  390. Node* node = (Node*)ikNode->user_data;
  391. node->SetWorldRotation(QuatIK2Urho(&ikNode->rotation));
  392. node->SetWorldPosition(Vec3IK2Urho(&ikNode->position));
  393. }
  394. void IKSolver::ApplyActivePoseToScene()
  395. {
  396. ik_solver_iterate_tree(solver_, ApplyActivePoseToSceneCallback);
  397. }
  398. // ----------------------------------------------------------------------------
  399. static void ApplySceneToActivePoseCallback(ik_node_t* ikNode)
  400. {
  401. Node* node = (Node*)ikNode->user_data;
  402. ikNode->rotation = QuatUrho2IK(node->GetWorldRotation());
  403. ikNode->position = Vec3Urho2IK(node->GetWorldPosition());
  404. }
  405. void IKSolver::ApplySceneToActivePose()
  406. {
  407. ik_solver_iterate_tree(solver_, ApplySceneToActivePoseCallback);
  408. }
  409. // ----------------------------------------------------------------------------
  410. void IKSolver::ApplyOriginalPoseToActivePose()
  411. {
  412. ik_solver_reset_to_original_pose(solver_);
  413. }
  414. // ----------------------------------------------------------------------------
  415. void IKSolver::MarkChainsNeedUpdating()
  416. {
  417. chainTreesNeedUpdating_ = true;
  418. }
  419. // ----------------------------------------------------------------------------
  420. void IKSolver::MarkTreeNeedsRebuild()
  421. {
  422. treeNeedsRebuild = true;
  423. }
  424. // ----------------------------------------------------------------------------
  425. bool IKSolver::IsSolverTreeValid() const
  426. {
  427. return solverTreeValid_;
  428. }
  429. // ----------------------------------------------------------------------------
  430. /*
  431. * This next section maintains the internal list of effector nodes. Whenever
  432. * nodes are deleted or added to the scene, or whenever components are added
  433. * or removed from nodes, we must check to see which of those nodes are/were
  434. * IK effector nodes and update our internal list accordingly.
  435. *
  436. * Unfortunately, E_COMPONENTREMOVED and E_COMPONENTADDED do not fire when a
  437. * parent node is removed/added containing child effector nodes, so we must
  438. * also monitor E_NODEREMOVED AND E_NODEADDED.
  439. */
  440. // ----------------------------------------------------------------------------
  441. void IKSolver::OnSceneSet(Scene* scene)
  442. {
  443. if (features_ & AUTO_SOLVE)
  444. SubscribeToEvent(scene, E_SCENEDRAWABLEUPDATEFINISHED, ATOMIC_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished));
  445. }
  446. // ----------------------------------------------------------------------------
  447. void IKSolver::OnNodeSet(Node* node)
  448. {
  449. ApplyOriginalPoseToScene();
  450. DestroyTree();
  451. if (node != NULL)
  452. RebuildTree();
  453. }
  454. // ----------------------------------------------------------------------------
  455. void IKSolver::HandleComponentAdded(StringHash eventType, VariantMap& eventData)
  456. {
  457. using namespace ComponentAdded;
  458. (void)eventType;
  459. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  460. Component* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr());
  461. /*
  462. * When a solver gets added into the scene, any parent solver's tree will
  463. * be invalidated. We need to find all parent solvers (by iterating up the
  464. * tree) and mark them as such.
  465. */
  466. if (component->GetType() == IKSolver::GetTypeStatic())
  467. {
  468. for (Node* iterNode = node; iterNode != NULL; iterNode = iterNode->GetParent())
  469. {
  470. IKSolver* parentSolver = iterNode->GetComponent<IKSolver>();
  471. if (parentSolver != NULL)
  472. parentSolver->MarkTreeNeedsRebuild();
  473. }
  474. return; // No need to continue processing effectors or constraints
  475. }
  476. if (solver_->tree == NULL)
  477. return;
  478. /*
  479. * Update tree if component is an effector and is part of our subtree.
  480. */
  481. if (component->GetType() == IKEffector::GetTypeStatic())
  482. {
  483. // Not interested in components that won't be part of our
  484. if (ComponentIsInOurSubtree(component) == false)
  485. return;
  486. BuildTreeToEffector(static_cast<IKEffector*>(component));
  487. effectorList_.Push(static_cast<IKEffector*>(component));
  488. return;
  489. }
  490. if (component->GetType() == IKConstraint::GetTypeStatic())
  491. {
  492. if (ComponentIsInOurSubtree(component) == false)
  493. return;
  494. constraintList_.Push(static_cast<IKConstraint*>(component));
  495. }
  496. }
  497. // ----------------------------------------------------------------------------
  498. void IKSolver::HandleComponentRemoved(StringHash eventType, VariantMap& eventData)
  499. {
  500. using namespace ComponentRemoved;
  501. if (solver_->tree == NULL)
  502. return;
  503. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  504. Component* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr());
  505. /*
  506. * When a solver gets added into the scene, any parent solver's tree will
  507. * be invalidated. We need to find all parent solvers (by iterating up the
  508. * tree) and mark them as such.
  509. */
  510. if (component->GetType() == IKSolver::GetTypeStatic())
  511. {
  512. for (Node* iterNode = node; iterNode != NULL; iterNode = iterNode->GetParent())
  513. {
  514. IKSolver* parentSolver = iterNode->GetComponent<IKSolver>();
  515. if (parentSolver != NULL)
  516. parentSolver->MarkTreeNeedsRebuild();
  517. }
  518. return; // No need to continue processing effectors or constraints
  519. }
  520. // If an effector was removed, the tree will have to be rebuilt.
  521. if (component->GetType() == IKEffector::GetTypeStatic())
  522. {
  523. if (ComponentIsInOurSubtree(component) == false)
  524. return;
  525. ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID());
  526. assert(ikNode != NULL);
  527. ik_node_destroy_effector(ikNode);
  528. static_cast<IKEffector*>(component)->SetIKEffectorNode(NULL);
  529. effectorList_.RemoveSwap(static_cast<IKEffector*>(component));
  530. ApplyOriginalPoseToScene();
  531. MarkTreeNeedsRebuild();
  532. return;
  533. }
  534. // Remove the ikNode* reference the IKConstraint was holding
  535. if (component->GetType() == IKConstraint::GetTypeStatic())
  536. {
  537. if (ComponentIsInOurSubtree(component) == false)
  538. return;
  539. ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID());
  540. assert(ikNode != NULL);
  541. static_cast<IKConstraint*>(component)->SetIKConstraintNode(NULL);
  542. constraintList_.RemoveSwap(static_cast<IKConstraint*>(component));
  543. }
  544. }
  545. // ----------------------------------------------------------------------------
  546. void IKSolver::HandleNodeAdded(StringHash eventType, VariantMap& eventData)
  547. {
  548. using namespace NodeAdded;
  549. if (solver_->tree == NULL)
  550. return;
  551. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  552. PODVector<IKEffector*> effectors;
  553. node->GetComponents<IKEffector>(effectors, true);
  554. for (PODVector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it)
  555. {
  556. if (ComponentIsInOurSubtree(*it) == false)
  557. continue;
  558. BuildTreeToEffector(*it);
  559. effectorList_.Push(*it);
  560. }
  561. PODVector<IKConstraint*> constraints;
  562. node->GetComponents<IKConstraint>(constraints, true);
  563. for (PODVector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it)
  564. {
  565. if (ComponentIsInOurSubtree(*it) == false)
  566. continue;
  567. constraintList_.Push(*it);
  568. }
  569. }
  570. // ----------------------------------------------------------------------------
  571. void IKSolver::HandleNodeRemoved(StringHash eventType, VariantMap& eventData)
  572. {
  573. using namespace NodeRemoved;
  574. if (solver_->tree == NULL)
  575. return;
  576. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  577. // Remove cached IKEffectors from our list
  578. PODVector<IKEffector*> effectors;
  579. node->GetComponents<IKEffector>(effectors, true);
  580. for (PODVector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it)
  581. {
  582. (*it)->SetIKEffectorNode(NULL);
  583. effectorList_.RemoveSwap(*it);
  584. }
  585. PODVector<IKConstraint*> constraints;
  586. node->GetComponents<IKConstraint>(constraints, true);
  587. for (PODVector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it)
  588. {
  589. constraintList_.RemoveSwap(*it);
  590. }
  591. // Special case, if the node being destroyed is the root node, destroy the
  592. // solver's tree instead of destroying the single node. Calling
  593. // ik_node_destroy() on the solver's root node will cause segfaults.
  594. ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID());
  595. if (ikNode != NULL)
  596. {
  597. if (ikNode == solver_->tree)
  598. ik_solver_destroy_tree(solver_);
  599. else
  600. ik_node_destroy(ikNode);
  601. MarkChainsNeedUpdating();
  602. }
  603. }
  604. // ----------------------------------------------------------------------------
  605. void IKSolver::HandleSceneDrawableUpdateFinished(StringHash eventType, VariantMap& eventData)
  606. {
  607. Solve();
  608. }
  609. // ----------------------------------------------------------------------------
  610. void IKSolver::DrawDebugGeometry(bool depthTest)
  611. {
  612. DebugRenderer* debug = GetScene()->GetComponent<DebugRenderer>();
  613. if (debug)
  614. DrawDebugGeometry(debug, depthTest);
  615. }
  616. // ----------------------------------------------------------------------------
  617. void IKSolver::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  618. {
  619. // Draws all scene segments
  620. for (PODVector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it)
  621. (*it)->DrawDebugGeometry(debug, depthTest);
  622. ORDERED_VECTOR_FOR_EACH(&solver_->effector_nodes_list, ik_node_t*, pnode)
  623. ik_effector_t* effector = (*pnode)->effector;
  624. // Calculate average length of all segments so we can determine the radius
  625. // of the debug spheres to draw
  626. int chainLength = effector->chain_length == 0 ? -1 : effector->chain_length;
  627. ik_node_t* a = *pnode;
  628. ik_node_t* b = a->parent;
  629. float averageLength = 0.0f;
  630. unsigned numberOfSegments = 0;
  631. while (b && chainLength-- != 0)
  632. {
  633. vec3_t v = a->original_position;
  634. vec3_sub_vec3(v.f, b->original_position.f);
  635. averageLength += vec3_length(v.f);
  636. ++numberOfSegments;
  637. a = b;
  638. b = b->parent;
  639. }
  640. averageLength /= numberOfSegments;
  641. // connect all chained nodes together with lines
  642. chainLength = effector->chain_length == 0 ? -1 : effector->chain_length;
  643. a = *pnode;
  644. b = a->parent;
  645. debug->AddSphere(
  646. Sphere(Vec3IK2Urho(&a->original_position), averageLength * 0.1f),
  647. Color(0, 0, 255),
  648. depthTest
  649. );
  650. debug->AddSphere(
  651. Sphere(Vec3IK2Urho(&a->position), averageLength * 0.1f),
  652. Color(255, 128, 0),
  653. depthTest
  654. );
  655. while (b && chainLength-- != 0)
  656. {
  657. debug->AddLine(
  658. Vec3IK2Urho(&a->original_position),
  659. Vec3IK2Urho(&b->original_position),
  660. Color(0, 255, 255),
  661. depthTest
  662. );
  663. debug->AddSphere(
  664. Sphere(Vec3IK2Urho(&b->original_position), averageLength * 0.1f),
  665. Color(0, 0, 255),
  666. depthTest
  667. );
  668. debug->AddLine(
  669. Vec3IK2Urho(&a->position),
  670. Vec3IK2Urho(&b->position),
  671. Color(255, 0, 0),
  672. depthTest
  673. );
  674. debug->AddSphere(
  675. Sphere(Vec3IK2Urho(&b->position), averageLength * 0.1f),
  676. Color(255, 128, 0),
  677. depthTest
  678. );
  679. a = b;
  680. b = b->parent;
  681. }
  682. ORDERED_VECTOR_END_EACH
  683. }
  684. // ----------------------------------------------------------------------------
  685. // Need these wrapper functions flags of GetFeature/SetFeature can be correctly
  686. // exposed to the editor
  687. // ----------------------------------------------------------------------------
  688. #define DEF_FEATURE_GETTER(feature_name) \
  689. bool IKSolver::Get##feature_name() const \
  690. { \
  691. return GetFeature(feature_name); \
  692. }
  693. #define DEF_FEATURE_SETTER(feature_name) \
  694. void IKSolver::Set##feature_name(bool enable) \
  695. { \
  696. SetFeature(feature_name, enable); \
  697. }
  698. DEF_FEATURE_GETTER(JOINT_ROTATIONS)
  699. DEF_FEATURE_GETTER(TARGET_ROTATIONS)
  700. DEF_FEATURE_GETTER(UPDATE_ORIGINAL_POSE)
  701. DEF_FEATURE_GETTER(UPDATE_ACTIVE_POSE)
  702. DEF_FEATURE_GETTER(USE_ORIGINAL_POSE)
  703. DEF_FEATURE_GETTER(CONSTRAINTS)
  704. DEF_FEATURE_GETTER(AUTO_SOLVE)
  705. DEF_FEATURE_SETTER(JOINT_ROTATIONS)
  706. DEF_FEATURE_SETTER(TARGET_ROTATIONS)
  707. DEF_FEATURE_SETTER(UPDATE_ORIGINAL_POSE)
  708. DEF_FEATURE_SETTER(UPDATE_ACTIVE_POSE)
  709. DEF_FEATURE_SETTER(USE_ORIGINAL_POSE)
  710. DEF_FEATURE_SETTER(CONSTRAINTS)
  711. DEF_FEATURE_SETTER(AUTO_SOLVE)
  712. } // namespace Atomic