CCSpriteFrameCache.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2009 Jason Booth
  4. Copyright (c) 2009 Robert J Payne
  5. Copyright (c) 2010-2012 cocos2d-x.org
  6. Copyright (c) 2011 Zynga Inc.
  7. Copyright (c) 2013-2017 Chukong Technologies Inc.
  8. http://www.cocos2d-x.org
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in
  16. all copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. THE SOFTWARE.
  24. ****************************************************************************/
  25. #include "2d/CCSpriteFrameCache.h"
  26. #include <vector>
  27. #include "2d/CCSprite.h"
  28. #include "2d/CCAutoPolygon.h"
  29. #include "platform/CCFileUtils.h"
  30. #include "base/CCNS.h"
  31. #include "base/ccMacros.h"
  32. #include "base/ccUTF8.h"
  33. #include "base/CCDirector.h"
  34. #include "renderer/CCTexture2D.h"
  35. #include "renderer/CCTextureCache.h"
  36. #include "base/CCNinePatchImageParser.h"
  37. using namespace std;
  38. NS_CC_BEGIN
  39. static SpriteFrameCache *_sharedSpriteFrameCache = nullptr;
  40. SpriteFrameCache* SpriteFrameCache::getInstance()
  41. {
  42. if (! _sharedSpriteFrameCache)
  43. {
  44. _sharedSpriteFrameCache = new (std::nothrow) SpriteFrameCache();
  45. _sharedSpriteFrameCache->init();
  46. }
  47. return _sharedSpriteFrameCache;
  48. }
  49. void SpriteFrameCache::destroyInstance()
  50. {
  51. CC_SAFE_RELEASE_NULL(_sharedSpriteFrameCache);
  52. }
  53. bool SpriteFrameCache::init()
  54. {
  55. _spriteFrames.reserve(20);
  56. _spriteFramesAliases.reserve(20);
  57. _loadedFileNames = new std::set<std::string>();
  58. return true;
  59. }
  60. SpriteFrameCache::~SpriteFrameCache()
  61. {
  62. CC_SAFE_DELETE(_loadedFileNames);
  63. }
  64. void SpriteFrameCache::parseIntegerList(const std::string &string, std::vector<int> &res)
  65. {
  66. std::string delim(" ");
  67. size_t n = std::count(string.begin(), string.end(), ' ');
  68. res.resize(n+1);
  69. size_t start = 0U;
  70. size_t end = string.find(delim);
  71. int i=0;
  72. while (end != std::string::npos)
  73. {
  74. res[i++] = atoi(string.substr(start, end - start).c_str());
  75. start = end + delim.length();
  76. end = string.find(delim, start);
  77. }
  78. res[i] = atoi(string.substr(start, end).c_str());
  79. }
  80. void SpriteFrameCache::initializePolygonInfo(const Size &textureSize,
  81. const Size &spriteSize,
  82. const std::vector<int> &vertices,
  83. const std::vector<int> &verticesUV,
  84. const std::vector<int> &triangleIndices,
  85. PolygonInfo &info)
  86. {
  87. size_t vertexCount = vertices.size();
  88. size_t indexCount = triangleIndices.size();
  89. float scaleFactor = CC_CONTENT_SCALE_FACTOR();
  90. V3F_C4B_T2F *vertexData = new (std::nothrow) V3F_C4B_T2F[vertexCount];
  91. for (size_t i = 0; i < vertexCount/2; i++)
  92. {
  93. vertexData[i].colors = Color4B::WHITE;
  94. vertexData[i].vertices = Vec3(vertices[i*2] / scaleFactor,
  95. (spriteSize.height - vertices[i*2+1]) / scaleFactor,
  96. 0);
  97. vertexData[i].texCoords = Tex2F(verticesUV[i*2] / textureSize.width,
  98. verticesUV[i*2+1] / textureSize.height);
  99. }
  100. unsigned short *indexData = new unsigned short[indexCount];
  101. for (size_t i = 0; i < indexCount; i++)
  102. {
  103. indexData[i] = static_cast<unsigned short>(triangleIndices[i]);
  104. }
  105. info.triangles.vertCount = static_cast<int>(vertexCount);
  106. info.triangles.verts = vertexData;
  107. info.triangles.indexCount = static_cast<int>(indexCount);
  108. info.triangles.indices = indexData;
  109. info.setRect(Rect(0, 0, spriteSize.width, spriteSize.height));
  110. }
  111. void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture)
  112. {
  113. /*
  114. Supported Zwoptex Formats:
  115. ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
  116. ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
  117. ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
  118. ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
  119. Version 3 with TexturePacker 4.0 polygon mesh packing
  120. */
  121. if (dictionary["frames"].getType() != cocos2d::Value::Type::MAP)
  122. return;
  123. ValueMap& framesDict = dictionary["frames"].asValueMap();
  124. int format = 0;
  125. Size textureSize;
  126. // get the format
  127. if (dictionary.find("metadata") != dictionary.end())
  128. {
  129. ValueMap& metadataDict = dictionary["metadata"].asValueMap();
  130. format = metadataDict["format"].asInt();
  131. if(metadataDict.find("size") != metadataDict.end())
  132. {
  133. textureSize = SizeFromString(metadataDict["size"].asString());
  134. }
  135. }
  136. // check the format
  137. CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");
  138. auto textureFileName = Director::getInstance()->getTextureCache()->getTextureFilePath(texture);
  139. Image* image = nullptr;
  140. NinePatchImageParser parser;
  141. for (auto& iter : framesDict)
  142. {
  143. ValueMap& frameDict = iter.second.asValueMap();
  144. std::string spriteFrameName = iter.first;
  145. SpriteFrame* spriteFrame = _spriteFrames.at(spriteFrameName);
  146. if (spriteFrame)
  147. {
  148. continue;
  149. }
  150. if(format == 0)
  151. {
  152. float x = frameDict["x"].asFloat();
  153. float y = frameDict["y"].asFloat();
  154. float w = frameDict["width"].asFloat();
  155. float h = frameDict["height"].asFloat();
  156. float ox = frameDict["offsetX"].asFloat();
  157. float oy = frameDict["offsetY"].asFloat();
  158. int ow = frameDict["originalWidth"].asInt();
  159. int oh = frameDict["originalHeight"].asInt();
  160. // check ow/oh
  161. if(!ow || !oh)
  162. {
  163. CCLOGWARN("cocos2d: WARNING: originalWidth/Height not found on the SpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist");
  164. }
  165. // abs ow/oh
  166. ow = std::abs(ow);
  167. oh = std::abs(oh);
  168. // create frame
  169. spriteFrame = SpriteFrame::createWithTexture(texture,
  170. Rect(x, y, w, h),
  171. false,
  172. Vec2(ox, oy),
  173. Size((float)ow, (float)oh)
  174. );
  175. }
  176. else if(format == 1 || format == 2)
  177. {
  178. Rect frame = RectFromString(frameDict["frame"].asString());
  179. bool rotated = false;
  180. // rotation
  181. if (format == 2)
  182. {
  183. rotated = frameDict["rotated"].asBool();
  184. }
  185. Vec2 offset = PointFromString(frameDict["offset"].asString());
  186. Size sourceSize = SizeFromString(frameDict["sourceSize"].asString());
  187. // create frame
  188. spriteFrame = SpriteFrame::createWithTexture(texture,
  189. frame,
  190. rotated,
  191. offset,
  192. sourceSize
  193. );
  194. }
  195. else if (format == 3)
  196. {
  197. // get values
  198. Size spriteSize = SizeFromString(frameDict["spriteSize"].asString());
  199. Vec2 spriteOffset = PointFromString(frameDict["spriteOffset"].asString());
  200. Size spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString());
  201. Rect textureRect = RectFromString(frameDict["textureRect"].asString());
  202. bool textureRotated = frameDict["textureRotated"].asBool();
  203. // get aliases
  204. ValueVector& aliases = frameDict["aliases"].asValueVector();
  205. for(const auto &value : aliases) {
  206. std::string oneAlias = value.asString();
  207. if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end())
  208. {
  209. CCLOGWARN("cocos2d: WARNING: an alias with name %s already exists", oneAlias.c_str());
  210. }
  211. _spriteFramesAliases[oneAlias] = Value(spriteFrameName);
  212. }
  213. // create frame
  214. spriteFrame = SpriteFrame::createWithTexture(texture,
  215. Rect(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height),
  216. textureRotated,
  217. spriteOffset,
  218. spriteSourceSize);
  219. if(frameDict.find("vertices") != frameDict.end())
  220. {
  221. std::vector<int> vertices;
  222. parseIntegerList(frameDict["vertices"].asString(), vertices);
  223. std::vector<int> verticesUV;
  224. parseIntegerList(frameDict["verticesUV"].asString(), verticesUV);
  225. std::vector<int> indices;
  226. parseIntegerList(frameDict["triangles"].asString(), indices);
  227. PolygonInfo info;
  228. initializePolygonInfo(textureSize, spriteSourceSize, vertices, verticesUV, indices, info);
  229. spriteFrame->setPolygonInfo(info);
  230. }
  231. if (frameDict.find("anchor") != frameDict.end())
  232. {
  233. spriteFrame->setAnchorPoint(PointFromString(frameDict["anchor"].asString()));
  234. }
  235. }
  236. bool flag = NinePatchImageParser::isNinePatchImage(spriteFrameName);
  237. if(flag)
  238. {
  239. if (image == nullptr) {
  240. image = new (std::nothrow) Image();
  241. image->initWithImageFile(textureFileName);
  242. }
  243. parser.setSpriteFrameInfo(image, spriteFrame->getRectInPixels(), spriteFrame->isRotated());
  244. texture->addSpriteFrameCapInset(spriteFrame, parser.parseCapInset());
  245. }
  246. // add sprite frame
  247. _spriteFrames.insert(spriteFrameName, spriteFrame);
  248. }
  249. CC_SAFE_DELETE(image);
  250. }
  251. void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dict, const std::string &texturePath)
  252. {
  253. std::string pixelFormatName;
  254. if (dict.find("metadata") != dict.end())
  255. {
  256. ValueMap& metadataDict = dict.at("metadata").asValueMap();
  257. if (metadataDict.find("pixelFormat") != metadataDict.end())
  258. {
  259. pixelFormatName = metadataDict.at("pixelFormat").asString();
  260. }
  261. }
  262. Texture2D *texture = nullptr;
  263. static std::unordered_map<std::string, Texture2D::PixelFormat> pixelFormats = {
  264. {"RGBA8888", Texture2D::PixelFormat::RGBA8888},
  265. {"RGBA4444", Texture2D::PixelFormat::RGBA4444},
  266. {"RGB5A1", Texture2D::PixelFormat::RGB5A1},
  267. {"RGBA5551", Texture2D::PixelFormat::RGB5A1},
  268. {"RGB565", Texture2D::PixelFormat::RGB565},
  269. {"A8", Texture2D::PixelFormat::A8},
  270. {"ALPHA", Texture2D::PixelFormat::A8},
  271. {"I8", Texture2D::PixelFormat::I8},
  272. {"AI88", Texture2D::PixelFormat::AI88},
  273. {"ALPHA_INTENSITY", Texture2D::PixelFormat::AI88},
  274. //{"BGRA8888", Texture2D::PixelFormat::BGRA8888}, no Image conversion RGBA -> BGRA
  275. {"RGB888", Texture2D::PixelFormat::RGB888}
  276. };
  277. auto pixelFormatIt = pixelFormats.find(pixelFormatName);
  278. if (pixelFormatIt != pixelFormats.end())
  279. {
  280. const Texture2D::PixelFormat pixelFormat = (*pixelFormatIt).second;
  281. const Texture2D::PixelFormat currentPixelFormat = Texture2D::getDefaultAlphaPixelFormat();
  282. Texture2D::setDefaultAlphaPixelFormat(pixelFormat);
  283. texture = Director::getInstance()->getTextureCache()->addImage(texturePath);
  284. Texture2D::setDefaultAlphaPixelFormat(currentPixelFormat);
  285. }
  286. else
  287. {
  288. texture = Director::getInstance()->getTextureCache()->addImage(texturePath);
  289. }
  290. if (texture)
  291. {
  292. addSpriteFramesWithDictionary(dict, texture);
  293. }
  294. else
  295. {
  296. CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
  297. }
  298. }
  299. void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, Texture2D *texture)
  300. {
  301. if (_loadedFileNames->find(plist) != _loadedFileNames->end())
  302. {
  303. return; // We already added it
  304. }
  305. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  306. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  307. addSpriteFramesWithDictionary(dict, texture);
  308. _loadedFileNames->insert(plist);
  309. }
  310. void SpriteFrameCache::addSpriteFramesWithFileContent(const std::string& plist_content, Texture2D *texture)
  311. {
  312. ValueMap dict = FileUtils::getInstance()->getValueMapFromData(plist_content.c_str(), static_cast<int>(plist_content.size()));
  313. addSpriteFramesWithDictionary(dict, texture);
  314. }
  315. void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName)
  316. {
  317. CCASSERT(textureFileName.size()>0, "texture name should not be null");
  318. if (_loadedFileNames->find(plist) != _loadedFileNames->end())
  319. {
  320. return; // We already added it
  321. }
  322. const std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  323. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  324. addSpriteFramesWithDictionary(dict, textureFileName);
  325. _loadedFileNames->insert(plist);
  326. }
  327. void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist)
  328. {
  329. CCASSERT(!plist.empty(), "plist filename should not be nullptr");
  330. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  331. if (fullPath.empty())
  332. {
  333. // return if plist file doesn't exist
  334. CCLOG("cocos2d: SpriteFrameCache: can not find %s", plist.c_str());
  335. return;
  336. }
  337. if (_loadedFileNames->find(plist) == _loadedFileNames->end())
  338. {
  339. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  340. string texturePath("");
  341. if (dict.find("metadata") != dict.end())
  342. {
  343. ValueMap& metadataDict = dict["metadata"].asValueMap();
  344. // try to read texture file name from meta data
  345. texturePath = metadataDict["textureFileName"].asString();
  346. }
  347. if (!texturePath.empty())
  348. {
  349. // build texture path relative to plist file
  350. texturePath = FileUtils::getInstance()->fullPathFromRelativeFile(texturePath, plist);
  351. }
  352. else
  353. {
  354. // build texture path by replacing file extension
  355. texturePath = plist;
  356. // remove .xxx
  357. size_t startPos = texturePath.find_last_of(".");
  358. texturePath = texturePath.erase(startPos);
  359. // append .png
  360. texturePath = texturePath.append(".png");
  361. CCLOG("cocos2d: SpriteFrameCache: Trying to use file %s as texture", texturePath.c_str());
  362. }
  363. addSpriteFramesWithDictionary(dict, texturePath);
  364. _loadedFileNames->insert(plist);
  365. }
  366. }
  367. bool SpriteFrameCache::isSpriteFramesWithFileLoaded(const std::string& plist) const
  368. {
  369. bool result = false;
  370. if (_loadedFileNames->find(plist) != _loadedFileNames->end())
  371. {
  372. result = true;
  373. }
  374. return result;
  375. }
  376. void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, const std::string& frameName)
  377. {
  378. CCASSERT(frame, "frame should not be nil");
  379. _spriteFrames.insert(frameName, frame);
  380. }
  381. void SpriteFrameCache::removeSpriteFrames()
  382. {
  383. _spriteFrames.clear();
  384. _spriteFramesAliases.clear();
  385. _loadedFileNames->clear();
  386. }
  387. void SpriteFrameCache::removeUnusedSpriteFrames()
  388. {
  389. bool removed = false;
  390. std::vector<std::string> toRemoveFrames;
  391. for (auto& iter : _spriteFrames)
  392. {
  393. SpriteFrame* spriteFrame = iter.second;
  394. if( spriteFrame->getReferenceCount() == 1 )
  395. {
  396. toRemoveFrames.push_back(iter.first);
  397. spriteFrame->getTexture()->removeSpriteFrameCapInset(spriteFrame);
  398. CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", iter.first.c_str());
  399. removed = true;
  400. }
  401. }
  402. _spriteFrames.erase(toRemoveFrames);
  403. // FIXME:. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
  404. if( removed )
  405. {
  406. _loadedFileNames->clear();
  407. }
  408. }
  409. void SpriteFrameCache::removeSpriteFrameByName(const std::string& name)
  410. {
  411. // explicit nil handling
  412. if (name.empty())
  413. return;
  414. // Is this an alias ?
  415. bool foundAlias = _spriteFramesAliases.find(name) != _spriteFramesAliases.end();
  416. std::string key = foundAlias ? _spriteFramesAliases[name].asString() : "";
  417. if (!key.empty())
  418. {
  419. _spriteFrames.erase(key);
  420. _spriteFramesAliases.erase(key);
  421. }
  422. else
  423. {
  424. _spriteFrames.erase(name);
  425. }
  426. // FIXME:. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
  427. _loadedFileNames->clear();
  428. }
  429. void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist)
  430. {
  431. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  432. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  433. if (dict.empty())
  434. {
  435. CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str());
  436. return;
  437. }
  438. removeSpriteFramesFromDictionary(dict);
  439. // remove it from the cache
  440. set<string>::iterator ret = _loadedFileNames->find(plist);
  441. if (ret != _loadedFileNames->end())
  442. {
  443. _loadedFileNames->erase(ret);
  444. }
  445. }
  446. void SpriteFrameCache::removeSpriteFramesFromFileContent(const std::string& plist_content)
  447. {
  448. ValueMap dict = FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast<int>(plist_content.size()));
  449. if (dict.empty())
  450. {
  451. CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFileContent: create dict by fail.");
  452. return;
  453. }
  454. removeSpriteFramesFromDictionary(dict);
  455. }
  456. void SpriteFrameCache::removeSpriteFramesFromDictionary(ValueMap& dictionary)
  457. {
  458. if (dictionary["frames"].getType() != cocos2d::Value::Type::MAP)
  459. return;
  460. ValueMap framesDict = dictionary["frames"].asValueMap();
  461. std::vector<std::string> keysToRemove;
  462. for (const auto& iter : framesDict)
  463. {
  464. if (_spriteFrames.at(iter.first))
  465. {
  466. keysToRemove.push_back(iter.first);
  467. }
  468. }
  469. _spriteFrames.erase(keysToRemove);
  470. }
  471. void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture)
  472. {
  473. std::vector<std::string> keysToRemove;
  474. for (auto& iter : _spriteFrames)
  475. {
  476. std::string key = iter.first;
  477. SpriteFrame* frame = _spriteFrames.at(key);
  478. if (frame && (frame->getTexture() == texture))
  479. {
  480. keysToRemove.push_back(key);
  481. }
  482. }
  483. _spriteFrames.erase(keysToRemove);
  484. }
  485. SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name)
  486. {
  487. SpriteFrame* frame = _spriteFrames.at(name);
  488. if (!frame)
  489. {
  490. // try alias dictionary
  491. if (_spriteFramesAliases.find(name) != _spriteFramesAliases.end())
  492. {
  493. std::string key = _spriteFramesAliases[name].asString();
  494. if (!key.empty())
  495. {
  496. frame = _spriteFrames.at(key);
  497. if (!frame)
  498. {
  499. CCLOG("cocos2d: SpriteFrameCache: Frame aliases '%s' isn't found", key.c_str());
  500. }
  501. }
  502. }
  503. else
  504. {
  505. CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.c_str());
  506. }
  507. }
  508. return frame;
  509. }
  510. void SpriteFrameCache::reloadSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D *texture)
  511. {
  512. ValueMap& framesDict = dictionary["frames"].asValueMap();
  513. int format = 0;
  514. // get the format
  515. if (dictionary.find("metadata") != dictionary.end())
  516. {
  517. ValueMap& metadataDict = dictionary["metadata"].asValueMap();
  518. format = metadataDict["format"].asInt();
  519. }
  520. // check the format
  521. CCASSERT(format >= 0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");
  522. for (auto& iter : framesDict)
  523. {
  524. ValueMap& frameDict = iter.second.asValueMap();
  525. std::string spriteFrameName = iter.first;
  526. auto it = _spriteFrames.find(spriteFrameName);
  527. if (it != _spriteFrames.end())
  528. {
  529. _spriteFrames.erase(it);
  530. }
  531. SpriteFrame* spriteFrame = nullptr;
  532. if (format == 0)
  533. {
  534. float x = frameDict["x"].asFloat();
  535. float y = frameDict["y"].asFloat();
  536. float w = frameDict["width"].asFloat();
  537. float h = frameDict["height"].asFloat();
  538. float ox = frameDict["offsetX"].asFloat();
  539. float oy = frameDict["offsetY"].asFloat();
  540. int ow = frameDict["originalWidth"].asInt();
  541. int oh = frameDict["originalHeight"].asInt();
  542. // check ow/oh
  543. if (!ow || !oh)
  544. {
  545. CCLOGWARN("cocos2d: WARNING: originalWidth/Height not found on the SpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist");
  546. }
  547. // abs ow/oh
  548. ow = std::abs(ow);
  549. oh = std::abs(oh);
  550. // create frame
  551. spriteFrame = SpriteFrame::createWithTexture(texture,
  552. Rect(x, y, w, h),
  553. false,
  554. Vec2(ox, oy),
  555. Size((float)ow, (float)oh)
  556. );
  557. }
  558. else if (format == 1 || format == 2)
  559. {
  560. Rect frame = RectFromString(frameDict["frame"].asString());
  561. bool rotated = false;
  562. // rotation
  563. if (format == 2)
  564. {
  565. rotated = frameDict["rotated"].asBool();
  566. }
  567. Vec2 offset = PointFromString(frameDict["offset"].asString());
  568. Size sourceSize = SizeFromString(frameDict["sourceSize"].asString());
  569. // create frame
  570. spriteFrame = SpriteFrame::createWithTexture(texture,
  571. frame,
  572. rotated,
  573. offset,
  574. sourceSize
  575. );
  576. }
  577. else if (format == 3)
  578. {
  579. // get values
  580. Size spriteSize = SizeFromString(frameDict["spriteSize"].asString());
  581. Vec2 spriteOffset = PointFromString(frameDict["spriteOffset"].asString());
  582. Size spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString());
  583. Rect textureRect = RectFromString(frameDict["textureRect"].asString());
  584. bool textureRotated = frameDict["textureRotated"].asBool();
  585. // get aliases
  586. ValueVector& aliases = frameDict["aliases"].asValueVector();
  587. for (const auto &value : aliases) {
  588. std::string oneAlias = value.asString();
  589. if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end())
  590. {
  591. CCLOGWARN("cocos2d: WARNING: an alias with name %s already exists", oneAlias.c_str());
  592. }
  593. _spriteFramesAliases[oneAlias] = Value(spriteFrameName);
  594. }
  595. // create frame
  596. spriteFrame = SpriteFrame::createWithTexture(texture,
  597. Rect(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height),
  598. textureRotated,
  599. spriteOffset,
  600. spriteSourceSize);
  601. }
  602. // add sprite frame
  603. _spriteFrames.insert(spriteFrameName, spriteFrame);
  604. }
  605. }
  606. bool SpriteFrameCache::reloadTexture(const std::string& plist)
  607. {
  608. CCASSERT(plist.size()>0, "plist filename should not be nullptr");
  609. auto it = _loadedFileNames->find(plist);
  610. if (it != _loadedFileNames->end()) {
  611. _loadedFileNames->erase(it);
  612. }
  613. else
  614. {
  615. //If one plist has't be loaded, we don't load it here.
  616. return false;
  617. }
  618. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  619. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  620. string texturePath("");
  621. if (dict.find("metadata") != dict.end())
  622. {
  623. ValueMap& metadataDict = dict["metadata"].asValueMap();
  624. // try to read texture file name from meta data
  625. texturePath = metadataDict["textureFileName"].asString();
  626. }
  627. if (!texturePath.empty())
  628. {
  629. // build texture path relative to plist file
  630. texturePath = FileUtils::getInstance()->fullPathFromRelativeFile(texturePath, plist);
  631. }
  632. else
  633. {
  634. // build texture path by replacing file extension
  635. texturePath = plist;
  636. // remove .xxx
  637. size_t startPos = texturePath.find_last_of(".");
  638. texturePath = texturePath.erase(startPos);
  639. // append .png
  640. texturePath = texturePath.append(".png");
  641. }
  642. Texture2D *texture = nullptr;
  643. if (Director::getInstance()->getTextureCache()->reloadTexture(texturePath))
  644. texture = Director::getInstance()->getTextureCache()->getTextureForKey(texturePath);
  645. if (texture)
  646. {
  647. reloadSpriteFramesWithDictionary(dict, texture);
  648. _loadedFileNames->insert(plist);
  649. }
  650. else
  651. {
  652. CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
  653. }
  654. return true;
  655. }
  656. NS_CC_END