AnimationState.cpp 16 KB

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