CCSpriteFrameCache.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2011-2012 cocos2d-x.org
  4. Copyright (c) 2013-2014 Chukong Technologies Inc.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. /**
  23. * <p>
  24. * cc.spriteFrameCache is a singleton that handles the loading of the sprite frames. It saves in a cache the sprite frames.<br/>
  25. * <br/>
  26. * example<br/>
  27. * // add SpriteFrames to spriteFrameCache With File<br/>
  28. * cc.spriteFrameCache.addSpriteFrames(s_grossiniPlist);<br/>
  29. * </p>
  30. * @class
  31. * @name cc.spriteFrameCache
  32. */
  33. cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
  34. _CCNS_REG1 : /^\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*$/,
  35. _CCNS_REG2 : /^\s*\{\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*,\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*\}\s*$/,
  36. _spriteFrames: {},
  37. _spriteFramesAliases: {},
  38. _frameConfigCache : {},
  39. _rectFromString : function (content) {
  40. var result = this._CCNS_REG2.exec(content);
  41. if(!result) return cc.rect(0, 0, 0, 0);
  42. return cc.rect(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]), parseFloat(result[4]));
  43. },
  44. _pointFromString : function (content) {
  45. var result = this._CCNS_REG1.exec(content);
  46. if(!result) return cc.p(0,0);
  47. return cc.p(parseFloat(result[1]), parseFloat(result[2]));
  48. },
  49. _sizeFromString : function (content) {
  50. var result = this._CCNS_REG1.exec(content);
  51. if(!result) return cc.size(0, 0);
  52. return cc.size(parseFloat(result[1]), parseFloat(result[2]));
  53. },
  54. _getFrameConfig : function(url){
  55. var dict = cc.loader.getRes(url);
  56. cc.assert(dict, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url);
  57. cc.loader.release(url);//release it in loader
  58. if(dict._inited){
  59. this._frameConfigCache[url] = dict;
  60. return dict;
  61. }
  62. var tempFrames = dict["frames"], tempMeta = dict["metadata"] || dict["meta"];
  63. var frames = {}, meta = {};
  64. var format = 0;
  65. if(tempMeta){//init meta
  66. var tmpFormat = tempMeta["format"];
  67. format = (tmpFormat.length <= 1) ? parseInt(tmpFormat) : tmpFormat;
  68. meta.image = tempMeta["textureFileName"] || tempMeta["textureFileName"] || tempMeta["image"];
  69. }
  70. for (var key in tempFrames) {
  71. var frameDict = tempFrames[key];
  72. if(!frameDict) continue;
  73. var tempFrame = {};
  74. if (format == 0) {
  75. tempFrame.rect = cc.rect(frameDict["x"], frameDict["y"], frameDict["width"], frameDict["height"]);
  76. tempFrame.rotated = false;
  77. tempFrame.offset = cc.p(frameDict["offsetX"], frameDict["offsetY"]);
  78. var ow = frameDict["originalWidth"];
  79. var oh = frameDict["originalHeight"];
  80. // check ow/oh
  81. if (!ow || !oh) {
  82. cc.log(cc._LogInfos.spriteFrameCache__getFrameConfig);
  83. }
  84. // Math.abs ow/oh
  85. ow = Math.abs(ow);
  86. oh = Math.abs(oh);
  87. tempFrame.size = cc.size(ow, oh);
  88. } else if (format == 1 || format == 2) {
  89. tempFrame.rect = this._rectFromString(frameDict["frame"]);
  90. tempFrame.rotated = frameDict["rotated"] || false;
  91. tempFrame.offset = this._pointFromString(frameDict["offset"]);
  92. tempFrame.size = this._sizeFromString(frameDict["sourceSize"]);
  93. } else if (format == 3) {
  94. // get values
  95. var spriteSize = this._sizeFromString(frameDict["spriteSize"]);
  96. var textureRect = this._rectFromString(frameDict["textureRect"]);
  97. if (spriteSize) {
  98. textureRect = cc.rect(textureRect.x, textureRect.y, spriteSize.width, spriteSize.height);
  99. }
  100. tempFrame.rect = textureRect;
  101. tempFrame.rotated = frameDict["textureRotated"] || false; // == "true";
  102. tempFrame.offset = this._pointFromString(frameDict["spriteOffset"]);
  103. tempFrame.size = this._sizeFromString(frameDict["spriteSourceSize"]);
  104. tempFrame.aliases = frameDict["aliases"];
  105. } else {
  106. var tmpFrame = frameDict["frame"], tmpSourceSize = frameDict["sourceSize"];
  107. key = frameDict["filename"] || key;
  108. tempFrame.rect = cc.rect(tmpFrame["x"], tmpFrame["y"], tmpFrame["w"], tmpFrame["h"]);
  109. tempFrame.rotated = frameDict["rotated"] || false;
  110. tempFrame.offset = cc.p(0, 0);
  111. tempFrame.size = cc.size(tmpSourceSize["w"], tmpSourceSize["h"]);
  112. }
  113. frames[key] = tempFrame;
  114. }
  115. var cfg = this._frameConfigCache[url] = {
  116. _inited : true,
  117. frames : frames,
  118. meta : meta
  119. };
  120. return cfg;
  121. },
  122. /**
  123. * <p>
  124. * Adds multiple Sprite Frames from a plist or json file.<br/>
  125. * A texture will be loaded automatically. The texture name will composed by replacing the .plist or .json suffix with .png<br/>
  126. * If you want to use another texture, you should use the addSpriteFrames:texture method.<br/>
  127. * </p>
  128. * @param {String} url file path
  129. * @param {HTMLImageElement|cc.Texture2D|string} texture
  130. * @example
  131. * // add SpriteFrames to SpriteFrameCache With File
  132. * cc.spriteFrameCache.addSpriteFrames(s_grossiniPlist);
  133. * cc.spriteFrameCache.addSpriteFrames(s_grossiniJson);
  134. */
  135. addSpriteFrames: function (url, texture) {
  136. cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2);
  137. //Is it a SpriteFrame plist?
  138. var dict = this._frameConfigCache[url] || cc.loader.getRes(url);
  139. if(!dict || !dict["frames"])
  140. return;
  141. var self = this;
  142. var frameConfig = self._frameConfigCache[url] || self._getFrameConfig(url);
  143. //self._checkConflict(frameConfig); //TODO
  144. var frames = frameConfig.frames, meta = frameConfig.meta;
  145. if(!texture){
  146. var texturePath = cc.path.changeBasename(url, meta.image || ".png");
  147. texture = cc.textureCache.addImage(texturePath);
  148. }else if(texture instanceof cc.Texture2D){
  149. //do nothing
  150. }else if(typeof texture == "string"){//string
  151. texture = cc.textureCache.addImage(texture);
  152. }else{
  153. cc.assert(0, cc._LogInfos.spriteFrameCache_addSpriteFrames_3);
  154. }
  155. //create sprite frames
  156. var spAliases = self._spriteFramesAliases, spriteFrames = self._spriteFrames;
  157. for (var key in frames) {
  158. var frame = frames[key];
  159. var spriteFrame = spriteFrames[key];
  160. if (!spriteFrame) {
  161. spriteFrame = cc.SpriteFrame.create(texture, frame.rect, frame.rotated, frame.offset, frame.size);
  162. var aliases = frame.aliases;
  163. if(aliases){//set aliases
  164. for(var i = 0, li = aliases.length; i < li; i++){
  165. var alias = aliases[i];
  166. if (spAliases[alias]) {
  167. cc.log(cc._LogInfos.spriteFrameCache_addSpriteFrames, alias);
  168. }
  169. spAliases[alias] = key;
  170. }
  171. }
  172. if (cc._renderType === cc._RENDER_TYPE_CANVAS && spriteFrame.isRotated()) {
  173. //clip to canvas
  174. var locTexture = spriteFrame.getTexture();
  175. if (locTexture.isLoaded()) {
  176. var tempElement = spriteFrame.getTexture().getHtmlElementObj();
  177. tempElement = cc.cutRotateImageToCanvas(tempElement, spriteFrame.getRectInPixels());
  178. var tempTexture = new cc.Texture2D();
  179. tempTexture.initWithElement(tempElement);
  180. tempTexture.handleLoadedTexture();
  181. spriteFrame.setTexture(tempTexture);
  182. var rect = spriteFrame._rect;
  183. spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height));
  184. }
  185. }
  186. spriteFrames[key] = spriteFrame;
  187. }
  188. }
  189. },
  190. // Function to check if frames to add exists already, if so there may be name conflit that must be solved
  191. _checkConflict: function (dictionary) {
  192. var framesDict = dictionary["frames"];
  193. for (var key in framesDict) {
  194. if (this._spriteFrames[key]) {
  195. cc.log(cc._LogInfos.spriteFrameCache__checkConflict, key);
  196. }
  197. }
  198. },
  199. /**
  200. * <p>
  201. * Adds an sprite frame with a given name.<br/>
  202. * If the name already exists, then the contents of the old name will be replaced with the new one.
  203. * </p>
  204. * @param {cc.SpriteFrame} frame
  205. * @param {String} frameName
  206. */
  207. addSpriteFrame: function (frame, frameName) {
  208. this._spriteFrames[frameName] = frame;
  209. },
  210. /**
  211. * <p>
  212. * Purges the dictionary of loaded sprite frames.<br/>
  213. * Call this method if you receive the "Memory Warning".<br/>
  214. * In the short term: it will free some resources preventing your app from being killed.<br/>
  215. * In the medium term: it will allocate more resources.<br/>
  216. * In the long term: it will be the same.<br/>
  217. * </p>
  218. */
  219. removeSpriteFrames: function () {
  220. this._spriteFrames = {};
  221. this._spriteFramesAliases = {};
  222. },
  223. /**
  224. * Deletes an sprite frame from the sprite frame cache.
  225. * @param {String} name
  226. */
  227. removeSpriteFrameByName: function (name) {
  228. // explicit nil handling
  229. if (!name) {
  230. return;
  231. }
  232. // Is this an alias ?
  233. if (this._spriteFramesAliases[name]) {
  234. delete(this._spriteFramesAliases[name]);
  235. }
  236. if (this._spriteFrames[name]) {
  237. delete(this._spriteFrames[name]);
  238. }
  239. // XXX. Since we don't know the .plist file that originated the frame, we must remove all .plist from the cache
  240. },
  241. /**
  242. * <p>
  243. * Removes multiple Sprite Frames from a plist file.<br/>
  244. * Sprite Frames stored in this file will be removed.<br/>
  245. * It is convinient to call this method when a specific texture needs to be removed.<br/>
  246. * </p>
  247. * @param {String} url Plist filename
  248. */
  249. removeSpriteFramesFromFile: function (url) {
  250. var self = this, spriteFrames = self._spriteFrames,
  251. aliases = self._spriteFramesAliases, cfg = self._frameConfigCache[url];
  252. if(!cfg) return;
  253. var frames = cfg.frames;
  254. for (var key in frames) {
  255. if (spriteFrames[key]) {
  256. delete(spriteFrames[key]);
  257. for (var alias in aliases) {//remove alias
  258. if(aliases[alias] == key) delete aliases[alias];
  259. }
  260. }
  261. }
  262. },
  263. /**
  264. * <p>
  265. * Removes all Sprite Frames associated with the specified textures.<br/>
  266. * It is convenient to call this method when a specific texture needs to be removed.
  267. * </p>
  268. * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture
  269. */
  270. removeSpriteFramesFromTexture: function (texture) {
  271. var self = this, spriteFrames = self._spriteFrames, aliases = self._spriteFramesAliases;
  272. for (var key in spriteFrames) {
  273. var frame = spriteFrames[key];
  274. if (frame && (frame.getTexture() == texture)) {
  275. delete(spriteFrames[key]);
  276. for (var alias in aliases) {//remove alias
  277. if(aliases[alias] == key) delete aliases[alias];
  278. }
  279. }
  280. }
  281. },
  282. /**
  283. * <p>
  284. * Returns an Sprite Frame that was previously added.<br/>
  285. * If the name is not found it will return nil.<br/>
  286. * You should retain the returned copy if you are going to use it.<br/>
  287. * </p>
  288. * @param {String} name name of SpriteFrame
  289. * @return {cc.SpriteFrame}
  290. * @example
  291. * //get a SpriteFrame by name
  292. * var frame = cc.spriteFrameCache.getSpriteFrame("grossini_dance_01.png");
  293. */
  294. getSpriteFrame: function (name) {
  295. var self = this, frame = self._spriteFrames[name];
  296. if (!frame) {
  297. // try alias dictionary
  298. var key = self._spriteFramesAliases[name];
  299. if (key) {
  300. frame = self._spriteFrames[key.toString()];
  301. if(!frame) delete self._spriteFramesAliases[name];
  302. }
  303. }
  304. if (!frame) cc.log(cc._LogInfos.spriteFrameCache_getSpriteFrame, name);
  305. return frame;
  306. },
  307. _clear: function () {
  308. this._spriteFrames = {};
  309. this._spriteFramesAliases = {};
  310. this._frameConfigCache = {};
  311. }
  312. };