AnimationState.cpp 17 KB

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