AnimationSet2D.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. //
  2. // Copyright (c) 2008-2016 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 "../Container/ArrayPtr.h"
  24. #include "../Core/Context.h"
  25. #include "../Graphics/Graphics.h"
  26. #include "../Graphics/Texture2D.h"
  27. #include "../IO/FileSystem.h"
  28. #include "../IO/Log.h"
  29. #include "../Math/AreaAllocator.h"
  30. #include "../Resource/Image.h"
  31. #include "../Resource/ResourceCache.h"
  32. #include "../Resource/XMLFile.h"
  33. #include "../Urho2D/AnimationSet2D.h"
  34. #include "../Urho2D/Sprite2D.h"
  35. #include "../Urho2D/SpriterData2D.h"
  36. #include "../Urho2D/SpriteSheet2D.h"
  37. #include "../DebugNew.h"
  38. #ifdef URHO3D_SPINE
  39. #include <spine/spine.h>
  40. #include <spine/extension.h>
  41. #endif
  42. #ifdef URHO3D_SPINE
  43. // Current animation set
  44. static Urho3D::AnimationSet2D* currentAnimationSet = 0;
  45. void _spAtlasPage_createTexture(spAtlasPage* self, const char* path)
  46. {
  47. using namespace Urho3D;
  48. if (!currentAnimationSet)
  49. return;
  50. ResourceCache* cache = currentAnimationSet->GetSubsystem<ResourceCache>();
  51. Sprite2D* sprite = cache->GetResource<Sprite2D>(path);
  52. // Add reference
  53. if (sprite)
  54. sprite->AddRef();
  55. self->width = sprite->GetTexture()->GetWidth();
  56. self->height = sprite->GetTexture()->GetHeight();
  57. self->rendererObject = sprite;
  58. }
  59. void _spAtlasPage_disposeTexture(spAtlasPage* self)
  60. {
  61. using namespace Urho3D;
  62. Sprite2D* sprite = static_cast<Sprite2D*>(self->rendererObject);
  63. if (sprite)
  64. sprite->ReleaseRef();
  65. self->rendererObject = 0;
  66. }
  67. char* _spUtil_readFile(const char* path, int* length)
  68. {
  69. using namespace Urho3D;
  70. if (!currentAnimationSet)
  71. return 0;
  72. ResourceCache* cache = currentAnimationSet->GetSubsystem<ResourceCache>();
  73. SharedPtr<File> file = cache->GetFile(path);
  74. if (!file)
  75. return 0;
  76. unsigned size = file->GetSize();
  77. char* data = MALLOC(char, size + 1);
  78. file->Read(data, size);
  79. data[size] = '\0';
  80. file.Reset();
  81. *length = size;
  82. return data;
  83. }
  84. #endif
  85. namespace Urho3D
  86. {
  87. AnimationSet2D::AnimationSet2D(Context* context) :
  88. Resource(context),
  89. #ifdef URHO3D_SPINE
  90. skeletonData_(0),
  91. atlas_(0),
  92. #endif
  93. spriterData_(0),
  94. hasSpriteSheet_(false)
  95. {
  96. }
  97. AnimationSet2D::~AnimationSet2D()
  98. {
  99. Dispose();
  100. }
  101. void AnimationSet2D::RegisterObject(Context* context)
  102. {
  103. context->RegisterFactory<AnimationSet2D>();
  104. }
  105. bool AnimationSet2D::BeginLoad(Deserializer& source)
  106. {
  107. Dispose();
  108. if (GetName().Empty())
  109. SetName(source.GetName());
  110. String extension = GetExtension(source.GetName());
  111. #ifdef URHO3D_SPINE
  112. if (extension == ".json")
  113. return BeginLoadSpine(source);
  114. #endif
  115. if (extension == ".scml")
  116. return BeginLoadSpriter(source);
  117. URHO3D_LOGERROR("Unsupport animation set file: " + source.GetName());
  118. return false;
  119. }
  120. bool AnimationSet2D::EndLoad()
  121. {
  122. #ifdef URHO3D_SPINE
  123. if (jsonData_)
  124. return EndLoadSpine();
  125. #endif
  126. if (spriterData_)
  127. return EndLoadSpriter();
  128. return false;
  129. }
  130. unsigned AnimationSet2D::GetNumAnimations() const
  131. {
  132. #ifdef URHO3D_SPINE
  133. if (skeletonData_)
  134. return (unsigned)skeletonData_->animationsCount;
  135. #endif
  136. if (spriterData_ && !spriterData_->entities_.Empty())
  137. return (unsigned)spriterData_->entities_[0]->animations_.Size();
  138. return 0;
  139. }
  140. String AnimationSet2D::GetAnimation(unsigned index) const
  141. {
  142. if (index >= GetNumAnimations())
  143. return String::EMPTY;
  144. #ifdef URHO3D_SPINE
  145. if (skeletonData_)
  146. return skeletonData_->animations[index]->name;
  147. #endif
  148. if (spriterData_ && !spriterData_->entities_.Empty())
  149. return spriterData_->entities_[0]->animations_[index]->name_;
  150. return String::EMPTY;
  151. }
  152. bool AnimationSet2D::HasAnimation(const String& animationName) const
  153. {
  154. #ifdef URHO3D_SPINE
  155. if (skeletonData_)
  156. {
  157. for (int i = 0; i < skeletonData_->animationsCount; ++i)
  158. {
  159. if (animationName == skeletonData_->animations[i]->name)
  160. return true;
  161. }
  162. }
  163. #endif
  164. if (spriterData_ && !spriterData_->entities_.Empty())
  165. {
  166. const PODVector<Spriter::Animation*>& animations = spriterData_->entities_[0]->animations_;
  167. for (size_t i = 0; i < animations.Size(); ++i)
  168. {
  169. if (animationName == animations[i]->name_)
  170. return true;
  171. }
  172. }
  173. return false;
  174. }
  175. Sprite2D* AnimationSet2D::GetSprite() const
  176. {
  177. return sprite_;
  178. }
  179. Sprite2D* AnimationSet2D::GetSpriterFileSprite(int folderId, int fileId) const
  180. {
  181. int key = (folderId << 16) + fileId;
  182. HashMap<int, SharedPtr<Sprite2D> >::ConstIterator i = spriterFileSprites_.Find(key);
  183. if (i != spriterFileSprites_.End())
  184. return i->second_;
  185. return 0;
  186. }
  187. #ifdef URHO3D_SPINE
  188. bool AnimationSet2D::BeginLoadSpine(Deserializer& source)
  189. {
  190. if (GetName().Empty())
  191. SetName(source.GetName());
  192. unsigned size = source.GetSize();
  193. jsonData_ = new char[size + 1];
  194. source.Read(jsonData_, size);
  195. jsonData_[size] = '\0';
  196. SetMemoryUse(size);
  197. return true;
  198. }
  199. bool AnimationSet2D::EndLoadSpine()
  200. {
  201. currentAnimationSet = this;
  202. String atlasFileName = ReplaceExtension(GetName(), ".atlas");
  203. atlas_ = spAtlas_createFromFile(atlasFileName.CString(), 0);
  204. if (!atlas_)
  205. {
  206. URHO3D_LOGERROR("Create spine atlas failed");
  207. return false;
  208. }
  209. int numAtlasPages = 0;
  210. spAtlasPage* atlasPage = atlas_->pages;
  211. while (atlasPage)
  212. {
  213. ++numAtlasPages;
  214. atlasPage = atlasPage->next;
  215. }
  216. if (numAtlasPages > 1)
  217. {
  218. URHO3D_LOGERROR("Only one page is supported in Urho3D");
  219. return false;
  220. }
  221. sprite_ = static_cast<Sprite2D*>(atlas_->pages->rendererObject);
  222. spSkeletonJson* skeletonJson = spSkeletonJson_create(atlas_);
  223. if (!skeletonJson)
  224. {
  225. URHO3D_LOGERROR("Create skeleton Json failed");
  226. return false;
  227. }
  228. skeletonJson->scale = 0.01f; // PIXEL_SIZE;
  229. skeletonData_ = spSkeletonJson_readSkeletonData(skeletonJson, &jsonData_[0]);
  230. spSkeletonJson_dispose(skeletonJson);
  231. jsonData_.Reset();
  232. currentAnimationSet = 0;
  233. return true;
  234. }
  235. #endif
  236. bool AnimationSet2D::BeginLoadSpriter(Deserializer& source)
  237. {
  238. unsigned dataSize = source.GetSize();
  239. if (!dataSize && !source.GetName().Empty())
  240. {
  241. URHO3D_LOGERROR("Zero sized XML data in " + source.GetName());
  242. return false;
  243. }
  244. SharedArrayPtr<char> buffer(new char[dataSize]);
  245. if (source.Read(buffer.Get(), dataSize) != dataSize)
  246. return false;
  247. spriterData_ = new Spriter::SpriterData();
  248. if (!spriterData_->Load(buffer.Get(), dataSize))
  249. {
  250. URHO3D_LOGERROR("Could not spriter data from " + source.GetName());
  251. return false;
  252. }
  253. // Check has sprite sheet
  254. String parentPath = GetParentPath(GetName());
  255. ResourceCache* cache = GetSubsystem<ResourceCache>();
  256. spriteSheetFilePath_ = parentPath + GetFileName(GetName()) + ".xml";
  257. hasSpriteSheet_ = cache->Exists(spriteSheetFilePath_);
  258. if (!hasSpriteSheet_)
  259. {
  260. spriteSheetFilePath_ = parentPath + GetFileName(GetName()) + ".plist";
  261. hasSpriteSheet_ = cache->Exists(spriteSheetFilePath_);
  262. }
  263. if (GetAsyncLoadState() == ASYNC_LOADING)
  264. {
  265. if (hasSpriteSheet_)
  266. cache->BackgroundLoadResource<SpriteSheet2D>(spriteSheetFilePath_, true, this);
  267. else
  268. {
  269. for (size_t i = 0; i < spriterData_->folders_.Size(); ++i)
  270. {
  271. Spriter::Folder* folder = spriterData_->folders_[i];
  272. for (size_t j = 0; j < folder->files_.Size(); ++j)
  273. {
  274. Spriter::File* file = folder->files_[j];
  275. String imagePath = parentPath + file->name_;
  276. cache->BackgroundLoadResource<Image>(imagePath, true, this);
  277. }
  278. }
  279. }
  280. }
  281. // Note: this probably does not reflect internal data structure size accurately
  282. SetMemoryUse(dataSize);
  283. return true;
  284. }
  285. struct SpriteInfo
  286. {
  287. int x;
  288. int y;
  289. Spriter::File* file_;
  290. SharedPtr<Image> image_;
  291. };
  292. bool AnimationSet2D::EndLoadSpriter()
  293. {
  294. if (!spriterData_)
  295. return false;
  296. ResourceCache* cache = GetSubsystem<ResourceCache>();
  297. if (hasSpriteSheet_)
  298. {
  299. spriteSheet_ = cache->GetResource<SpriteSheet2D>(spriteSheetFilePath_);
  300. if (!spriteSheet_)
  301. return false;
  302. for (unsigned i = 0; i < spriterData_->folders_.Size(); ++i)
  303. {
  304. Spriter::Folder* folder = spriterData_->folders_[i];
  305. for (unsigned j = 0; j < folder->files_.Size(); ++j)
  306. {
  307. Spriter::File* file = folder->files_[j];
  308. SharedPtr<Sprite2D> sprite(spriteSheet_->GetSprite(GetFileName(file->name_)));
  309. if (!sprite)
  310. {
  311. URHO3D_LOGERROR("Could not load sprite " + file->name_);
  312. return false;
  313. }
  314. Vector2 hotSpot(file->pivotX_, file->pivotY_);
  315. // If sprite is trimmed, recalculate hot spot
  316. const IntVector2& offset = sprite->GetOffset();
  317. if (offset != IntVector2::ZERO)
  318. {
  319. float pivotX = file->width_ * hotSpot.x_;
  320. float pivotY = file->height_ * (1.0f - hotSpot.y_);
  321. const IntRect& rectangle = sprite->GetRectangle();
  322. hotSpot.x_ = (offset.x_ + pivotX) / rectangle.Width();
  323. hotSpot.y_ = 1.0f - (offset.y_ + pivotY) / rectangle.Height();
  324. }
  325. sprite->SetHotSpot(hotSpot);
  326. if (!sprite_)
  327. sprite_ = sprite;
  328. int key = (folder->id_ << 16) + file->id_;
  329. spriterFileSprites_[key] = sprite;
  330. }
  331. }
  332. }
  333. else
  334. {
  335. Vector<SpriteInfo> spriteInfos;
  336. String parentPath = GetParentPath(GetName());
  337. for (unsigned i = 0; i < spriterData_->folders_.Size(); ++i)
  338. {
  339. Spriter::Folder* folder = spriterData_->folders_[i];
  340. for (unsigned j = 0; j < folder->files_.Size(); ++j)
  341. {
  342. Spriter::File* file = folder->files_[j];
  343. String imagePath = parentPath + file->name_;
  344. SharedPtr<Image> image(cache->GetResource<Image>(imagePath));
  345. if (!image)
  346. {
  347. URHO3D_LOGERROR("Could not load image");
  348. return false;
  349. }
  350. if (image->IsCompressed())
  351. {
  352. URHO3D_LOGERROR("Compressed image is not support");
  353. return false;
  354. }
  355. if (image->GetComponents() != 4)
  356. {
  357. URHO3D_LOGERROR("Only support image with 4 components");
  358. return false;
  359. }
  360. SpriteInfo def;
  361. def.x = 0;
  362. def.y = 0;
  363. def.file_ = file;
  364. def.image_ = image;
  365. spriteInfos.Push(def);
  366. }
  367. }
  368. if (spriteInfos.Empty())
  369. return false;
  370. if (spriteInfos.Size() > 1)
  371. {
  372. AreaAllocator allocator(128, 128, 2048, 2048);
  373. for (unsigned i = 0; i < spriteInfos.Size(); ++i)
  374. {
  375. SpriteInfo& info = spriteInfos[i];
  376. Image* image = info.image_;
  377. if (!allocator.Allocate(image->GetWidth() + 1, image->GetHeight() + 1, info.x, info.y))
  378. {
  379. URHO3D_LOGERROR("Could not allocate area");
  380. return false;
  381. }
  382. }
  383. SharedPtr<Texture2D> texture(new Texture2D(context_));
  384. texture->SetMipsToSkip(QUALITY_LOW, 0);
  385. texture->SetNumLevels(1);
  386. texture->SetSize(allocator.GetWidth(), allocator.GetHeight(), Graphics::GetRGBAFormat());
  387. unsigned textureDataSize = allocator.GetWidth() * allocator.GetHeight() * 4;
  388. SharedArrayPtr<unsigned char> textureData(new unsigned char[textureDataSize]);
  389. memset(textureData.Get(), 0, textureDataSize);
  390. sprite_ = new Sprite2D(context_);
  391. sprite_->SetTexture(texture);
  392. for (unsigned i = 0; i < spriteInfos.Size(); ++i)
  393. {
  394. SpriteInfo& info = spriteInfos[i];
  395. Image* image = info.image_;
  396. for (int y = 0; y < image->GetHeight(); ++y)
  397. {
  398. memcpy(textureData.Get() + ((info.y + y) * allocator.GetWidth() + info.x) * 4,
  399. image->GetData() + y * image->GetWidth() * 4, image->GetWidth() * 4);
  400. }
  401. SharedPtr<Sprite2D> sprite(new Sprite2D(context_));
  402. sprite->SetTexture(texture);
  403. sprite->SetRectangle(IntRect(info.x, info.y, info.x + image->GetWidth(), info.y + image->GetHeight()));
  404. sprite->SetHotSpot(Vector2(info.file_->pivotX_, info.file_->pivotY_));
  405. int key = (info.file_->folder_->id_ << 16) + info.file_->id_;
  406. spriterFileSprites_[key] = sprite;
  407. }
  408. texture->SetData(0, 0, 0, allocator.GetWidth(), allocator.GetHeight(), textureData.Get());
  409. }
  410. else
  411. {
  412. SharedPtr<Texture2D> texture(new Texture2D(context_));
  413. texture->SetMipsToSkip(QUALITY_LOW, 0);
  414. texture->SetNumLevels(1);
  415. SpriteInfo& info = spriteInfos[0];
  416. texture->SetData(info.image_, true);
  417. sprite_ = new Sprite2D(context_);
  418. sprite_->SetTexture(texture);
  419. sprite_->SetRectangle(IntRect(info.x, info.y, info.x + info.image_->GetWidth(), info.y + info.image_->GetHeight()));
  420. sprite_->SetHotSpot(Vector2(info.file_->pivotX_, info.file_->pivotY_));
  421. int key = (info.file_->folder_->id_ << 16) + info.file_->id_;
  422. spriterFileSprites_[key] = sprite_;
  423. }
  424. }
  425. return true;
  426. }
  427. void AnimationSet2D::Dispose()
  428. {
  429. #ifdef URHO3D_SPINE
  430. if (skeletonData_)
  431. {
  432. spSkeletonData_dispose(skeletonData_);
  433. skeletonData_ = 0;
  434. }
  435. if (atlas_)
  436. {
  437. spAtlas_dispose(atlas_);
  438. atlas_ = 0;
  439. }
  440. #endif
  441. if (spriterData_)
  442. {
  443. delete spriterData_;
  444. spriterData_ = 0;
  445. }
  446. sprite_.Reset();
  447. spriteSheet_.Reset();
  448. spriterFileSprites_.Clear();
  449. }
  450. }