AnimationController.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/AnimatedModel.h"
  26. #include "../Graphics/Animation.h"
  27. #include "../Graphics/AnimationController.h"
  28. #include "../Graphics/AnimationState.h"
  29. #include "../IO/FileSystem.h"
  30. #include "../IO/Log.h"
  31. #include "../IO/MemoryBuffer.h"
  32. #include "../Resource/ResourceCache.h"
  33. #include "../Scene/Scene.h"
  34. #include "../Scene/SceneEvents.h"
  35. #include "../DebugNew.h"
  36. namespace Urho3D
  37. {
  38. static const unsigned char CTRL_LOOPED = 0x1;
  39. static const unsigned char CTRL_STARTBONE = 0x2;
  40. static const unsigned char CTRL_AUTOFADE = 0x4;
  41. static const unsigned char CTRL_SETTIME = 0x08;
  42. static const unsigned char CTRL_SETWEIGHT = 0x10;
  43. static const unsigned char CTRL_REMOVEONCOMPLETION = 0x20;
  44. static const unsigned char CTRL_ADDITIVE = 0x40;
  45. static const float EXTRA_ANIM_FADEOUT_TIME = 0.1f;
  46. static const float COMMAND_STAY_TIME = 0.25f;
  47. static const unsigned MAX_NODE_ANIMATION_STATES = 256;
  48. extern const char* LOGIC_CATEGORY;
  49. AnimationController::AnimationController(Context* context) :
  50. Component(context)
  51. {
  52. }
  53. AnimationController::~AnimationController() = default;
  54. void AnimationController::RegisterObject(Context* context)
  55. {
  56. context->RegisterFactory<AnimationController>(LOGIC_CATEGORY);
  57. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  58. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Animations", GetAnimationsAttr, SetAnimationsAttr, VariantVector, Variant::emptyVariantVector,
  59. AM_FILE | AM_NOEDIT);
  60. URHO3D_ACCESSOR_ATTRIBUTE("Network Animations", GetNetAnimationsAttr, SetNetAnimationsAttr, PODVector<unsigned char>,
  61. Variant::emptyBuffer, AM_NET | AM_LATESTDATA | AM_NOEDIT);
  62. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Node Animation States", GetNodeAnimationStatesAttr, SetNodeAnimationStatesAttr, VariantVector,
  63. Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  64. }
  65. void AnimationController::OnSetEnabled()
  66. {
  67. Scene* scene = GetScene();
  68. if (scene)
  69. {
  70. if (IsEnabledEffective())
  71. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, URHO3D_HANDLER(AnimationController, HandleScenePostUpdate));
  72. else
  73. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  74. }
  75. }
  76. void AnimationController::Update(float timeStep)
  77. {
  78. // Loop through animations
  79. for (unsigned i = 0; i < animations_.Size();)
  80. {
  81. AnimationControl& ctrl = animations_[i];
  82. AnimationState* state = GetAnimationState(ctrl.hash_);
  83. bool remove = false;
  84. if (!state)
  85. remove = true;
  86. else
  87. {
  88. // Advance the animation
  89. if (ctrl.speed_ != 0.0f)
  90. state->AddTime(ctrl.speed_ * timeStep);
  91. float targetWeight = ctrl.targetWeight_;
  92. float fadeTime = ctrl.fadeTime_;
  93. // If non-looped animation at the end, activate autofade as applicable
  94. if (!state->IsLooped() && state->GetTime() >= state->GetLength() && ctrl.autoFadeTime_ > 0.0f)
  95. {
  96. targetWeight = 0.0f;
  97. fadeTime = ctrl.autoFadeTime_;
  98. }
  99. // Process weight fade
  100. float currentWeight = state->GetWeight();
  101. if (currentWeight != targetWeight)
  102. {
  103. if (fadeTime > 0.0f)
  104. {
  105. float weightDelta = 1.0f / fadeTime * timeStep;
  106. if (currentWeight < targetWeight)
  107. currentWeight = Min(currentWeight + weightDelta, targetWeight);
  108. else if (currentWeight > targetWeight)
  109. currentWeight = Max(currentWeight - weightDelta, targetWeight);
  110. state->SetWeight(currentWeight);
  111. }
  112. else
  113. state->SetWeight(targetWeight);
  114. }
  115. // Remove if weight zero and target weight zero
  116. if (state->GetWeight() == 0.0f && (targetWeight == 0.0f || fadeTime == 0.0f) && ctrl.removeOnCompletion_)
  117. remove = true;
  118. }
  119. // Decrement the command time-to-live values
  120. if (ctrl.setTimeTtl_ > 0.0f)
  121. ctrl.setTimeTtl_ = Max(ctrl.setTimeTtl_ - timeStep, 0.0f);
  122. if (ctrl.setWeightTtl_ > 0.0f)
  123. ctrl.setWeightTtl_ = Max(ctrl.setWeightTtl_ - timeStep, 0.0f);
  124. if (remove)
  125. {
  126. if (state)
  127. RemoveAnimationState(state);
  128. animations_.Erase(i);
  129. MarkNetworkUpdate();
  130. }
  131. else
  132. ++i;
  133. }
  134. // Node hierarchy animations need to be applied manually
  135. for (Vector<SharedPtr<AnimationState> >::Iterator i = nodeAnimationStates_.Begin(); i != nodeAnimationStates_.End(); ++i)
  136. (*i)->Apply();
  137. }
  138. bool AnimationController::Play(const String& name, unsigned char layer, bool looped, float fadeInTime)
  139. {
  140. // Get the animation resource first to be able to get the canonical resource name
  141. // (avoids potential adding of duplicate animations)
  142. auto* newAnimation = GetSubsystem<ResourceCache>()->GetResource<Animation>(name);
  143. if (!newAnimation)
  144. return false;
  145. // Check if already exists
  146. unsigned index;
  147. AnimationState* state;
  148. FindAnimation(newAnimation->GetName(), index, state);
  149. if (!state)
  150. {
  151. state = AddAnimationState(newAnimation);
  152. if (!state)
  153. return false;
  154. }
  155. if (index == M_MAX_UNSIGNED)
  156. {
  157. AnimationControl newControl;
  158. newControl.name_ = newAnimation->GetName();
  159. newControl.hash_ = newAnimation->GetNameHash();
  160. animations_.Push(newControl);
  161. index = animations_.Size() - 1;
  162. }
  163. state->SetLayer(layer);
  164. state->SetLooped(looped);
  165. animations_[index].targetWeight_ = 1.0f;
  166. animations_[index].fadeTime_ = fadeInTime;
  167. MarkNetworkUpdate();
  168. return true;
  169. }
  170. bool AnimationController::PlayExclusive(const String& name, unsigned char layer, bool looped, float fadeTime)
  171. {
  172. bool success = Play(name, layer, looped, fadeTime);
  173. // Fade other animations only if successfully started the new one
  174. if (success)
  175. FadeOthers(name, 0.0f, fadeTime);
  176. return success;
  177. }
  178. bool AnimationController::Stop(const String& name, float fadeOutTime)
  179. {
  180. unsigned index;
  181. AnimationState* state;
  182. FindAnimation(name, index, state);
  183. if (index != M_MAX_UNSIGNED)
  184. {
  185. animations_[index].targetWeight_ = 0.0f;
  186. animations_[index].fadeTime_ = fadeOutTime;
  187. MarkNetworkUpdate();
  188. }
  189. return index != M_MAX_UNSIGNED || state != nullptr;
  190. }
  191. void AnimationController::StopLayer(unsigned char layer, float fadeOutTime)
  192. {
  193. bool needUpdate = false;
  194. for (Vector<AnimationControl>::Iterator i = animations_.Begin(); i != animations_.End(); ++i)
  195. {
  196. AnimationState* state = GetAnimationState(i->hash_);
  197. if (state && state->GetLayer() == layer)
  198. {
  199. i->targetWeight_ = 0.0f;
  200. i->fadeTime_ = fadeOutTime;
  201. needUpdate = true;
  202. }
  203. }
  204. if (needUpdate)
  205. MarkNetworkUpdate();
  206. }
  207. void AnimationController::StopAll(float fadeOutTime)
  208. {
  209. if (animations_.Size())
  210. {
  211. for (Vector<AnimationControl>::Iterator i = animations_.Begin(); i != animations_.End(); ++i)
  212. {
  213. i->targetWeight_ = 0.0f;
  214. i->fadeTime_ = fadeOutTime;
  215. }
  216. MarkNetworkUpdate();
  217. }
  218. }
  219. bool AnimationController::Fade(const String& name, float targetWeight, float fadeTime)
  220. {
  221. unsigned index;
  222. AnimationState* state;
  223. FindAnimation(name, index, state);
  224. if (index == M_MAX_UNSIGNED)
  225. return false;
  226. animations_[index].targetWeight_ = Clamp(targetWeight, 0.0f, 1.0f);
  227. animations_[index].fadeTime_ = fadeTime;
  228. MarkNetworkUpdate();
  229. return true;
  230. }
  231. bool AnimationController::FadeOthers(const String& name, float targetWeight, float fadeTime)
  232. {
  233. unsigned index;
  234. AnimationState* state;
  235. FindAnimation(name, index, state);
  236. if (index == M_MAX_UNSIGNED || !state)
  237. return false;
  238. unsigned char layer = state->GetLayer();
  239. bool needUpdate = false;
  240. for (unsigned i = 0; i < animations_.Size(); ++i)
  241. {
  242. if (i != index)
  243. {
  244. AnimationControl& control = animations_[i];
  245. AnimationState* otherState = GetAnimationState(control.hash_);
  246. if (otherState && otherState->GetLayer() == layer)
  247. {
  248. control.targetWeight_ = Clamp(targetWeight, 0.0f, 1.0f);
  249. control.fadeTime_ = fadeTime;
  250. needUpdate = true;
  251. }
  252. }
  253. }
  254. if (needUpdate)
  255. MarkNetworkUpdate();
  256. return true;
  257. }
  258. bool AnimationController::SetLayer(const String& name, unsigned char layer)
  259. {
  260. AnimationState* state = GetAnimationState(name);
  261. if (!state)
  262. return false;
  263. state->SetLayer(layer);
  264. MarkNetworkUpdate();
  265. return true;
  266. }
  267. bool AnimationController::SetStartBone(const String& name, const String& startBoneName)
  268. {
  269. // Start bone can only be set in model mode
  270. auto* model = GetComponent<AnimatedModel>();
  271. if (!model)
  272. return false;
  273. AnimationState* state = model->GetAnimationState(name);
  274. if (!state)
  275. return false;
  276. Bone* bone = model->GetSkeleton().GetBone(startBoneName);
  277. state->SetStartBone(bone);
  278. MarkNetworkUpdate();
  279. return true;
  280. }
  281. bool AnimationController::SetTime(const String& name, float time)
  282. {
  283. unsigned index;
  284. AnimationState* state;
  285. FindAnimation(name, index, state);
  286. if (index == M_MAX_UNSIGNED || !state)
  287. return false;
  288. time = Clamp(time, 0.0f, state->GetLength());
  289. state->SetTime(time);
  290. // Prepare "set time" command for network replication
  291. animations_[index].setTime_ = (unsigned short)(time / state->GetLength() * 65535.0f);
  292. animations_[index].setTimeTtl_ = COMMAND_STAY_TIME;
  293. ++animations_[index].setTimeRev_;
  294. MarkNetworkUpdate();
  295. return true;
  296. }
  297. bool AnimationController::SetSpeed(const String& name, float speed)
  298. {
  299. unsigned index;
  300. AnimationState* state;
  301. FindAnimation(name, index, state);
  302. if (index == M_MAX_UNSIGNED)
  303. return false;
  304. animations_[index].speed_ = speed;
  305. MarkNetworkUpdate();
  306. return true;
  307. }
  308. bool AnimationController::SetWeight(const String& name, float weight)
  309. {
  310. unsigned index;
  311. AnimationState* state;
  312. FindAnimation(name, index, state);
  313. if (index == M_MAX_UNSIGNED || !state)
  314. return false;
  315. weight = Clamp(weight, 0.0f, 1.0f);
  316. state->SetWeight(weight);
  317. // Prepare "set weight" command for network replication
  318. animations_[index].setWeight_ = (unsigned char)(weight * 255.0f);
  319. animations_[index].setWeightTtl_ = COMMAND_STAY_TIME;
  320. ++animations_[index].setWeightRev_;
  321. // Cancel any ongoing weight fade
  322. animations_[index].targetWeight_ = weight;
  323. animations_[index].fadeTime_ = 0.0f;
  324. MarkNetworkUpdate();
  325. return true;
  326. }
  327. bool AnimationController::SetRemoveOnCompletion(const String& name, bool removeOnCompletion)
  328. {
  329. unsigned index;
  330. AnimationState* state;
  331. FindAnimation(name, index, state);
  332. if (index == M_MAX_UNSIGNED || !state)
  333. return false;
  334. animations_[index].removeOnCompletion_ = removeOnCompletion;
  335. MarkNetworkUpdate();
  336. return true;
  337. }
  338. bool AnimationController::SetLooped(const String& name, bool enable)
  339. {
  340. AnimationState* state = GetAnimationState(name);
  341. if (!state)
  342. return false;
  343. state->SetLooped(enable);
  344. MarkNetworkUpdate();
  345. return true;
  346. }
  347. bool AnimationController::SetBlendMode(const String& name, AnimationBlendMode mode)
  348. {
  349. AnimationState* state = GetAnimationState(name);
  350. if (!state)
  351. return false;
  352. state->SetBlendMode(mode);
  353. MarkNetworkUpdate();
  354. return true;
  355. }
  356. bool AnimationController::SetAutoFade(const String& name, float fadeOutTime)
  357. {
  358. unsigned index;
  359. AnimationState* state;
  360. FindAnimation(name, index, state);
  361. if (index == M_MAX_UNSIGNED)
  362. return false;
  363. animations_[index].autoFadeTime_ = Max(fadeOutTime, 0.0f);
  364. MarkNetworkUpdate();
  365. return true;
  366. }
  367. bool AnimationController::IsPlaying(const String& name) const
  368. {
  369. unsigned index;
  370. AnimationState* state;
  371. FindAnimation(name, index, state);
  372. return index != M_MAX_UNSIGNED;
  373. }
  374. bool AnimationController::IsPlaying(unsigned char layer) const
  375. {
  376. for (Vector<AnimationControl>::ConstIterator i = animations_.Begin(); i != animations_.End(); ++i)
  377. {
  378. AnimationState* state = GetAnimationState(i->hash_);
  379. if (state && state->GetLayer() == layer)
  380. return true;
  381. }
  382. return false;
  383. }
  384. bool AnimationController::IsFadingIn(const String& name) const
  385. {
  386. unsigned index;
  387. AnimationState* state;
  388. FindAnimation(name, index, state);
  389. if (index == M_MAX_UNSIGNED || !state)
  390. return false;
  391. return animations_[index].fadeTime_ && animations_[index].targetWeight_ > state->GetWeight();
  392. }
  393. bool AnimationController::IsFadingOut(const String& name) const
  394. {
  395. unsigned index;
  396. AnimationState* state;
  397. FindAnimation(name, index, state);
  398. if (index == M_MAX_UNSIGNED || !state)
  399. return false;
  400. return (animations_[index].fadeTime_ && animations_[index].targetWeight_ < state->GetWeight())
  401. || (!state->IsLooped() && state->GetTime() >= state->GetLength() && animations_[index].autoFadeTime_);
  402. }
  403. bool AnimationController::IsAtEnd(const String& name) const
  404. {
  405. unsigned index;
  406. AnimationState* state;
  407. FindAnimation(name, index, state);
  408. if (index == M_MAX_UNSIGNED || !state)
  409. return false;
  410. else
  411. return state->GetTime() >= state->GetLength();
  412. }
  413. unsigned char AnimationController::GetLayer(const String& name) const
  414. {
  415. AnimationState* state = GetAnimationState(name);
  416. return (unsigned char)(state ? state->GetLayer() : 0);
  417. }
  418. Bone* AnimationController::GetStartBone(const String& name) const
  419. {
  420. AnimationState* state = GetAnimationState(name);
  421. return state ? state->GetStartBone() : nullptr;
  422. }
  423. const String& AnimationController::GetStartBoneName(const String& name) const
  424. {
  425. Bone* bone = GetStartBone(name);
  426. return bone ? bone->name_ : String::EMPTY;
  427. }
  428. float AnimationController::GetTime(const String& name) const
  429. {
  430. AnimationState* state = GetAnimationState(name);
  431. return state ? state->GetTime() : 0.0f;
  432. }
  433. float AnimationController::GetWeight(const String& name) const
  434. {
  435. AnimationState* state = GetAnimationState(name);
  436. return state ? state->GetWeight() : 0.0f;
  437. }
  438. bool AnimationController::IsLooped(const String& name) const
  439. {
  440. AnimationState* state = GetAnimationState(name);
  441. return state ? state->IsLooped() : false;
  442. }
  443. AnimationBlendMode AnimationController::GetBlendMode(const String& name) const
  444. {
  445. AnimationState* state = GetAnimationState(name);
  446. return state ? state->GetBlendMode() : ABM_LERP;
  447. }
  448. float AnimationController::GetLength(const String& name) const
  449. {
  450. AnimationState* state = GetAnimationState(name);
  451. return state ? state->GetLength() : 0.0f;
  452. }
  453. float AnimationController::GetSpeed(const String& name) const
  454. {
  455. unsigned index;
  456. AnimationState* state;
  457. FindAnimation(name, index, state);
  458. return index != M_MAX_UNSIGNED ? animations_[index].speed_ : 0.0f;
  459. }
  460. float AnimationController::GetFadeTarget(const String& name) const
  461. {
  462. unsigned index;
  463. AnimationState* state;
  464. FindAnimation(name, index, state);
  465. return index != M_MAX_UNSIGNED ? animations_[index].targetWeight_ : 0.0f;
  466. }
  467. float AnimationController::GetFadeTime(const String& name) const
  468. {
  469. unsigned index;
  470. AnimationState* state;
  471. FindAnimation(name, index, state);
  472. return index != M_MAX_UNSIGNED ? animations_[index].targetWeight_ : 0.0f;
  473. }
  474. float AnimationController::GetAutoFade(const String& name) const
  475. {
  476. unsigned index;
  477. AnimationState* state;
  478. FindAnimation(name, index, state);
  479. return index != M_MAX_UNSIGNED ? animations_[index].autoFadeTime_ : 0.0f;
  480. }
  481. bool AnimationController::GetRemoveOnCompletion(const String& name) const
  482. {
  483. unsigned index;
  484. AnimationState* state;
  485. FindAnimation(name, index, state);
  486. return index != M_MAX_UNSIGNED ? animations_[index].removeOnCompletion_ : false;
  487. }
  488. AnimationState* AnimationController::GetAnimationState(const String& name) const
  489. {
  490. return GetAnimationState(StringHash(name));
  491. }
  492. AnimationState* AnimationController::GetAnimationState(StringHash nameHash) const
  493. {
  494. // Model mode
  495. auto* model = GetComponent<AnimatedModel>();
  496. if (model)
  497. return model->GetAnimationState(nameHash);
  498. // Node hierarchy mode
  499. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = nodeAnimationStates_.Begin(); i != nodeAnimationStates_.End(); ++i)
  500. {
  501. Animation* animation = (*i)->GetAnimation();
  502. if (animation->GetNameHash() == nameHash || animation->GetAnimationNameHash() == nameHash)
  503. return *i;
  504. }
  505. return nullptr;
  506. }
  507. void AnimationController::SetAnimationsAttr(const VariantVector& value)
  508. {
  509. animations_.Clear();
  510. animations_.Reserve(value.Size() / 5); // Incomplete data is discarded
  511. unsigned index = 0;
  512. while (index + 4 < value.Size()) // Prevent out-of-bound index access
  513. {
  514. AnimationControl newControl;
  515. newControl.name_ = value[index++].GetString();
  516. newControl.hash_ = StringHash(newControl.name_);
  517. newControl.speed_ = value[index++].GetFloat();
  518. newControl.targetWeight_ = value[index++].GetFloat();
  519. newControl.fadeTime_ = value[index++].GetFloat();
  520. newControl.autoFadeTime_ = value[index++].GetFloat();
  521. animations_.Push(newControl);
  522. }
  523. }
  524. void AnimationController::SetNetAnimationsAttr(const PODVector<unsigned char>& value)
  525. {
  526. MemoryBuffer buf(value);
  527. auto* model = GetComponent<AnimatedModel>();
  528. // Check which animations we need to remove
  529. HashSet<StringHash> processedAnimations;
  530. unsigned numAnimations = buf.ReadVLE();
  531. while (numAnimations--)
  532. {
  533. String animName = buf.ReadString();
  534. StringHash animHash(animName);
  535. processedAnimations.Insert(animHash);
  536. // Check if the animation state exists. If not, add new
  537. AnimationState* state = GetAnimationState(animHash);
  538. if (!state)
  539. {
  540. auto* newAnimation = GetSubsystem<ResourceCache>()->GetResource<Animation>(animName);
  541. state = AddAnimationState(newAnimation);
  542. if (!state)
  543. {
  544. URHO3D_LOGERROR("Animation update applying aborted due to unknown animation");
  545. return;
  546. }
  547. }
  548. // Check if the internal control structure exists. If not, add new
  549. unsigned index;
  550. for (index = 0; index < animations_.Size(); ++index)
  551. {
  552. if (animations_[index].hash_ == animHash)
  553. break;
  554. }
  555. if (index == animations_.Size())
  556. {
  557. AnimationControl newControl;
  558. newControl.name_ = animName;
  559. newControl.hash_ = animHash;
  560. animations_.Push(newControl);
  561. }
  562. unsigned char ctrl = buf.ReadUByte();
  563. state->SetLayer(buf.ReadUByte());
  564. state->SetLooped((ctrl & CTRL_LOOPED) != 0);
  565. state->SetBlendMode((ctrl & CTRL_ADDITIVE) != 0 ? ABM_ADDITIVE : ABM_LERP);
  566. animations_[index].speed_ = (float)buf.ReadShort() / 2048.0f; // 11 bits of decimal precision, max. 16x playback speed
  567. animations_[index].targetWeight_ = (float)buf.ReadUByte() / 255.0f; // 8 bits of decimal precision
  568. animations_[index].fadeTime_ = (float)buf.ReadUByte() / 64.0f; // 6 bits of decimal precision, max. 4 seconds fade
  569. if (ctrl & CTRL_STARTBONE)
  570. {
  571. StringHash boneHash = buf.ReadStringHash();
  572. if (model)
  573. state->SetStartBone(model->GetSkeleton().GetBone(boneHash));
  574. }
  575. else
  576. state->SetStartBone(nullptr);
  577. if (ctrl & CTRL_AUTOFADE)
  578. animations_[index].autoFadeTime_ = (float)buf.ReadUByte() / 64.0f; // 6 bits of decimal precision, max. 4 seconds fade
  579. else
  580. animations_[index].autoFadeTime_ = 0.0f;
  581. animations_[index].removeOnCompletion_ = (ctrl & CTRL_REMOVEONCOMPLETION) != 0;
  582. if (ctrl & CTRL_SETTIME)
  583. {
  584. unsigned char setTimeRev = buf.ReadUByte();
  585. unsigned short setTime = buf.ReadUShort();
  586. // Apply set time command only if revision differs
  587. if (setTimeRev != animations_[index].setTimeRev_)
  588. {
  589. state->SetTime(((float)setTime / 65535.0f) * state->GetLength());
  590. animations_[index].setTimeRev_ = setTimeRev;
  591. }
  592. }
  593. if (ctrl & CTRL_SETWEIGHT)
  594. {
  595. unsigned char setWeightRev = buf.ReadUByte();
  596. unsigned char setWeight = buf.ReadUByte();
  597. // Apply set weight command only if revision differs
  598. if (setWeightRev != animations_[index].setWeightRev_)
  599. {
  600. state->SetWeight((float)setWeight / 255.0f);
  601. animations_[index].setWeightRev_ = setWeightRev;
  602. }
  603. }
  604. }
  605. // Set any extra animations to fade out
  606. for (Vector<AnimationControl>::Iterator i = animations_.Begin(); i != animations_.End(); ++i)
  607. {
  608. if (!processedAnimations.Contains(i->hash_))
  609. {
  610. i->targetWeight_ = 0.0f;
  611. i->fadeTime_ = EXTRA_ANIM_FADEOUT_TIME;
  612. }
  613. }
  614. }
  615. void AnimationController::SetNodeAnimationStatesAttr(const VariantVector& value)
  616. {
  617. auto* cache = GetSubsystem<ResourceCache>();
  618. nodeAnimationStates_.Clear();
  619. unsigned index = 0;
  620. unsigned numStates = index < value.Size() ? value[index++].GetUInt() : 0;
  621. // Prevent negative or overly large value being assigned from the editor
  622. if (numStates > M_MAX_INT)
  623. numStates = 0;
  624. if (numStates > MAX_NODE_ANIMATION_STATES)
  625. numStates = MAX_NODE_ANIMATION_STATES;
  626. nodeAnimationStates_.Reserve(numStates);
  627. while (numStates--)
  628. {
  629. if (index + 2 < value.Size())
  630. {
  631. // Note: null animation is allowed here for editing
  632. const ResourceRef& animRef = value[index++].GetResourceRef();
  633. SharedPtr<AnimationState> newState(new AnimationState(GetNode(), cache->GetResource<Animation>(animRef.name_)));
  634. nodeAnimationStates_.Push(newState);
  635. newState->SetLooped(value[index++].GetBool());
  636. newState->SetTime(value[index++].GetFloat());
  637. }
  638. else
  639. {
  640. // If not enough data, just add an empty animation state
  641. SharedPtr<AnimationState> newState(new AnimationState(GetNode(), nullptr));
  642. nodeAnimationStates_.Push(newState);
  643. }
  644. }
  645. }
  646. VariantVector AnimationController::GetAnimationsAttr() const
  647. {
  648. VariantVector ret;
  649. ret.Reserve(animations_.Size() * 5);
  650. for (Vector<AnimationControl>::ConstIterator i = animations_.Begin(); i != animations_.End(); ++i)
  651. {
  652. ret.Push(i->name_);
  653. ret.Push(i->speed_);
  654. ret.Push(i->targetWeight_);
  655. ret.Push(i->fadeTime_);
  656. ret.Push(i->autoFadeTime_);
  657. }
  658. return ret;
  659. }
  660. const PODVector<unsigned char>& AnimationController::GetNetAnimationsAttr() const
  661. {
  662. attrBuffer_.Clear();
  663. auto* model = GetComponent<AnimatedModel>();
  664. unsigned validAnimations = 0;
  665. for (Vector<AnimationControl>::ConstIterator i = animations_.Begin(); i != animations_.End(); ++i)
  666. {
  667. if (GetAnimationState(i->hash_))
  668. ++validAnimations;
  669. }
  670. attrBuffer_.WriteVLE(validAnimations);
  671. for (Vector<AnimationControl>::ConstIterator i = animations_.Begin(); i != animations_.End(); ++i)
  672. {
  673. AnimationState* state = GetAnimationState(i->hash_);
  674. if (!state)
  675. continue;
  676. unsigned char ctrl = 0;
  677. Bone* startBone = state->GetStartBone();
  678. if (state->IsLooped())
  679. ctrl |= CTRL_LOOPED;
  680. if (state->GetBlendMode() == ABM_ADDITIVE)
  681. ctrl |= CTRL_ADDITIVE;
  682. if (startBone && model && startBone != model->GetSkeleton().GetRootBone())
  683. ctrl |= CTRL_STARTBONE;
  684. if (i->autoFadeTime_ > 0.0f)
  685. ctrl |= CTRL_AUTOFADE;
  686. if (i->removeOnCompletion_)
  687. ctrl |= CTRL_REMOVEONCOMPLETION;
  688. if (i->setTimeTtl_ > 0.0f)
  689. ctrl |= CTRL_SETTIME;
  690. if (i->setWeightTtl_ > 0.0f)
  691. ctrl |= CTRL_SETWEIGHT;
  692. attrBuffer_.WriteString(i->name_);
  693. attrBuffer_.WriteUByte(ctrl);
  694. attrBuffer_.WriteUByte(state->GetLayer());
  695. attrBuffer_.WriteShort((short)Clamp(i->speed_ * 2048.0f, -32767.0f, 32767.0f));
  696. attrBuffer_.WriteUByte((unsigned char)(i->targetWeight_ * 255.0f));
  697. attrBuffer_.WriteUByte((unsigned char)Clamp(i->fadeTime_ * 64.0f, 0.0f, 255.0f));
  698. if (ctrl & CTRL_STARTBONE)
  699. attrBuffer_.WriteStringHash(startBone->nameHash_);
  700. if (ctrl & CTRL_AUTOFADE)
  701. attrBuffer_.WriteUByte((unsigned char)Clamp(i->autoFadeTime_ * 64.0f, 0.0f, 255.0f));
  702. if (ctrl & CTRL_SETTIME)
  703. {
  704. attrBuffer_.WriteUByte(i->setTimeRev_);
  705. attrBuffer_.WriteUShort(i->setTime_);
  706. }
  707. if (ctrl & CTRL_SETWEIGHT)
  708. {
  709. attrBuffer_.WriteUByte(i->setWeightRev_);
  710. attrBuffer_.WriteUByte(i->setWeight_);
  711. }
  712. }
  713. return attrBuffer_.GetBuffer();
  714. }
  715. VariantVector AnimationController::GetNodeAnimationStatesAttr() const
  716. {
  717. VariantVector ret;
  718. ret.Reserve(nodeAnimationStates_.Size() * 3 + 1);
  719. ret.Push(nodeAnimationStates_.Size());
  720. for (Vector<SharedPtr<AnimationState> >::ConstIterator i = nodeAnimationStates_.Begin(); i != nodeAnimationStates_.End(); ++i)
  721. {
  722. AnimationState* state = *i;
  723. Animation* animation = state->GetAnimation();
  724. ret.Push(GetResourceRef(animation, Animation::GetTypeStatic()));
  725. ret.Push(state->IsLooped());
  726. ret.Push(state->GetTime());
  727. }
  728. return ret;
  729. }
  730. void AnimationController::OnSceneSet(Scene* scene)
  731. {
  732. if (scene && IsEnabledEffective())
  733. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, URHO3D_HANDLER(AnimationController, HandleScenePostUpdate));
  734. else if (!scene)
  735. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  736. }
  737. AnimationState* AnimationController::AddAnimationState(Animation* animation)
  738. {
  739. if (!animation)
  740. return nullptr;
  741. // Model mode
  742. auto* model = GetComponent<AnimatedModel>();
  743. if (model)
  744. return model->AddAnimationState(animation);
  745. // Node hierarchy mode
  746. SharedPtr<AnimationState> newState(new AnimationState(node_, animation));
  747. nodeAnimationStates_.Push(newState);
  748. return newState;
  749. }
  750. void AnimationController::RemoveAnimationState(AnimationState* state)
  751. {
  752. if (!state)
  753. return;
  754. // Model mode
  755. auto* model = GetComponent<AnimatedModel>();
  756. if (model)
  757. {
  758. model->RemoveAnimationState(state);
  759. return;
  760. }
  761. // Node hierarchy mode
  762. for (Vector<SharedPtr<AnimationState> >::Iterator i = nodeAnimationStates_.Begin(); i != nodeAnimationStates_.End(); ++i)
  763. {
  764. if ((*i) == state)
  765. {
  766. nodeAnimationStates_.Erase(i);
  767. return;
  768. }
  769. }
  770. }
  771. void AnimationController::FindAnimation(const String& name, unsigned& index, AnimationState*& state) const
  772. {
  773. StringHash nameHash(GetInternalPath(name));
  774. // Find the AnimationState
  775. state = GetAnimationState(nameHash);
  776. if (state)
  777. {
  778. // Either a resource name or animation name may be specified. We store resource names, so correct the hash if necessary
  779. nameHash = state->GetAnimation()->GetNameHash();
  780. }
  781. // Find the internal control structure
  782. index = M_MAX_UNSIGNED;
  783. for (unsigned i = 0; i < animations_.Size(); ++i)
  784. {
  785. if (animations_[i].hash_ == nameHash)
  786. {
  787. index = i;
  788. break;
  789. }
  790. }
  791. }
  792. void AnimationController::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  793. {
  794. using namespace ScenePostUpdate;
  795. Update(eventData[P_TIMESTEP].GetFloat());
  796. }
  797. }