CCLabelAtlas.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2008-2010 Ricardo Quesada
  4. Copyright (c) 2011 Zynga 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. * using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont
  24. * @class
  25. * @extends cc.AtlasNode
  26. */
  27. cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{
  28. // string to render
  29. _string:null,
  30. // the first char in the charmap
  31. _mapStartChar:null,
  32. _textureLoaded:false,
  33. _loadedEventListeners: null,
  34. ctor:function(){
  35. cc.AtlasNode.prototype.ctor.call(this);
  36. },
  37. /**
  38. * return texture is loaded
  39. * @returns {boolean}
  40. */
  41. textureLoaded:function(){
  42. return this._textureLoaded;
  43. },
  44. /**
  45. * add texture loaded event listener
  46. * @param {Function} callback
  47. * @param {Object} target
  48. */
  49. addLoadedEventListener:function(callback, target){
  50. if(!this._loadedEventListeners)
  51. this._loadedEventListeners = [];
  52. this._loadedEventListeners.push({eventCallback:callback, eventTarget:target});
  53. },
  54. _callLoadedEventCallbacks:function(){
  55. if(!this._loadedEventListeners)
  56. return;
  57. this._textureLoaded = true;
  58. var locListeners = this._loadedEventListeners;
  59. for(var i = 0, len = locListeners.length; i < len; i++){
  60. var selCallback = locListeners[i];
  61. cc.doCallback(selCallback.eventCallback, selCallback.eventTarget, this);
  62. }
  63. locListeners.length = 0;
  64. },
  65. /**
  66. * <p>
  67. * initializes the cc.LabelAtlas with a string, a char map file(the atlas), <br/>
  68. * the width and height of each element and the starting char of the atlas <br/>
  69. * It accepts two groups of parameters: <br/>
  70. * a) string, fntFile <br/>
  71. * b) label, textureFilename, width, height, startChar <br/>
  72. * </p>
  73. * @param {String} strText
  74. * @param {String|cc.Texture2D} charMapFile charMapFile or fntFile or texture file
  75. * @param {Number} [itemWidth=0]
  76. * @param {Number} [itemHeight=0]
  77. * @param {Number} [startCharMap=""]
  78. * @return {Boolean} returns true on success
  79. */
  80. initWithString:function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
  81. var label = strText + "", textureFilename, width, height, startChar;
  82. if (arguments.length === 2) {
  83. var fileUtils = cc.FileUtils.getInstance();
  84. var pathStr = fileUtils.fullPathForFilename(charMapFile);
  85. var relPathStr = pathStr.substr(0, pathStr.lastIndexOf('/')) + '/';
  86. var dict = fileUtils.dictionaryWithContentsOfFileThreadSafe(pathStr);
  87. if(parseInt(dict["version"], 10) !== 1) {
  88. cc.log("cc.LabelAtlas.initWithString(): Unsupported version. Upgrade cocos2d version");
  89. return false;
  90. }
  91. textureFilename = relPathStr + dict["textureFilename"];
  92. var locScaleFactor = cc.CONTENT_SCALE_FACTOR();
  93. width = parseInt(dict["itemWidth"], 10) / locScaleFactor;
  94. height = parseInt(dict["itemHeight"], 10) / locScaleFactor;
  95. startChar = String.fromCharCode(parseInt(dict["firstChar"], 10));
  96. } else {
  97. textureFilename = charMapFile;
  98. width = itemWidth || 0;
  99. height = itemHeight || 0;
  100. startChar = startCharMap || " ";
  101. }
  102. var texture = null;
  103. if(textureFilename instanceof cc.Texture2D)
  104. texture = textureFilename;
  105. else
  106. texture = cc.TextureCache.getInstance().addImage(textureFilename);
  107. var locLoaded = texture.isLoaded();
  108. this._textureLoaded = locLoaded;
  109. if(!locLoaded){
  110. texture.addLoadedEventListener(function(sender){
  111. this.initWithTexture(texture, width, height, label.length);
  112. this.setString(label);
  113. this._callLoadedEventCallbacks();
  114. },this);
  115. }
  116. if (this.initWithTexture(texture, width, height, label.length)) {
  117. this._mapStartChar = startChar;
  118. this.setString(label);
  119. return true;
  120. }
  121. return false;
  122. },
  123. /**
  124. * @param {cc.Color3B} color3
  125. */
  126. setColor:function (color3) {
  127. cc.AtlasNode.prototype.setColor.call(this, color3);
  128. this.updateAtlasValues();
  129. },
  130. /**
  131. * return the text of this label
  132. * @return {String}
  133. */
  134. getString:function () {
  135. return this._string;
  136. },
  137. /**
  138. * draw the label
  139. */
  140. draw:function (ctx) {
  141. cc.AtlasNode.prototype.draw.call(this,ctx);
  142. if (cc.LABELATLAS_DEBUG_DRAW) {
  143. var s = this.getContentSize();
  144. var vertices = [cc.p(0, 0), cc.p(s.width, 0),
  145. cc.p(s.width, s.height), cc.p(0, s.height)];
  146. cc.drawingUtil.drawPoly(vertices, 4, true);
  147. }
  148. },
  149. /**
  150. * Atlas generation
  151. */
  152. updateAtlasValues: null,
  153. _updateAtlasValuesForCanvas: function () {
  154. var locString = this._string;
  155. var n = locString.length;
  156. var texture = this.getTexture();
  157. var locItemWidth = this._itemWidth , locItemHeight = this._itemHeight ; //needn't multiply cc.CONTENT_SCALE_FACTOR(), because sprite's draw will do this
  158. for (var i = 0; i < n; i++) {
  159. var a = locString.charCodeAt(i) - this._mapStartChar.charCodeAt(0);
  160. var row = parseInt(a % this._itemsPerRow, 10);
  161. var col = parseInt(a / this._itemsPerRow, 10);
  162. var rect = cc.rect(row * locItemWidth, col * locItemHeight, locItemWidth, locItemHeight);
  163. var c = locString.charCodeAt(i);
  164. var fontChar = this.getChildByTag(i);
  165. if (!fontChar) {
  166. fontChar = new cc.Sprite();
  167. if (c == 32) {
  168. fontChar.init();
  169. fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.SizeZero());
  170. } else
  171. fontChar.initWithTexture(texture, rect);
  172. this.addChild(fontChar, 0, i);
  173. } else {
  174. if (c == 32) {
  175. fontChar.init();
  176. fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.SizeZero());
  177. } else {
  178. // reusing fonts
  179. fontChar.initWithTexture(texture, rect);
  180. // restore to default in case they were modified
  181. fontChar.setVisible(true);
  182. fontChar.setOpacity(this._displayedOpacity);
  183. }
  184. }
  185. fontChar.setPosition(i * locItemWidth + locItemWidth / 2, locItemHeight / 2);
  186. }
  187. },
  188. _updateAtlasValuesForWebGL: function () {
  189. var locString = this._string;
  190. var n = locString.length;
  191. var locTextureAtlas = this._textureAtlas;
  192. var texture = locTextureAtlas.getTexture();
  193. var textureWide = texture.getPixelsWide();
  194. var textureHigh = texture.getPixelsHigh();
  195. var itemWidthInPixels = this._itemWidth;
  196. var itemHeightInPixels = this._itemHeight;
  197. if (!this._ignoreContentScaleFactor) {
  198. itemWidthInPixels = this._itemWidth * cc.CONTENT_SCALE_FACTOR();
  199. itemHeightInPixels = this._itemHeight * cc.CONTENT_SCALE_FACTOR();
  200. }
  201. if(n > locTextureAtlas.getCapacity())
  202. cc.log("cc.LabelAtlas._updateAtlasValues(): Invalid String length");
  203. var quads = locTextureAtlas.getQuads();
  204. var locDisplayedColor = this._displayedColor;
  205. var curColor = {r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: this._displayedOpacity};
  206. var locItemWidth = this._itemWidth;
  207. for (var i = 0; i < n; i++) {
  208. var a = locString.charCodeAt(i) - this._mapStartChar.charCodeAt(0);
  209. var row = a % this._itemsPerRow;
  210. var col = 0 | (a / this._itemsPerRow);
  211. var left, right, top, bottom;
  212. if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
  213. // Issue #938. Don't use texStepX & texStepY
  214. left = (2 * row * itemWidthInPixels + 1) / (2 * textureWide);
  215. right = left + (itemWidthInPixels * 2 - 2) / (2 * textureWide);
  216. top = (2 * col * itemHeightInPixels + 1) / (2 * textureHigh);
  217. bottom = top + (itemHeightInPixels * 2 - 2) / (2 * textureHigh);
  218. } else {
  219. left = row * itemWidthInPixels / textureWide;
  220. right = left + itemWidthInPixels / textureWide;
  221. top = col * itemHeightInPixels / textureHigh;
  222. bottom = top + itemHeightInPixels / textureHigh;
  223. }
  224. var quad = quads[i];
  225. var locQuadTL = quad.tl, locQuadTR = quad.tr, locQuadBL = quad.bl, locQuadBR = quad.br;
  226. locQuadTL.texCoords.u = left;
  227. locQuadTL.texCoords.v = top;
  228. locQuadTR.texCoords.u = right;
  229. locQuadTR.texCoords.v = top;
  230. locQuadBL.texCoords.u = left;
  231. locQuadBL.texCoords.v = bottom;
  232. locQuadBR.texCoords.u = right;
  233. locQuadBR.texCoords.v = bottom;
  234. locQuadBL.vertices.x = (i * locItemWidth);
  235. locQuadBL.vertices.y = 0;
  236. locQuadBL.vertices.z = 0.0;
  237. locQuadBR.vertices.x = (i * locItemWidth + locItemWidth);
  238. locQuadBR.vertices.y = 0;
  239. locQuadBR.vertices.z = 0.0;
  240. locQuadTL.vertices.x = i * locItemWidth;
  241. locQuadTL.vertices.y = this._itemHeight;
  242. locQuadTL.vertices.z = 0.0;
  243. locQuadTR.vertices.x = i * locItemWidth + locItemWidth;
  244. locQuadTR.vertices.y = this._itemHeight;
  245. locQuadTR.vertices.z = 0.0;
  246. locQuadTL.colors = curColor;
  247. locQuadTR.colors = curColor;
  248. locQuadBL.colors = curColor;
  249. locQuadBR.colors = curColor;
  250. }
  251. if (n > 0) {
  252. locTextureAtlas.setDirty(true);
  253. var totalQuads = locTextureAtlas.getTotalQuads();
  254. if (n > totalQuads)
  255. locTextureAtlas.increaseTotalQuadsWith(n - totalQuads);
  256. }
  257. },
  258. /**
  259. * set the display string
  260. * @param {String} label
  261. */
  262. setString: null,
  263. _setStringForCanvas: function (label) {
  264. label = String(label);
  265. var len = label.length;
  266. this._string = label;
  267. this.setContentSize(len * this._itemWidth, this._itemHeight);
  268. if (this._children) {
  269. var locChildren = this._children;
  270. len = locChildren.length;
  271. for (var i = 0; i < len; i++) {
  272. var node = locChildren[i];
  273. if (node)
  274. node.setVisible(false);
  275. }
  276. }
  277. this.updateAtlasValues();
  278. this._quadsToDraw = len;
  279. },
  280. _setStringForWebGL: function (label) {
  281. label = String(label);
  282. var len = label.length;
  283. if (len > this._textureAtlas.getTotalQuads())
  284. this._textureAtlas.resizeCapacity(len);
  285. this._string = label;
  286. this.setContentSize(len * this._itemWidth, this._itemHeight);
  287. this.updateAtlasValues();
  288. this._quadsToDraw = len;
  289. },
  290. setOpacity: null,
  291. _setOpacityForCanvas: function (opacity) {
  292. if (this._displayedOpacity !== opacity) {
  293. cc.AtlasNode.prototype.setOpacity.call(this, opacity);
  294. var locChildren = this._children;
  295. for (var i = 0, len = locChildren.length; i < len; i++) {
  296. if (locChildren[i])
  297. locChildren[i].setOpacity(opacity);
  298. }
  299. }
  300. },
  301. _setOpacityForWebGL: function (opacity) {
  302. if (this._opacity !== opacity)
  303. cc.AtlasNode.prototype.setOpacity.call(this, opacity);
  304. }
  305. });
  306. if(cc.Browser.supportWebGL){
  307. cc.LabelAtlas.prototype.updateAtlasValues = cc.LabelAtlas.prototype._updateAtlasValuesForWebGL;
  308. cc.LabelAtlas.prototype.setString = cc.LabelAtlas.prototype._setStringForWebGL;
  309. cc.LabelAtlas.prototype.setOpacity = cc.LabelAtlas.prototype._setOpacityForWebGL;
  310. } else {
  311. cc.LabelAtlas.prototype.updateAtlasValues = cc.LabelAtlas.prototype._updateAtlasValuesForCanvas;
  312. cc.LabelAtlas.prototype.setString = cc.LabelAtlas.prototype._setStringForCanvas;
  313. cc.LabelAtlas.prototype.setOpacity = cc.LabelAtlas.prototype._setOpacityForCanvas;
  314. }
  315. /**
  316. * <p>
  317. * It accepts two groups of parameters: <br/>
  318. * a) string, fntFile <br/>
  319. * b) label, textureFilename, width, height, startChar <br/>
  320. * </p>
  321. * @param {String} strText
  322. * @param {String} charMapFile charMapFile or fntFile
  323. * @param {Number} [itemWidth=0]
  324. * @param {Number} [itemHeight=0]
  325. * @param {Number} [startCharMap=""]
  326. * @return {cc.LabelAtlas|Null} returns the LabelAtlas object on success
  327. * @example
  328. * //Example
  329. * //creates the cc.LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas
  330. * var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapfile.png', 12, 20, ' ')
  331. *
  332. * //creates the cc.LabelAtlas with a string, a fnt file
  333. * var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapFile.plist‘);
  334. */
  335. cc.LabelAtlas.create = function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
  336. var ret = new cc.LabelAtlas();
  337. if (ret && cc.LabelAtlas.prototype.initWithString.apply(ret,arguments)) {
  338. return ret;
  339. }
  340. return null;
  341. };