AnimationState.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. //
  2. // Copyright (c) 2008-2015 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 "../Graphics/AnimatedModel.h"
  24. #include "../Graphics/Animation.h"
  25. #include "../Graphics/AnimationState.h"
  26. #include "../Graphics/DrawableEvents.h"
  27. #include "../IO/Log.h"
  28. #include "../DebugNew.h"
  29. namespace Urho3D
  30. {
  31. AnimationStateTrack::AnimationStateTrack() :
  32. track_(0),
  33. bone_(0),
  34. weight_(1.0f),
  35. keyFrame_(0)
  36. {
  37. }
  38. AnimationStateTrack::~AnimationStateTrack()
  39. {
  40. }
  41. AnimationState::AnimationState(AnimatedModel* model, Animation* animation) :
  42. model_(model),
  43. animation_(animation),
  44. startBone_(0),
  45. looped_(false),
  46. weight_(0.0f),
  47. time_(0.0f),
  48. layer_(0)
  49. {
  50. // Set default start bone (use all tracks.)
  51. SetStartBone(0);
  52. }
  53. AnimationState::AnimationState(Node* node, Animation* animation) :
  54. node_(node),
  55. animation_(animation),
  56. startBone_(0),
  57. looped_(false),
  58. weight_(1.0f),
  59. time_(0.0f),
  60. layer_(0)
  61. {
  62. if (animation_)
  63. {
  64. // Setup animation track to scene node mapping
  65. if (node_)
  66. {
  67. const HashMap<StringHash, AnimationTrack>& tracks = animation_->GetTracks();
  68. stateTracks_.Clear();
  69. for (HashMap<StringHash, AnimationTrack>::ConstIterator i = tracks.Begin(); i != tracks.End(); ++i)
  70. {
  71. const StringHash& nameHash = i->second_.nameHash_;
  72. AnimationStateTrack stateTrack;
  73. stateTrack.track_ = &i->second_;
  74. if (node_->GetNameHash() == nameHash || tracks.Size() == 1)
  75. stateTrack.node_ = node_;
  76. else
  77. {
  78. Node* targetNode = node_->GetChild(nameHash, true);
  79. if (targetNode)
  80. stateTrack.node_ = targetNode;
  81. else
  82. URHO3D_LOGWARNING("Node " + i->second_.name_ + " not found for node animation " + animation_->GetName());
  83. }
  84. if (stateTrack.node_)
  85. stateTracks_.Push(stateTrack);
  86. }
  87. }
  88. }
  89. }
  90. AnimationState::~AnimationState()
  91. {
  92. }
  93. void AnimationState::SetStartBone(Bone* startBone)
  94. {
  95. if (!model_ || !animation_)
  96. return;
  97. Skeleton& skeleton = model_->GetSkeleton();
  98. if (!startBone)
  99. {
  100. Bone* rootBone = skeleton.GetRootBone();
  101. if (!rootBone)
  102. return;
  103. startBone = rootBone;
  104. }
  105. // Do not reassign if the start bone did not actually change, and we already have valid bone nodes
  106. if (startBone == startBone_ && !stateTracks_.Empty())
  107. return;
  108. startBone_ = startBone;
  109. const HashMap<StringHash, AnimationTrack>& tracks = animation_->GetTracks();
  110. stateTracks_.Clear();
  111. if (!startBone->node_)
  112. return;
  113. for (HashMap<StringHash, AnimationTrack>::ConstIterator i = tracks.Begin(); i != tracks.End(); ++i)
  114. {
  115. AnimationStateTrack stateTrack;
  116. stateTrack.track_ = &i->second_;
  117. // Include those tracks that are either the start bone itself, or its children
  118. Bone* trackBone = 0;
  119. const StringHash& nameHash = i->second_.nameHash_;
  120. if (nameHash == startBone->nameHash_)
  121. trackBone = startBone;
  122. else
  123. {
  124. Node* trackBoneNode = startBone->node_->GetChild(nameHash, true);
  125. if (trackBoneNode)
  126. trackBone = skeleton.GetBone(nameHash);
  127. }
  128. if (trackBone && trackBone->node_)
  129. {
  130. stateTrack.bone_ = trackBone;
  131. stateTrack.node_ = trackBone->node_;
  132. stateTracks_.Push(stateTrack);
  133. }
  134. }
  135. model_->MarkAnimationDirty();
  136. }
  137. void AnimationState::SetLooped(bool looped)
  138. {
  139. looped_ = looped;
  140. }
  141. void AnimationState::SetWeight(float weight)
  142. {
  143. // Weight can only be set in model mode. In node animation it is hardcoded to full
  144. if (model_)
  145. {
  146. weight = Clamp(weight, 0.0f, 1.0f);
  147. if (weight != weight_)
  148. {
  149. weight_ = weight;
  150. model_->MarkAnimationDirty();
  151. }
  152. }
  153. }
  154. void AnimationState::SetTime(float time)
  155. {
  156. if (!animation_)
  157. return;
  158. time = Clamp(time, 0.0f, animation_->GetLength());
  159. if (time != time_)
  160. {
  161. time_ = time;
  162. if (model_)
  163. model_->MarkAnimationDirty();
  164. }
  165. }
  166. void AnimationState::SetBoneWeight(unsigned index, float weight, bool recursive)
  167. {
  168. if (index >= stateTracks_.Size())
  169. return;
  170. weight = Clamp(weight, 0.0f, 1.0f);
  171. if (weight != stateTracks_[index].weight_)
  172. {
  173. stateTracks_[index].weight_ = weight;
  174. if (model_)
  175. model_->MarkAnimationDirty();
  176. }
  177. if (recursive)
  178. {
  179. Node* boneNode = stateTracks_[index].node_;
  180. if (boneNode)
  181. {
  182. const Vector<SharedPtr<Node> >& children = boneNode->GetChildren();
  183. for (unsigned i = 0; i < children.Size(); ++i)
  184. {
  185. unsigned childTrackIndex = GetTrackIndex(children[i]);
  186. if (childTrackIndex != M_MAX_UNSIGNED)
  187. SetBoneWeight(childTrackIndex, weight, true);
  188. }
  189. }
  190. }
  191. }
  192. void AnimationState::SetBoneWeight(const String& name, float weight, bool recursive)
  193. {
  194. SetBoneWeight(GetTrackIndex(name), weight, recursive);
  195. }
  196. void AnimationState::SetBoneWeight(StringHash nameHash, float weight, bool recursive)
  197. {
  198. SetBoneWeight(GetTrackIndex(nameHash), weight, recursive);
  199. }
  200. void AnimationState::AddWeight(float delta)
  201. {
  202. if (delta == 0.0f)
  203. return;
  204. SetWeight(GetWeight() + delta);
  205. }
  206. void AnimationState::AddTime(float delta)
  207. {
  208. if (!animation_ || (!model_ && !node_))
  209. return;
  210. float length = animation_->GetLength();
  211. if (delta == 0.0f || length == 0.0f)
  212. return;
  213. bool sendFinishEvent = false;
  214. float oldTime = GetTime();
  215. float time = oldTime + delta;
  216. if (looped_)
  217. {
  218. while (time >= length)
  219. {
  220. time -= length;
  221. sendFinishEvent = true;
  222. }
  223. while (time < 0.0f)
  224. {
  225. time += length;
  226. sendFinishEvent = true;
  227. }
  228. }
  229. SetTime(time);
  230. if (!looped_)
  231. {
  232. if (delta > 0.0f && oldTime < length && GetTime() == length)
  233. sendFinishEvent = true;
  234. else if (delta < 0.0f && oldTime > 0.0f && GetTime() == 0.0f)
  235. sendFinishEvent = true;
  236. }
  237. // Process finish event
  238. if (sendFinishEvent)
  239. {
  240. using namespace AnimationFinished;
  241. WeakPtr<AnimationState> self(this);
  242. WeakPtr<Node> senderNode(model_ ? model_->GetNode() : node_);
  243. VariantMap& eventData = senderNode->GetEventDataMap();
  244. eventData[P_NODE] = senderNode;
  245. eventData[P_ANIMATION] = animation_;
  246. eventData[P_NAME] = animation_->GetAnimationName();
  247. eventData[P_LOOPED] = looped_;
  248. // Note: this may cause arbitrary deletion of animation states, including the one we are currently processing
  249. senderNode->SendEvent(E_ANIMATIONFINISHED, eventData);
  250. if (senderNode.Expired() || self.Expired())
  251. return;
  252. }
  253. // Process animation triggers
  254. if (animation_->GetNumTriggers())
  255. {
  256. bool wrap = false;
  257. if (delta > 0.0f)
  258. {
  259. if (oldTime > time)
  260. {
  261. oldTime -= length;
  262. wrap = true;
  263. }
  264. }
  265. if (delta < 0.0f)
  266. {
  267. if (time > oldTime)
  268. {
  269. time -= length;
  270. wrap = true;
  271. }
  272. }
  273. if (oldTime > time)
  274. Swap(oldTime, time);
  275. const Vector<AnimationTriggerPoint>& triggers = animation_->GetTriggers();
  276. for (Vector<AnimationTriggerPoint>::ConstIterator i = triggers.Begin(); i != triggers.End(); ++i)
  277. {
  278. float frameTime = i->time_;
  279. if (looped_ && wrap)
  280. frameTime = fmodf(frameTime, length);
  281. if (oldTime <= frameTime && time > frameTime)
  282. {
  283. using namespace AnimationTrigger;
  284. WeakPtr<AnimationState> self(this);
  285. WeakPtr<Node> senderNode(model_ ? model_->GetNode() : node_);
  286. VariantMap& eventData = senderNode->GetEventDataMap();
  287. eventData[P_NODE] = senderNode;
  288. eventData[P_ANIMATION] = animation_;
  289. eventData[P_NAME] = animation_->GetAnimationName();
  290. eventData[P_TIME] = i->time_;
  291. eventData[P_DATA] = i->data_;
  292. // Note: this may cause arbitrary deletion of animation states, including the one we are currently processing
  293. senderNode->SendEvent(E_ANIMATIONTRIGGER, eventData);
  294. if (senderNode.Expired() || self.Expired())
  295. return;
  296. }
  297. }
  298. }
  299. }
  300. void AnimationState::SetLayer(unsigned char layer)
  301. {
  302. if (layer != layer_)
  303. {
  304. layer_ = layer;
  305. if (model_)
  306. model_->MarkAnimationOrderDirty();
  307. }
  308. }
  309. AnimatedModel* AnimationState::GetModel() const
  310. {
  311. return model_;
  312. }
  313. Node* AnimationState::GetNode() const
  314. {
  315. return node_;
  316. }
  317. Bone* AnimationState::GetStartBone() const
  318. {
  319. return model_ ? startBone_ : 0;
  320. }
  321. float AnimationState::GetBoneWeight(unsigned index) const
  322. {
  323. return index < stateTracks_.Size() ? stateTracks_[index].weight_ : 0.0f;
  324. }
  325. float AnimationState::GetBoneWeight(const String& name) const
  326. {
  327. return GetBoneWeight(GetTrackIndex(name));
  328. }
  329. float AnimationState::GetBoneWeight(StringHash nameHash) const
  330. {
  331. return GetBoneWeight(GetTrackIndex(nameHash));
  332. }
  333. unsigned AnimationState::GetTrackIndex(const String& name) const
  334. {
  335. for (unsigned i = 0; i < stateTracks_.Size(); ++i)
  336. {
  337. Node* node = stateTracks_[i].node_;
  338. if (node && node->GetName() == name)
  339. return i;
  340. }
  341. return M_MAX_UNSIGNED;
  342. }
  343. unsigned AnimationState::GetTrackIndex(Node* node) const
  344. {
  345. for (unsigned i = 0; i < stateTracks_.Size(); ++i)
  346. {
  347. if (stateTracks_[i].node_ == node)
  348. return i;
  349. }
  350. return M_MAX_UNSIGNED;
  351. }
  352. unsigned AnimationState::GetTrackIndex(StringHash nameHash) const
  353. {
  354. for (unsigned i = 0; i < stateTracks_.Size(); ++i)
  355. {
  356. Node* node = stateTracks_[i].node_;
  357. if (node && node->GetNameHash() == nameHash)
  358. return i;
  359. }
  360. return M_MAX_UNSIGNED;
  361. }
  362. float AnimationState::GetLength() const
  363. {
  364. return animation_ ? animation_->GetLength() : 0.0f;
  365. }
  366. void AnimationState::Apply()
  367. {
  368. if (!animation_ || !IsEnabled())
  369. return;
  370. if (model_)
  371. ApplyToModel();
  372. else
  373. ApplyToNodes();
  374. }
  375. void AnimationState::ApplyToModel()
  376. {
  377. for (Vector<AnimationStateTrack>::Iterator i = stateTracks_.Begin(); i != stateTracks_.End(); ++i)
  378. {
  379. AnimationStateTrack& stateTrack = *i;
  380. float finalWeight = weight_ * stateTrack.weight_;
  381. // Do not apply if zero effective weight or the bone has animation disabled
  382. if (Equals(finalWeight, 0.0f) || !stateTrack.bone_->animated_)
  383. continue;
  384. if (Equals(finalWeight, 1.0f))
  385. ApplyTrackFullWeightSilent(stateTrack);
  386. else
  387. ApplyTrackBlendedSilent(stateTrack, finalWeight);
  388. }
  389. }
  390. void AnimationState::ApplyToNodes()
  391. {
  392. // When applying to a node hierarchy, can only use full weight (nothing to blend to)
  393. for (Vector<AnimationStateTrack>::Iterator i = stateTracks_.Begin(); i != stateTracks_.End(); ++i)
  394. ApplyTrackFullWeight(*i);
  395. }
  396. void AnimationState::ApplyTrackFullWeight(AnimationStateTrack& stateTrack)
  397. {
  398. const AnimationTrack* track = stateTrack.track_;
  399. Node* node = stateTrack.node_;
  400. if (track->keyFrames_.Empty() || !node)
  401. return;
  402. unsigned& frame = stateTrack.keyFrame_;
  403. track->GetKeyFrameIndex(time_, frame);
  404. // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
  405. unsigned nextFrame = frame + 1;
  406. bool interpolate = true;
  407. if (nextFrame >= track->keyFrames_.Size())
  408. {
  409. if (!looped_)
  410. {
  411. nextFrame = frame;
  412. interpolate = false;
  413. }
  414. else
  415. nextFrame = 0;
  416. }
  417. const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
  418. unsigned char channelMask = track->channelMask_;
  419. if (!interpolate)
  420. {
  421. // No interpolation, full weight
  422. if (channelMask & CHANNEL_POSITION)
  423. node->SetPosition(keyFrame->position_);
  424. if (channelMask & CHANNEL_ROTATION)
  425. node->SetRotation(keyFrame->rotation_);
  426. if (channelMask & CHANNEL_SCALE)
  427. node->SetScale(keyFrame->scale_);
  428. }
  429. else
  430. {
  431. const AnimationKeyFrame* nextKeyFrame = &track->keyFrames_[nextFrame];
  432. float timeInterval = nextKeyFrame->time_ - keyFrame->time_;
  433. if (timeInterval < 0.0f)
  434. timeInterval += animation_->GetLength();
  435. float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
  436. // Interpolation, full weight
  437. if (channelMask & CHANNEL_POSITION)
  438. node->SetPosition(keyFrame->position_.Lerp(nextKeyFrame->position_, t));
  439. if (channelMask & CHANNEL_ROTATION)
  440. node->SetRotation(keyFrame->rotation_.Slerp(nextKeyFrame->rotation_, t));
  441. if (channelMask & CHANNEL_SCALE)
  442. node->SetScale(keyFrame->scale_.Lerp(nextKeyFrame->scale_, t));
  443. }
  444. }
  445. void AnimationState::ApplyTrackFullWeightSilent(AnimationStateTrack& stateTrack)
  446. {
  447. const AnimationTrack* track = stateTrack.track_;
  448. Node* node = stateTrack.node_;
  449. if (track->keyFrames_.Empty() || !node)
  450. return;
  451. unsigned& frame = stateTrack.keyFrame_;
  452. track->GetKeyFrameIndex(time_, frame);
  453. // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
  454. unsigned nextFrame = frame + 1;
  455. bool interpolate = true;
  456. if (nextFrame >= track->keyFrames_.Size())
  457. {
  458. if (!looped_)
  459. {
  460. nextFrame = frame;
  461. interpolate = false;
  462. }
  463. else
  464. nextFrame = 0;
  465. }
  466. const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
  467. unsigned char channelMask = track->channelMask_;
  468. if (!interpolate)
  469. {
  470. // No interpolation, full weight
  471. if (channelMask & CHANNEL_POSITION)
  472. node->SetPositionSilent(keyFrame->position_);
  473. if (channelMask & CHANNEL_ROTATION)
  474. node->SetRotationSilent(keyFrame->rotation_);
  475. if (channelMask & CHANNEL_SCALE)
  476. node->SetScaleSilent(keyFrame->scale_);
  477. }
  478. else
  479. {
  480. const AnimationKeyFrame* nextKeyFrame = &track->keyFrames_[nextFrame];
  481. float timeInterval = nextKeyFrame->time_ - keyFrame->time_;
  482. if (timeInterval < 0.0f)
  483. timeInterval += animation_->GetLength();
  484. float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
  485. // Interpolation, full weight
  486. if (channelMask & CHANNEL_POSITION)
  487. node->SetPositionSilent(keyFrame->position_.Lerp(nextKeyFrame->position_, t));
  488. if (channelMask & CHANNEL_ROTATION)
  489. node->SetRotationSilent(keyFrame->rotation_.Slerp(nextKeyFrame->rotation_, t));
  490. if (channelMask & CHANNEL_SCALE)
  491. node->SetScaleSilent(keyFrame->scale_.Lerp(nextKeyFrame->scale_, t));
  492. }
  493. }
  494. void AnimationState::ApplyTrackBlendedSilent(AnimationStateTrack& stateTrack, float weight)
  495. {
  496. const AnimationTrack* track = stateTrack.track_;
  497. Node* node = stateTrack.node_;
  498. if (track->keyFrames_.Empty() || !node)
  499. return;
  500. unsigned& frame = stateTrack.keyFrame_;
  501. track->GetKeyFrameIndex(time_, frame);
  502. // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
  503. unsigned nextFrame = frame + 1;
  504. bool interpolate = true;
  505. if (nextFrame >= track->keyFrames_.Size())
  506. {
  507. if (!looped_)
  508. {
  509. nextFrame = frame;
  510. interpolate = false;
  511. }
  512. else
  513. nextFrame = 0;
  514. }
  515. const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
  516. unsigned char channelMask = track->channelMask_;
  517. if (!interpolate)
  518. {
  519. // No interpolation, blend between old transform & animation
  520. if (channelMask & CHANNEL_POSITION)
  521. node->SetPositionSilent(node->GetPosition().Lerp(keyFrame->position_, weight));
  522. if (channelMask & CHANNEL_ROTATION)
  523. node->SetRotationSilent(node->GetRotation().Slerp(keyFrame->rotation_, weight));
  524. if (channelMask & CHANNEL_SCALE)
  525. node->SetScaleSilent(node->GetScale().Lerp(keyFrame->scale_, weight));
  526. }
  527. else
  528. {
  529. const AnimationKeyFrame* nextKeyFrame = &track->keyFrames_[nextFrame];
  530. float timeInterval = nextKeyFrame->time_ - keyFrame->time_;
  531. if (timeInterval < 0.0f)
  532. timeInterval += animation_->GetLength();
  533. float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
  534. // Interpolation, blend between old transform & animation
  535. if (channelMask & CHANNEL_POSITION)
  536. {
  537. node->SetPositionSilent(node->GetPosition().Lerp(
  538. keyFrame->position_.Lerp(nextKeyFrame->position_, t), weight));
  539. }
  540. if (channelMask & CHANNEL_ROTATION)
  541. {
  542. node->SetRotationSilent(node->GetRotation().Slerp(
  543. keyFrame->rotation_.Slerp(nextKeyFrame->rotation_, t), weight));
  544. }
  545. if (channelMask & CHANNEL_SCALE)
  546. {
  547. node->SetScaleSilent(node->GetScale().Lerp(
  548. keyFrame->scale_.Lerp(nextKeyFrame->scale_, t), weight));
  549. }
  550. }
  551. }
  552. }