AnimatedSprite2D.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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 "../Core/Context.h"
  24. #include "../Resource/ResourceCache.h"
  25. #include "../Scene/Scene.h"
  26. #include "../Scene/SceneEvents.h"
  27. #include "../Atomic2D/AnimatedSprite2D.h"
  28. #include "../Atomic2D/Animation2D.h"
  29. #include "../Atomic2D/AnimationSet2D.h"
  30. #include "../Atomic2D/Sprite2D.h"
  31. #include "../Atomic2D/StaticSprite2D.h"
  32. #include "../DebugNew.h"
  33. namespace Atomic
  34. {
  35. extern const char* ATOMIC2D_CATEGORY;
  36. extern const char* blendModeNames[];
  37. const char* loopModeNames[] =
  38. {
  39. "Default",
  40. "ForceLooped",
  41. "ForceClamped",
  42. 0
  43. };
  44. AnimatedSprite2D::AnimatedSprite2D(Context* context) :
  45. StaticSprite2D(context),
  46. speed_(1.0f),
  47. loopMode_(LM_DEFAULT),
  48. looped_(false),
  49. currentTime_(0.0f),
  50. numTracks_(0)
  51. {
  52. }
  53. AnimatedSprite2D::~AnimatedSprite2D()
  54. {
  55. }
  56. void AnimatedSprite2D::RegisterObject(Context* context)
  57. {
  58. context->RegisterFactory<AnimatedSprite2D>(ATOMIC2D_CATEGORY);
  59. COPY_BASE_ATTRIBUTES(StaticSprite2D);
  60. REMOVE_ATTRIBUTE("Sprite");
  61. ACCESSOR_ATTRIBUTE("Speed", GetSpeed, SetSpeed, float, 1.0f, AM_DEFAULT);
  62. MIXED_ACCESSOR_ATTRIBUTE("Animation Set", GetAnimationSetAttr, SetAnimationSetAttr, ResourceRef, ResourceRef(AnimatedSprite2D::GetTypeStatic()), AM_DEFAULT);
  63. ACCESSOR_ATTRIBUTE("Animation", GetAnimation, SetAnimationAttr, String, String::EMPTY, AM_DEFAULT);
  64. ENUM_ACCESSOR_ATTRIBUTE("Loop Mode", GetLoopMode, SetLoopMode, LoopMode2D, loopModeNames, LM_DEFAULT, AM_DEFAULT);
  65. }
  66. void AnimatedSprite2D::OnSetEnabled()
  67. {
  68. StaticSprite2D::OnSetEnabled();
  69. bool enabled = IsEnabledEffective();
  70. Scene* scene = GetScene();
  71. if (scene)
  72. {
  73. if (enabled)
  74. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
  75. else
  76. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  77. }
  78. for (unsigned i = 0; i < trackNodes_.Size(); ++i)
  79. {
  80. if (!trackNodes_[i])
  81. continue;
  82. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  83. if (staticSprite)
  84. staticSprite->SetEnabled(enabled);
  85. }
  86. }
  87. void AnimatedSprite2D::SetSpeed(float speed)
  88. {
  89. speed_ = speed;
  90. MarkNetworkUpdate();
  91. }
  92. void AnimatedSprite2D::SetAnimation(AnimationSet2D* animationSet, const String& name, LoopMode2D loopMode)
  93. {
  94. animationSet_ = animationSet;
  95. SetAnimation(name, loopMode);
  96. }
  97. void AnimatedSprite2D::SetAnimation(const String& name, LoopMode2D loopMode)
  98. {
  99. animationName_ = name;
  100. if (animationSet_)
  101. SetAnimation(animationSet_->GetAnimation(animationName_), loopMode);
  102. }
  103. void AnimatedSprite2D::SetAnimationSet(AnimationSet2D* animationSet)
  104. {
  105. if (animationSet == animationSet_)
  106. return;
  107. animationSet_ = animationSet;
  108. SetAnimation(animationName_, loopMode_);
  109. }
  110. void AnimatedSprite2D::SetLoopMode(LoopMode2D loopMode)
  111. {
  112. if (!animation_)
  113. return;
  114. loopMode_ = loopMode;
  115. switch (loopMode_)
  116. {
  117. case LM_FORCE_LOOPED:
  118. looped_ = true;
  119. break;
  120. case LM_FORCE_CLAMPED:
  121. looped_ = false;
  122. break;
  123. default:
  124. looped_ = animation_->IsLooped();
  125. break;
  126. }
  127. }
  128. AnimationSet2D* AnimatedSprite2D::GetAnimationSet() const
  129. {
  130. return animationSet_;
  131. }
  132. Node* AnimatedSprite2D::GetRootNode() const
  133. {
  134. return rootNode_;
  135. }
  136. void AnimatedSprite2D::SetAnimationSetAttr(const ResourceRef& value)
  137. {
  138. ResourceCache* cache = GetSubsystem<ResourceCache>();
  139. SetAnimationSet(cache->GetResource<AnimationSet2D>(value.name_));
  140. }
  141. ResourceRef AnimatedSprite2D::GetAnimationSetAttr() const
  142. {
  143. return GetResourceRef(animationSet_, AnimationSet2D::GetTypeStatic());
  144. }
  145. void AnimatedSprite2D::OnNodeSet(Node* node)
  146. {
  147. StaticSprite2D::OnNodeSet(node);
  148. if (node)
  149. {
  150. Scene* scene = GetScene();
  151. if (scene && IsEnabledEffective())
  152. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
  153. }
  154. else
  155. {
  156. if (rootNode_)
  157. rootNode_->Remove();
  158. rootNode_ = 0;
  159. numTracks_ = 0;
  160. trackNodes_.Clear();
  161. trackNodeInfos_.Clear();
  162. }
  163. }
  164. void AnimatedSprite2D::SetAnimationAttr(const String& name)
  165. {
  166. animationName_ = name;
  167. if (animationSet_)
  168. SetAnimation(animationSet_->GetAnimation(animationName_), loopMode_);
  169. }
  170. void AnimatedSprite2D::OnWorldBoundingBoxUpdate()
  171. {
  172. boundingBox_.Clear();
  173. worldBoundingBox_.Clear();
  174. for (unsigned i = 0; i < numTracks_; ++i)
  175. {
  176. if (!trackNodes_[i])
  177. continue;
  178. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  179. if (staticSprite)
  180. worldBoundingBox_.Merge(staticSprite->GetWorldBoundingBox());
  181. }
  182. boundingBox_ = worldBoundingBox_.Transformed(node_->GetWorldTransform().Inverse());
  183. }
  184. void AnimatedSprite2D::OnDrawOrderChanged()
  185. {
  186. for (unsigned i = 0; i < numTracks_; ++i)
  187. {
  188. if (!trackNodes_[i])
  189. continue;
  190. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  191. if (staticSprite)
  192. staticSprite->SetLayer(layer_);
  193. }
  194. }
  195. void AnimatedSprite2D::OnFlipChanged()
  196. {
  197. for (unsigned i = 0; i < numTracks_; ++i)
  198. {
  199. if (!trackNodes_[i])
  200. continue;
  201. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  202. if (staticSprite)
  203. staticSprite->SetFlip(flipX_, flipY_);
  204. }
  205. // For editor paused mode
  206. UpdateAnimation(0.0f);
  207. }
  208. void AnimatedSprite2D::UpdateSourceBatches()
  209. {
  210. sourceBatchesDirty_ = false;
  211. }
  212. void AnimatedSprite2D::SetAnimation(Animation2D* animation, LoopMode2D loopMode)
  213. {
  214. if (animation == animation_)
  215. {
  216. SetLoopMode(loopMode_);
  217. currentTime_ = 0.0f;
  218. UpdateAnimation(0.0f);
  219. return;
  220. }
  221. for (unsigned i = 0; i < numTracks_; ++i)
  222. {
  223. if (trackNodes_[i])
  224. trackNodes_[i]->SetEnabled(false);
  225. }
  226. numTracks_ = 0;
  227. trackNodes_.Clear();
  228. trackNodeInfos_.Clear();
  229. animation_ = animation;
  230. if (!animation_)
  231. return;
  232. currentTime_ = 0.0f;
  233. if (!rootNode_)
  234. {
  235. rootNode_ = GetNode()->CreateChild("_root_", LOCAL);
  236. rootNode_->SetTemporary(true);
  237. }
  238. numTracks_ = animation_->GetNumTracks();
  239. trackNodes_.Resize(numTracks_);
  240. trackNodeInfos_.Resize(numTracks_);
  241. for (unsigned i = 0; i < numTracks_; ++i)
  242. {
  243. const AnimationTrack2D& track = animation->GetTrack(i);
  244. SharedPtr<Node> trackNode(rootNode_->GetChild(track.name_));
  245. StaticSprite2D* staticSprite = 0;
  246. if (trackNode)
  247. {
  248. // Enable track node
  249. trackNode->SetEnabled(true);
  250. // Get StaticSprite2D component
  251. if (track.hasSprite_)
  252. staticSprite = trackNode->GetComponent<StaticSprite2D>();
  253. }
  254. else
  255. {
  256. // Create new track node
  257. trackNode = rootNode_->CreateChild(track.name_, LOCAL);
  258. trackNode->SetTemporary(true);
  259. // Create StaticSprite2D component
  260. if (track.hasSprite_)
  261. {
  262. staticSprite = trackNode->CreateComponent<StaticSprite2D>();
  263. staticSprite->SetEnabled(IsEnabledEffective());
  264. }
  265. }
  266. if (staticSprite)
  267. {
  268. staticSprite->SetLayer(layer_);
  269. staticSprite->SetBlendMode(blendMode_);
  270. staticSprite->SetFlip(flipX_, flipY_);
  271. staticSprite->SetUseHotSpot(true);
  272. }
  273. trackNodes_[i] = trackNode;
  274. trackNodeInfos_[i].hasSprite = track.hasSprite_;
  275. }
  276. SetLoopMode(loopMode);
  277. UpdateAnimation(0.0f);
  278. MarkNetworkUpdate();
  279. }
  280. void AnimatedSprite2D::UpdateAnimation(float timeStep)
  281. {
  282. if (!animation_)
  283. return;
  284. currentTime_ += timeStep * speed_;
  285. float time;
  286. float animationLength = animation_->GetLength();
  287. if (looped_)
  288. {
  289. time = fmodf(currentTime_, animationLength);
  290. if (time < 0.0f)
  291. time += animation_->GetLength();
  292. }
  293. else
  294. time = Clamp(currentTime_, 0.0f, animationLength);
  295. for (unsigned i = 0; i < numTracks_; ++i)
  296. {
  297. trackNodeInfos_[i].worldSpace = false;
  298. const AnimationTrack2D& track = animation_->GetTrack(i);
  299. const Vector<AnimationKeyFrame2D>& keyFrames = track.keyFrames_;
  300. // Time out of range
  301. if (time < keyFrames[0].time_ || time > keyFrames.Back().time_)
  302. trackNodeInfos_[i].value.enabled_ = false;
  303. else
  304. {
  305. unsigned index = keyFrames.Size() - 1;
  306. for (unsigned j = 0; j < keyFrames.Size() - 1; ++j)
  307. {
  308. if (time <= keyFrames[j + 1].time_)
  309. {
  310. index = j;
  311. break;
  312. }
  313. }
  314. const AnimationKeyFrame2D& currKey = keyFrames[index];
  315. AnimationKeyFrame2D& value = trackNodeInfos_[i].value;
  316. value.enabled_ = currKey.enabled_;
  317. value.parent_ = currKey.parent_;
  318. if (index < keyFrames.Size() - 1)
  319. {
  320. const AnimationKeyFrame2D& nextKey = keyFrames[index + 1];
  321. float t = (time - currKey.time_) / (nextKey.time_ - currKey.time_);
  322. value.transform_ = currKey.transform_.Lerp(nextKey.transform_, t, currKey.spin_);
  323. if (trackNodeInfos_[i].hasSprite)
  324. value.alpha_ = Atomic::Lerp(currKey.alpha_, nextKey.alpha_, t);
  325. }
  326. else
  327. {
  328. value.transform_ = currKey.transform_;
  329. if (trackNodeInfos_[i].hasSprite)
  330. value.alpha_ = currKey.alpha_;
  331. }
  332. if (trackNodeInfos_[i].hasSprite)
  333. {
  334. value.zIndex_ = currKey.zIndex_;
  335. value.sprite_ = currKey.sprite_;
  336. value.useHotSpot_ = currKey.useHotSpot_;
  337. value.hotSpot_ = currKey.hotSpot_;
  338. }
  339. }
  340. }
  341. for (unsigned i = 0; i < numTracks_; ++i)
  342. {
  343. Node* node = trackNodes_[i];
  344. if (!node)
  345. continue;
  346. TrackNodeInfo& nodeInfo = trackNodeInfos_[i];
  347. if (!nodeInfo.value.enabled_)
  348. node->SetEnabled(false);
  349. else
  350. {
  351. node->SetEnabled(true);
  352. // Calculate world transform.
  353. CalculateTimelineWorldTransform(i);
  354. // Update node's transform
  355. Vector2 position = nodeInfo.value.transform_.position_ * PIXEL_SIZE;
  356. if (flipX_)
  357. position.x_ = -position.x_;
  358. if (flipY_)
  359. position.y_ = -position.y_;
  360. node->SetPosition(position);
  361. float angle = nodeInfo.value.transform_.angle_;
  362. if (flipX_ != flipY_)
  363. angle = -angle;
  364. node->SetRotation(angle);
  365. node->SetScale(nodeInfo.value.transform_.scale_);
  366. if (nodeInfo.hasSprite)
  367. {
  368. StaticSprite2D* staticSprite = node->GetComponent<StaticSprite2D>();
  369. if (staticSprite)
  370. {
  371. staticSprite->SetOrderInLayer(orderInLayer_ + nodeInfo.value.zIndex_);
  372. staticSprite->SetSprite(nodeInfo.value.sprite_);
  373. staticSprite->SetAlpha(nodeInfo.value.alpha_);
  374. staticSprite->SetUseHotSpot(nodeInfo.value.useHotSpot_);
  375. staticSprite->SetHotSpot(nodeInfo.value.hotSpot_);
  376. }
  377. }
  378. }
  379. }
  380. }
  381. void AnimatedSprite2D::CalculateTimelineWorldTransform(unsigned index)
  382. {
  383. TrackNodeInfo& info = trackNodeInfos_[index];
  384. if (info.worldSpace)
  385. return;
  386. info.worldSpace = true;
  387. int parent = info.value.parent_;
  388. if (parent != -1)
  389. {
  390. CalculateTimelineWorldTransform(parent);
  391. info.value.transform_ = trackNodeInfos_[parent].value.transform_ * info.value.transform_;
  392. }
  393. }
  394. void AnimatedSprite2D::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  395. {
  396. using namespace ScenePostUpdate;
  397. float timeStep = eventData[P_TIMESTEP].GetFloat();
  398. UpdateAnimation(timeStep);
  399. }
  400. }