AnimatedSprite2D.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. //
  2. // Copyright (c) 2008-2014 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 "AnimatedSprite2D.h"
  24. #include "Animation2D.h"
  25. #include "AnimationSet2D.h"
  26. #include "Context.h"
  27. #include "ResourceCache.h"
  28. #include "Scene.h"
  29. #include "SceneEvents.h"
  30. #include "Sprite2D.h"
  31. #include "StaticSprite2D.h"
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. extern const char* URHO2D_CATEGORY;
  36. extern const char* blendModeNames[];
  37. AnimatedSprite2D::AnimatedSprite2D(Context* context) :
  38. Drawable(context, DRAWABLE_GEOMETRY),
  39. layer_(0),
  40. orderInLayer_(0),
  41. blendMode_(BLEND_ALPHA),
  42. flipX_(false),
  43. flipY_(false),
  44. color_(Color::WHITE),
  45. speed_(1.0f),
  46. currentTime_(0.0f)
  47. {
  48. }
  49. AnimatedSprite2D::~AnimatedSprite2D()
  50. {
  51. }
  52. void AnimatedSprite2D::RegisterObject(Context* context)
  53. {
  54. context->RegisterFactory<AnimatedSprite2D>(URHO2D_CATEGORY);
  55. ACCESSOR_ATTRIBUTE(AnimatedSprite2D, VAR_INT, "Layer", GetLayer, SetLayer, int, 0, AM_DEFAULT);
  56. ACCESSOR_ATTRIBUTE(AnimatedSprite2D, VAR_INT, "Order in Layer", GetOrderInLayer, SetOrderInLayer, int, 0, AM_DEFAULT);
  57. ENUM_ACCESSOR_ATTRIBUTE(AnimatedSprite2D, "Blend Mode", GetBlendMode, SetBlendMode, BlendMode, blendModeNames, BLEND_ALPHA, AM_DEFAULT);
  58. ACCESSOR_ATTRIBUTE(AnimatedSprite2D, VAR_BOOL, "Flip X", GetFlipX, SetFlipX, bool, false, AM_DEFAULT);
  59. ACCESSOR_ATTRIBUTE(AnimatedSprite2D, VAR_BOOL, "Flip Y", GetFlipY, SetFlipY, bool, false, AM_DEFAULT);
  60. REF_ACCESSOR_ATTRIBUTE(AnimatedSprite2D, VAR_COLOR, "Color", GetColor, SetColor, Color, Color::WHITE, AM_DEFAULT);
  61. ACCESSOR_ATTRIBUTE(AnimatedSprite2D, VAR_FLOAT, "Speed", GetSpeed, SetSpeed, float, 1.0f, AM_DEFAULT);
  62. ACCESSOR_ATTRIBUTE(AnimatedSprite2D, VAR_RESOURCEREF, "Animation Set", GetAnimationSetAttr, SetAnimationSetAttr, ResourceRef, ResourceRef(AnimatedSprite2D::GetTypeStatic()), AM_DEFAULT);
  63. REF_ACCESSOR_ATTRIBUTE(AnimatedSprite2D, VAR_STRING, "Animation", GetAnimation, SetAnimation, String, String::EMPTY, AM_DEFAULT);
  64. COPY_BASE_ATTRIBUTES(Drawable2D, Drawable);
  65. }
  66. void AnimatedSprite2D::OnSetEnabled()
  67. {
  68. Drawable::OnSetEnabled();
  69. Scene* scene = GetScene();
  70. if (scene)
  71. {
  72. if (IsEnabledEffective())
  73. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
  74. else
  75. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  76. }
  77. }
  78. void AnimatedSprite2D::SetLayer(int layer)
  79. {
  80. if (layer == layer_)
  81. return;
  82. layer_ = layer;
  83. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  84. {
  85. if (!timelineNodes_[i])
  86. continue;
  87. StaticSprite2D* staticSprite = timelineNodes_[i]->GetComponent<StaticSprite2D>();
  88. staticSprite->SetLayer(layer_);
  89. }
  90. }
  91. void AnimatedSprite2D::SetOrderInLayer(int orderInLayer)
  92. {
  93. orderInLayer_ = orderInLayer;
  94. }
  95. void AnimatedSprite2D::SetBlendMode(BlendMode blendMode)
  96. {
  97. if (blendMode == blendMode_)
  98. return;
  99. blendMode_ = blendMode;
  100. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  101. {
  102. if (!timelineNodes_[i])
  103. continue;
  104. StaticSprite2D* staticSprite = timelineNodes_[i]->GetComponent<StaticSprite2D>();
  105. staticSprite->SetBlendMode(blendMode_);
  106. }
  107. }
  108. void AnimatedSprite2D::SetFlip(bool flipX, bool flipY)
  109. {
  110. if (flipX_ == flipX && flipY_ == flipY)
  111. return;
  112. flipX_ = flipX;
  113. flipY_ = flipY;
  114. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  115. {
  116. if (!timelineNodes_[i])
  117. continue;
  118. StaticSprite2D* staticSprite = timelineNodes_[i]->GetComponent<StaticSprite2D>();
  119. staticSprite->SetFlip(flipX_, flipY_);
  120. }
  121. MarkNetworkUpdate();
  122. }
  123. void AnimatedSprite2D::SetFlipX(bool flipX)
  124. {
  125. SetFlip(flipX, flipY_);
  126. }
  127. void AnimatedSprite2D::SetFlipY(bool flipY)
  128. {
  129. SetFlip(flipX_, flipY);
  130. }
  131. void AnimatedSprite2D::SetColor(const Color& color)
  132. {
  133. color_ = color;
  134. MarkNetworkUpdate();
  135. }
  136. void AnimatedSprite2D::SetSpeed(float speed)
  137. {
  138. speed_ = speed;
  139. MarkNetworkUpdate();
  140. }
  141. void AnimatedSprite2D::SetAnimation(AnimationSet2D* animationSet, const String& name)
  142. {
  143. animationSet_ = animationSet;
  144. animationName_ = name;
  145. if (animationSet)
  146. SetAnimation(animationSet->GetAnimation(name));
  147. else
  148. SetAnimation(0);
  149. }
  150. void AnimatedSprite2D::SetAnimationSet(AnimationSet2D* animationSet)
  151. {
  152. if (animationSet == animationSet_)
  153. return;
  154. animationSet_ = animationSet;
  155. if (animationSet_)
  156. SetAnimation(animationSet_->GetAnimation(animationName_));
  157. else
  158. SetAnimation(0);
  159. }
  160. void AnimatedSprite2D::SetAnimation(const String& name)
  161. {
  162. animationName_ = name;
  163. if (animationSet_)
  164. SetAnimation(animationSet_->GetAnimation(animationName_));
  165. }
  166. AnimationSet2D* AnimatedSprite2D::GetAnimationSet() const
  167. {
  168. return animationSet_;
  169. }
  170. void AnimatedSprite2D::SetAnimationSetAttr(ResourceRef value)
  171. {
  172. ResourceCache* cache = GetSubsystem<ResourceCache>();
  173. SetAnimationSet(cache->GetResource<AnimationSet2D>(value.name_));
  174. }
  175. Urho3D::ResourceRef AnimatedSprite2D::GetAnimationSetAttr() const
  176. {
  177. return GetResourceRef(animationSet_, AnimationSet2D::GetTypeStatic());
  178. }
  179. void AnimatedSprite2D::OnNodeSet(Node* node)
  180. {
  181. Drawable::OnNodeSet(node);
  182. if (node)
  183. {
  184. Scene* scene = GetScene();
  185. if (scene && IsEnabledEffective())
  186. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
  187. }
  188. }
  189. void AnimatedSprite2D::OnWorldBoundingBoxUpdate()
  190. {
  191. boundingBox_.Clear();
  192. worldBoundingBox_.Clear();
  193. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  194. {
  195. if (!timelineNodes_[i])
  196. continue;
  197. StaticSprite2D* staticSprite = timelineNodes_[i]->GetComponent<StaticSprite2D>();
  198. worldBoundingBox_.Merge(staticSprite->GetWorldBoundingBox());
  199. }
  200. boundingBox_ = worldBoundingBox_.Transformed(node_->GetWorldTransform().Inverse());
  201. }
  202. void AnimatedSprite2D::SetAnimation(Animation2D* animation)
  203. {
  204. if (animation == animation_)
  205. {
  206. // Reset time
  207. currentTime_ = 0.0f;
  208. return;
  209. }
  210. if (animation_)
  211. {
  212. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  213. {
  214. if (timelineNodes_[i])
  215. timelineNodes_[i]->Remove();
  216. }
  217. timelineNodes_.Clear();
  218. }
  219. animation_ = animation;
  220. if (!animation_)
  221. return;
  222. currentTime_ = 0.0f;
  223. timelineNodes_.Resize(animation_->GetNumTimelines());
  224. timelineTransformInfos_.Resize(animation_->GetNumTimelines());
  225. for (unsigned i = 0; i < animation_->GetNumTimelines(); ++i)
  226. {
  227. const Timeline2D& timeline = animation->GetTimeline(i);
  228. // Just create sprite type node
  229. if (timeline.type_ == OT_SPRITE)
  230. {
  231. SharedPtr<Node> timelineNode(GetNode()->CreateChild(timeline.name_));
  232. StaticSprite2D* staticSprite = timelineNode->CreateComponent<StaticSprite2D>();
  233. staticSprite->SetLayer(layer_);
  234. staticSprite->SetBlendMode(blendMode_);
  235. staticSprite->SetFlip(flipX_, flipY_);
  236. staticSprite->SetUseHotSpot(true);
  237. timelineNodes_[i] = timelineNode;
  238. }
  239. timelineTransformInfos_[i].parent_ = timeline.parent_;
  240. }
  241. UpdateAnimation(0.0f);
  242. MarkNetworkUpdate();
  243. }
  244. void AnimatedSprite2D::UpdateAnimation(float timeStep)
  245. {
  246. if (!animation_)
  247. return;
  248. currentTime_ += timeStep * speed_;
  249. float time;
  250. float animtationLength = animation_->GetLength();
  251. if (animation_->IsLooped())
  252. {
  253. time = fmodf(currentTime_, animtationLength);
  254. if (time < 0.0f)
  255. time += animation_->GetLength();
  256. }
  257. else
  258. time = Clamp(currentTime_, 0.0f, animtationLength);
  259. // Update timeline's local transform
  260. for (unsigned i = 0; i < timelineTransformInfos_.Size(); ++i)
  261. {
  262. const Timeline2D& timeline = animation_->GetTimeline(i);
  263. const Vector<TimelineKey2D>& objectKeys = timeline.timelineKeys_;
  264. for (unsigned j = 0; j < objectKeys.Size() - 1; ++j)
  265. {
  266. if (time <= objectKeys[j + 1].time_)
  267. {
  268. const TimelineKey2D& currKey = objectKeys[j];
  269. const TimelineKey2D& nextKey = objectKeys[j + 1];
  270. float t = (time - currKey.time_) / (nextKey.time_ - currKey.time_);
  271. timelineTransformInfos_[i].worldSpace_ = false;
  272. timelineTransformInfos_[i].transform_ = currKey.transform_.Lerp(nextKey.transform_, t, currKey.spin_);
  273. // Update sprite's sprite and hot spot and color
  274. Node* timelineNode = timelineNodes_[i];
  275. if (timelineNode)
  276. {
  277. StaticSprite2D* staticSprite = timelineNode->GetComponent<StaticSprite2D>();
  278. staticSprite->SetSprite(currKey.sprite_);
  279. staticSprite->SetHotSpot(currKey.hotSpot_.Lerp(nextKey.hotSpot_, t));
  280. float alpha = Lerp(currKey.alpha_, nextKey.alpha_, t);
  281. staticSprite->SetColor(Color(color_.r_, color_.g_, color_.b_, color_.a_ * alpha));
  282. }
  283. break;
  284. }
  285. }
  286. }
  287. // Calculate timeline world transform.
  288. for (unsigned i = 0; i < timelineTransformInfos_.Size(); ++i)
  289. CalculateTimelineWorldTransform(i);
  290. // Get mainline key
  291. const Vector<MainlineKey2D>& mainlineKeys = animation_->GetMainlineKeys();
  292. const MainlineKey2D* mainlineKey = 0;
  293. for (unsigned i = 1; i < mainlineKeys.Size(); ++i)
  294. {
  295. if (time < mainlineKeys[i].time_)
  296. {
  297. mainlineKey = &mainlineKeys[i - 1];
  298. break;
  299. }
  300. }
  301. if (!mainlineKey)
  302. mainlineKey = &mainlineKeys.Back();
  303. // Update node's transform and sprite's z order
  304. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  305. {
  306. Node* timelineNode = timelineNodes_[i];
  307. if (!timelineNode)
  308. continue;
  309. const Reference2D* ref = mainlineKey->GetReference(i);
  310. if (!ref)
  311. {
  312. // Disable node
  313. if (timelineNode->IsEnabled())
  314. timelineNode->SetEnabled(false);
  315. }
  316. else
  317. {
  318. // Enable node
  319. if (!timelineNode->IsEnabled())
  320. timelineNode->SetEnabled(true);
  321. // Update node's transform
  322. const Transform2D& transform = timelineTransformInfos_[i].transform_;
  323. Vector2 position = transform.position_;
  324. if (flipX_)
  325. position.x_ = -position.x_;
  326. if (flipY_)
  327. position.y_ = -position.y_;
  328. timelineNode->SetPosition(position);
  329. float angle = transform.angle_;
  330. if (flipX_ != flipY_)
  331. angle = -angle;
  332. timelineNode->SetRotation(angle);
  333. timelineNode->SetScale(transform.scale_);
  334. // Update sprite's z order
  335. StaticSprite2D* staticSprite = timelineNode->GetComponent<StaticSprite2D>();
  336. staticSprite->SetOrderInLayer(orderInLayer_ + ref->zIndex_);
  337. }
  338. }
  339. MarkForUpdate();
  340. }
  341. void AnimatedSprite2D::CalculateTimelineWorldTransform(unsigned index)
  342. {
  343. TransformInfo& info = timelineTransformInfos_[index];
  344. if (info.worldSpace_)
  345. return;
  346. info.worldSpace_ = true;
  347. if (info.parent_ != -1)
  348. {
  349. CalculateTimelineWorldTransform(info.parent_);
  350. info.transform_ = timelineTransformInfos_[info.parent_].transform_ * info.transform_;
  351. }
  352. }
  353. void AnimatedSprite2D::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  354. {
  355. using namespace ScenePostUpdate;
  356. float timeStep = eventData[P_TIMESTEP].GetFloat();
  357. UpdateAnimation(timeStep);
  358. }
  359. }