AnimatedSprite2D.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 "../Atomic2D/AnimatedSprite2D.h"
  24. #include "../Atomic2D/Animation2D.h"
  25. #include "../Atomic2D/AnimationSet2D.h"
  26. #include "../Core/Context.h"
  27. #include "../Resource/ResourceCache.h"
  28. #include "../Scene/Scene.h"
  29. #include "../Scene/SceneEvents.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::OnLayerChanged()
  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::OnBlendModeChanged()
  196. {
  197. for (unsigned i = 0; i < numTracks_; ++i)
  198. {
  199. if (!trackNodes_[i])
  200. continue;
  201. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  202. staticSprite->SetBlendMode(blendMode_);
  203. }
  204. }
  205. void AnimatedSprite2D::OnFlipChanged()
  206. {
  207. for (unsigned i = 0; i < numTracks_; ++i)
  208. {
  209. if (!trackNodes_[i])
  210. continue;
  211. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  212. staticSprite->SetFlip(flipX_, flipY_);
  213. }
  214. // For editor paused mode
  215. UpdateAnimation(0.0f);
  216. }
  217. void AnimatedSprite2D::UpdateVertices()
  218. {
  219. verticesDirty_ = false;
  220. }
  221. void AnimatedSprite2D::SetAnimation(Animation2D* animation, LoopMode2D loopMode)
  222. {
  223. if (animation == animation_)
  224. {
  225. SetLoopMode(loopMode_);
  226. currentTime_ = 0.0f;
  227. UpdateAnimation(0.0f);
  228. return;
  229. }
  230. for (unsigned i = 0; i < numTracks_; ++i)
  231. {
  232. if (trackNodes_[i])
  233. trackNodes_[i]->SetEnabled(false);
  234. }
  235. numTracks_ = 0;
  236. trackNodes_.Clear();
  237. trackNodeInfos_.Clear();
  238. animation_ = animation;
  239. if (!animation_)
  240. return;
  241. currentTime_ = 0.0f;
  242. if (!rootNode_)
  243. {
  244. rootNode_ = GetNode()->CreateChild("_root_", LOCAL);
  245. rootNode_->SetTemporary(true);
  246. }
  247. numTracks_ = animation_->GetNumTracks();
  248. trackNodes_.Resize(numTracks_);
  249. trackNodeInfos_.Resize(numTracks_);
  250. for (unsigned i = 0; i < numTracks_; ++i)
  251. {
  252. const AnimationTrack2D& track = animation->GetTrack(i);
  253. SharedPtr<Node> trackNode(rootNode_->GetChild(track.name_));
  254. StaticSprite2D* staticSprite = 0;
  255. if (trackNode)
  256. {
  257. // Enable track node
  258. trackNode->SetEnabled(true);
  259. // Get StaticSprite2D component
  260. if (track.hasSprite_)
  261. staticSprite = trackNode->GetComponent<StaticSprite2D>();
  262. }
  263. else
  264. {
  265. // Create new track node
  266. trackNode = rootNode_->CreateChild(track.name_, LOCAL);
  267. trackNode->SetTemporary(true);
  268. // Create StaticSprite2D component
  269. if (track.hasSprite_)
  270. {
  271. staticSprite = trackNode->CreateComponent<StaticSprite2D>();
  272. staticSprite->SetEnabled(IsEnabledEffective());
  273. }
  274. }
  275. if (staticSprite)
  276. {
  277. staticSprite->SetLayer(layer_);
  278. staticSprite->SetBlendMode(blendMode_);
  279. staticSprite->SetFlip(flipX_, flipY_);
  280. staticSprite->SetUseHotSpot(true);
  281. }
  282. trackNodes_[i] = trackNode;
  283. trackNodeInfos_[i].hasSprite = track.hasSprite_;
  284. }
  285. SetLoopMode(loopMode);
  286. UpdateAnimation(0.0f);
  287. MarkNetworkUpdate();
  288. }
  289. void AnimatedSprite2D::UpdateAnimation(float timeStep)
  290. {
  291. if (!animation_)
  292. return;
  293. currentTime_ += timeStep * speed_;
  294. float time;
  295. float animationLength = animation_->GetLength();
  296. if (looped_)
  297. {
  298. time = fmodf(currentTime_, animationLength);
  299. if (time < 0.0f)
  300. time += animation_->GetLength();
  301. }
  302. else
  303. time = Clamp(currentTime_, 0.0f, animationLength);
  304. for (unsigned i = 0; i < numTracks_; ++i)
  305. {
  306. trackNodeInfos_[i].worldSpace = false;
  307. const AnimationTrack2D& track = animation_->GetTrack(i);
  308. const Vector<AnimationKeyFrame2D>& keyFrames = track.keyFrames_;
  309. // Time out of range
  310. if (time < keyFrames[0].time_ || time > keyFrames.Back().time_)
  311. trackNodeInfos_[i].value.enabled_ = false;
  312. else
  313. {
  314. unsigned index = keyFrames.Size() - 1;
  315. for (unsigned j = 0; j < keyFrames.Size() - 1; ++j)
  316. {
  317. if (time <= keyFrames[j + 1].time_)
  318. {
  319. index = j;
  320. break;
  321. }
  322. }
  323. const AnimationKeyFrame2D& currKey = keyFrames[index];
  324. AnimationKeyFrame2D& value = trackNodeInfos_[i].value;
  325. value.enabled_ = currKey.enabled_;
  326. value.parent_ = currKey.parent_;
  327. if (index < keyFrames.Size() - 1)
  328. {
  329. const AnimationKeyFrame2D& nextKey = keyFrames[index + 1];
  330. float t = (time - currKey.time_) / (nextKey.time_ - currKey.time_);
  331. value.transform_ = currKey.transform_.Lerp(nextKey.transform_, t, currKey.spin_);
  332. if (trackNodeInfos_[i].hasSprite)
  333. value.alpha_ = Atomic::Lerp(currKey.alpha_, nextKey.alpha_, t);
  334. }
  335. else
  336. {
  337. value.transform_ = currKey.transform_;
  338. if (trackNodeInfos_[i].hasSprite)
  339. value.alpha_ = currKey.alpha_;
  340. }
  341. if (trackNodeInfos_[i].hasSprite)
  342. {
  343. value.zIndex_ = currKey.zIndex_;
  344. value.sprite_ = currKey.sprite_;
  345. value.useHotSpot_ = currKey.useHotSpot_;
  346. value.hotSpot_ = currKey.hotSpot_;
  347. }
  348. }
  349. }
  350. for (unsigned i = 0; i < numTracks_; ++i)
  351. {
  352. Node* node = trackNodes_[i];
  353. TrackNodeInfo& nodeInfo = trackNodeInfos_[i];
  354. if (!nodeInfo.value.enabled_)
  355. node->SetEnabled(false);
  356. else
  357. {
  358. node->SetEnabled(true);
  359. // Calculate world transform.
  360. CalculateTimelineWorldTransform(i);
  361. // Update node's transform
  362. Vector2 position = nodeInfo.value.transform_.position_ * PIXEL_SIZE;
  363. if (flipX_)
  364. position.x_ = -position.x_;
  365. if (flipY_)
  366. position.y_ = -position.y_;
  367. node->SetPosition(position);
  368. float angle = nodeInfo.value.transform_.angle_;
  369. if (flipX_ != flipY_)
  370. angle = -angle;
  371. node->SetRotation(angle);
  372. node->SetScale(nodeInfo.value.transform_.scale_);
  373. if (nodeInfo.hasSprite)
  374. {
  375. StaticSprite2D* staticSprite = node->GetComponent<StaticSprite2D>();
  376. if (staticSprite)
  377. {
  378. staticSprite->SetOrderInLayer(orderInLayer_ + nodeInfo.value.zIndex_);
  379. staticSprite->SetSprite(nodeInfo.value.sprite_);
  380. staticSprite->SetAlpha(nodeInfo.value.alpha_);
  381. staticSprite->SetUseHotSpot(nodeInfo.value.useHotSpot_);
  382. staticSprite->SetHotSpot(nodeInfo.value.hotSpot_);
  383. }
  384. }
  385. }
  386. }
  387. }
  388. void AnimatedSprite2D::CalculateTimelineWorldTransform(unsigned index)
  389. {
  390. TrackNodeInfo& info = trackNodeInfos_[index];
  391. if (info.worldSpace)
  392. return;
  393. info.worldSpace = true;
  394. int parent = info.value.parent_;
  395. if (parent != -1)
  396. {
  397. CalculateTimelineWorldTransform(parent);
  398. info.value.transform_ = trackNodeInfos_[parent].value.transform_ * info.value.transform_;
  399. }
  400. }
  401. void AnimatedSprite2D::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  402. {
  403. using namespace ScenePostUpdate;
  404. float timeStep = eventData[P_TIMESTEP].GetFloat();
  405. UpdateAnimation(timeStep);
  406. }
  407. }