CCSpriteFrameCache.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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 <unordered_set>
  28. #include "2d/CCSprite.h"
  29. #include "2d/CCAutoPolygon.h"
  30. #include "platform/CCFileUtils.h"
  31. #include "base/CCNS.h"
  32. #include "base/ccMacros.h"
  33. #include "base/ccUTF8.h"
  34. #include "base/CCDirector.h"
  35. #include "renderer/CCTexture2D.h"
  36. #include "renderer/CCTextureCache.h"
  37. #include "base/CCNinePatchImageParser.h"
  38. #include "common/CocosConfig.h"
  39. using namespace std;
  40. NS_CC_BEGIN
  41. static SpriteFrameCache *_sharedSpriteFrameCache = nullptr;
  42. SpriteFrameCache* SpriteFrameCache::getInstance()
  43. {
  44. if (! _sharedSpriteFrameCache)
  45. {
  46. _sharedSpriteFrameCache = new (std::nothrow) SpriteFrameCache();
  47. _sharedSpriteFrameCache->init();
  48. }
  49. return _sharedSpriteFrameCache;
  50. }
  51. void SpriteFrameCache::destroyInstance()
  52. {
  53. CC_SAFE_RELEASE_NULL(_sharedSpriteFrameCache);
  54. }
  55. bool SpriteFrameCache::init()
  56. {
  57. _spriteFrames.reserve(20);
  58. _spriteFramesAliases.reserve(20);
  59. _loadedFileNames = new std::set<std::string>();
  60. return true;
  61. }
  62. SpriteFrameCache::~SpriteFrameCache()
  63. {
  64. CC_SAFE_DELETE(_loadedFileNames);
  65. }
  66. void SpriteFrameCache::parseIntegerList(const std::string &string, std::vector<int> &res)
  67. {
  68. std::string delim(" ");
  69. size_t n = std::count(string.begin(), string.end(), ' ');
  70. res.resize(n+1);
  71. size_t start = 0U;
  72. size_t end = string.find(delim);
  73. int i=0;
  74. while (end != std::string::npos)
  75. {
  76. res[i++] = atoi(string.substr(start, end - start).c_str());
  77. start = end + delim.length();
  78. end = string.find(delim, start);
  79. }
  80. res[i] = atoi(string.substr(start, end).c_str());
  81. }
  82. void SpriteFrameCache::initializePolygonInfo(const Size &textureSize,
  83. const Size &spriteSize,
  84. const std::vector<int> &vertices,
  85. const std::vector<int> &verticesUV,
  86. const std::vector<int> &triangleIndices,
  87. PolygonInfo &info)
  88. {
  89. size_t vertexCount = vertices.size();
  90. size_t indexCount = triangleIndices.size();
  91. float scaleFactor = CC_CONTENT_SCALE_FACTOR();
  92. V3F_C4B_T2F *vertexData = new (std::nothrow) V3F_C4B_T2F[vertexCount];
  93. for (size_t i = 0; i < vertexCount/2; i++)
  94. {
  95. vertexData[i].colors = Color4B::WHITE;
  96. vertexData[i].vertices = Vec3(vertices[i*2] / scaleFactor,
  97. (spriteSize.height - vertices[i*2+1]) / scaleFactor,
  98. 0);
  99. vertexData[i].texCoords = Tex2F(verticesUV[i*2] / textureSize.width,
  100. verticesUV[i*2+1] / textureSize.height);
  101. }
  102. unsigned short *indexData = new unsigned short[indexCount];
  103. for (size_t i = 0; i < indexCount; i++)
  104. {
  105. indexData[i] = static_cast<unsigned short>(triangleIndices[i]);
  106. }
  107. info.triangles.vertCount = static_cast<int>(vertexCount);
  108. info.triangles.verts = vertexData;
  109. info.triangles.indexCount = static_cast<int>(indexCount);
  110. info.triangles.indices = indexData;
  111. info.setRect(Rect(0, 0, spriteSize.width, spriteSize.height));
  112. }
  113. void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D* texture)
  114. {
  115. /*
  116. Supported Zwoptex Formats:
  117. ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
  118. ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
  119. ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
  120. ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
  121. Version 3 with TexturePacker 4.0 polygon mesh packing
  122. */
  123. if (dictionary["frames"].getType() != cocos2d::Value::Type::MAP)
  124. return;
  125. ValueMap& framesDict = dictionary["frames"].asValueMap();
  126. int format = 0;
  127. float scale = 1.0;
  128. Size textureSize;
  129. std::string plistName = "";
  130. // get the format
  131. if (dictionary.find("metadata") != dictionary.end())
  132. {
  133. ValueMap& metadataDict = dictionary["metadata"].asValueMap();
  134. format = metadataDict["format"].asInt();
  135. if(metadataDict.find("scaleRatio") != metadataDict.end())
  136. {
  137. scale = metadataDict["scaleRatio"].asFloat();
  138. }
  139. if(metadataDict.find("size") != metadataDict.end())
  140. {
  141. textureSize = SizeFromString(metadataDict["size"].asString());
  142. }
  143. if(metadataDict.find("plist")!= metadataDict.end()){
  144. plistName = metadataDict["plist"].asString();
  145. }
  146. }
  147. // check the format
  148. CCASSERT(format >=0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");
  149. auto textureFileName = Director::getInstance()->getTextureCache()->getTextureFilePath(texture);
  150. Image* image = nullptr;
  151. NinePatchImageParser parser;
  152. for (auto& iter : framesDict)
  153. {
  154. ValueMap& frameDict = iter.second.asValueMap();
  155. std::string spriteFrameName = iter.first;
  156. SpriteFrame* spriteFrame = nullptr;// _spriteFrames.at(spriteFrameName);
  157. if (spriteFrame)
  158. {
  159. // continue;
  160. }
  161. if(format == 0)
  162. {
  163. float x = frameDict["x"].asFloat();
  164. float y = frameDict["y"].asFloat();
  165. float w = frameDict["width"].asFloat();
  166. float h = frameDict["height"].asFloat();
  167. float ox = frameDict["offsetX"].asFloat();
  168. float oy = frameDict["offsetY"].asFloat();
  169. int ow = frameDict["originalWidth"].asInt();
  170. int oh = frameDict["originalHeight"].asInt();
  171. // check ow/oh
  172. if(!ow || !oh)
  173. {
  174. CCLOGWARN("cocos2d: WARNING: originalWidth/Height not found on the SpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist");
  175. }
  176. // abs ow/oh
  177. ow = std::abs(ow);
  178. oh = std::abs(oh);
  179. // create frame
  180. spriteFrame = SpriteFrame::createWithTexture(texture,
  181. Rect(x, y, w, h),
  182. false,
  183. Vec2(ox, oy),
  184. Size((float)ow, (float)oh)
  185. );
  186. }
  187. else if(format == 1 || format == 2)
  188. {
  189. Rect frame = RectFromString(frameDict["frame"].asString());
  190. bool rotated = false;
  191. // rotation
  192. if (format == 2)
  193. {
  194. rotated = frameDict["rotated"].asBool();
  195. }
  196. Vec2 offset = PointFromString(frameDict["offset"].asString());
  197. Size sourceSize = SizeFromString(frameDict["sourceSize"].asString());
  198. // create frame
  199. spriteFrame = SpriteFrame::createWithTexture(texture,
  200. frame,
  201. rotated,
  202. offset,
  203. sourceSize
  204. );
  205. }
  206. else if (format == 3)
  207. {
  208. // get values
  209. Size spriteSize = SizeFromString(frameDict["spriteSize"].asString());
  210. Vec2 spriteOffset = PointFromString(frameDict["spriteOffset"].asString());
  211. Size spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString());
  212. Rect textureRect = RectFromString(frameDict["textureRect"].asString());
  213. bool textureRotated = frameDict["textureRotated"].asBool();
  214. float _tmpScale = scale;
  215. // get aliases
  216. ValueVector& aliases = frameDict["aliases"].asValueVector();
  217. // get scaleRatio
  218. if(frameDict.find("scaleRatio") != frameDict.end())
  219. {
  220. _tmpScale = frameDict["scaleRatio"].asFloat();
  221. }
  222. for(const auto &value : aliases) {
  223. std::string oneAlias = value.asString();
  224. if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end())
  225. {
  226. CCLOGWARN("cocos2d: WARNING: an alias with name %s already exists", oneAlias.c_str());
  227. }
  228. _spriteFramesAliases[oneAlias] = Value(spriteFrameName);
  229. }
  230. // create frame
  231. spriteFrame = SpriteFrame::createWithTexture(texture,
  232. Rect(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height),
  233. textureRotated,
  234. spriteOffset,
  235. spriteSourceSize,
  236. _tmpScale);
  237. if(frameDict.find("vertices") != frameDict.end())
  238. {
  239. std::vector<int> vertices;
  240. parseIntegerList(frameDict["vertices"].asString(), vertices);
  241. std::vector<int> verticesUV;
  242. parseIntegerList(frameDict["verticesUV"].asString(), verticesUV);
  243. std::vector<int> indices;
  244. parseIntegerList(frameDict["triangles"].asString(), indices);
  245. PolygonInfo info;
  246. initializePolygonInfo(textureSize, spriteSourceSize, vertices, verticesUV, indices, info);
  247. spriteFrame->setPolygonInfo(info);
  248. }
  249. if (frameDict.find("anchor") != frameDict.end())
  250. {
  251. spriteFrame->setAnchorPoint(PointFromString(frameDict["anchor"].asString()));
  252. }
  253. }
  254. bool flag = NinePatchImageParser::isNinePatchImage(spriteFrameName);
  255. if(flag)
  256. {
  257. if (image == nullptr) {
  258. image = new (std::nothrow) Image();
  259. image->initWithImageFile(textureFileName);
  260. }
  261. parser.setSpriteFrameInfo(image, spriteFrame->getRectInPixels(), spriteFrame->isRotated());
  262. texture->addSpriteFrameCapInset(spriteFrame, parser.parseCapInset());
  263. }
  264. //add by yuntao 优先用单独的plist,动态拼图的.
  265. if(false == plistName.empty()){
  266. spriteFrame->setPlist(plistName);
  267. }
  268. // add sprite frame
  269. auto it = _spriteFrames.find(spriteFrameName);
  270. if (it == _spriteFrames.end()) {
  271. _spriteFrames.insert(spriteFrameName, spriteFrame);
  272. }
  273. else{
  274. auto fd = _plistSpriteFrames.find(plistName);
  275. if (fd == _plistSpriteFrames.end()) {
  276. Map<std::string, SpriteFrame*> spriteFrames;
  277. spriteFrames.insert(spriteFrameName, spriteFrame);
  278. _plistSpriteFrames.emplace(plistName,spriteFrames);
  279. }
  280. else{
  281. fd->second.insert(spriteFrameName, spriteFrame);
  282. }
  283. }
  284. spriteFrame->setSpriteFrameName(std::move(spriteFrameName));
  285. }
  286. CC_SAFE_DELETE(image);
  287. }
  288. void SpriteFrameCache::addSpriteFramesWithDictionary(ValueMap& dict, const std::string &texturePath)
  289. {
  290. std::string pixelFormatName;
  291. if (dict.find("metadata") != dict.end())
  292. {
  293. ValueMap& metadataDict = dict.at("metadata").asValueMap();
  294. if (metadataDict.find("pixelFormat") != metadataDict.end())
  295. {
  296. pixelFormatName = metadataDict.at("pixelFormat").asString();
  297. }
  298. }
  299. Texture2D *texture = nullptr;
  300. static std::unordered_map<std::string, Texture2D::PixelFormat> pixelFormats = {
  301. {"RGBA8888", Texture2D::PixelFormat::RGBA8888},
  302. {"RGBA4444", Texture2D::PixelFormat::RGBA4444},
  303. {"RGB5A1", Texture2D::PixelFormat::RGB5A1},
  304. {"RGBA5551", Texture2D::PixelFormat::RGB5A1},
  305. {"RGB565", Texture2D::PixelFormat::RGB565},
  306. {"A8", Texture2D::PixelFormat::A8},
  307. {"ALPHA", Texture2D::PixelFormat::A8},
  308. {"I8", Texture2D::PixelFormat::I8},
  309. {"AI88", Texture2D::PixelFormat::AI88},
  310. {"ALPHA_INTENSITY", Texture2D::PixelFormat::AI88},
  311. //{"BGRA8888", Texture2D::PixelFormat::BGRA8888}, no Image conversion RGBA -> BGRA
  312. {"RGB888", Texture2D::PixelFormat::RGB888}
  313. };
  314. auto pixelFormatIt = pixelFormats.find(pixelFormatName);
  315. if (pixelFormatIt != pixelFormats.end())
  316. {
  317. const Texture2D::PixelFormat pixelFormat = (*pixelFormatIt).second;
  318. const Texture2D::PixelFormat currentPixelFormat = Texture2D::getDefaultAlphaPixelFormat();
  319. Texture2D::setDefaultAlphaPixelFormat(pixelFormat);
  320. texture = Director::getInstance()->getTextureCache()->addImage(texturePath);
  321. Texture2D::setDefaultAlphaPixelFormat(currentPixelFormat);
  322. }
  323. else
  324. {
  325. texture = Director::getInstance()->getTextureCache()->addImage(texturePath);
  326. }
  327. if (texture)
  328. {
  329. addSpriteFramesWithDictionary(dict, texture);
  330. }
  331. else
  332. {
  333. CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
  334. }
  335. }
  336. void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, Texture2D *texture)
  337. {
  338. if (_loadedFileNames->find(plist) != _loadedFileNames->end())
  339. {
  340. return; // We already added it
  341. }
  342. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  343. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  344. //add by yuntao
  345. if (dict.find("metadata") != dict.end())
  346. {
  347. ValueMap& metadataDict = dict["metadata"].asValueMap();
  348. metadataDict["plist"] = plist;
  349. }
  350. addSpriteFramesWithDictionary(dict, texture);
  351. _loadedFileNames->insert(plist);
  352. }
  353. void SpriteFrameCache::addSpriteFramesWithFileContent(const std::string& plist_content, Texture2D *texture)
  354. {
  355. ValueMap dict = FileUtils::getInstance()->getValueMapFromData(plist_content.c_str(), static_cast<int>(plist_content.size()));
  356. addSpriteFramesWithDictionary(dict, texture);
  357. }
  358. void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist, const std::string& textureFileName)
  359. {
  360. CCASSERT(textureFileName.size()>0, "texture name should not be null");
  361. if (_loadedFileNames->find(plist) != _loadedFileNames->end())
  362. {
  363. return; // We already added it
  364. }
  365. const std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  366. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  367. //add by yuntao
  368. if (dict.find("metadata") != dict.end())
  369. {
  370. ValueMap& metadataDict = dict["metadata"].asValueMap();
  371. metadataDict["plist"] = plist;
  372. }
  373. addSpriteFramesWithDictionary(dict, textureFileName);
  374. _loadedFileNames->insert(plist);
  375. }
  376. void SpriteFrameCache::addSpriteFramesWithFile(const std::string& plist)
  377. {
  378. CCASSERT(!plist.empty(), "plist filename should not be nullptr");
  379. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  380. if (fullPath.empty())
  381. {
  382. // return if plist file doesn't exist
  383. CCLOG("cocos2d: SpriteFrameCache: can not find %s", plist.c_str());
  384. return;
  385. }
  386. if (_loadedFileNames->find(plist) == _loadedFileNames->end())
  387. {
  388. CCLOG("cocos2d: SpriteFrameCache: 加载新的plist %s", plist.c_str());
  389. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  390. string texturePath("");
  391. if (dict.find("metadata") != dict.end())
  392. {
  393. ValueMap& metadataDict = dict["metadata"].asValueMap();
  394. // try to read texture file name from meta data
  395. texturePath = metadataDict["textureFileName"].asString();
  396. //add by yuntao.
  397. metadataDict["plist"] = plist;
  398. }
  399. if (!texturePath.empty())
  400. {
  401. // build texture path relative to plist file
  402. texturePath = FileUtils::getInstance()->fullPathFromRelativeFile(texturePath, plist);
  403. }
  404. else
  405. {
  406. // build texture path by replacing file extension
  407. texturePath = plist;
  408. // remove .xxx
  409. size_t startPos = texturePath.find_last_of(".");
  410. texturePath = texturePath.substr(0,startPos);
  411. // append .png
  412. texturePath = texturePath.append(".png");
  413. CCLOG("cocos2d: SpriteFrameCache: Trying to use file %s as texture", texturePath.c_str());
  414. }
  415. addSpriteFramesWithDictionary(dict, texturePath);
  416. _loadedFileNames->insert(plist);
  417. }
  418. }
  419. bool SpriteFrameCache::isSpriteFramesWithFileLoaded(const std::string& plist) const
  420. {
  421. bool result = false;
  422. if (_loadedFileNames->find(plist) != _loadedFileNames->end())
  423. {
  424. result = true;
  425. }
  426. return result;
  427. }
  428. void SpriteFrameCache::addSpriteFrame(SpriteFrame* frame, const std::string& frameName)
  429. {
  430. CCASSERT(frame, "frame should not be nil");
  431. _spriteFrames.insert(frameName, frame);
  432. frame->setSpriteFrameName(std::move(frameName));
  433. }
  434. void SpriteFrameCache::removeSpriteFrames()
  435. {
  436. _spriteFrames.clear();
  437. _spriteFramesAliases.clear();
  438. _loadedFileNames->clear();
  439. _plistSpriteFrames.clear();
  440. }
  441. void SpriteFrameCache::removeUnusedSpriteFrames()
  442. {
  443. bool removed = false;
  444. std::vector<std::string> toRemoveFrames;
  445. for (auto& iter : _spriteFrames)
  446. {
  447. SpriteFrame* spriteFrame = iter.second;
  448. if( spriteFrame->getReferenceCount() == 1 )
  449. {
  450. toRemoveFrames.push_back(iter.first);
  451. spriteFrame->getTexture()->removeSpriteFrameCapInset(spriteFrame);
  452. CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", iter.first.c_str());
  453. removed = true;
  454. }else{
  455. CCLOG("cocos2d: SpriteFrameCache: cann't remove, used frame: %s", iter.first.c_str());
  456. }
  457. }
  458. _spriteFrames.erase(toRemoveFrames);
  459. for (auto& it : _plistSpriteFrames) {
  460. toRemoveFrames.clear();
  461. for (auto iter : it.second) {
  462. SpriteFrame* spriteFrame = iter.second;
  463. if( spriteFrame->getReferenceCount() == 1 )
  464. {
  465. toRemoveFrames.push_back(iter.first);
  466. spriteFrame->getTexture()->removeSpriteFrameCapInset(spriteFrame);
  467. CCLOG("cocos2d: SpriteFrameCache: removing unused frame: %s", iter.first.c_str());
  468. removed = true;
  469. }else{
  470. CCLOG("cocos2d: SpriteFrameCache: cann't remove, used frame: %s", iter.first.c_str());
  471. }
  472. }
  473. it.second.erase(toRemoveFrames);
  474. }
  475. // FIXME:. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
  476. if( removed )
  477. {
  478. _loadedFileNames->clear();
  479. }
  480. }
  481. void SpriteFrameCache::removeSpriteFrameByName(const std::string& name)
  482. {
  483. // explicit nil handling
  484. if (name.empty())
  485. return;
  486. // Is this an alias ?
  487. bool foundAlias = _spriteFramesAliases.find(name) != _spriteFramesAliases.end();
  488. std::string key = foundAlias ? _spriteFramesAliases[name].asString() : "";
  489. if (!key.empty())
  490. {
  491. _spriteFrames.erase(key);
  492. _spriteFramesAliases.erase(key);
  493. }
  494. else
  495. {
  496. _spriteFrames.erase(name);
  497. }
  498. // FIXME:. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
  499. _loadedFileNames->clear();
  500. }
  501. void SpriteFrameCache::removeSpriteFramesFromFile(const std::string& plist, bool fThisPlist)
  502. {
  503. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  504. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  505. if (dict.empty())
  506. {
  507. CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFile: create dict by %s fail.",plist.c_str());
  508. return;
  509. }
  510. removeSpriteFramesFromDictionary(dict, fThisPlist ? plist : "");
  511. // remove it from the cache
  512. set<string>::iterator ret = _loadedFileNames->find(plist);
  513. if (ret != _loadedFileNames->end())
  514. {
  515. _loadedFileNames->erase(ret);
  516. }
  517. }
  518. void SpriteFrameCache::removeSpriteFramesFromFileContent(const std::string& plist_content)
  519. {
  520. ValueMap dict = FileUtils::getInstance()->getValueMapFromData(plist_content.data(), static_cast<int>(plist_content.size()));
  521. if (dict.empty())
  522. {
  523. CCLOG("cocos2d:SpriteFrameCache:removeSpriteFramesFromFileContent: create dict by fail.");
  524. return;
  525. }
  526. removeSpriteFramesFromDictionary(dict);
  527. }
  528. void SpriteFrameCache::removeSpriteFramesFromDictionary(ValueMap& dictionary, const std::string fPlistName)
  529. {
  530. if (dictionary["frames"].getType() != cocos2d::Value::Type::MAP)
  531. return;
  532. ValueMap framesDict = dictionary["frames"].asValueMap();
  533. std::vector<std::string> keysToRemove;
  534. _plistSpriteFrames.erase(fPlistName);
  535. for (const auto& iter : framesDict)
  536. {
  537. if (_spriteFrames.at(iter.first))
  538. {
  539. if (fPlistName != "") {
  540. SpriteFrame * frame = _spriteFrames.at(iter.first);
  541. if( frame->getPlist() == fPlistName ){
  542. keysToRemove.push_back(iter.first);
  543. }
  544. }else{
  545. keysToRemove.push_back(iter.first);
  546. }
  547. }
  548. }
  549. _spriteFrames.erase(keysToRemove);
  550. }
  551. void SpriteFrameCache::removeSpriteFramesFromTexture(Texture2D* texture)
  552. {
  553. std::vector<std::string> keysToRemove;
  554. for (auto& iter : _spriteFrames)
  555. {
  556. std::string key = iter.first;
  557. SpriteFrame* frame = _spriteFrames.at(key);
  558. if (frame && (frame->getTexture() == texture))
  559. {
  560. keysToRemove.push_back(key);
  561. }
  562. }
  563. _spriteFrames.erase(keysToRemove);
  564. std::string path = texture->getPath();
  565. //get fileName
  566. size_t pos = path.rfind("/");
  567. path = path.substr(pos+1);
  568. // remove .xxx
  569. size_t startPos = path.find_last_of(".");
  570. path = path.substr(0,startPos);
  571. // append .plist
  572. path = path.append(".plist");
  573. _plistSpriteFrames.erase(path);
  574. }
  575. SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name)
  576. {
  577. SpriteFrame* frame = _spriteFrames.at(name);
  578. if (!frame)
  579. {
  580. // try alias dictionary
  581. if (_spriteFramesAliases.find(name) != _spriteFramesAliases.end())
  582. {
  583. std::string key = _spriteFramesAliases[name].asString();
  584. if (!key.empty())
  585. {
  586. frame = _spriteFrames.at(key);
  587. if (!frame)
  588. {
  589. CCLOG("cocos2d: SpriteFrameCache: Frame aliases '%s' isn't found", key.c_str());
  590. }
  591. }
  592. }
  593. else
  594. {
  595. if (CocosConfig::getIgnoreCCBPath() == false) {
  596. CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.c_str());
  597. }
  598. }
  599. }
  600. return frame;
  601. }
  602. SpriteFrame* SpriteFrameCache::getSpriteFrameByName(const std::string& name, const std::unordered_set<std::string>& plistSt){
  603. SpriteFrame* frame = _spriteFrames.at(name);
  604. if (!frame)
  605. {
  606. // try alias dictionary
  607. if (_spriteFramesAliases.find(name) != _spriteFramesAliases.end())
  608. {
  609. std::string key = _spriteFramesAliases[name].asString();
  610. if (!key.empty())
  611. {
  612. frame = _spriteFrames.at(key);
  613. if (!frame)
  614. {
  615. CCLOG("cocos2d: SpriteFrameCache: Frame aliases '%s' isn't found", key.c_str());
  616. }
  617. }
  618. }
  619. else
  620. {
  621. if (CocosConfig::getIgnoreCCBPath() == false) {
  622. CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found", name.c_str());
  623. }
  624. }
  625. }
  626. if (frame) {
  627. if (plistSt.empty()) {
  628. return frame;
  629. }
  630. else if(plistSt.count(frame->getPlist())>0){
  631. return frame;
  632. }
  633. }
  634. //frame 如果是nullptr 则 _plistSpriteFrames 里面更不会有.所以排除这种情况
  635. if (!plistSt.empty()) {
  636. // string framePlist = frame->getPlist();
  637. for (auto plist : plistSt) {
  638. auto find = _plistSpriteFrames.find(plist);
  639. if (find != _plistSpriteFrames.end()) {
  640. frame = find->second.at(name);
  641. if (!frame)
  642. {
  643. // try alias dictionary
  644. if (_spriteFramesAliases.find(name) != _spriteFramesAliases.end())
  645. {
  646. std::string key = _spriteFramesAliases[name].asString();
  647. if (!key.empty())
  648. {
  649. frame = find->second.at(key);
  650. if (!frame)
  651. {
  652. CCLOG("cocos2d: SpriteFrameCache: Frame aliases '%s' isn't found", key.c_str());
  653. }
  654. }
  655. }
  656. else
  657. {
  658. if (CocosConfig::getIgnoreCCBPath() == false) {
  659. // CCLOG("cocos2d: SpriteFrameCache: Frame '%s' isn't found thisPlist:%s framePlist:%s", name.c_str(),plist.c_str(),framePlist.c_str());
  660. }
  661. }
  662. }
  663. if(frame && frame->getPlist()==plist){
  664. return frame;
  665. }
  666. }
  667. }
  668. }
  669. return frame;
  670. }
  671. void SpriteFrameCache::reloadSpriteFramesWithDictionary(ValueMap& dictionary, Texture2D *texture)
  672. {
  673. ValueMap& framesDict = dictionary["frames"].asValueMap();
  674. int format = 0;
  675. float scale = 1.0;
  676. std::string plistName;
  677. // get the format
  678. if (dictionary.find("metadata") != dictionary.end())
  679. {
  680. ValueMap& metadataDict = dictionary["metadata"].asValueMap();
  681. format = metadataDict["format"].asInt();
  682. plistName = metadataDict["plist"].asString();
  683. if(metadataDict.find("scaleRatio") != metadataDict.end())
  684. {
  685. scale = metadataDict["scaleRatio"].asFloat();
  686. }
  687. }
  688. // check the format
  689. CCASSERT(format >= 0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");
  690. for (auto& iter : framesDict)
  691. {
  692. ValueMap& frameDict = iter.second.asValueMap();
  693. std::string spriteFrameName = iter.first;
  694. auto it = _spriteFrames.find(spriteFrameName);
  695. if (it != _spriteFrames.end() && it->second->getPlist()==plistName)
  696. {
  697. _spriteFrames.erase(it);
  698. }
  699. SpriteFrame* spriteFrame = nullptr;
  700. if (format == 0)
  701. {
  702. float x = frameDict["x"].asFloat();
  703. float y = frameDict["y"].asFloat();
  704. float w = frameDict["width"].asFloat();
  705. float h = frameDict["height"].asFloat();
  706. float ox = frameDict["offsetX"].asFloat();
  707. float oy = frameDict["offsetY"].asFloat();
  708. int ow = frameDict["originalWidth"].asInt();
  709. int oh = frameDict["originalHeight"].asInt();
  710. // check ow/oh
  711. if (!ow || !oh)
  712. {
  713. CCLOGWARN("cocos2d: WARNING: originalWidth/Height not found on the SpriteFrame. AnchorPoint won't work as expected. Regenerate the .plist");
  714. }
  715. // abs ow/oh
  716. ow = std::abs(ow);
  717. oh = std::abs(oh);
  718. // create frame
  719. spriteFrame = SpriteFrame::createWithTexture(texture,
  720. Rect(x, y, w, h),
  721. false,
  722. Vec2(ox, oy),
  723. Size((float)ow, (float)oh)
  724. );
  725. }
  726. else if (format == 1 || format == 2)
  727. {
  728. Rect frame = RectFromString(frameDict["frame"].asString());
  729. bool rotated = false;
  730. // rotation
  731. if (format == 2)
  732. {
  733. rotated = frameDict["rotated"].asBool();
  734. }
  735. Vec2 offset = PointFromString(frameDict["offset"].asString());
  736. Size sourceSize = SizeFromString(frameDict["sourceSize"].asString());
  737. // create frame
  738. spriteFrame = SpriteFrame::createWithTexture(texture,
  739. frame,
  740. rotated,
  741. offset,
  742. sourceSize
  743. );
  744. }
  745. else if (format == 3)
  746. {
  747. // get values
  748. Size spriteSize = SizeFromString(frameDict["spriteSize"].asString());
  749. Vec2 spriteOffset = PointFromString(frameDict["spriteOffset"].asString());
  750. Size spriteSourceSize = SizeFromString(frameDict["spriteSourceSize"].asString());
  751. Rect textureRect = RectFromString(frameDict["textureRect"].asString());
  752. bool textureRotated = frameDict["textureRotated"].asBool();
  753. float _tmpScale = scale;
  754. // get aliases
  755. ValueVector& aliases = frameDict["aliases"].asValueVector();
  756. //get scaleRatio
  757. if(frameDict.find("scaleRatio") != frameDict.end())
  758. {
  759. _tmpScale = frameDict["scaleRatio"].asFloat();
  760. }
  761. for (const auto &value : aliases) {
  762. std::string oneAlias = value.asString();
  763. if (_spriteFramesAliases.find(oneAlias) != _spriteFramesAliases.end())
  764. {
  765. CCLOGWARN("cocos2d: WARNING: an alias with name %s already exists", oneAlias.c_str());
  766. }
  767. _spriteFramesAliases[oneAlias] = Value(spriteFrameName);
  768. }
  769. // create frame
  770. spriteFrame = SpriteFrame::createWithTexture(texture,
  771. Rect(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height),
  772. textureRotated,
  773. spriteOffset,
  774. spriteSourceSize,
  775. _tmpScale);
  776. }
  777. //add by yuntao 优先用单独的plist,动态拼图的.
  778. ValueMap& metadataDict = dictionary["metadata"].asValueMap();
  779. if( !metadataDict["plist"].isNull() ){
  780. spriteFrame->setPlist(metadataDict["plist"].asString());
  781. }
  782. // add sprite frame
  783. auto it1 = _spriteFrames.find(spriteFrameName);
  784. if (it1 == _spriteFrames.end()) {
  785. _spriteFrames.insert(spriteFrameName, spriteFrame);
  786. }
  787. else{
  788. auto fd = _plistSpriteFrames.find(plistName);
  789. if (fd == _plistSpriteFrames.end()) {
  790. Map<std::string, SpriteFrame*> spriteFrames;
  791. spriteFrames.insert(spriteFrameName, spriteFrame);
  792. _plistSpriteFrames.emplace(plistName,spriteFrames);
  793. }
  794. else{
  795. fd->second.insert(spriteFrameName, spriteFrame);
  796. }
  797. }
  798. spriteFrame->setSpriteFrameName(std::move(spriteFrameName));
  799. }
  800. }
  801. bool SpriteFrameCache::reloadTexture(const std::string& plist)
  802. {
  803. CCASSERT(plist.size()>0, "plist filename should not be nullptr");
  804. auto it = _loadedFileNames->find(plist);
  805. if (it != _loadedFileNames->end()) {
  806. _loadedFileNames->erase(it);
  807. }
  808. else
  809. {
  810. //If one plist has't be loaded, we don't load it here.
  811. return false;
  812. }
  813. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(plist);
  814. ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(fullPath);
  815. string texturePath("");
  816. if (dict.find("metadata") != dict.end())
  817. {
  818. ValueMap& metadataDict = dict["metadata"].asValueMap();
  819. // try to read texture file name from meta data
  820. texturePath = metadataDict["textureFileName"].asString();
  821. //add by yuntao
  822. metadataDict["plist"] = plist;
  823. }
  824. if (!texturePath.empty())
  825. {
  826. // build texture path relative to plist file
  827. texturePath = FileUtils::getInstance()->fullPathFromRelativeFile(texturePath, plist);
  828. }
  829. else
  830. {
  831. // build texture path by replacing file extension
  832. texturePath = plist;
  833. // remove .xxx
  834. size_t startPos = texturePath.find_last_of(".");
  835. texturePath = texturePath.substr(0,startPos);
  836. // append .png
  837. texturePath = texturePath.append(".png");
  838. }
  839. Texture2D *texture = nullptr;
  840. if (Director::getInstance()->getTextureCache()->reloadTexture(texturePath))
  841. texture = Director::getInstance()->getTextureCache()->getTextureForKey(texturePath);
  842. if (texture)
  843. {
  844. reloadSpriteFramesWithDictionary(dict, texture);
  845. _loadedFileNames->insert(plist);
  846. }
  847. else
  848. {
  849. CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
  850. }
  851. return true;
  852. }
  853. void SpriteFrameCache::printInfo(){
  854. CCLOG("SpriteFrameCache::printInfo ----> begin");
  855. for (pair<std::string, SpriteFrame*> item : _spriteFrames ) {
  856. item.second->printInfo();
  857. }
  858. CCLOG("SpriteFrameCache::printInfo ----> end");
  859. }
  860. NS_CC_END