AnimationState.cpp 17 KB

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