CCTextureCache.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. #ifndef __CCTEXTURE_CACHE_H__
  25. #define __CCTEXTURE_CACHE_H__
  26. #include <mutex>
  27. #include <thread>
  28. #include <condition_variable>
  29. #include <queue>
  30. #include <string>
  31. #include <unordered_map>
  32. #include <functional>
  33. #include "base/CCRef.h"
  34. #include "renderer/CCTexture2D.h"
  35. #include "platform/CCImage.h"
  36. #if CC_ENABLE_CACHE_TEXTURE_DATA
  37. #include <list>
  38. #endif
  39. NS_CC_BEGIN
  40. /**
  41. * @addtogroup _2d
  42. * @{
  43. */
  44. /*
  45. * From version 3.0, TextureCache will never to treated as a singleton, it will be owned by director.
  46. * All call by TextureCache::getInstance() should be replaced by Director::getInstance()->getTextureCache().
  47. */
  48. /** @brief Singleton that handles the loading of textures.
  49. * Once the texture is loaded, the next time it will return.
  50. * A reference of the previously loaded texture reducing GPU & CPU memory.
  51. */
  52. class CC_DLL TextureCache : public Ref
  53. {
  54. public:
  55. /** Returns the shared instance of the cache. */
  56. CC_DEPRECATED_ATTRIBUTE static TextureCache * getInstance();
  57. /** @deprecated Use getInstance() instead. */
  58. CC_DEPRECATED_ATTRIBUTE static TextureCache * sharedTextureCache();
  59. /** Purges the cache. It releases the retained instance.
  60. @since v0.99.0
  61. */
  62. CC_DEPRECATED_ATTRIBUTE static void destroyInstance();
  63. /** @deprecated Use destroyInstance() instead. */
  64. CC_DEPRECATED_ATTRIBUTE static void purgeSharedTextureCache();
  65. /** Reload all textures.
  66. Should not call it, called by frame work.
  67. Now the function do nothing, use VolatileTextureMgr::reloadAllTextures.
  68. */
  69. CC_DEPRECATED_ATTRIBUTE static void reloadAllTextures();
  70. // ETC1 ALPHA supports.
  71. static void setETC1AlphaFileSuffix(const std::string& suffix);
  72. static std::string getETC1AlphaFileSuffix();
  73. public:
  74. /**
  75. * @js ctor
  76. */
  77. TextureCache();
  78. /**
  79. * @js NA
  80. * @lua NA
  81. */
  82. virtual ~TextureCache();
  83. /**
  84. * @js NA
  85. * @lua NA
  86. */
  87. virtual std::string getDescription() const;
  88. // Dictionary* snapshotTextures();
  89. /** Returns a Texture2D object given an filename.
  90. * If the filename was not previously loaded, it will create a new Texture2D.
  91. * Object and it will return it. It will use the filename as a key.
  92. * Otherwise it will return a reference of a previously loaded image.
  93. * Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr.
  94. @param filepath A null terminated string.
  95. */
  96. Texture2D* addImage(const std::string &filepath);
  97. /** Returns a Texture2D object given a file image.
  98. * If the file image was not previously loaded, it will create a new Texture2D object and it will return it.
  99. * Otherwise it will load a texture in a new thread, and when the image is loaded, the callback will be called with the Texture2D as a parameter.
  100. * The callback will be called from the main thread, so it is safe to create any cocos2d object from the callback.
  101. * Supported image extensions: .png, .jpg
  102. @param filepath A null terminated string.
  103. @param callback A callback function would be invoked after the image is loaded.
  104. @since v0.8
  105. */
  106. virtual void addImageAsync(const std::string &filepath, const std::function<void(Texture2D*)>& callback);
  107. void addImageAsync(const std::string &path, const std::function<void(Texture2D*)>& callback, const std::string& callbackKey );
  108. /** Unbind a specified bound image asynchronous callback.
  109. * In the case an object who was bound to an image asynchronous callback was destroyed before the callback is invoked,
  110. * the object always need to unbind this callback manually.
  111. * @param filename It's the related/absolute path of the file image.
  112. * @since v3.1
  113. */
  114. virtual void unbindImageAsync(const std::string &filename);
  115. /** Unbind all bound image asynchronous load callbacks.
  116. * @since v3.1
  117. */
  118. virtual void unbindAllImageAsync();
  119. /** Returns a Texture2D object given an Image.
  120. * If the image was not previously loaded, it will create a new Texture2D object and it will return it.
  121. * Otherwise it will return a reference of a previously loaded image.
  122. * @param key The "key" parameter will be used as the "key" for the cache.
  123. * If "key" is nil, then a new texture will be created each time.
  124. */
  125. Texture2D* addImage(Image *image, const std::string &key);
  126. CC_DEPRECATED_ATTRIBUTE Texture2D* addUIImage(Image *image, const std::string& key) { return addImage(image,key); }
  127. /** Returns an already created texture. Returns nil if the texture doesn't exist.
  128. @param key It's the related/absolute path of the file image.
  129. @since v0.99.5
  130. */
  131. Texture2D* getTextureForKey(const std::string& key) const;
  132. CC_DEPRECATED_ATTRIBUTE Texture2D* textureForKey(const std::string& key) const { return getTextureForKey(key); }
  133. /** Reload texture from the image file.
  134. * If the file image hasn't loaded before, load it.
  135. * Otherwise the texture will be reloaded from the file image.
  136. * @param fileName It's the related/absolute path of the file image.
  137. * @return True if the reloading is succeed, otherwise return false.
  138. */
  139. bool reloadTexture(const std::string& fileName);
  140. /** Purges the dictionary of loaded textures.
  141. * Call this method if you receive the "Memory Warning".
  142. * In the short term: it will free some resources preventing your app from being killed.
  143. * In the medium term: it will allocate more resources.
  144. * In the long term: it will be the same.
  145. */
  146. void removeAllTextures();
  147. /** Removes unused textures.
  148. * Textures that have a retain count of 1 will be deleted.
  149. * It is convenient to call this method after when starting a new Scene.
  150. * @since v0.8
  151. */
  152. void removeUnusedTextures();
  153. /** Deletes a texture from the cache given a texture.
  154. */
  155. void removeTexture(Texture2D* texture);
  156. /** Deletes a texture from the cache given a its key name.
  157. @param key It's the related/absolute path of the file image.
  158. @since v0.99.4
  159. */
  160. void removeTextureForKey(const std::string &key);
  161. /** Output to CCLOG the current contents of this TextureCache.
  162. * This will attempt to calculate the size of each texture, and the total texture memory in use.
  163. *
  164. * @since v1.0
  165. */
  166. std::string getCachedTextureInfo() const;
  167. //Wait for texture cache to quit before destroy instance.
  168. /**Called by director, please do not called outside.*/
  169. void waitForQuit();
  170. /**
  171. * Get the file path of the texture
  172. *
  173. * @param texture A Texture2D object pointer.
  174. *
  175. * @return The full path of the file.
  176. */
  177. std::string getTextureFilePath(Texture2D* texture) const;
  178. /** Reload texture from a new file.
  179. * This function is mainly for editor, won't suggest use it in game for performance reason.
  180. *
  181. * @param srcName Original texture file name.
  182. * @param dstName New texture file name.
  183. *
  184. * @since v3.10
  185. */
  186. void renameTextureWithKey(const std::string& srcName, const std::string& dstName);
  187. private:
  188. void addImageAsyncCallBack(float dt);
  189. void loadImage();
  190. void parseNinePatchImage(Image* image, Texture2D* texture, const std::string& path);
  191. public:
  192. protected:
  193. struct AsyncStruct;
  194. std::thread* _loadingThread;
  195. std::deque<AsyncStruct*> _asyncStructQueue;
  196. std::deque<AsyncStruct*> _requestQueue;
  197. std::deque<AsyncStruct*> _responseQueue;
  198. std::mutex _requestMutex;
  199. std::mutex _responseMutex;
  200. std::condition_variable _sleepCondition;
  201. bool _needQuit;
  202. int _asyncRefCount;
  203. std::unordered_map<std::string, Texture2D*> _textures;
  204. static std::string s_etc1AlphaFileSuffix;
  205. };
  206. #if CC_ENABLE_CACHE_TEXTURE_DATA
  207. class VolatileTexture
  208. {
  209. typedef enum {
  210. kInvalid = 0,
  211. kImageFile,
  212. kImageData,
  213. kString,
  214. kImage,
  215. }ccCachedImageType;
  216. private:
  217. VolatileTexture(Texture2D *t);
  218. /**
  219. * @js NA
  220. * @lua NA
  221. */
  222. ~VolatileTexture();
  223. protected:
  224. friend class VolatileTextureMgr;
  225. Texture2D *_texture;
  226. Image *_uiImage;
  227. ccCachedImageType _cashedImageType;
  228. void *_textureData;
  229. int _dataLen;
  230. Size _textureSize;
  231. Texture2D::PixelFormat _pixelFormat;
  232. std::string _fileName;
  233. bool _hasMipmaps;
  234. Texture2D::TexParams _texParams;
  235. std::string _text;
  236. FontDefinition _fontDefinition;
  237. };
  238. class CC_DLL VolatileTextureMgr
  239. {
  240. public:
  241. static void addImageTexture(Texture2D *tt, const std::string& imageFileName);
  242. static void addStringTexture(Texture2D *tt, const char* text, const FontDefinition& fontDefinition);
  243. static void addDataTexture(Texture2D *tt, void* data, int dataLen, Texture2D::PixelFormat pixelFormat, const Size& contentSize);
  244. static void addImage(Texture2D *tt, Image *image);
  245. static void setHasMipmaps(Texture2D *t, bool hasMipmaps);
  246. static void setTexParameters(Texture2D *t, const Texture2D::TexParams &texParams);
  247. static void removeTexture(Texture2D *t);
  248. static void reloadAllTextures();
  249. public:
  250. static std::list<VolatileTexture*> _textures;
  251. static bool _isReloading;
  252. private:
  253. // find VolatileTexture by Texture2D*
  254. // if not found, create a new one
  255. static VolatileTexture* findVolotileTexture(Texture2D *tt);
  256. static void reloadTexture(Texture2D* texture, const std::string& filename, Texture2D::PixelFormat pixelFormat);
  257. };
  258. #endif
  259. // end of textures group
  260. /// @}
  261. NS_CC_END
  262. #endif //__CCTEXTURE_CACHE_H__