IKSolver.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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 Urho3D
  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, URHO3D_HANDLER(IKSolver, HandleComponentAdded));
  54. SubscribeToEvent(E_COMPONENTREMOVED, URHO3D_HANDLER(IKSolver, HandleComponentRemoved));
  55. SubscribeToEvent(E_NODEADDED, URHO3D_HANDLER(IKSolver, HandleNodeAdded));
  56. SubscribeToEvent(E_NODEREMOVED, URHO3D_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. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Algorithm", GetAlgorithm, SetAlgorithm, Algorithm, algorithmNames, FABRIK, AM_DEFAULT);
  83. URHO3D_ACCESSOR_ATTRIBUTE("Max Iterations", GetMaximumIterations, SetMaximumIterations, unsigned, 20, AM_DEFAULT);
  84. URHO3D_ACCESSOR_ATTRIBUTE("Convergence Tolerance", GetTolerance, SetTolerance, float, 0.001, AM_DEFAULT);
  85. URHO3D_ACCESSOR_ATTRIBUTE("Joint Rotations", GetJOINT_ROTATIONS, SetJOINT_ROTATIONS, bool, true, AM_DEFAULT);
  86. URHO3D_ACCESSOR_ATTRIBUTE("Target Rotations", GetTARGET_ROTATIONS, SetTARGET_ROTATIONS, bool, false, AM_DEFAULT);
  87. URHO3D_ACCESSOR_ATTRIBUTE("Update Original Pose", GetUPDATE_ORIGINAL_POSE, SetUPDATE_ORIGINAL_POSE, bool, false, AM_DEFAULT);
  88. URHO3D_ACCESSOR_ATTRIBUTE("Update Active Pose", GetUPDATE_ACTIVE_POSE, SetUPDATE_ACTIVE_POSE, bool, true, AM_DEFAULT);
  89. URHO3D_ACCESSOR_ATTRIBUTE("Use Original Pose", GetUSE_ORIGINAL_POSE, SetUSE_ORIGINAL_POSE, bool, false, AM_DEFAULT);
  90. URHO3D_ACCESSOR_ATTRIBUTE("Enable Constraints", GetCONSTRAINTS, SetCONSTRAINTS, bool, false, AM_DEFAULT);
  91. URHO3D_ACCESSOR_ATTRIBUTE("Auto Solve", GetAUTO_SOLVE, SetAUTO_SOLVE, 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, URHO3D_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. URHO3D_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. URHO3D_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. }
  334. // ----------------------------------------------------------------------------
  335. void IKSolver::CalculateJointRotations()
  336. {
  337. ik_solver_calculate_joint_rotations(solver_);
  338. }
  339. // ----------------------------------------------------------------------------
  340. void IKSolver::Solve()
  341. {
  342. URHO3D_PROFILE(IKSolve);
  343. if (treeNeedsRebuild)
  344. RebuildTree();
  345. if (chainTreesNeedUpdating_)
  346. RebuildChainTrees();
  347. if (IsSolverTreeValid() == false)
  348. return;
  349. if (features_ & UPDATE_ORIGINAL_POSE)
  350. ApplySceneToOriginalPose();
  351. if (features_ & UPDATE_ACTIVE_POSE)
  352. ApplySceneToActivePose();
  353. if (features_ & USE_ORIGINAL_POSE)
  354. ApplyOriginalPoseToActivePose();
  355. for (PODVector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it)
  356. {
  357. (*it)->UpdateTargetNodePosition();
  358. }
  359. ik_solver_solve(solver_);
  360. if (features_ & JOINT_ROTATIONS)
  361. ik_solver_calculate_joint_rotations(solver_);
  362. ApplyActivePoseToScene();
  363. }
  364. // ----------------------------------------------------------------------------
  365. static void ApplyInitialPoseToSceneCallback(ik_node_t* ikNode)
  366. {
  367. Node* node = (Node*)ikNode->user_data;
  368. node->SetWorldRotation(QuatIK2Urho(&ikNode->original_rotation));
  369. node->SetWorldPosition(Vec3IK2Urho(&ikNode->original_position));
  370. }
  371. void IKSolver::ApplyOriginalPoseToScene()
  372. {
  373. ik_solver_iterate_tree(solver_, ApplyInitialPoseToSceneCallback);
  374. }
  375. // ----------------------------------------------------------------------------
  376. static void ApplySceneToInitialPoseCallback(ik_node_t* ikNode)
  377. {
  378. Node* node = (Node*)ikNode->user_data;
  379. ikNode->original_rotation = QuatUrho2IK(node->GetWorldRotation());
  380. ikNode->original_position = Vec3Urho2IK(node->GetWorldPosition());
  381. }
  382. void IKSolver::ApplySceneToOriginalPose()
  383. {
  384. ik_solver_iterate_tree(solver_, ApplySceneToInitialPoseCallback);
  385. }
  386. // ----------------------------------------------------------------------------
  387. static void ApplyActivePoseToSceneCallback(ik_node_t* ikNode)
  388. {
  389. Node* node = (Node*)ikNode->user_data;
  390. node->SetWorldRotation(QuatIK2Urho(&ikNode->rotation));
  391. node->SetWorldPosition(Vec3IK2Urho(&ikNode->position));
  392. }
  393. void IKSolver::ApplyActivePoseToScene()
  394. {
  395. ik_solver_iterate_tree(solver_, ApplyActivePoseToSceneCallback);
  396. }
  397. // ----------------------------------------------------------------------------
  398. static void ApplySceneToActivePoseCallback(ik_node_t* ikNode)
  399. {
  400. Node* node = (Node*)ikNode->user_data;
  401. ikNode->rotation = QuatUrho2IK(node->GetWorldRotation());
  402. ikNode->position = Vec3Urho2IK(node->GetWorldPosition());
  403. }
  404. void IKSolver::ApplySceneToActivePose()
  405. {
  406. ik_solver_iterate_tree(solver_, ApplySceneToActivePoseCallback);
  407. }
  408. // ----------------------------------------------------------------------------
  409. void IKSolver::ApplyOriginalPoseToActivePose()
  410. {
  411. ik_solver_reset_to_original_pose(solver_);
  412. }
  413. // ----------------------------------------------------------------------------
  414. void IKSolver::MarkChainsNeedUpdating()
  415. {
  416. chainTreesNeedUpdating_ = true;
  417. }
  418. // ----------------------------------------------------------------------------
  419. void IKSolver::MarkTreeNeedsRebuild()
  420. {
  421. treeNeedsRebuild = true;
  422. }
  423. // ----------------------------------------------------------------------------
  424. bool IKSolver::IsSolverTreeValid() const
  425. {
  426. return solverTreeValid_;
  427. }
  428. // ----------------------------------------------------------------------------
  429. /*
  430. * This next section maintains the internal list of effector nodes. Whenever
  431. * nodes are deleted or added to the scene, or whenever components are added
  432. * or removed from nodes, we must check to see which of those nodes are/were
  433. * IK effector nodes and update our internal list accordingly.
  434. *
  435. * Unfortunately, E_COMPONENTREMOVED and E_COMPONENTADDED do not fire when a
  436. * parent node is removed/added containing child effector nodes, so we must
  437. * also monitor E_NODEREMOVED AND E_NODEADDED.
  438. */
  439. // ----------------------------------------------------------------------------
  440. void IKSolver::OnSceneSet(Scene* scene)
  441. {
  442. if (features_ & AUTO_SOLVE)
  443. SubscribeToEvent(scene, E_SCENEDRAWABLEUPDATEFINISHED, URHO3D_HANDLER(IKSolver, HandleSceneDrawableUpdateFinished));
  444. }
  445. // ----------------------------------------------------------------------------
  446. void IKSolver::OnNodeSet(Node* node)
  447. {
  448. ApplyOriginalPoseToScene();
  449. DestroyTree();
  450. if (node != NULL)
  451. RebuildTree();
  452. }
  453. // ----------------------------------------------------------------------------
  454. void IKSolver::HandleComponentAdded(StringHash eventType, VariantMap& eventData)
  455. {
  456. using namespace ComponentAdded;
  457. (void)eventType;
  458. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  459. Component* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr());
  460. /*
  461. * When a solver gets added into the scene, any parent solver's tree will
  462. * be invalidated. We need to find all parent solvers (by iterating up the
  463. * tree) and mark them as such.
  464. */
  465. if (component->GetType() == IKSolver::GetTypeStatic())
  466. {
  467. for (Node* iterNode = node; iterNode != NULL; iterNode = iterNode->GetParent())
  468. {
  469. IKSolver* parentSolver = iterNode->GetComponent<IKSolver>();
  470. if (parentSolver != NULL)
  471. parentSolver->MarkTreeNeedsRebuild();
  472. }
  473. return; // No need to continue processing effectors or constraints
  474. }
  475. if (solver_->tree == NULL)
  476. return;
  477. /*
  478. * Update tree if component is an effector and is part of our subtree.
  479. */
  480. if (component->GetType() == IKEffector::GetTypeStatic())
  481. {
  482. // Not interested in components that won't be part of our
  483. if (ComponentIsInOurSubtree(component) == false)
  484. return;
  485. BuildTreeToEffector(static_cast<IKEffector*>(component));
  486. effectorList_.Push(static_cast<IKEffector*>(component));
  487. return;
  488. }
  489. if (component->GetType() == IKConstraint::GetTypeStatic())
  490. {
  491. if (ComponentIsInOurSubtree(component) == false)
  492. return;
  493. constraintList_.Push(static_cast<IKConstraint*>(component));
  494. }
  495. }
  496. // ----------------------------------------------------------------------------
  497. void IKSolver::HandleComponentRemoved(StringHash eventType, VariantMap& eventData)
  498. {
  499. using namespace ComponentRemoved;
  500. if (solver_->tree == NULL)
  501. return;
  502. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  503. Component* component = static_cast<Component*>(eventData[P_COMPONENT].GetPtr());
  504. /*
  505. * When a solver gets added into the scene, any parent solver's tree will
  506. * be invalidated. We need to find all parent solvers (by iterating up the
  507. * tree) and mark them as such.
  508. */
  509. if (component->GetType() == IKSolver::GetTypeStatic())
  510. {
  511. for (Node* iterNode = node; iterNode != NULL; iterNode = iterNode->GetParent())
  512. {
  513. IKSolver* parentSolver = iterNode->GetComponent<IKSolver>();
  514. if (parentSolver != NULL)
  515. parentSolver->MarkTreeNeedsRebuild();
  516. }
  517. return; // No need to continue processing effectors or constraints
  518. }
  519. // If an effector was removed, the tree will have to be rebuilt.
  520. if (component->GetType() == IKEffector::GetTypeStatic())
  521. {
  522. if (ComponentIsInOurSubtree(component) == false)
  523. return;
  524. ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID());
  525. assert(ikNode != NULL);
  526. ik_node_destroy_effector(ikNode);
  527. static_cast<IKEffector*>(component)->SetIKEffectorNode(NULL);
  528. effectorList_.RemoveSwap(static_cast<IKEffector*>(component));
  529. ApplyOriginalPoseToScene();
  530. MarkTreeNeedsRebuild();
  531. return;
  532. }
  533. // Remove the ikNode* reference the IKConstraint was holding
  534. if (component->GetType() == IKConstraint::GetTypeStatic())
  535. {
  536. if (ComponentIsInOurSubtree(component) == false)
  537. return;
  538. ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID());
  539. assert(ikNode != NULL);
  540. static_cast<IKConstraint*>(component)->SetIKConstraintNode(NULL);
  541. constraintList_.RemoveSwap(static_cast<IKConstraint*>(component));
  542. }
  543. }
  544. // ----------------------------------------------------------------------------
  545. void IKSolver::HandleNodeAdded(StringHash eventType, VariantMap& eventData)
  546. {
  547. using namespace NodeAdded;
  548. if (solver_->tree == NULL)
  549. return;
  550. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  551. PODVector<IKEffector*> effectors;
  552. node->GetComponents<IKEffector>(effectors, true);
  553. for (PODVector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it)
  554. {
  555. if (ComponentIsInOurSubtree(*it) == false)
  556. continue;
  557. BuildTreeToEffector(*it);
  558. effectorList_.Push(*it);
  559. }
  560. PODVector<IKConstraint*> constraints;
  561. node->GetComponents<IKConstraint>(constraints, true);
  562. for (PODVector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it)
  563. {
  564. if (ComponentIsInOurSubtree(*it) == false)
  565. continue;
  566. constraintList_.Push(*it);
  567. }
  568. }
  569. // ----------------------------------------------------------------------------
  570. void IKSolver::HandleNodeRemoved(StringHash eventType, VariantMap& eventData)
  571. {
  572. using namespace NodeRemoved;
  573. if (solver_->tree == NULL)
  574. return;
  575. Node* node = static_cast<Node*>(eventData[P_NODE].GetPtr());
  576. // Remove cached IKEffectors from our list
  577. PODVector<IKEffector*> effectors;
  578. node->GetComponents<IKEffector>(effectors, true);
  579. for (PODVector<IKEffector*>::ConstIterator it = effectors.Begin(); it != effectors.End(); ++it)
  580. {
  581. (*it)->SetIKEffectorNode(NULL);
  582. effectorList_.RemoveSwap(*it);
  583. }
  584. PODVector<IKConstraint*> constraints;
  585. node->GetComponents<IKConstraint>(constraints, true);
  586. for (PODVector<IKConstraint*>::ConstIterator it = constraints.Begin(); it != constraints.End(); ++it)
  587. {
  588. constraintList_.RemoveSwap(*it);
  589. }
  590. // Special case, if the node being destroyed is the root node, destroy the
  591. // solver's tree instead of destroying the single node. Calling
  592. // ik_node_destroy() on the solver's root node will cause segfaults.
  593. ik_node_t* ikNode = ik_node_find_child(solver_->tree, node->GetID());
  594. if (ikNode != NULL)
  595. {
  596. if (ikNode == solver_->tree)
  597. ik_solver_destroy_tree(solver_);
  598. else
  599. ik_node_destroy(ikNode);
  600. MarkChainsNeedUpdating();
  601. }
  602. }
  603. // ----------------------------------------------------------------------------
  604. void IKSolver::HandleSceneDrawableUpdateFinished(StringHash eventType, VariantMap& eventData)
  605. {
  606. Solve();
  607. }
  608. // ----------------------------------------------------------------------------
  609. void IKSolver::DrawDebugGeometry(bool depthTest)
  610. {
  611. DebugRenderer* debug = GetScene()->GetComponent<DebugRenderer>();
  612. if (debug)
  613. DrawDebugGeometry(debug, depthTest);
  614. }
  615. // ----------------------------------------------------------------------------
  616. void IKSolver::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  617. {
  618. // Draws all scene segments
  619. for (PODVector<IKEffector*>::ConstIterator it = effectorList_.Begin(); it != effectorList_.End(); ++it)
  620. (*it)->DrawDebugGeometry(debug, depthTest);
  621. ORDERED_VECTOR_FOR_EACH(&solver_->effector_nodes_list, ik_node_t*, pnode)
  622. ik_effector_t* effector = (*pnode)->effector;
  623. // Calculate average length of all segments so we can determine the radius
  624. // of the debug spheres to draw
  625. int chainLength = effector->chain_length == 0 ? -1 : effector->chain_length;
  626. ik_node_t* a = *pnode;
  627. ik_node_t* b = a->parent;
  628. float averageLength = 0.0f;
  629. unsigned numberOfSegments = 0;
  630. while (b && chainLength-- != 0)
  631. {
  632. vec3_t v = a->original_position;
  633. vec3_sub_vec3(v.f, b->original_position.f);
  634. averageLength += vec3_length(v.f);
  635. ++numberOfSegments;
  636. a = b;
  637. b = b->parent;
  638. }
  639. averageLength /= numberOfSegments;
  640. // connect all chained nodes together with lines
  641. chainLength = effector->chain_length == 0 ? -1 : effector->chain_length;
  642. a = *pnode;
  643. b = a->parent;
  644. debug->AddSphere(
  645. Sphere(Vec3IK2Urho(&a->original_position), averageLength * 0.1f),
  646. Color(0, 0, 255),
  647. depthTest
  648. );
  649. debug->AddSphere(
  650. Sphere(Vec3IK2Urho(&a->position), averageLength * 0.1f),
  651. Color(255, 128, 0),
  652. depthTest
  653. );
  654. while (b && chainLength-- != 0)
  655. {
  656. debug->AddLine(
  657. Vec3IK2Urho(&a->original_position),
  658. Vec3IK2Urho(&b->original_position),
  659. Color(0, 255, 255),
  660. depthTest
  661. );
  662. debug->AddSphere(
  663. Sphere(Vec3IK2Urho(&b->original_position), averageLength * 0.1f),
  664. Color(0, 0, 255),
  665. depthTest
  666. );
  667. debug->AddLine(
  668. Vec3IK2Urho(&a->position),
  669. Vec3IK2Urho(&b->position),
  670. Color(255, 0, 0),
  671. depthTest
  672. );
  673. debug->AddSphere(
  674. Sphere(Vec3IK2Urho(&b->position), averageLength * 0.1f),
  675. Color(255, 128, 0),
  676. depthTest
  677. );
  678. a = b;
  679. b = b->parent;
  680. }
  681. ORDERED_VECTOR_END_EACH
  682. }
  683. // ----------------------------------------------------------------------------
  684. // Need these wrapper functions flags of GetFeature/SetFeature can be correctly
  685. // exposed to the editor
  686. // ----------------------------------------------------------------------------
  687. #define DEF_FEATURE_GETTER(feature_name) \
  688. bool IKSolver::Get##feature_name() const \
  689. { \
  690. return GetFeature(feature_name); \
  691. }
  692. #define DEF_FEATURE_SETTER(feature_name) \
  693. void IKSolver::Set##feature_name(bool enable) \
  694. { \
  695. SetFeature(feature_name, enable); \
  696. }
  697. DEF_FEATURE_GETTER(JOINT_ROTATIONS)
  698. DEF_FEATURE_GETTER(TARGET_ROTATIONS)
  699. DEF_FEATURE_GETTER(UPDATE_ORIGINAL_POSE)
  700. DEF_FEATURE_GETTER(UPDATE_ACTIVE_POSE)
  701. DEF_FEATURE_GETTER(USE_ORIGINAL_POSE)
  702. DEF_FEATURE_GETTER(CONSTRAINTS)
  703. DEF_FEATURE_GETTER(AUTO_SOLVE)
  704. DEF_FEATURE_SETTER(JOINT_ROTATIONS)
  705. DEF_FEATURE_SETTER(TARGET_ROTATIONS)
  706. DEF_FEATURE_SETTER(UPDATE_ORIGINAL_POSE)
  707. DEF_FEATURE_SETTER(UPDATE_ACTIVE_POSE)
  708. DEF_FEATURE_SETTER(USE_ORIGINAL_POSE)
  709. DEF_FEATURE_SETTER(CONSTRAINTS)
  710. DEF_FEATURE_SETTER(AUTO_SOLVE)
  711. } // namespace Urho3D