AnimatedSprite2D.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 "../IO/Log.h"
  25. #include "../Resource/ResourceCache.h"
  26. #include "../Scene/Scene.h"
  27. #include "../Scene/SceneEvents.h"
  28. #include "../Atomic2D/AnimatedSprite2D.h"
  29. #include "../Atomic2D/AnimationSet2D.h"
  30. #include "../Atomic2D/Sprite2D.h"
  31. #include "../DebugNew.h"
  32. namespace Atomic
  33. {
  34. extern const char* ATOMIC2D_CATEGORY;
  35. extern const char* blendModeNames[];
  36. const char* loopModeNames[] =
  37. {
  38. "Default",
  39. "ForceLooped",
  40. "ForceClamped",
  41. 0
  42. };
  43. AnimatedSprite2D::AnimatedSprite2D(Context* context) :
  44. StaticSprite2D(context),
  45. speed_(1.0f),
  46. loopMode_(LM_DEFAULT),
  47. looped_(false),
  48. currentTime_(0.0f),
  49. numTracks_(0)
  50. {
  51. }
  52. AnimatedSprite2D::~AnimatedSprite2D()
  53. {
  54. }
  55. void AnimatedSprite2D::RegisterObject(Context* context)
  56. {
  57. context->RegisterFactory<AnimatedSprite2D>(ATOMIC2D_CATEGORY);
  58. COPY_BASE_ATTRIBUTES(StaticSprite2D);
  59. REMOVE_ATTRIBUTE("Sprite");
  60. ACCESSOR_ATTRIBUTE("Speed", GetSpeed, SetSpeed, float, 1.0f, AM_DEFAULT);
  61. MIXED_ACCESSOR_ATTRIBUTE("Animation Set", GetAnimationSetAttr, SetAnimationSetAttr, ResourceRef,
  62. 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::OnSceneSet(Scene* scene)
  146. {
  147. StaticSprite2D::OnSceneSet(scene);
  148. if (scene)
  149. {
  150. if (scene == node_)
  151. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  152. if (IsEnabledEffective())
  153. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
  154. }
  155. else
  156. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  157. }
  158. void AnimatedSprite2D::SetAnimationAttr(const String& name)
  159. {
  160. animationName_ = name;
  161. if (animationSet_)
  162. SetAnimation(animationSet_->GetAnimation(animationName_), loopMode_);
  163. }
  164. void AnimatedSprite2D::OnWorldBoundingBoxUpdate()
  165. {
  166. boundingBox_.Clear();
  167. worldBoundingBox_.Clear();
  168. for (unsigned i = 0; i < numTracks_; ++i)
  169. {
  170. if (!trackNodes_[i])
  171. continue;
  172. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  173. if (staticSprite)
  174. worldBoundingBox_.Merge(staticSprite->GetWorldBoundingBox());
  175. }
  176. boundingBox_ = worldBoundingBox_.Transformed(node_->GetWorldTransform().Inverse());
  177. }
  178. void AnimatedSprite2D::OnDrawOrderChanged()
  179. {
  180. for (unsigned i = 0; i < numTracks_; ++i)
  181. {
  182. if (!trackNodes_[i])
  183. continue;
  184. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  185. if (staticSprite)
  186. staticSprite->SetLayer(layer_);
  187. }
  188. }
  189. void AnimatedSprite2D::OnFlipChanged()
  190. {
  191. for (unsigned i = 0; i < numTracks_; ++i)
  192. {
  193. if (!trackNodes_[i])
  194. continue;
  195. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  196. if (staticSprite)
  197. staticSprite->SetFlip(flipX_, flipY_);
  198. }
  199. // For editor paused mode
  200. UpdateAnimation(0.0f);
  201. }
  202. void AnimatedSprite2D::UpdateSourceBatches()
  203. {
  204. sourceBatchesDirty_ = false;
  205. }
  206. void AnimatedSprite2D::SetAnimation(Animation2D* animation, LoopMode2D loopMode)
  207. {
  208. if (animation == animation_)
  209. {
  210. SetLoopMode(loopMode_);
  211. currentTime_ = 0.0f;
  212. UpdateAnimation(0.0f);
  213. return;
  214. }
  215. for (unsigned i = 0; i < numTracks_; ++i)
  216. {
  217. if (trackNodes_[i])
  218. trackNodes_[i]->SetEnabled(false);
  219. }
  220. numTracks_ = 0;
  221. trackNodes_.Clear();
  222. trackNodeInfos_.Clear();
  223. animation_ = animation;
  224. if (!animation_)
  225. return;
  226. currentTime_ = 0.0f;
  227. if (!rootNode_)
  228. {
  229. rootNode_ = GetNode()->CreateChild("_root_", LOCAL);
  230. rootNode_->SetTemporary(true);
  231. }
  232. numTracks_ = animation_->GetNumTracks();
  233. trackNodes_.Resize(numTracks_);
  234. trackNodeInfos_.Resize(numTracks_);
  235. for (unsigned i = 0; i < numTracks_; ++i)
  236. {
  237. const AnimationTrack2D& track = animation->GetTrack(i);
  238. SharedPtr<Node> trackNode(rootNode_->GetChild(track.name_));
  239. StaticSprite2D* staticSprite = 0;
  240. if (trackNode)
  241. {
  242. // Enable track node
  243. trackNode->SetEnabled(true);
  244. // Get StaticSprite2D component
  245. if (track.hasSprite_)
  246. staticSprite = trackNode->GetComponent<StaticSprite2D>();
  247. }
  248. else
  249. {
  250. // Create new track node
  251. trackNode = rootNode_->CreateChild(track.name_, LOCAL);
  252. trackNode->SetTemporary(true);
  253. // Create StaticSprite2D component
  254. if (track.hasSprite_)
  255. {
  256. staticSprite = trackNode->CreateComponent<StaticSprite2D>();
  257. staticSprite->SetEnabled(IsEnabledEffective());
  258. }
  259. }
  260. if (staticSprite)
  261. {
  262. staticSprite->SetLayer(layer_);
  263. staticSprite->SetBlendMode(blendMode_);
  264. staticSprite->SetFlip(flipX_, flipY_);
  265. //use color of that object, animations doesn't have color
  266. staticSprite->SetColor(color_);
  267. staticSprite->SetUseHotSpot(true);
  268. }
  269. trackNodes_[i] = trackNode;
  270. trackNodeInfos_[i].hasSprite = track.hasSprite_;
  271. }
  272. SetLoopMode(loopMode);
  273. UpdateAnimation(0.0f);
  274. MarkNetworkUpdate();
  275. }
  276. void AnimatedSprite2D::UpdateAnimation(float timeStep)
  277. {
  278. if (!animation_)
  279. return;
  280. currentTime_ += timeStep * speed_;
  281. float time;
  282. float animationLength = animation_->GetLength();
  283. if (looped_)
  284. {
  285. time = fmodf(currentTime_, animationLength);
  286. if (time < 0.0f)
  287. time += animation_->GetLength();
  288. }
  289. else
  290. time = Clamp(currentTime_, 0.0f, animationLength);
  291. for (unsigned i = 0; i < numTracks_; ++i)
  292. {
  293. trackNodeInfos_[i].worldSpace = false;
  294. const AnimationTrack2D& track = animation_->GetTrack(i);
  295. const Vector<AnimationKeyFrame2D>& keyFrames = track.keyFrames_;
  296. // Time out of range
  297. if (time < keyFrames[0].time_ || time > keyFrames.Back().time_)
  298. trackNodeInfos_[i].value.enabled_ = false;
  299. else
  300. {
  301. unsigned index = keyFrames.Size() - 1;
  302. for (unsigned j = 0; j < keyFrames.Size() - 1; ++j)
  303. {
  304. if (time <= keyFrames[j + 1].time_)
  305. {
  306. index = j;
  307. break;
  308. }
  309. }
  310. const AnimationKeyFrame2D& currKey = keyFrames[index];
  311. AnimationKeyFrame2D& value = trackNodeInfos_[i].value;
  312. value.enabled_ = currKey.enabled_;
  313. value.parent_ = currKey.parent_;
  314. if (index < keyFrames.Size() - 1)
  315. {
  316. const AnimationKeyFrame2D& nextKey = keyFrames[index + 1];
  317. float t = (time - currKey.time_) / (nextKey.time_ - currKey.time_);
  318. value.transform_ = currKey.transform_.Lerp(nextKey.transform_, t, currKey.spin_);
  319. if (trackNodeInfos_[i].hasSprite)
  320. value.alpha_ = Atomic::Lerp(currKey.alpha_, nextKey.alpha_, t);
  321. }
  322. else
  323. {
  324. value.transform_ = currKey.transform_;
  325. if (trackNodeInfos_[i].hasSprite)
  326. value.alpha_ = currKey.alpha_;
  327. }
  328. if (trackNodeInfos_[i].hasSprite)
  329. {
  330. value.zIndex_ = currKey.zIndex_;
  331. value.sprite_ = currKey.sprite_;
  332. value.useHotSpot_ = currKey.useHotSpot_;
  333. value.hotSpot_ = currKey.hotSpot_;
  334. }
  335. }
  336. }
  337. for (unsigned i = 0; i < numTracks_; ++i)
  338. {
  339. Node* node = trackNodes_[i];
  340. if (!node)
  341. continue;
  342. TrackNodeInfo& nodeInfo = trackNodeInfos_[i];
  343. if (!nodeInfo.value.enabled_)
  344. node->SetEnabled(false);
  345. else
  346. {
  347. node->SetEnabled(true);
  348. // Calculate world transform.
  349. CalculateTimelineWorldTransform(i);
  350. // Update node's transform
  351. Vector2 position = nodeInfo.value.transform_.position_ * PIXEL_SIZE;
  352. if (flipX_)
  353. position.x_ = -position.x_;
  354. if (flipY_)
  355. position.y_ = -position.y_;
  356. node->SetPosition(position);
  357. float angle = nodeInfo.value.transform_.angle_;
  358. if (flipX_ != flipY_)
  359. angle = -angle;
  360. node->SetRotation(angle);
  361. node->SetScale(nodeInfo.value.transform_.scale_);
  362. if (nodeInfo.hasSprite)
  363. {
  364. StaticSprite2D* staticSprite = node->GetComponent<StaticSprite2D>();
  365. if (staticSprite)
  366. {
  367. staticSprite->SetOrderInLayer(orderInLayer_ + nodeInfo.value.zIndex_);
  368. staticSprite->SetSprite(nodeInfo.value.sprite_);
  369. staticSprite->SetAlpha(nodeInfo.value.alpha_);
  370. staticSprite->SetUseHotSpot(nodeInfo.value.useHotSpot_);
  371. staticSprite->SetHotSpot(nodeInfo.value.hotSpot_);
  372. //use color of that object, animations doesn't have color
  373. staticSprite->SetColor(color_);
  374. }
  375. }
  376. }
  377. }
  378. }
  379. void AnimatedSprite2D::CalculateTimelineWorldTransform(int index)
  380. {
  381. TrackNodeInfo& info = trackNodeInfos_[index];
  382. if (info.worldSpace)
  383. return;
  384. info.worldSpace = true;
  385. int parent = info.value.parent_;
  386. if (parent != -1)
  387. {
  388. CalculateTimelineWorldTransform(parent);
  389. info.value.transform_ = trackNodeInfos_[parent].value.transform_ * info.value.transform_;
  390. }
  391. }
  392. void AnimatedSprite2D::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  393. {
  394. using namespace ScenePostUpdate;
  395. float timeStep = eventData[P_TIMESTEP].GetFloat();
  396. UpdateAnimation(timeStep);
  397. }
  398. }