CCTextureCache.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2011 Zynga Inc.
  5. Copyright (c) 2013-2016 Chukong Technologies Inc.
  6. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  7. http://www.cocos2d-x.org
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in
  15. all copies or substantial portions of the Software.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. THE SOFTWARE.
  23. ****************************************************************************/
  24. #include "renderer/CCTextureCache.h"
  25. #include <errno.h>
  26. #include <stack>
  27. #include <cctype>
  28. #include <list>
  29. #include "renderer/CCTexture2D.h"
  30. #include "base/ccMacros.h"
  31. #include "base/ccUTF8.h"
  32. #include "base/CCDirector.h"
  33. #include "base/CCScheduler.h"
  34. #include "platform/CCFileUtils.h"
  35. #include "base/ccUtils.h"
  36. #include "base/CCNinePatchImageParser.h"
  37. #include "common/CocosConfig.h"
  38. using namespace std;
  39. NS_CC_BEGIN
  40. std::string TextureCache::s_etc1AlphaFileSuffix = "@alpha";
  41. // implementation TextureCache
  42. void TextureCache::setETC1AlphaFileSuffix(const std::string& suffix)
  43. {
  44. s_etc1AlphaFileSuffix = suffix;
  45. }
  46. std::string TextureCache::getETC1AlphaFileSuffix()
  47. {
  48. return s_etc1AlphaFileSuffix;
  49. }
  50. TextureCache * TextureCache::getInstance()
  51. {
  52. return Director::getInstance()->getTextureCache();
  53. }
  54. TextureCache::TextureCache()
  55. : _loadingThread(nullptr)
  56. , _loadingThread2(nullptr)
  57. , _needQuit(false)
  58. , _asyncRefCount(0)
  59. {
  60. }
  61. TextureCache::~TextureCache()
  62. {
  63. CCLOGINFO("deallocing TextureCache: %p", this);
  64. for (auto& texture : _textures)
  65. texture.second->release();
  66. CC_SAFE_DELETE(_loadingThread);
  67. CC_SAFE_DELETE(_loadingThread2);
  68. }
  69. void TextureCache::destroyInstance()
  70. {
  71. }
  72. TextureCache * TextureCache::sharedTextureCache()
  73. {
  74. return Director::getInstance()->getTextureCache();
  75. }
  76. void TextureCache::purgeSharedTextureCache()
  77. {
  78. }
  79. std::string TextureCache::getDescription() const
  80. {
  81. return StringUtils::format("<TextureCache | Number of textures = %d>", static_cast<int>(_textures.size()));
  82. }
  83. struct TextureCache::AsyncStruct
  84. {
  85. public:
  86. AsyncStruct
  87. ( const std::string& fn,const std::function<void(Texture2D*)>& f,
  88. const std::string& key )
  89. : filename(fn), callback(f),callbackKey( key ),
  90. pixelFormat(Texture2D::getDefaultAlphaPixelFormat()),
  91. loadSuccess(false)
  92. {}
  93. std::string filename;
  94. std::function<void(Texture2D*)> callback;
  95. std::string callbackKey;
  96. Image image;
  97. Image imageAlpha;
  98. Texture2D::PixelFormat pixelFormat;
  99. bool loadSuccess;
  100. };
  101. /**
  102. The addImageAsync logic follow the steps:
  103. - find the image has been add or not, if not add an AsyncStruct to _requestQueue (GL thread)
  104. - get AsyncStruct from _requestQueue, load res and fill image data to AsyncStruct.image, then add AsyncStruct to _responseQueue (Load thread)
  105. - on schedule callback, get AsyncStruct from _responseQueue, convert image to texture, then delete AsyncStruct (GL thread)
  106. the Critical Area include these members:
  107. - _requestQueue: locked by _requestMutex
  108. - _responseQueue: locked by _responseMutex
  109. the object's life time:
  110. - AsyncStruct: construct and destruct in GL thread
  111. - image data: new in Load thread, delete in GL thread(by Image instance)
  112. Note:
  113. - all AsyncStruct referenced in _asyncStructQueue, for unbind function use.
  114. How to deal add image many times?
  115. - At first, this situation is abnormal, we only ensure the logic is correct.
  116. - If the image has been loaded, the after load image call will return immediately.
  117. - If the image request is in queue already, there will be more than one request in queue,
  118. - In addImageAsyncCallback, will deduplicate the request to ensure only create one texture.
  119. Does process all response in addImageAsyncCallback consume more time?
  120. - Convert image to texture faster than load image from disk, so this isn't a
  121. problem.
  122. Call unbindImageAsync(path) to prevent the call to the callback when the
  123. texture is loaded.
  124. */
  125. void TextureCache::addImageAsync(const std::string &path, const std::function<void(Texture2D*)>& callback)
  126. {
  127. addImageAsync( path, callback, path );
  128. }
  129. /**
  130. The addImageAsync logic follow the steps:
  131. - find the image has been add or not, if not add an AsyncStruct to _requestQueue (GL thread)
  132. - get AsyncStruct from _requestQueue, load res and fill image data to AsyncStruct.image, then add AsyncStruct to _responseQueue (Load thread)
  133. - on schedule callback, get AsyncStruct from _responseQueue, convert image to texture, then delete AsyncStruct (GL thread)
  134. the Critical Area include these members:
  135. - _requestQueue: locked by _requestMutex
  136. - _responseQueue: locked by _responseMutex
  137. the object's life time:
  138. - AsyncStruct: construct and destruct in GL thread
  139. - image data: new in Load thread, delete in GL thread(by Image instance)
  140. Note:
  141. - all AsyncStruct referenced in _asyncStructQueue, for unbind function use.
  142. How to deal add image many times?
  143. - At first, this situation is abnormal, we only ensure the logic is correct.
  144. - If the image has been loaded, the after load image call will return immediately.
  145. - If the image request is in queue already, there will be more than one request in queue,
  146. - In addImageAsyncCallback, will deduplicate the request to ensure only create one texture.
  147. Does process all response in addImageAsyncCallback consume more time?
  148. - Convert image to texture faster than load image from disk, so this isn't a
  149. problem.
  150. The callbackKey allows to unbind the callback in cases where the loading of
  151. path is requested by several sources simultaneously. Each source can then
  152. unbind the callback independently as needed whilst a call to
  153. unbindImageAsync(path) would be ambiguous.
  154. */
  155. void TextureCache::addImageAsync(const std::string &path, const std::function<void(Texture2D*)>& callback, const std::string& callbackKey)
  156. {
  157. Texture2D *texture = nullptr;
  158. std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
  159. if(CocosConfig::isPictureReplaceWebp()){
  160. if(fullpath.size() == 0){
  161. string suffixStr = path.substr(0,path.find_last_of('.'));
  162. fullpath = FileUtils::getInstance()->fullPathForFilename(suffixStr+".webp");
  163. }
  164. }
  165. auto it = _textures.find(fullpath);
  166. if (it != _textures.end())
  167. texture = it->second;
  168. if (texture != nullptr)
  169. {
  170. if (callback) callback(texture);
  171. return;
  172. }
  173. // check if file exists
  174. if (fullpath.empty() || !FileUtils::getInstance()->isFileExist(fullpath)) {
  175. if (callback) callback(nullptr);
  176. return;
  177. }
  178. // lazy init
  179. if (_loadingThread == nullptr)
  180. {
  181. // create a new thread to load images
  182. _needQuit = false;
  183. _loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this);
  184. }
  185. if (_loadingThread2 == nullptr && CocosConfig::isAddImageAsyncWith2Threads() == true)
  186. {
  187. // create a new thread to load images
  188. _needQuit = false;
  189. _loadingThread2 = new (std::nothrow) std::thread(&TextureCache::loadImage, this);
  190. }
  191. if (0 == _asyncRefCount)
  192. {
  193. Director::getInstance()->getScheduler()->schedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this, 0, false);
  194. }
  195. ++_asyncRefCount;
  196. // generate async struct
  197. AsyncStruct *data =
  198. new (std::nothrow) AsyncStruct(fullpath, callback, callbackKey);
  199. // add async struct into queue
  200. _asyncStructQueue.push_back(data);
  201. std::unique_lock<std::mutex> ul(_requestMutex);
  202. _requestQueue.push_back(data);
  203. _sleepCondition.notify_all();
  204. }
  205. void TextureCache::unbindImageAsync(const std::string& callbackKey)
  206. {
  207. if (_asyncStructQueue.empty())
  208. {
  209. return;
  210. }
  211. for (auto& asyncStruct : _asyncStructQueue)
  212. {
  213. if (asyncStruct->callbackKey == callbackKey)
  214. {
  215. asyncStruct->callback = nullptr;
  216. }
  217. }
  218. }
  219. void TextureCache::unbindAllImageAsync()
  220. {
  221. if (_asyncStructQueue.empty())
  222. {
  223. return;
  224. }
  225. for (auto& asyncStruct : _asyncStructQueue)
  226. {
  227. asyncStruct->callback = nullptr;
  228. }
  229. }
  230. void TextureCache::loadImage()
  231. {
  232. AsyncStruct *asyncStruct = nullptr;
  233. while (!_needQuit)
  234. {
  235. std::unique_lock<std::mutex> ul(_requestMutex);
  236. // pop an AsyncStruct from request queue
  237. if (_requestQueue.empty())
  238. {
  239. asyncStruct = nullptr;
  240. }
  241. else
  242. {
  243. asyncStruct = _requestQueue.front();
  244. _requestQueue.pop_front();
  245. }
  246. if (nullptr == asyncStruct) {
  247. if (_needQuit) {
  248. break;
  249. }
  250. _sleepCondition.wait(ul);
  251. continue;
  252. }
  253. ul.unlock();
  254. // load image
  255. asyncStruct->loadSuccess = asyncStruct->image.initWithImageFileThreadSafe(asyncStruct->filename);
  256. // ETC1 ALPHA supports.
  257. if (asyncStruct->loadSuccess && asyncStruct->image.getFileType() == Image::Format::ETC && !s_etc1AlphaFileSuffix.empty())
  258. { // check whether alpha texture exists & load it
  259. auto alphaFile = asyncStruct->filename + s_etc1AlphaFileSuffix;
  260. if (FileUtils::getInstance()->isFileExist(alphaFile))
  261. asyncStruct->imageAlpha.initWithImageFileThreadSafe(alphaFile);
  262. }
  263. // push the asyncStruct to response queue
  264. _responseMutex.lock();
  265. _responseQueue.push_back(asyncStruct);
  266. _responseMutex.unlock();
  267. }
  268. }
  269. void TextureCache::addImageAsyncCallBack(float /*dt*/)
  270. {
  271. Texture2D *texture = nullptr;
  272. AsyncStruct *asyncStruct = nullptr;
  273. while (true)
  274. {
  275. // pop an AsyncStruct from response queue
  276. _responseMutex.lock();
  277. if (_responseQueue.empty())
  278. {
  279. asyncStruct = nullptr;
  280. }
  281. else
  282. {
  283. asyncStruct = _responseQueue.front();
  284. _responseQueue.pop_front();
  285. // the asyncStruct's sequence order in _asyncStructQueue must equal to the order in _responseQueue
  286. // CC_ASSERT(asyncStruct == _asyncStructQueue.front()); //如改用双线程加载图片,该行得注释掉,因为并不是线性的,并不能保证一致
  287. _asyncStructQueue.remove(asyncStruct);
  288. }
  289. _responseMutex.unlock();
  290. if (nullptr == asyncStruct) {
  291. break;
  292. }
  293. // check the image has been convert to texture or not
  294. auto it = _textures.find(asyncStruct->filename);
  295. if (it != _textures.end())
  296. {
  297. texture = it->second;
  298. }
  299. else
  300. {
  301. // convert image to texture
  302. if (asyncStruct->loadSuccess)
  303. {
  304. Image* image = &(asyncStruct->image);
  305. // generate texture in render thread
  306. texture = new (std::nothrow) Texture2D();
  307. texture->initWithImage(image, asyncStruct->pixelFormat);
  308. //parse 9-patch info
  309. this->parseNinePatchImage(image, texture, asyncStruct->filename);
  310. #if CC_ENABLE_CACHE_TEXTURE_DATA
  311. // cache the texture file name
  312. VolatileTextureMgr::addImageTexture(texture, asyncStruct->filename);
  313. #endif
  314. // cache the texture. retain it, since it is added in the map
  315. _textures.emplace(asyncStruct->filename, texture);
  316. texture->retain();
  317. texture->autorelease();
  318. // ETC1 ALPHA supports.
  319. if (asyncStruct->imageAlpha.getFileType() == Image::Format::ETC) {
  320. auto alphaTexture = new(std::nothrow) Texture2D();
  321. if(alphaTexture != nullptr && alphaTexture->initWithImage(&asyncStruct->imageAlpha, asyncStruct->pixelFormat)) {
  322. texture->setAlphaTexture(alphaTexture);
  323. }
  324. CC_SAFE_RELEASE(alphaTexture);
  325. }
  326. }
  327. else {
  328. texture = nullptr;
  329. CCLOG("cocos2d: failed to call TextureCache::addImageAsync(%s)", asyncStruct->filename.c_str());
  330. }
  331. }
  332. // call callback function
  333. if (asyncStruct->callback)
  334. {
  335. (asyncStruct->callback)(texture);
  336. }
  337. // release the asyncStruct
  338. delete asyncStruct;
  339. --_asyncRefCount;
  340. }
  341. if (0 == _asyncRefCount)
  342. {
  343. Director::getInstance()->getScheduler()->unschedule(CC_SCHEDULE_SELECTOR(TextureCache::addImageAsyncCallBack), this);
  344. }
  345. }
  346. Texture2D * TextureCache::addImage(const std::string &path)
  347. {
  348. Texture2D * texture = nullptr;
  349. Image* image = nullptr;
  350. // Split up directory and filename
  351. // MUTEX:
  352. // Needed since addImageAsync calls this method from a different thread
  353. std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path);
  354. if(CocosConfig::isPictureReplaceWebp()){
  355. if(fullpath.size() == 0){
  356. string suffixStr = path.substr(0,path.find_last_of('.'));
  357. fullpath = FileUtils::getInstance()->fullPathForFilename(suffixStr+".webp");
  358. }
  359. }
  360. if (fullpath.size() == 0)
  361. {
  362. string defaultEmptyPic = CocosConfig::getDefaultEmptyPic();
  363. if(defaultEmptyPic == ""){
  364. return nullptr;
  365. }else{
  366. if (path == "(null).tiff") {//粒子效果会有问题的 如果粒子效果是plist且plist里面包含图片的话
  367. return nullptr;
  368. }
  369. fullpath = FileUtils::getInstance()->fullPathForFilename(defaultEmptyPic);
  370. if(CocosConfig::isPictureReplaceWebp()){
  371. if(fullpath.size() == 0){
  372. string suffixStr = defaultEmptyPic.substr(0,defaultEmptyPic.find_last_of('.'));
  373. fullpath = FileUtils::getInstance()->fullPathForFilename(suffixStr+".webp");
  374. }
  375. }
  376. }
  377. }
  378. auto it = _textures.find(fullpath);
  379. if (it != _textures.end())
  380. texture = it->second;
  381. if (!texture)
  382. {
  383. // all images are handled by UIImage except PVR extension that is handled by our own handler
  384. do
  385. {
  386. image = new (std::nothrow) Image();
  387. CC_BREAK_IF(nullptr == image);
  388. bool bRet = image->initWithImageFile(fullpath);
  389. CC_BREAK_IF(!bRet);
  390. texture = new (std::nothrow) Texture2D();
  391. if (texture && texture->initWithImage(image))
  392. {
  393. #if CC_ENABLE_CACHE_TEXTURE_DATA
  394. // cache the texture file name
  395. VolatileTextureMgr::addImageTexture(texture, fullpath);
  396. #endif
  397. // texture already retained, no need to re-retain it
  398. _textures.emplace(fullpath, texture);
  399. //-- ANDROID ETC1 ALPHA SUPPORTS.
  400. std::string alphaFullPath = path + s_etc1AlphaFileSuffix;
  401. if (image->getFileType() == Image::Format::ETC && !s_etc1AlphaFileSuffix.empty() && FileUtils::getInstance()->isFileExist(alphaFullPath))
  402. {
  403. Image alphaImage;
  404. if (alphaImage.initWithImageFile(alphaFullPath))
  405. {
  406. Texture2D *pAlphaTexture = new(std::nothrow) Texture2D;
  407. if(pAlphaTexture != nullptr && pAlphaTexture->initWithImage(&alphaImage)) {
  408. texture->setAlphaTexture(pAlphaTexture);
  409. }
  410. CC_SAFE_RELEASE(pAlphaTexture);
  411. }
  412. }
  413. //parse 9-patch info
  414. this->parseNinePatchImage(image, texture, path);
  415. }
  416. else
  417. {
  418. CCLOG("cocos2d: Couldn't create texture for file:%s in TextureCache", path.c_str());
  419. CC_SAFE_RELEASE(texture);
  420. texture = nullptr;
  421. }
  422. } while (0);
  423. }
  424. CC_SAFE_RELEASE(image);
  425. return texture;
  426. }
  427. void TextureCache::parseNinePatchImage(cocos2d::Image *image, cocos2d::Texture2D *texture, const std::string& path)
  428. {
  429. if (NinePatchImageParser::isNinePatchImage(path))
  430. {
  431. Rect frameRect = Rect(0, 0, image->getWidth(), image->getHeight());
  432. NinePatchImageParser parser(image, frameRect, false);
  433. texture->addSpriteFrameCapInset(nullptr, parser.parseCapInset());
  434. }
  435. }
  436. Texture2D* TextureCache::addImage(Image *image, const std::string &key)
  437. {
  438. CCASSERT(image != nullptr, "TextureCache: image MUST not be nil");
  439. CCASSERT(image->getData() != nullptr, "TextureCache: image MUST not be nil");
  440. Texture2D * texture = nullptr;
  441. do
  442. {
  443. auto it = _textures.find(key);
  444. if (it != _textures.end()) {
  445. texture = it->second;
  446. break;
  447. }
  448. texture = new (std::nothrow) Texture2D();
  449. if (texture)
  450. {
  451. if (texture->initWithImage(image))
  452. {
  453. _textures.emplace(key, texture);
  454. }
  455. else
  456. {
  457. CC_SAFE_RELEASE(texture);
  458. texture = nullptr;
  459. CCLOG("cocos2d: initWithImage failed!");
  460. }
  461. }
  462. else
  463. {
  464. CCLOG("cocos2d: Allocating memory for Texture2D failed!");
  465. }
  466. } while (0);
  467. #if CC_ENABLE_CACHE_TEXTURE_DATA
  468. VolatileTextureMgr::addImage(texture, image);
  469. #endif
  470. return texture;
  471. }
  472. bool TextureCache::reloadTexture(const std::string& fileName)
  473. {
  474. Texture2D * texture = nullptr;
  475. Image * image = nullptr;
  476. std::string fullpath = FileUtils::getInstance()->fullPathForFilename(fileName);
  477. if (fullpath.size() == 0)
  478. {
  479. return false;
  480. }
  481. auto it = _textures.find(fullpath);
  482. if (it != _textures.end()) {
  483. texture = it->second;
  484. }
  485. bool ret = false;
  486. if (!texture) {
  487. texture = this->addImage(fullpath);
  488. ret = (texture != nullptr);
  489. }
  490. else
  491. {
  492. do {
  493. image = new (std::nothrow) Image();
  494. CC_BREAK_IF(nullptr == image);
  495. bool bRet = image->initWithImageFile(fullpath);
  496. CC_BREAK_IF(!bRet);
  497. ret = texture->initWithImage(image);
  498. } while (0);
  499. }
  500. CC_SAFE_RELEASE(image);
  501. return ret;
  502. }
  503. // TextureCache - Remove
  504. void TextureCache::removeAllTextures()
  505. {
  506. for (auto& texture : _textures) {
  507. texture.second->release();
  508. }
  509. _textures.clear();
  510. }
  511. void TextureCache::removeUnusedTextures()
  512. {
  513. for (auto it = _textures.cbegin(); it != _textures.cend(); /* nothing */) {
  514. Texture2D *tex = it->second;
  515. if (tex->getReferenceCount() == 1) {
  516. CCLOG("cocos2d: TextureCache: removing unused texture: %s", it->first.c_str());
  517. tex->release();
  518. it = _textures.erase(it);
  519. }
  520. else {
  521. CCLOG("cocos2d: TextureCache: cann't remove, used texture: %s refCnt:%d", it->first.c_str(), tex->getReferenceCount() );
  522. ++it;
  523. }
  524. }
  525. }
  526. void TextureCache::checkAndRemoveWithKeys(const std::unordered_set<std::string>& textureNames){
  527. for (auto key : textureNames) {
  528. auto fid = _textures.find(key);
  529. if (fid == _textures.end()) {
  530. key = FileUtils::getInstance()->fullPathForFilename(key);
  531. fid = _textures.find(key);
  532. }
  533. if (fid != _textures.end()) {
  534. Texture2D *tex = fid->second;
  535. if (tex->getReferenceCount() == 1) {
  536. CCLOG("cocos2d: TextureCache: removing unused texture: %s", key.c_str());
  537. tex->release();
  538. _textures.erase(fid);
  539. }
  540. }
  541. }
  542. }
  543. void TextureCache::removeTexture(Texture2D* texture)
  544. {
  545. if (!texture)
  546. {
  547. return;
  548. }
  549. for (auto it = _textures.cbegin(); it != _textures.cend(); /* nothing */) {
  550. if (it->second == texture) {
  551. it->second->release();
  552. it = _textures.erase(it);
  553. break;
  554. }
  555. else
  556. ++it;
  557. }
  558. }
  559. void TextureCache::removeTextureForKey(const std::string &textureKeyName)
  560. {
  561. std::string key = textureKeyName;
  562. auto it = _textures.find(key);
  563. if (it == _textures.end()) {
  564. key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
  565. it = _textures.find(key);
  566. }
  567. if (it != _textures.end()) {
  568. it->second->release();
  569. _textures.erase(it);
  570. }
  571. }
  572. Texture2D* TextureCache::getTextureForKey(const std::string &textureKeyName) const
  573. {
  574. std::string key = textureKeyName;
  575. auto it = _textures.find(key);
  576. if (it == _textures.end()) {
  577. key = FileUtils::getInstance()->fullPathForFilename(textureKeyName);
  578. it = _textures.find(key);
  579. }
  580. if (it != _textures.end())
  581. return it->second;
  582. return nullptr;
  583. }
  584. void TextureCache::reloadAllTextures()
  585. {
  586. //will do nothing
  587. // #if CC_ENABLE_CACHE_TEXTURE_DATA
  588. // VolatileTextureMgr::reloadAllTextures();
  589. // #endif
  590. }
  591. std::string TextureCache::getTextureFilePath(cocos2d::Texture2D* texture) const
  592. {
  593. for (auto& item : _textures)
  594. {
  595. if (item.second == texture)
  596. {
  597. return item.first;
  598. break;
  599. }
  600. }
  601. return "";
  602. }
  603. void TextureCache::waitForQuit()
  604. {
  605. // notify sub thread to quick
  606. std::unique_lock<std::mutex> ul(_requestMutex);
  607. _needQuit = true;
  608. _sleepCondition.notify_all();
  609. ul.unlock();
  610. if (_loadingThread) _loadingThread->join();
  611. if (_loadingThread2) _loadingThread2->join();
  612. }
  613. std::string TextureCache::getCachedTextureInfo() const
  614. {
  615. std::string buffer;
  616. char buftmp[4096];
  617. unsigned int count = 0;
  618. unsigned int totalBytes = 0;
  619. // 将unordered_map的元素复制到vector中
  620. std::vector<std::pair<std::string, Texture2D*>> vecTextures(_textures.begin(), _textures.end());
  621. // 定义lambda表达式用于比较
  622. auto compareByTexutreMem = [](const std::pair<std::string, Texture2D*>& a, const std::pair<std::string, Texture2D*>& b) {
  623. unsigned int a_bpp = a.second->getBitsPerPixelForFormat();
  624. auto a_bytes = a.second->getPixelsWide() * a.second->getPixelsHigh() * a_bpp / 8;
  625. unsigned int b_bpp = b.second->getBitsPerPixelForFormat();
  626. auto b_bytes = b.second->getPixelsWide() * b.second->getPixelsHigh() * b_bpp / 8;
  627. return a_bytes > b_bytes; // 按值进行降序排序
  628. };
  629. // 使用lambda表达式进行排序
  630. std::sort(vecTextures.begin(), vecTextures.end(), compareByTexutreMem);
  631. for (auto& texture : vecTextures) {
  632. memset(buftmp, 0, sizeof(buftmp));
  633. Texture2D* tex = texture.second;
  634. unsigned int bpp = tex->getBitsPerPixelForFormat();
  635. // Each texture takes up width * height * bytesPerPixel bytes.
  636. auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
  637. totalBytes += bytes;
  638. count++;
  639. snprintf(buftmp, sizeof(buftmp) - 1, "\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n",
  640. texture.first.c_str(),
  641. (long)tex->getReferenceCount(),
  642. (long)tex->getName(),
  643. (long)tex->getPixelsWide(),
  644. (long)tex->getPixelsHigh(),
  645. (long)bpp,
  646. (long)bytes / 1024);
  647. buffer += buftmp;
  648. }
  649. snprintf(buftmp, sizeof(buftmp) - 1, "TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)\n", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f));
  650. buffer += buftmp;
  651. return buffer;
  652. }
  653. void TextureCache::renameTextureWithKey(const std::string& srcName, const std::string& dstName)
  654. {
  655. std::string key = srcName;
  656. auto it = _textures.find(key);
  657. if (it == _textures.end()) {
  658. key = FileUtils::getInstance()->fullPathForFilename(srcName);
  659. it = _textures.find(key);
  660. }
  661. if (it != _textures.end()) {
  662. std::string fullpath = FileUtils::getInstance()->fullPathForFilename(dstName);
  663. Texture2D* tex = it->second;
  664. Image* image = new (std::nothrow) Image();
  665. if (image)
  666. {
  667. bool ret = image->initWithImageFile(dstName);
  668. if (ret)
  669. {
  670. tex->initWithImage(image);
  671. _textures.emplace(fullpath, tex);
  672. _textures.erase(it);
  673. }
  674. CC_SAFE_DELETE(image);
  675. }
  676. }
  677. }
  678. #if CC_ENABLE_CACHE_TEXTURE_DATA
  679. std::list<VolatileTexture*> VolatileTextureMgr::_textures;
  680. bool VolatileTextureMgr::_isReloading = false;
  681. VolatileTexture::VolatileTexture(Texture2D *t)
  682. : _texture(t)
  683. , _uiImage(nullptr)
  684. , _cashedImageType(kInvalid)
  685. , _textureData(nullptr)
  686. , _pixelFormat(Texture2D::PixelFormat::RGBA8888)
  687. , _fileName("")
  688. , _hasMipmaps(false)
  689. , _text("")
  690. {
  691. _texParams.minFilter = GL_LINEAR;
  692. _texParams.magFilter = GL_LINEAR;
  693. _texParams.wrapS = GL_CLAMP_TO_EDGE;
  694. _texParams.wrapT = GL_CLAMP_TO_EDGE;
  695. }
  696. VolatileTexture::~VolatileTexture()
  697. {
  698. CC_SAFE_RELEASE(_uiImage);
  699. }
  700. void VolatileTextureMgr::addImageTexture(Texture2D *tt, const std::string& imageFileName)
  701. {
  702. if (_isReloading)
  703. {
  704. return;
  705. }
  706. VolatileTexture *vt = findVolotileTexture(tt);
  707. vt->_cashedImageType = VolatileTexture::kImageFile;
  708. vt->_fileName = imageFileName;
  709. vt->_pixelFormat = tt->getPixelFormat();
  710. }
  711. void VolatileTextureMgr::addImage(Texture2D *tt, Image *image)
  712. {
  713. if (tt == nullptr || image == nullptr)
  714. return;
  715. VolatileTexture *vt = findVolotileTexture(tt);
  716. image->retain();
  717. vt->_uiImage = image;
  718. vt->_cashedImageType = VolatileTexture::kImage;
  719. }
  720. VolatileTexture* VolatileTextureMgr::findVolotileTexture(Texture2D *tt)
  721. {
  722. VolatileTexture *vt = nullptr;
  723. for (const auto& texture : _textures)
  724. {
  725. VolatileTexture *v = texture;
  726. if (v->_texture == tt)
  727. {
  728. vt = v;
  729. break;
  730. }
  731. }
  732. if (!vt)
  733. {
  734. vt = new (std::nothrow) VolatileTexture(tt);
  735. _textures.push_back(vt);
  736. }
  737. return vt;
  738. }
  739. void VolatileTextureMgr::addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize)
  740. {
  741. if (_isReloading)
  742. {
  743. return;
  744. }
  745. VolatileTexture *vt = findVolotileTexture(tt);
  746. vt->_cashedImageType = VolatileTexture::kImageData;
  747. vt->_textureData = data;
  748. vt->_dataLen = dataLen;
  749. vt->_pixelFormat = pixelFormat;
  750. vt->_textureSize = contentSize;
  751. }
  752. void VolatileTextureMgr::addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition)
  753. {
  754. if (_isReloading)
  755. {
  756. return;
  757. }
  758. VolatileTexture *vt = findVolotileTexture(tt);
  759. vt->_cashedImageType = VolatileTexture::kString;
  760. vt->_text = text;
  761. vt->_fontDefinition = fontDefinition;
  762. }
  763. void VolatileTextureMgr::setHasMipmaps(Texture2D *t, bool hasMipmaps)
  764. {
  765. VolatileTexture *vt = findVolotileTexture(t);
  766. vt->_hasMipmaps = hasMipmaps;
  767. }
  768. void VolatileTextureMgr::setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams)
  769. {
  770. VolatileTexture *vt = findVolotileTexture(t);
  771. if (texParams.minFilter != GL_NONE)
  772. vt->_texParams.minFilter = texParams.minFilter;
  773. if (texParams.magFilter != GL_NONE)
  774. vt->_texParams.magFilter = texParams.magFilter;
  775. if (texParams.wrapS != GL_NONE)
  776. vt->_texParams.wrapS = texParams.wrapS;
  777. if (texParams.wrapT != GL_NONE)
  778. vt->_texParams.wrapT = texParams.wrapT;
  779. }
  780. void VolatileTextureMgr::removeTexture(Texture2D *t)
  781. {
  782. for (auto& item : _textures)
  783. {
  784. VolatileTexture *vt = item;
  785. if (vt->_texture == t)
  786. {
  787. _textures.remove(vt);
  788. delete vt;
  789. break;
  790. }
  791. }
  792. }
  793. void VolatileTextureMgr::reloadAllTextures()
  794. {
  795. _isReloading = true;
  796. // we need to release all of the glTextures to avoid collisions of texture id's when reloading the textures onto the GPU
  797. for (auto& item : _textures)
  798. {
  799. item->_texture->releaseGLTexture();
  800. }
  801. CCLOG("reload all texture");
  802. for (auto& texture : _textures)
  803. {
  804. VolatileTexture *vt = texture;
  805. switch (vt->_cashedImageType)
  806. {
  807. case VolatileTexture::kImageFile:
  808. {
  809. reloadTexture(vt->_texture, vt->_fileName, vt->_pixelFormat);
  810. // etc1 support check whether alpha texture exists & load it
  811. auto alphaFile = vt->_fileName + TextureCache::getETC1AlphaFileSuffix();
  812. reloadTexture(vt->_texture->getAlphaTexture(), alphaFile, vt->_pixelFormat);
  813. }
  814. break;
  815. case VolatileTexture::kImageData:
  816. {
  817. vt->_texture->initWithData(vt->_textureData,
  818. vt->_dataLen,
  819. vt->_pixelFormat,
  820. vt->_textureSize.width,
  821. vt->_textureSize.height,
  822. vt->_textureSize);
  823. }
  824. break;
  825. case VolatileTexture::kString:
  826. {
  827. vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition);
  828. }
  829. break;
  830. case VolatileTexture::kImage:
  831. {
  832. vt->_texture->initWithImage(vt->_uiImage);
  833. }
  834. break;
  835. default:
  836. break;
  837. }
  838. if (vt->_hasMipmaps) {
  839. vt->_texture->generateMipmap();
  840. }
  841. vt->_texture->setTexParameters(vt->_texParams);
  842. }
  843. _isReloading = false;
  844. }
  845. void VolatileTextureMgr::reloadTexture(Texture2D* texture, const std::string& filename, Texture2D::PixelFormat pixelFormat)
  846. {
  847. if (!texture)
  848. return;
  849. Image* image = new (std::nothrow) Image();
  850. Data data = FileUtils::getInstance()->getDataFromFile(filename);
  851. if (image && image->initWithImageData(data.getBytes(), data.getSize()))
  852. texture->initWithImage(image, pixelFormat);
  853. CC_SAFE_RELEASE(image);
  854. }
  855. #endif // CC_ENABLE_CACHE_TEXTURE_DATA
  856. NS_CC_END