CCSpriteBatchNode.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. * @constant
  24. * @type Number
  25. */
  26. cc.DEFAULT_SPRITE_BATCH_CAPACITY = 29;
  27. /**
  28. * <p>
  29. * In Canvas render mode ,cc.SpriteBatchNodeCanvas is like a normal node: if it contains children. <br/>
  30. * If its _useCache is set to true, it can cache the result that all children of SpriteBatchNode to a canvas <br/>
  31. * (often known as "batch draw").<br/>
  32. * <br/>
  33. * A cc.SpriteBatchNode can reference one and only one texture (one image file, one texture atlas).<br/>
  34. * Only the cc.Sprites that are contained in that texture can be added to the cc.SpriteBatchNode.<br/>
  35. * All cc.Sprites added to a cc.SpriteBatchNode are drawn in one WebGL draw call. <br/>
  36. * If the cc.Sprites are not added to a cc.SpriteBatchNode then an WebGL draw call will be needed for each one, which is less efficient. <br/>
  37. * <br/>
  38. * Limitations:<br/>
  39. * - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is cc.Sprite or any subclass of cc.Sprite. <br/>
  40. * eg: particles, labels and layer can't be added to a cc.SpriteBatchNode. <br/>
  41. * - Either all its children are Aliased or Antialiased. It can't be a mix. <br/>
  42. * This is because "alias" is a property of the texture, and all the sprites share the same texture. </br>
  43. * </p>
  44. * @class
  45. * @extends cc.Node
  46. * @example
  47. * //create a SpriteBatchNode
  48. * var parent2 = cc.SpriteBatchNode.create("res/animations/grossini.png", 50);
  49. */
  50. cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
  51. _textureAtlas:null,
  52. _blendFunc:null,
  53. // all descendants: chlidren, gran children, etc...
  54. _descendants:null,
  55. /**
  56. * <p>
  57. * This is the opposite of "addQuadFromSprite.<br/>
  58. * It add the sprite to the children and descendants array, but it doesn't update add it to the texture atlas<br/>
  59. * </p>
  60. * @param {cc.Sprite} child
  61. * @param {Number} z zOrder
  62. * @param {Number} aTag
  63. * @return {cc.SpriteBatchNode}
  64. */
  65. addSpriteWithoutQuad:function (child, z, aTag) {
  66. if(!child)
  67. throw "cc.SpriteBatchNode.addQuadFromSprite(): child should be non-null";
  68. if(!(child instanceof cc.Sprite)){
  69. cc.log("cc.SpriteBatchNode.addQuadFromSprite(): SpriteBatchNode only supports cc.Sprites as children");
  70. return null;
  71. }
  72. // quad index is Z
  73. child.setAtlasIndex(z);
  74. // XXX: optimize with a binary search
  75. var i = 0, locDescendants = this._descendants;
  76. if (locDescendants && locDescendants.length > 0) {
  77. for (var index = 0; index < locDescendants.length; index++) {
  78. var obj = locDescendants[index];
  79. if (obj && (obj.getAtlasIndex() >= z))
  80. break;
  81. ++i;
  82. }
  83. }
  84. this._descendants = cc.ArrayAppendObjectToIndex(locDescendants, child, i);
  85. // IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array
  86. cc.Node.prototype.addChild.call(this, child, z, aTag);
  87. //#issue 1262 don't use lazy sorting, tiles are added as quads not as sprites, so sprites need to be added in order
  88. this.reorderBatch(false);
  89. return this;
  90. },
  91. // property
  92. /**
  93. * Return TextureAtlas of cc.SpriteBatchNode
  94. * @return {cc.TextureAtlas}
  95. */
  96. getTextureAtlas:function () {
  97. return this._textureAtlas;
  98. },
  99. /**
  100. * TextureAtlas of cc.SpriteBatchNode setter
  101. * @param {cc.TextureAtlas} textureAtlas
  102. */
  103. setTextureAtlas:function (textureAtlas) {
  104. if (textureAtlas != this._textureAtlas) {
  105. this._textureAtlas = textureAtlas;
  106. }
  107. },
  108. /**
  109. * Return Descendants of cc.SpriteBatchNode
  110. * @return {Array}
  111. */
  112. getDescendants:function () {
  113. return this._descendants;
  114. },
  115. /**
  116. * <p>
  117. * initializes a cc.SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.<br/>
  118. * The capacity will be increased in 33% in runtime if it run out of space.<br/>
  119. * The file will be loaded using the TextureMgr.
  120. * </p>
  121. * @param {String} fileImage
  122. * @param {Number} capacity
  123. * @return {Boolean}
  124. */
  125. initWithFile:function (fileImage, capacity) {
  126. var texture2D = cc.TextureCache.getInstance().textureForKey(fileImage);
  127. if (!texture2D)
  128. texture2D = cc.TextureCache.getInstance().addImage(fileImage);
  129. return this.initWithTexture(texture2D, capacity);
  130. },
  131. _setNodeDirtyForCache:function () {
  132. this._cacheDirty = true;
  133. },
  134. /**
  135. * <p>
  136. * initializes a cc.SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.<br/>
  137. * The capacity will be increased in 33% in runtime if it run out of space.<br/>
  138. * The file will be loaded using the TextureMgr.
  139. * </p>
  140. * @param {String} fileImage
  141. * @param {Number} capacity
  142. * @return {Boolean}
  143. */
  144. init:function (fileImage, capacity) {
  145. var texture2D = cc.TextureCache.getInstance().textureForKey(fileImage);
  146. if (!texture2D)
  147. texture2D = cc.TextureCache.getInstance().addImage(fileImage);
  148. return this.initWithTexture(texture2D, capacity);
  149. },
  150. /**
  151. * increase Atlas Capacity
  152. */
  153. increaseAtlasCapacity:function () {
  154. // if we're going beyond the current TextureAtlas's capacity,
  155. // all the previously initialized sprites will need to redo their texture coords
  156. // this is likely computationally expensive
  157. var locCapacity = this._textureAtlas.getCapacity();
  158. var quantity = Math.floor((locCapacity + 1) * 4 / 3);
  159. cc.log("cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from " + locCapacity + " to " + quantity + ".");
  160. if (!this._textureAtlas.resizeCapacity(quantity)) {
  161. // serious problems
  162. cc.log("cocos2d: WARNING: Not enough memory to resize the atlas");
  163. }
  164. },
  165. /**
  166. * removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.
  167. * @warning Removing a child from a cc.SpriteBatchNode is very slow
  168. * @param {Number} index
  169. * @param {Boolean} doCleanup
  170. */
  171. removeChildAtIndex:function (index, doCleanup) {
  172. this.removeChild(this._children[index], doCleanup);
  173. },
  174. /**
  175. * rebuild index in order for child
  176. * @param {cc.Sprite} pobParent
  177. * @param {Number} index
  178. * @return {Number}
  179. */
  180. rebuildIndexInOrder:function (pobParent, index) {
  181. var children = pobParent.getChildren();
  182. if (children && children.length > 0) {
  183. for (var i = 0; i < children.length; i++) {
  184. var obj = children[i];
  185. if (obj && (obj.getZOrder() < 0)) {
  186. index = this.rebuildIndexInOrder(obj, index);
  187. }
  188. }
  189. }
  190. // ignore self (batch node)
  191. if (!pobParent == this) {
  192. pobParent.setAtlasIndex(index);
  193. index++;
  194. }
  195. if (children && children.length > 0) {
  196. for (i = 0; i < children.length; i++) {
  197. obj = children[i];
  198. if (obj && (obj.getZOrder() >= 0)) {
  199. index = this.rebuildIndexInOrder(obj, index);
  200. }
  201. }
  202. }
  203. return index;
  204. },
  205. /**
  206. * get highest atlas index in child
  207. * @param {cc.Sprite} sprite
  208. * @return {Number}
  209. */
  210. highestAtlasIndexInChild:function (sprite) {
  211. var children = sprite.getChildren();
  212. if (!children || children.length == 0)
  213. return sprite.getAtlasIndex();
  214. else
  215. return this.highestAtlasIndexInChild(children[children.length - 1]);
  216. },
  217. /**
  218. * get lowest atlas index in child
  219. * @param {cc.Sprite} sprite
  220. * @return {Number}
  221. */
  222. lowestAtlasIndexInChild:function (sprite) {
  223. var children = sprite.getChildren();
  224. if (!children || children.length == 0)
  225. return sprite.getAtlasIndex();
  226. else
  227. return this.lowestAtlasIndexInChild(children[children.length - 1]);
  228. },
  229. /**
  230. * get atlas index for child
  231. * @param {cc.Sprite} sprite
  232. * @param {Number} nZ
  233. * @return {Number}
  234. */
  235. atlasIndexForChild:function (sprite, nZ) {
  236. var brothers = sprite.getParent().getChildren();
  237. var childIndex = cc.ArrayGetIndexOfObject(brothers, sprite);
  238. // ignore parent Z if parent is spriteSheet
  239. var ignoreParent = sprite.getParent() == this;
  240. var previous = null;
  241. if (childIndex > 0 && childIndex < cc.UINT_MAX)
  242. previous = brothers[childIndex - 1];
  243. // first child of the sprite sheet
  244. if (ignoreParent) {
  245. if (childIndex == 0)
  246. return 0;
  247. return this.highestAtlasIndexInChild(previous) + 1;
  248. }
  249. // parent is a cc.Sprite, so, it must be taken into account
  250. // first child of an cc.Sprite ?
  251. var selParent;
  252. if (childIndex == 0) {
  253. selParent = sprite.getParent();
  254. // less than parent and brothers
  255. if (nZ < 0)
  256. return selParent.getAtlasIndex();
  257. else
  258. return selParent.getAtlasIndex() + 1;
  259. } else {
  260. // previous & sprite belong to the same branch
  261. if ((previous.getZOrder() < 0 && nZ < 0) || (previous.getZOrder() >= 0 && nZ >= 0))
  262. return this.highestAtlasIndexInChild(previous) + 1;
  263. // else (previous < 0 and sprite >= 0 )
  264. selParent = sprite.getParent();
  265. return selParent.getAtlasIndex() + 1;
  266. }
  267. },
  268. /**
  269. * Sprites use this to start sortChildren, don't call this manually
  270. * @param {Boolean} reorder
  271. */
  272. reorderBatch:function (reorder) {
  273. this._reorderChildDirty = reorder;
  274. },
  275. /**
  276. * set the source blending function for the texture
  277. * @param {Number | cc.BlendFunc} src
  278. * @param {Number} dst
  279. */
  280. setBlendFunc:function (src, dst) {
  281. if (dst === undefined)
  282. this._blendFunc = src;
  283. else
  284. this._blendFunc = {src:src, dst:dst};
  285. },
  286. /**
  287. * returns the blending function used for the texture
  288. * @return {cc.BlendFunc}
  289. */
  290. getBlendFunc:function () {
  291. return this._blendFunc;
  292. },
  293. /**
  294. * (override reorderChild of cc.Node)
  295. * @override
  296. * @param {cc.Sprite} child
  297. * @param {Number} zOrder
  298. */
  299. reorderChild:function (child, zOrder) {
  300. if(!child)
  301. throw "cc.SpriteBatchNode.addChild():child should be non-null";
  302. if(this._children.indexOf(child) === -1) {
  303. cc.log("cc.SpriteBatchNode.addChild(): Child doesn't belong to Sprite");
  304. return;
  305. }
  306. if (zOrder === child.getZOrder())
  307. return;
  308. //set the z-order and sort later
  309. cc.Node.prototype.reorderChild.call(this, child, zOrder);
  310. this.setNodeDirty();
  311. },
  312. /**
  313. * remove child from cc.SpriteBatchNode (override removeChild of cc.Node)
  314. * @param {cc.Sprite} child
  315. * @param cleanup
  316. */
  317. removeChild:function (child, cleanup) {
  318. // explicit null handling
  319. if (child == null)
  320. return;
  321. if(this._children.indexOf(child) === -1){
  322. cc.log("cc.SpriteBatchNode.addChild(): sprite batch node should contain the child");
  323. return;
  324. }
  325. // cleanup before removing
  326. this.removeSpriteFromAtlas(child);
  327. cc.Node.prototype.removeChild.call(this, child, cleanup);
  328. },
  329. _mvpMatrix:null,
  330. _textureForCanvas:null,
  331. _useCache:false,
  332. _originalTexture:null,
  333. /**
  334. * Constructor
  335. * @param {String} fileImage
  336. */
  337. ctor: null,
  338. _ctorForCanvas: function (fileImage) {
  339. cc.Node.prototype.ctor.call(this);
  340. if (fileImage)
  341. this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY);
  342. },
  343. _ctorForWebGL: function (fileImage) {
  344. cc.Node.prototype.ctor.call(this);
  345. this._mvpMatrix = new cc.kmMat4();
  346. if (fileImage)
  347. this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY);
  348. },
  349. /**
  350. * <p>
  351. * Updates a quad at a certain index into the texture atlas. The CCSprite won't be added into the children array. <br/>
  352. * This method should be called only when you are dealing with very big AtlasSrite and when most of the cc.Sprite won't be updated.<br/>
  353. * For example: a tile map (cc.TMXMap) or a label with lots of characters (BitmapFontAtlas)<br/>
  354. * </p>
  355. * @param {cc.Sprite} sprite
  356. * @param {Number} index
  357. */
  358. updateQuadFromSprite:null,
  359. _updateQuadFromSpriteForCanvas:function (sprite, index) {
  360. if(!sprite)
  361. throw "cc.SpriteBatchNode.updateQuadFromSprite(): sprite should be non-null";
  362. if(!(sprite instanceof cc.Sprite)){
  363. cc.log("cc.SpriteBatchNode.updateQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children");
  364. return;
  365. }
  366. //
  367. // update the quad directly. Don't add the sprite to the scene graph
  368. //
  369. sprite.setBatchNode(this);
  370. sprite.setAtlasIndex(index);
  371. sprite.setDirty(true);
  372. // UpdateTransform updates the textureAtlas quad
  373. sprite.updateTransform();
  374. },
  375. _updateQuadFromSpriteForWebGL:function (sprite, index) {
  376. if(!sprite)
  377. throw "cc.SpriteBatchNode.updateQuadFromSprite(): sprite should be non-null";
  378. if(!(sprite instanceof cc.Sprite)){
  379. cc.log("cc.SpriteBatchNode.updateQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children");
  380. return;
  381. }
  382. // make needed room
  383. var locCapacity = this._textureAtlas.getCapacity();
  384. while (index >= locCapacity || locCapacity == this._textureAtlas.getTotalQuads()) {
  385. this.increaseAtlasCapacity();
  386. }
  387. //
  388. // update the quad directly. Don't add the sprite to the scene graph
  389. //
  390. sprite.setBatchNode(this);
  391. sprite.setAtlasIndex(index);
  392. sprite.setDirty(true);
  393. // UpdateTransform updates the textureAtlas quad
  394. sprite.updateTransform();
  395. },
  396. _swap:function (oldIndex, newIndex) {
  397. var locDescendants = this._descendants;
  398. var locTextureAtlas = this._textureAtlas;
  399. var quads = locTextureAtlas.getQuads();
  400. var tempItem = locDescendants[oldIndex];
  401. var tempIteQuad = cc.V3F_C4B_T2F_QuadCopy(quads[oldIndex]);
  402. //update the index of other swapped item
  403. locDescendants[newIndex].setAtlasIndex(oldIndex);
  404. locDescendants[oldIndex] = locDescendants[newIndex];
  405. locTextureAtlas.updateQuad(quads[newIndex], oldIndex);
  406. locDescendants[newIndex] = tempItem;
  407. locTextureAtlas.updateQuad(tempIteQuad, newIndex);
  408. },
  409. /**
  410. * <p>
  411. * Inserts a quad at a certain index into the texture atlas. The cc.Sprite won't be added into the children array. <br/>
  412. * This method should be called only when you are dealing with very big AtlasSprite and when most of the cc.Sprite won't be updated. <br/>
  413. * For example: a tile map (cc.TMXMap) or a label with lots of characters (cc.LabelBMFont)
  414. * </p>
  415. * @param {cc.Sprite} sprite
  416. * @param {Number} index
  417. */
  418. insertQuadFromSprite:null,
  419. _insertQuadFromSpriteForCanvas:function (sprite, index) {
  420. if(!sprite)
  421. throw "cc.SpriteBatchNode.insertQuadFromSprite(): sprite should be non-null";
  422. if(!(sprite instanceof cc.Sprite)){
  423. cc.log("cc.SpriteBatchNode.insertQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children");
  424. return;
  425. }
  426. //
  427. // update the quad directly. Don't add the sprite to the scene graph
  428. //
  429. sprite.setBatchNode(this);
  430. sprite.setAtlasIndex(index);
  431. // XXX: updateTransform will update the textureAtlas too, using updateQuad.
  432. // XXX: so, it should be AFTER the insertQuad
  433. sprite.setDirty(true);
  434. sprite.updateTransform();
  435. this._children = cc.ArrayAppendObjectToIndex(this._children, sprite, index);
  436. },
  437. _insertQuadFromSpriteForWebGL:function (sprite, index) {
  438. if(!sprite)
  439. throw "cc.SpriteBatchNode.insertQuadFromSprite(): sprite should be non-null";
  440. if(!(sprite instanceof cc.Sprite)){
  441. cc.log("cc.SpriteBatchNode.insertQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children");
  442. return;
  443. }
  444. // make needed room
  445. var locTextureAtlas = this._textureAtlas;
  446. while (index >= locTextureAtlas.getCapacity() || locTextureAtlas.getCapacity() === locTextureAtlas.getTotalQuads())
  447. this.increaseAtlasCapacity();
  448. //
  449. // update the quad directly. Don't add the sprite to the scene graph
  450. //
  451. sprite.setBatchNode(this);
  452. sprite.setAtlasIndex(index);
  453. locTextureAtlas.insertQuad(sprite.getQuad(), index);
  454. // XXX: updateTransform will update the textureAtlas too, using updateQuad.
  455. // XXX: so, it should be AFTER the insertQuad
  456. sprite.setDirty(true);
  457. sprite.updateTransform();
  458. },
  459. _updateAtlasIndex:function (sprite, curIndex) {
  460. var count = 0;
  461. var pArray = sprite.getChildren();
  462. if (pArray)
  463. count = pArray.length;
  464. var oldIndex = 0;
  465. if (count === 0) {
  466. oldIndex = sprite.getAtlasIndex();
  467. sprite.setAtlasIndex(curIndex);
  468. sprite.setOrderOfArrival(0);
  469. if (oldIndex != curIndex)
  470. this._swap(oldIndex, curIndex);
  471. curIndex++;
  472. } else {
  473. var needNewIndex = true;
  474. if (pArray[0].getZOrder() >= 0) {
  475. //all children are in front of the parent
  476. oldIndex = sprite.getAtlasIndex();
  477. sprite.setAtlasIndex(curIndex);
  478. sprite.setOrderOfArrival(0);
  479. if (oldIndex != curIndex)
  480. this._swap(oldIndex, curIndex);
  481. curIndex++;
  482. needNewIndex = false;
  483. }
  484. for (var i = 0; i < pArray.length; i++) {
  485. var child = pArray[i];
  486. if (needNewIndex && child.getZOrder() >= 0) {
  487. oldIndex = sprite.getAtlasIndex();
  488. sprite.setAtlasIndex(curIndex);
  489. sprite.setOrderOfArrival(0);
  490. if (oldIndex != curIndex) {
  491. this._swap(oldIndex, curIndex);
  492. }
  493. curIndex++;
  494. needNewIndex = false;
  495. }
  496. curIndex = this._updateAtlasIndex(child, curIndex);
  497. }
  498. if (needNewIndex) {
  499. //all children have a zOrder < 0)
  500. oldIndex = sprite.getAtlasIndex();
  501. sprite.setAtlasIndex(curIndex);
  502. sprite.setOrderOfArrival(0);
  503. if (oldIndex != curIndex) {
  504. this._swap(oldIndex, curIndex);
  505. }
  506. curIndex++;
  507. }
  508. }
  509. return curIndex;
  510. },
  511. _updateBlendFunc:function () {
  512. if (!this._textureAtlas.getTexture().hasPremultipliedAlpha()) {
  513. this._blendFunc.src = gl.SRC_ALPHA;
  514. this._blendFunc.dst = gl.ONE_MINUS_SRC_ALPHA;
  515. }
  516. },
  517. /**
  518. * <p>
  519. * initializes a CCSpriteBatchNode with a texture2d and capacity of children.<br/>
  520. * The capacity will be increased in 33% in runtime if it run out of space.
  521. * </p>
  522. * @param {cc.Texture2D} tex
  523. * @param {Number} [capacity]
  524. * @return {Boolean}
  525. */
  526. initWithTexture:null,
  527. _initWithTextureForCanvas:function (tex, capacity) {
  528. this._children = [];
  529. this._descendants = [];
  530. this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
  531. this._originalTexture = tex;
  532. this._textureForCanvas = tex;
  533. return true;
  534. },
  535. _initWithTextureForWebGL:function (tex, capacity) {
  536. this._children = [];
  537. this._descendants = [];
  538. this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
  539. capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY;
  540. this._textureAtlas = new cc.TextureAtlas();
  541. this._textureAtlas.initWithTexture(tex, capacity);
  542. this._updateBlendFunc();
  543. this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLOR));
  544. return true;
  545. },
  546. /**
  547. * add child helper
  548. * @param {cc.Sprite} sprite
  549. * @param {Number} index
  550. */
  551. insertChild:function (sprite, index) {
  552. sprite.setBatchNode(this);
  553. sprite.setAtlasIndex(index);
  554. sprite.setDirty(true);
  555. var locTextureAtlas = this._textureAtlas;
  556. if (locTextureAtlas.getTotalQuads() >= locTextureAtlas.getCapacity())
  557. this.increaseAtlasCapacity();
  558. locTextureAtlas.insertQuad(sprite.getQuad(), index);
  559. this._descendants = cc.ArrayAppendObjectToIndex(this._descendants, sprite, index);
  560. // update indices
  561. var i = index + 1, locDescendant = this._descendants;
  562. if (locDescendant && locDescendant.length > 0) {
  563. for (; i < locDescendant.length; i++)
  564. locDescendant[i].setAtlasIndex(locDescendant[i].getAtlasIndex() + 1);
  565. }
  566. // add children recursively
  567. var locChildren = sprite.getChildren();
  568. if (locChildren && locChildren.length > 0) {
  569. for (i = 0; i < locChildren.length; i++) {
  570. if (locChildren[i]) {
  571. var getIndex = this.atlasIndexForChild(locChildren[i], locChildren[i].getZOrder());
  572. this.insertChild(locChildren[i], getIndex);
  573. }
  574. }
  575. }
  576. },
  577. /**
  578. * addChild helper, faster than insertChild
  579. * @param {cc.Sprite} sprite
  580. */
  581. appendChild:null,
  582. _appendChildForCanvas:function (sprite) {
  583. this._reorderChildDirty = true;
  584. sprite.setBatchNode(this);
  585. sprite.setDirty(true);
  586. this._descendants.push(sprite);
  587. var index = this._descendants.length - 1;
  588. sprite.setAtlasIndex(index);
  589. // add children recursively
  590. var children = sprite.getChildren();
  591. for (var i = 0; i < children.length; i++)
  592. this.appendChild(children[i]);
  593. },
  594. _appendChildForWebGL:function (sprite) {
  595. this._reorderChildDirty = true;
  596. sprite.setBatchNode(this);
  597. sprite.setDirty(true);
  598. this._descendants.push(sprite);
  599. var index = this._descendants.length - 1;
  600. sprite.setAtlasIndex(index);
  601. var locTextureAtlas = this._textureAtlas;
  602. if (locTextureAtlas.getTotalQuads() == locTextureAtlas.getCapacity())
  603. this.increaseAtlasCapacity();
  604. locTextureAtlas.insertQuad(sprite.getQuad(), index);
  605. // add children recursively
  606. var children = sprite.getChildren();
  607. for (var i = 0; i < children.length; i++)
  608. this.appendChild(children[i]);
  609. },
  610. /**
  611. * remove sprite from TextureAtlas
  612. * @param {cc.Sprite} sprite
  613. */
  614. removeSpriteFromAtlas:null,
  615. _removeSpriteFromAtlasForCanvas:function (sprite) {
  616. // Cleanup sprite. It might be reused (issue #569)
  617. sprite.setBatchNode(null);
  618. var locDescendants = this._descendants;
  619. var index = cc.ArrayGetIndexOfObject(locDescendants, sprite);
  620. if (index != -1) {
  621. cc.ArrayRemoveObjectAtIndex(locDescendants, index);
  622. // update all sprites beyond this one
  623. var len = locDescendants.length;
  624. for (; index < len; ++index) {
  625. var s = locDescendants[index];
  626. s.setAtlasIndex(s.getAtlasIndex() - 1);
  627. }
  628. }
  629. // remove children recursively
  630. var children = sprite.getChildren();
  631. if (children && children.length > 0) {
  632. for (var i = 0; i < children.length; i++)
  633. if (children[i])
  634. this.removeSpriteFromAtlas(children[i]);
  635. }
  636. },
  637. _removeSpriteFromAtlasForWebGL:function (sprite) {
  638. this._textureAtlas.removeQuadAtIndex(sprite.getAtlasIndex()); // remove from TextureAtlas
  639. // Cleanup sprite. It might be reused (issue #569)
  640. sprite.setBatchNode(null);
  641. var locDescendants = this._descendants;
  642. var index = cc.ArrayGetIndexOfObject(locDescendants, sprite);
  643. if (index != -1) {
  644. cc.ArrayRemoveObjectAtIndex(locDescendants, index);
  645. // update all sprites beyond this one
  646. var len = locDescendants.length;
  647. for (; index < len; ++index) {
  648. var s = locDescendants[index];
  649. s.setAtlasIndex(s.getAtlasIndex() - 1);
  650. }
  651. }
  652. // remove children recursively
  653. var children = sprite.getChildren();
  654. if (children && children.length > 0) {
  655. for (var i = 0; i < children.length; i++)
  656. if (children[i])
  657. this.removeSpriteFromAtlas(children[i]);
  658. }
  659. },
  660. // CCTextureProtocol
  661. /**
  662. * Return texture of cc.SpriteBatchNode
  663. * @return {cc.Texture2D|HTMLImageElement|HTMLCanvasElement}
  664. */
  665. getTexture:null,
  666. _getTextureForCanvas:function () {
  667. return this._textureForCanvas;
  668. },
  669. _getTextureForWebGL:function () {
  670. return this._textureAtlas.getTexture();
  671. },
  672. /**
  673. * texture of cc.SpriteBatchNode setter
  674. * @param {cc.Texture2D} texture
  675. */
  676. setTexture:null,
  677. _setTextureForCanvas:function (texture) {
  678. this._textureForCanvas = texture;
  679. var locChildren = this._children;
  680. for (var i = 0; i < locChildren.length; i++)
  681. locChildren[i].setTexture(texture);
  682. },
  683. _setTextureForWebGL:function (texture) {
  684. this._textureAtlas.setTexture(texture);
  685. this._updateBlendFunc();
  686. },
  687. /**
  688. * don't call visit on it's children ( override visit of cc.Node )
  689. * @override
  690. * @param {CanvasRenderingContext2D} ctx
  691. */
  692. visit:null,
  693. _visitForCanvas:function (ctx) {
  694. var context = ctx || cc.renderContext;
  695. // quick return if not visible
  696. if (!this._visible)
  697. return;
  698. context.save();
  699. this.transform(ctx);
  700. var i, locChildren = this._children;
  701. if (locChildren) {
  702. this.sortAllChildren();
  703. for (i = 0; i < locChildren.length; i++) {
  704. if (locChildren[i])
  705. locChildren[i].visit(context);
  706. }
  707. }
  708. context.restore();
  709. },
  710. _visitForWebGL:function (ctx) {
  711. var gl = ctx || cc.renderContext;
  712. // CAREFUL:
  713. // This visit is almost identical to CocosNode#visit
  714. // with the exception that it doesn't call visit on it's children
  715. //
  716. // The alternative is to have a void CCSprite#visit, but
  717. // although this is less mantainable, is faster
  718. //
  719. if (!this._visible)
  720. return;
  721. cc.kmGLPushMatrix();
  722. var locGrid = this._grid;
  723. if (locGrid && locGrid.isActive()) {
  724. locGrid.beforeDraw();
  725. this.transformAncestors();
  726. }
  727. this.sortAllChildren();
  728. this.transform(gl);
  729. this.draw(gl);
  730. if (locGrid && locGrid.isActive())
  731. locGrid.afterDraw(this);
  732. cc.kmGLPopMatrix();
  733. this.setOrderOfArrival(0);
  734. },
  735. /**
  736. * add child to cc.SpriteBatchNode (override addChild of cc.Node)
  737. * @override
  738. * @param {cc.Sprite} child
  739. * @param {Number} [zOrder]
  740. * @param {Number} [tag]
  741. */
  742. addChild: null,
  743. _addChildForCanvas: function (child, zOrder, tag) {
  744. if (child == null)
  745. throw "cc.SpriteBatchNode.addChild(): child should be non-null";
  746. if(!(child instanceof cc.Sprite)){
  747. cc.log( "cc.SpriteBatchNode.addChild(): cc.SpriteBatchNode only supports cc.Sprites as children");
  748. return;
  749. }
  750. zOrder = (zOrder == null) ? child.getZOrder() : zOrder;
  751. tag = (tag == null) ? child.getTag() : tag;
  752. cc.Node.prototype.addChild.call(this, child, zOrder, tag);
  753. this.appendChild(child);
  754. this.setNodeDirty();
  755. },
  756. _addChildForWebGL: function (child, zOrder, tag) {
  757. if (child == null)
  758. throw "cc.SpriteBatchNode.addChild(): child should be non-null";
  759. if(!(child instanceof cc.Sprite)){
  760. cc.log( "cc.SpriteBatchNode.addChild(): cc.SpriteBatchNode only supports cc.Sprites as children");
  761. return;
  762. }
  763. if(child.getTexture() != this._textureAtlas.getTexture()){ // check cc.Sprite is using the same texture id
  764. cc.log( "cc.SpriteBatchNode.addChild(): cc.Sprite is not using the same texture");
  765. return;
  766. }
  767. zOrder = (zOrder == null) ? child.getZOrder() : zOrder;
  768. tag = (tag == null) ? child.getTag() : tag;
  769. cc.Node.prototype.addChild.call(this, child, zOrder, tag);
  770. this.appendChild(child);
  771. this.setNodeDirty();
  772. },
  773. /**
  774. * <p>Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter. <br/>
  775. * (override removeAllChildren of cc.Node)</p>
  776. * @param {Boolean} cleanup
  777. */
  778. removeAllChildren:null,
  779. _removeAllChildrenForCanvas:function (cleanup) {
  780. // Invalidate atlas index. issue #569
  781. // useSelfRender should be performed on all descendants. issue #1216
  782. var locDescendants = this._descendants;
  783. if (locDescendants && locDescendants.length > 0) {
  784. for (var i = 0, len = locDescendants.length; i < len; i++) {
  785. if (locDescendants[i])
  786. locDescendants[i].setBatchNode(null);
  787. }
  788. }
  789. cc.Node.prototype.removeAllChildren.call(this, cleanup);
  790. this._descendants.length = 0;
  791. },
  792. _removeAllChildrenForWebGL:function (cleanup) {
  793. // Invalidate atlas index. issue #569
  794. // useSelfRender should be performed on all descendants. issue #1216
  795. var locDescendants = this._descendants;
  796. if (locDescendants && locDescendants.length > 0) {
  797. for (var i = 0, len = locDescendants.length; i < len; i++) {
  798. if (locDescendants[i])
  799. locDescendants[i].setBatchNode(null);
  800. }
  801. }
  802. cc.Node.prototype.removeAllChildren.call(this, cleanup);
  803. this._descendants.length = 0;
  804. this._textureAtlas.removeAllQuads();
  805. },
  806. sortAllChildren:null,
  807. _sortAllChildrenForCanvas:function () {
  808. if (this._reorderChildDirty) {
  809. var i, j = 0, locChildren = this._children;
  810. var length = locChildren.length, tempChild;
  811. //insertion sort
  812. for (i = 1; i < length; i++) {
  813. var tempItem = locChildren[i];
  814. j = i - 1;
  815. tempChild = locChildren[j];
  816. //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
  817. while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
  818. ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
  819. locChildren[j + 1] = tempChild;
  820. j = j - 1;
  821. tempChild = locChildren[j];
  822. }
  823. locChildren[j + 1] = tempItem;
  824. }
  825. //sorted now check all children
  826. if (locChildren.length > 0) {
  827. //first sort all children recursively based on zOrder
  828. this._arrayMakeObjectsPerformSelector(locChildren, cc.Node.StateCallbackType.sortAllChildren);
  829. }
  830. this._reorderChildDirty = false;
  831. }
  832. },
  833. _sortAllChildrenForWebGL:function () {
  834. if (this._reorderChildDirty) {
  835. var childrenArr = this._children;
  836. var i, j = 0, length = childrenArr.length, tempChild;
  837. //insertion sort
  838. for (i = 1; i < length; i++) {
  839. var tempItem = childrenArr[i];
  840. j = i - 1;
  841. tempChild = childrenArr[j];
  842. //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
  843. while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
  844. ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
  845. childrenArr[j + 1] = tempChild;
  846. j = j - 1;
  847. tempChild = childrenArr[j];
  848. }
  849. childrenArr[j + 1] = tempItem;
  850. }
  851. //sorted now check all children
  852. if (childrenArr.length > 0) {
  853. //first sort all children recursively based on zOrder
  854. this._arrayMakeObjectsPerformSelector(childrenArr, cc.Node.StateCallbackType.sortAllChildren);
  855. var index = 0;
  856. //fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact)
  857. // and at the same time reorder descedants and the quads to the right index
  858. for (i = 0; i < childrenArr.length; i++)
  859. index = this._updateAtlasIndex(childrenArr[i], index);
  860. }
  861. this._reorderChildDirty = false;
  862. }
  863. },
  864. /**
  865. * draw cc.SpriteBatchNode (override draw of cc.Node)
  866. */
  867. draw:null,
  868. _drawForWebGL:function () {
  869. // Optimization: Fast Dispatch
  870. if (this._textureAtlas.getTotalQuads() === 0)
  871. return;
  872. //cc.NODE_DRAW_SETUP(this);
  873. this._shaderProgram.use();
  874. this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4();
  875. this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.updateTransform);
  876. cc.glBlendFunc(this._blendFunc.src, this._blendFunc.dst);
  877. this._textureAtlas.drawQuads();
  878. }
  879. });
  880. if(cc.Browser.supportWebGL){
  881. cc.SpriteBatchNode.prototype.ctor = cc.SpriteBatchNode.prototype._ctorForWebGL;
  882. cc.SpriteBatchNode.prototype.updateQuadFromSprite = cc.SpriteBatchNode.prototype._updateQuadFromSpriteForWebGL;
  883. cc.SpriteBatchNode.prototype.insertQuadFromSprite = cc.SpriteBatchNode.prototype._insertQuadFromSpriteForWebGL;
  884. cc.SpriteBatchNode.prototype.initWithTexture = cc.SpriteBatchNode.prototype._initWithTextureForWebGL;
  885. cc.SpriteBatchNode.prototype.appendChild = cc.SpriteBatchNode.prototype._appendChildForWebGL;
  886. cc.SpriteBatchNode.prototype.removeSpriteFromAtlas = cc.SpriteBatchNode.prototype._removeSpriteFromAtlasForWebGL;
  887. cc.SpriteBatchNode.prototype.getTexture = cc.SpriteBatchNode.prototype._getTextureForWebGL;
  888. cc.SpriteBatchNode.prototype.setTexture = cc.SpriteBatchNode.prototype._setTextureForWebGL;
  889. cc.SpriteBatchNode.prototype.visit = cc.SpriteBatchNode.prototype._visitForWebGL;
  890. cc.SpriteBatchNode.prototype.addChild = cc.SpriteBatchNode.prototype._addChildForWebGL;
  891. cc.SpriteBatchNode.prototype.removeAllChildren = cc.SpriteBatchNode.prototype._removeAllChildrenForWebGL;
  892. cc.SpriteBatchNode.prototype.sortAllChildren = cc.SpriteBatchNode.prototype._sortAllChildrenForWebGL;
  893. cc.SpriteBatchNode.prototype.draw = cc.SpriteBatchNode.prototype._drawForWebGL;
  894. } else {
  895. cc.SpriteBatchNode.prototype.ctor = cc.SpriteBatchNode.prototype._ctorForCanvas;
  896. cc.SpriteBatchNode.prototype.updateQuadFromSprite = cc.SpriteBatchNode.prototype._updateQuadFromSpriteForCanvas;
  897. cc.SpriteBatchNode.prototype.insertQuadFromSprite = cc.SpriteBatchNode.prototype._insertQuadFromSpriteForCanvas;
  898. cc.SpriteBatchNode.prototype.initWithTexture = cc.SpriteBatchNode.prototype._initWithTextureForCanvas;
  899. cc.SpriteBatchNode.prototype.appendChild = cc.SpriteBatchNode.prototype._appendChildForCanvas;
  900. cc.SpriteBatchNode.prototype.removeSpriteFromAtlas = cc.SpriteBatchNode.prototype._removeSpriteFromAtlasForCanvas;
  901. cc.SpriteBatchNode.prototype.getTexture = cc.SpriteBatchNode.prototype._getTextureForCanvas;
  902. cc.SpriteBatchNode.prototype.setTexture = cc.SpriteBatchNode.prototype._setTextureForCanvas;
  903. cc.SpriteBatchNode.prototype.visit = cc.SpriteBatchNode.prototype._visitForCanvas;
  904. cc.SpriteBatchNode.prototype.removeAllChildren = cc.SpriteBatchNode.prototype._removeAllChildrenForCanvas;
  905. cc.SpriteBatchNode.prototype.addChild = cc.SpriteBatchNode.prototype._addChildForCanvas;
  906. cc.SpriteBatchNode.prototype.sortAllChildren = cc.SpriteBatchNode.prototype._sortAllChildrenForCanvas;
  907. cc.SpriteBatchNode.prototype.draw = cc.Node.prototype.draw;
  908. }
  909. /**
  910. * <p>
  911. * creates a cc.SpriteBatchNodeCanvas with a file image (.png, .jpg etc) with a default capacity of 29 children.<br/>
  912. * The capacity will be increased in 33% in runtime if it run out of space.<br/>
  913. * The file will be loaded using the TextureMgr.<br/>
  914. * </p>
  915. * @param {String} fileImage
  916. * @param {Number} capacity
  917. * @return {cc.SpriteBatchNode}
  918. * @example
  919. * //create a SpriteBatchNode
  920. * var parent2 = cc.SpriteBatchNode.create("res/animations/grossini.png", 50);
  921. */
  922. cc.SpriteBatchNode.create = function (fileImage, capacity) {
  923. capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY;
  924. var batchNode = new cc.SpriteBatchNode();
  925. batchNode.init(fileImage, capacity);
  926. return batchNode;
  927. };
  928. /**
  929. * <p>
  930. * creates a cc.SpriteBatchNodeCanvas with a texture2d and a default capacity of 29 children. <br/>
  931. * The capacity will be increased in 33% in runtime if it run out of space. <br/>
  932. * </p>
  933. * @param {cc.Texture2D} texture
  934. * @param {Number} [capacity]
  935. * @return {cc.SpriteBatchNode}
  936. */
  937. cc.SpriteBatchNode.createWithTexture = function (texture, capacity) {
  938. capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY;
  939. var batchNode = new cc.SpriteBatchNode();
  940. batchNode.initWithTexture(texture, capacity);
  941. return batchNode;
  942. };