CCLabelAtlas.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. * 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. * @property {String} string - Content string of label
  28. *
  29. * @param {String} strText
  30. * @param {String} charMapFile charMapFile or fntFile
  31. * @param {Number} [itemWidth=0]
  32. * @param {Number} [itemHeight=0]
  33. * @param {Number} [startCharMap=""]
  34. * @example
  35. * //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
  36. * var myLabel = new cc.LabelAtlas('Text to display', 'CharMapfile.png', 12, 20, ' ')
  37. *
  38. * //creates the cc.LabelAtlas with a string, a fnt file
  39. * var myLabel = new cc.LabelAtlas('Text to display', 'CharMapFile.plist‘);
  40. */
  41. cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{
  42. //property String is Getter and Setter
  43. // string to render
  44. _string: null,
  45. // the first char in the charmap
  46. _mapStartChar: null,
  47. _textureLoaded: false,
  48. _loadedEventListeners: null,
  49. _className: "LabelAtlas",
  50. /**
  51. * <p>
  52. * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. <br />
  53. * Create a label atlas. <br />
  54. * It accepts two groups of parameters: <br/>
  55. * a) string, fntFile <br/>
  56. * b) label, textureFilename, width, height, startChar <br/>
  57. * </p>
  58. * @param {String} strText
  59. * @param {String} charMapFile charMapFile or fntFile
  60. * @param {Number} [itemWidth=0]
  61. * @param {Number} [itemHeight=0]
  62. * @param {Number} [startCharMap=""]
  63. */
  64. ctor: function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
  65. cc.AtlasNode.prototype.ctor.call(this);
  66. charMapFile && cc.LabelAtlas.prototype.initWithString.call(this, strText, charMapFile, itemWidth, itemHeight, startCharMap);
  67. },
  68. /**
  69. * Return texture is loaded.
  70. * @returns {boolean}
  71. */
  72. textureLoaded: function () {
  73. return this._textureLoaded;
  74. },
  75. /**
  76. * Add texture loaded event listener.
  77. * @param {Function} callback
  78. * @param {cc.Node} target
  79. */
  80. addLoadedEventListener: function (callback, target) {
  81. if (!this._loadedEventListeners)
  82. this._loadedEventListeners = [];
  83. this._loadedEventListeners.push({eventCallback: callback, eventTarget: target});
  84. },
  85. _callLoadedEventCallbacks: function () {
  86. if (!this._loadedEventListeners)
  87. return;
  88. this._textureLoaded = true;
  89. var locListeners = this._loadedEventListeners;
  90. for (var i = 0, len = locListeners.length; i < len; i++) {
  91. var selCallback = locListeners[i];
  92. selCallback.eventCallback.call(selCallback.eventTarget, this);
  93. }
  94. locListeners.length = 0;
  95. },
  96. /**
  97. * <p>
  98. * initializes the cc.LabelAtlas with a string, a char map file(the atlas), <br/>
  99. * the width and height of each element and the starting char of the atlas <br/>
  100. * It accepts two groups of parameters: <br/>
  101. * a) string, fntFile <br/>
  102. * b) label, textureFilename, width, height, startChar <br/>
  103. * </p>
  104. * @param {String} strText
  105. * @param {String|cc.Texture2D} charMapFile charMapFile or fntFile or texture file
  106. * @param {Number} [itemWidth=0]
  107. * @param {Number} [itemHeight=0]
  108. * @param {Number} [startCharMap=""]
  109. * @return {Boolean} returns true on success
  110. */
  111. initWithString: function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
  112. var label = strText + "", textureFilename, width, height, startChar;
  113. if (itemWidth === undefined) {
  114. var dict = cc.loader.getRes(charMapFile);
  115. if (parseInt(dict["version"], 10) !== 1) {
  116. cc.log("cc.LabelAtlas.initWithString(): Unsupported version. Upgrade cocos2d version");
  117. return false;
  118. }
  119. textureFilename = cc.path.changeBasename(charMapFile, dict["textureFilename"]);
  120. var locScaleFactor = cc.contentScaleFactor();
  121. width = parseInt(dict["itemWidth"], 10) / locScaleFactor;
  122. height = parseInt(dict["itemHeight"], 10) / locScaleFactor;
  123. startChar = String.fromCharCode(parseInt(dict["firstChar"], 10));
  124. } else {
  125. textureFilename = charMapFile;
  126. width = itemWidth || 0;
  127. height = itemHeight || 0;
  128. startChar = startCharMap || " ";
  129. }
  130. var texture = null;
  131. if (textureFilename instanceof cc.Texture2D)
  132. texture = textureFilename;
  133. else
  134. texture = cc.textureCache.addImage(textureFilename);
  135. var locLoaded = texture.isLoaded();
  136. this._textureLoaded = locLoaded;
  137. if (!locLoaded) {
  138. texture.addLoadedEventListener(function (sender) {
  139. this.initWithTexture(texture, width, height, label.length);
  140. this.string = label;
  141. this._callLoadedEventCallbacks();
  142. }, this);
  143. }
  144. if (this.initWithTexture(texture, width, height, label.length)) {
  145. this._mapStartChar = startChar;
  146. this.string = label;
  147. return true;
  148. }
  149. return false;
  150. },
  151. /**
  152. * Set the color.
  153. * @param {cc.Color} color3
  154. */
  155. setColor: function (color3) {
  156. cc.AtlasNode.prototype.setColor.call(this, color3);
  157. this.updateAtlasValues();
  158. },
  159. /**
  160. * return the text of this label
  161. * @return {String}
  162. */
  163. getString: function () {
  164. return this._string;
  165. },
  166. /**
  167. * draw the label
  168. */
  169. draw: function (ctx) {
  170. cc.AtlasNode.prototype.draw.call(this, ctx);
  171. if (cc.LABELATLAS_DEBUG_DRAW) {
  172. var s = this.size;
  173. var vertices = [cc.p(0, 0), cc.p(s.width, 0),
  174. cc.p(s.width, s.height), cc.p(0, s.height)];
  175. cc._drawingUtil.drawPoly(vertices, 4, true);
  176. }
  177. },
  178. _addChildForCanvas: function(child, zOrder, tag){
  179. child._lateChild = true;
  180. cc.Node.prototype.addChild.call(this, child, zOrder, tag);
  181. },
  182. /**
  183. * Atlas generation
  184. * @function
  185. */
  186. updateAtlasValues: null,
  187. _updateAtlasValuesForCanvas: function () {
  188. var locString = this._string || "";
  189. var n = locString.length;
  190. var texture = this.texture;
  191. var locItemWidth = this._itemWidth , locItemHeight = this._itemHeight; //needn't multiply cc.contentScaleFactor(), because sprite's draw will do this
  192. for (var i = 0; i < n; i++) {
  193. var a = locString.charCodeAt(i) - this._mapStartChar.charCodeAt(0);
  194. var row = parseInt(a % this._itemsPerRow, 10);
  195. var col = parseInt(a / this._itemsPerRow, 10);
  196. var rect = cc.rect(row * locItemWidth, col * locItemHeight, locItemWidth, locItemHeight);
  197. var c = locString.charCodeAt(i);
  198. var fontChar = this.getChildByTag(i);
  199. if (!fontChar) {
  200. fontChar = new cc.Sprite();
  201. if (c == 32) {
  202. fontChar.init();
  203. fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.size(0, 0));
  204. } else
  205. fontChar.initWithTexture(texture, rect);
  206. cc.Node.prototype.addChild.call(this, fontChar, 0, i);
  207. } else {
  208. if (c == 32) {
  209. fontChar.init();
  210. fontChar.setTextureRect(cc.rect(0, 0, 10, 10), false, cc.size(0, 0));
  211. } else {
  212. // reusing fonts
  213. fontChar.initWithTexture(texture, rect);
  214. // restore to default in case they were modified
  215. fontChar.visible = true;
  216. fontChar.opacity = this._displayedOpacity;
  217. }
  218. }
  219. fontChar.setPosition(i * locItemWidth + locItemWidth / 2, locItemHeight / 2);
  220. }
  221. },
  222. _updateAtlasValuesForWebGL: function () {
  223. var locString = this._string;
  224. var n = locString.length;
  225. var locTextureAtlas = this.textureAtlas;
  226. var texture = locTextureAtlas.texture;
  227. var textureWide = texture.pixelsWidth;
  228. var textureHigh = texture.pixelsHeight;
  229. var itemWidthInPixels = this._itemWidth;
  230. var itemHeightInPixels = this._itemHeight;
  231. if (!this._ignoreContentScaleFactor) {
  232. itemWidthInPixels = this._itemWidth * cc.contentScaleFactor();
  233. itemHeightInPixels = this._itemHeight * cc.contentScaleFactor();
  234. }
  235. if (n > locTextureAtlas.getCapacity())
  236. cc.log("cc.LabelAtlas._updateAtlasValues(): Invalid String length");
  237. var quads = locTextureAtlas.quads;
  238. var locDisplayedColor = this._displayedColor;
  239. var curColor = {r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: this._displayedOpacity};
  240. var locItemWidth = this._itemWidth;
  241. for (var i = 0; i < n; i++) {
  242. var a = locString.charCodeAt(i) - this._mapStartChar.charCodeAt(0);
  243. var row = a % this._itemsPerRow;
  244. var col = 0 | (a / this._itemsPerRow);
  245. var left, right, top, bottom;
  246. if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
  247. // Issue #938. Don't use texStepX & texStepY
  248. left = (2 * row * itemWidthInPixels + 1) / (2 * textureWide);
  249. right = left + (itemWidthInPixels * 2 - 2) / (2 * textureWide);
  250. top = (2 * col * itemHeightInPixels + 1) / (2 * textureHigh);
  251. bottom = top + (itemHeightInPixels * 2 - 2) / (2 * textureHigh);
  252. } else {
  253. left = row * itemWidthInPixels / textureWide;
  254. right = left + itemWidthInPixels / textureWide;
  255. top = col * itemHeightInPixels / textureHigh;
  256. bottom = top + itemHeightInPixels / textureHigh;
  257. }
  258. var quad = quads[i];
  259. var locQuadTL = quad.tl, locQuadTR = quad.tr, locQuadBL = quad.bl, locQuadBR = quad.br;
  260. locQuadTL.texCoords.u = left;
  261. locQuadTL.texCoords.v = top;
  262. locQuadTR.texCoords.u = right;
  263. locQuadTR.texCoords.v = top;
  264. locQuadBL.texCoords.u = left;
  265. locQuadBL.texCoords.v = bottom;
  266. locQuadBR.texCoords.u = right;
  267. locQuadBR.texCoords.v = bottom;
  268. locQuadBL.vertices.x = (i * locItemWidth);
  269. locQuadBL.vertices.y = 0;
  270. locQuadBL.vertices.z = 0.0;
  271. locQuadBR.vertices.x = (i * locItemWidth + locItemWidth);
  272. locQuadBR.vertices.y = 0;
  273. locQuadBR.vertices.z = 0.0;
  274. locQuadTL.vertices.x = i * locItemWidth;
  275. locQuadTL.vertices.y = this._itemHeight;
  276. locQuadTL.vertices.z = 0.0;
  277. locQuadTR.vertices.x = i * locItemWidth + locItemWidth;
  278. locQuadTR.vertices.y = this._itemHeight;
  279. locQuadTR.vertices.z = 0.0;
  280. locQuadTL.colors = curColor;
  281. locQuadTR.colors = curColor;
  282. locQuadBL.colors = curColor;
  283. locQuadBR.colors = curColor;
  284. }
  285. if (n > 0) {
  286. locTextureAtlas.dirty = true;
  287. var totalQuads = locTextureAtlas.totalQuads;
  288. if (n > totalQuads)
  289. locTextureAtlas.increaseTotalQuadsWith(n - totalQuads);
  290. }
  291. },
  292. /**
  293. * set the display string
  294. * @function
  295. * @param {String} label
  296. */
  297. setString: null,
  298. _setStringForCanvas: function (label) {
  299. label = String(label);
  300. var len = label.length;
  301. this._string = label;
  302. this.width = len * this._itemWidth;
  303. this.height = this._itemHeight;
  304. if (this._children) {
  305. var locChildren = this._children;
  306. len = locChildren.length;
  307. for (var i = 0; i < len; i++) {
  308. var node = locChildren[i];
  309. if (node && !node._lateChild)
  310. node.visible = false;
  311. }
  312. }
  313. this.updateAtlasValues();
  314. this.quadsToDraw = len;
  315. },
  316. _setStringForWebGL: function (label) {
  317. label = String(label);
  318. var len = label.length;
  319. if (len > this.textureAtlas.totalQuads)
  320. this.textureAtlas.resizeCapacity(len);
  321. this._string = label;
  322. this.width = len * this._itemWidth;
  323. this.height = this._itemHeight;
  324. this.updateAtlasValues();
  325. this.quadsToDraw = len;
  326. },
  327. /**
  328. * set the opacity
  329. * @function
  330. * @param {Number} opacity
  331. */
  332. setOpacity: null,
  333. _setOpacityForCanvas: function (opacity) {
  334. if (this._displayedOpacity !== opacity) {
  335. cc.AtlasNode.prototype.setOpacity.call(this, opacity);
  336. var locChildren = this._children;
  337. for (var i = 0, len = locChildren.length; i < len; i++) {
  338. if (locChildren[i])
  339. locChildren[i].opacity = opacity;
  340. }
  341. }
  342. },
  343. _setOpacityForWebGL: function (opacity) {
  344. if (this._opacity !== opacity)
  345. cc.AtlasNode.prototype.setOpacity.call(this, opacity);
  346. }
  347. });
  348. var _p = cc.LabelAtlas.prototype;
  349. if (cc._renderType === cc._RENDER_TYPE_WEBGL) {
  350. _p.updateAtlasValues = _p._updateAtlasValuesForWebGL;
  351. _p.setString = _p._setStringForWebGL;
  352. _p.setOpacity = _p._setOpacityForWebGL;
  353. } else {
  354. _p.updateAtlasValues = _p._updateAtlasValuesForCanvas;
  355. _p.setString = _p._setStringForCanvas;
  356. _p.setOpacity = _p._setOpacityForCanvas;
  357. _p.addChild = _p._addChildForCanvas;
  358. }
  359. // Override properties
  360. cc.defineGetterSetter(_p, "opacity", _p.getOpacity, _p.setOpacity);
  361. // Extended properties
  362. /** @expose */
  363. _p.string;
  364. cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
  365. /**
  366. * <p>
  367. * Please use new cc.LabelAtlas instead. <br />
  368. * Create a label atlas. <br />
  369. * It accepts two groups of parameters: <br/>
  370. * a) string, fntFile <br/>
  371. * b) label, textureFilename, width, height, startChar <br/>
  372. * </p>
  373. * @deprecated since v3.0 please use new cc.LabelAtlas
  374. * @param {String} strText
  375. * @param {String} charMapFile charMapFile or fntFile
  376. * @param {Number} [itemWidth=0]
  377. * @param {Number} [itemHeight=0]
  378. * @param {Number} [startCharMap=""]
  379. * @return {cc.LabelAtlas} returns the LabelAtlas object on success
  380. * @example
  381. * //Example
  382. * //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
  383. * var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapfile.png', 12, 20, ' ')
  384. *
  385. * //creates the cc.LabelAtlas with a string, a fnt file
  386. * var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapFile.plist‘);
  387. */
  388. cc.LabelAtlas.create = function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
  389. return new cc.LabelAtlas(strText, charMapFile, itemWidth, itemHeight, startCharMap);
  390. };