ZMLCCParticleSystemQuad.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2009 Leonardo Kasperavičius
  4. Copyright (c) 2010-2012 cocos2d-x.org
  5. Copyright (c) 2011 Zynga Inc.
  6. Copyright (c) 2013-2017 Chukong Technologies Inc.
  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. #include "2d/ZMLCCParticleSystemQuad.h"
  25. #include <algorithm>
  26. #include "2d/CCSpriteFrame.h"
  27. #include "2d/CCParticleBatchNode.h"
  28. #include "renderer/CCTextureAtlas.h"
  29. #include "renderer/ccGLStateCache.h"
  30. #include "renderer/CCRenderer.h"
  31. #include "base/CCDirector.h"
  32. #include "base/CCEventType.h"
  33. #include "base/CCConfiguration.h"
  34. #include "base/CCEventListenerCustom.h"
  35. #include "base/CCEventDispatcher.h"
  36. #include "base/ccUTF8.h"
  37. #include "common/CocosConfig.h"
  38. NS_CC_BEGIN
  39. ZMLCCParticleSystemQuad::ZMLCCParticleSystemQuad()
  40. :_quads(nullptr)
  41. ,_indices(nullptr)
  42. ,_VAOname(0)
  43. {
  44. memset(_buffersVBO, 0, sizeof(_buffersVBO));
  45. }
  46. ZMLCCParticleSystemQuad::~ZMLCCParticleSystemQuad()
  47. {
  48. if (nullptr == _batchNode)
  49. {
  50. CC_SAFE_FREE(_quads);
  51. CC_SAFE_FREE(_indices);
  52. glDeleteBuffers(2, &_buffersVBO[0]);
  53. if (Configuration::getInstance()->supportsShareableVAO())
  54. {
  55. glDeleteVertexArrays(1, &_VAOname);
  56. GL::bindVAO(0);
  57. }
  58. }
  59. }
  60. // implementation ZMLCCParticleSystemQuad
  61. ZMLCCParticleSystemQuad * ZMLCCParticleSystemQuad::create(const std::string& filename)
  62. {
  63. ZMLCCParticleSystemQuad *ret = new (std::nothrow) ZMLCCParticleSystemQuad();
  64. if (ret && ret->initWithFile(filename))
  65. {
  66. ret->autorelease();
  67. return ret;
  68. }
  69. CC_SAFE_DELETE(ret);
  70. return ret;
  71. }
  72. ZMLCCParticleSystemQuad * ZMLCCParticleSystemQuad::createWithTotalParticles(int numberOfParticles) {
  73. ZMLCCParticleSystemQuad *ret = new (std::nothrow) ZMLCCParticleSystemQuad();
  74. if (ret && ret->initWithTotalParticles(numberOfParticles))
  75. {
  76. ret->autorelease();
  77. return ret;
  78. }
  79. CC_SAFE_DELETE(ret);
  80. return ret;
  81. }
  82. ZMLCCParticleSystemQuad * ZMLCCParticleSystemQuad::create(ValueMap &dictionary)
  83. {
  84. ZMLCCParticleSystemQuad *ret = new (std::nothrow) ZMLCCParticleSystemQuad();
  85. if (ret && ret->initWithDictionary(dictionary))
  86. {
  87. ret->autorelease();
  88. return ret;
  89. }
  90. CC_SAFE_DELETE(ret);
  91. return ret;
  92. }
  93. //implementation ZMLCCParticleSystemQuad
  94. // overriding the init method
  95. bool ZMLCCParticleSystemQuad::initWithTotalParticles(int numberOfParticles)
  96. {
  97. // base initialization
  98. if( ZMLCCParticleSystem::initWithTotalParticles(numberOfParticles) )
  99. {
  100. // allocating data space
  101. if( ! this->allocMemory() ) {
  102. this->release();
  103. return false;
  104. }
  105. initIndices();
  106. if (Configuration::getInstance()->supportsShareableVAO())
  107. {
  108. setupVBOandVAO();
  109. }
  110. else
  111. {
  112. setupVBO();
  113. }
  114. setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP));
  115. #if CC_ENABLE_CACHE_TEXTURE_DATA
  116. // Need to listen the event only when not use batchnode, because it will use VBO
  117. auto listener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, CC_CALLBACK_1(ZMLCCParticleSystemQuad::listenRendererRecreated, this));
  118. _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
  119. #endif
  120. return true;
  121. }
  122. return false;
  123. }
  124. // pointRect should be in Texture coordinates, not pixel coordinates
  125. void ZMLCCParticleSystemQuad::initTexCoordsWithRect(const Rect& pointRect, bool isrotaed, Vec2 &offset, Vec2 &originalSize)
  126. {
  127. // convert to Tex coords
  128. Rect rect = Rect(
  129. pointRect.origin.x * CC_CONTENT_SCALE_FACTOR(),
  130. pointRect.origin.y * CC_CONTENT_SCALE_FACTOR(),
  131. pointRect.size.width * CC_CONTENT_SCALE_FACTOR(),
  132. pointRect.size.height * CC_CONTENT_SCALE_FACTOR());
  133. GLfloat wide = (GLfloat) pointRect.size.width;
  134. GLfloat high = (GLfloat) pointRect.size.height;
  135. float rw = rect.size.width;
  136. float rh = rect.size.height;
  137. if (isrotaed)
  138. std::swap(rw, rh);
  139. if (_texture)
  140. {
  141. wide = (GLfloat)_texture->getPixelsWide();
  142. high = (GLfloat)_texture->getPixelsHigh();
  143. }
  144. #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
  145. GLfloat left = (rect.origin.x*2+1) / (wide*2);
  146. GLfloat bottom = (rect.origin.y*2+1) / (high*2);
  147. GLfloat right = left + (rw*2-2) / (wide*2);
  148. GLfloat top = bottom + (rh*2-2) / (high*2);
  149. #else
  150. GLfloat left = rect.origin.x / wide;
  151. GLfloat bottom = rect.origin.y / high;
  152. GLfloat right = left + rw / wide;
  153. GLfloat top = bottom + rh / high;
  154. #endif // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
  155. // Important. Texture in cocos2d are inverted, so the Y component should be inverted
  156. std::swap(top, bottom);
  157. // CCASSERT(_texNumber < 100, "纹理数量超过上限");
  158. //
  159. if (isrotaed)
  160. {
  161. _vertexInfo.bl.u = left;
  162. _vertexInfo.bl.v = top;
  163. _vertexInfo.br.u = left;
  164. _vertexInfo.br.v = bottom;
  165. _vertexInfo.tl.u = right;
  166. _vertexInfo.tl.v = top;
  167. _vertexInfo.tr.u = right;
  168. _vertexInfo.tr.v = bottom;
  169. }
  170. else
  171. {
  172. _vertexInfo.bl.u = left;
  173. _vertexInfo.bl.v = bottom;
  174. _vertexInfo.br.u = right;
  175. _vertexInfo.br.v = bottom;
  176. _vertexInfo.tl.u = left;
  177. _vertexInfo.tl.v = top;
  178. _vertexInfo.tr.u = right;
  179. _vertexInfo.tr.v = top;
  180. }
  181. if (!offset.isZero()){
  182. // CCLOG("");
  183. }
  184. float originalSizeX_2 = 2 / originalSize.x; // 宽的一半的倒数
  185. float originalSizeY_2 = 2 / originalSize.y;
  186. float x1 = (pointRect.size.width * 0.5 - offset.x) * originalSizeX_2;
  187. float x2 = (pointRect.size.width * 0.5 + offset.x) * originalSizeX_2;
  188. float y1 = (pointRect.size.height * 0.5 - offset.y) * originalSizeY_2;
  189. float y2 = (pointRect.size.height * 0.5 + offset.y) * originalSizeY_2;
  190. _vertexInfo.TexturePercentage.set(x1, x2, y1, y2);
  191. }
  192. void ZMLCCParticleSystemQuad::updateTexCoords()
  193. {
  194. if (_texture)
  195. { // 走小图
  196. const Size& s = _texture->getContentSize();
  197. Vec2 offset(0,0);
  198. Vec2 originalSize(s.width, s.height);
  199. initTexCoordsWithRect(Rect(0, 0, s.width, s.height),false,offset,originalSize);
  200. }
  201. }
  202. void ZMLCCParticleSystemQuad::setTextureWithRect(Texture2D *texture, const Rect& rect, bool isrotaed, Vec2& offset, Vec2& originalSize)
  203. {
  204. if( !_texture || texture->getName() != _texture->getName() )
  205. {
  206. ZMLCCParticleSystem::setTexture(texture);
  207. }
  208. this->initTexCoordsWithRect(rect,isrotaed,offset,originalSize);
  209. }
  210. void ZMLCCParticleSystemQuad::setTexture(Texture2D* texture)
  211. {
  212. const Size& s = texture->getContentSize();
  213. Vec2 offset(0,0);
  214. Vec2 originalSize(s.width, s.height);
  215. this->setTextureWithRect(texture, Rect(0, 0, s.width, s.height),false,offset,originalSize);
  216. }
  217. void ZMLCCParticleSystemQuad::setDisplayFrame(SpriteFrame *spriteFrame)
  218. {
  219. // CCASSERT(spriteFrame->getOffsetInPixels().isZero(),
  220. // "QuadParticle only supports SpriteFrames with no offsets");
  221. bool isrotaed = spriteFrame->isRotated();
  222. Vec2 offset = spriteFrame->getOffset();
  223. Vec2 originalSize = spriteFrame->getOriginalSize();
  224. auto pointRect = spriteFrame->getRect();
  225. this->setTextureWithRect(spriteFrame->getTexture(), pointRect,isrotaed,offset,originalSize);
  226. }
  227. void ZMLCCParticleSystemQuad::initIndices()
  228. {
  229. for(int i = 0; i < _totalParticles; ++i)
  230. {
  231. const unsigned int i6 = i*6;
  232. const unsigned int i4 = i*4;
  233. _indices[i6+0] = (GLushort) i4+0;
  234. _indices[i6+1] = (GLushort) i4+1;
  235. _indices[i6+2] = (GLushort) i4+2;
  236. _indices[i6+5] = (GLushort) i4+1;
  237. _indices[i6+4] = (GLushort) i4+2;
  238. _indices[i6+3] = (GLushort) i4+3;
  239. }
  240. }
  241. inline void updatePosWithParticle(V3F_C4B_T2F_Quad *quad, const Vec2& newPosition, float rotation, float size,Vec4 texturePercentage)
  242. {
  243. // vertices
  244. GLfloat size_2 = size/2;
  245. GLfloat x1 = -size_2 * texturePercentage.x;
  246. GLfloat y1 = -size_2 * texturePercentage.z;
  247. GLfloat x2 = size_2 * texturePercentage.y;
  248. GLfloat y2 = size_2 * texturePercentage.w;
  249. GLfloat x = newPosition.x;
  250. GLfloat y = newPosition.y;
  251. GLfloat r = (GLfloat)-CC_DEGREES_TO_RADIANS(rotation);
  252. GLfloat cr = cosf(r);
  253. GLfloat sr = sinf(r);
  254. GLfloat ax = x1 * cr - y1 * sr + x;
  255. GLfloat ay = x1 * sr + y1 * cr + y;
  256. GLfloat bx = x2 * cr - y1 * sr + x;
  257. GLfloat by = x2 * sr + y1 * cr + y;
  258. GLfloat cx = x2 * cr - y2 * sr + x;
  259. GLfloat cy = x2 * sr + y2 * cr + y;
  260. GLfloat dx = x1 * cr - y2 * sr + x;
  261. GLfloat dy = x1 * sr + y2 * cr + y;
  262. // bottom-left
  263. quad->bl.vertices.x = ax;
  264. quad->bl.vertices.y = ay;
  265. // bottom-right vertex:
  266. quad->br.vertices.x = bx;
  267. quad->br.vertices.y = by;
  268. // top-left vertex:
  269. quad->tl.vertices.x = dx;
  270. quad->tl.vertices.y = dy;
  271. // top-right vertex:
  272. quad->tr.vertices.x = cx;
  273. quad->tr.vertices.y = cy;
  274. }
  275. void ZMLCCParticleSystemQuad::updateParticleQuads()
  276. {
  277. if (_particleCount <= 0) {
  278. return;
  279. }
  280. Vec2 currentPosition;
  281. if (_positionType == PositionType::FREE)
  282. {
  283. currentPosition = this->convertToWorldSpace(Vec2::ZERO);
  284. }
  285. else if (_positionType == PositionType::RELATIVE)
  286. {
  287. currentPosition = _position;
  288. }
  289. V3F_C4B_T2F_Quad *startQuad;
  290. Vec2 pos = Vec2::ZERO;
  291. if (_batchNode)
  292. {
  293. V3F_C4B_T2F_Quad *batchQuads = _batchNode->getTextureAtlas()->getQuads();
  294. startQuad = &(batchQuads[_atlasIndex]);
  295. pos = _position;
  296. }
  297. else
  298. {
  299. startQuad = &(_quads[0]);
  300. }
  301. if( _positionType == PositionType::FREE )
  302. {
  303. Vec3 p1(currentPosition.x, currentPosition.y, 0);
  304. Mat4 worldToNodeTM = getWorldToNodeTransform();
  305. worldToNodeTM.transformPoint(&p1);
  306. Vec3 p2;
  307. Vec2 newPos;
  308. float* startX = _particleData.startPosX;
  309. float* startY = _particleData.startPosY;
  310. float* x = _particleData.posx;
  311. float* y = _particleData.posy;
  312. float* s = _particleData.size;
  313. float* r = _particleData.rotation;
  314. V3F_C4B_T2F_Quad* quadStart = startQuad;
  315. for (int i = 0 ; i < _particleCount; ++i, ++startX, ++startY, ++x, ++y, ++quadStart, ++s, ++r)
  316. {
  317. p2.set(*startX, *startY, 0);
  318. worldToNodeTM.transformPoint(&p2);
  319. newPos.set(*x,*y);
  320. p2 = p1 - p2;
  321. newPos.x -= p2.x - pos.x;
  322. newPos.y -= p2.y - pos.y;
  323. Vec4 texturePercentage = _vertexInfo.TexturePercentage;
  324. updatePosWithParticle(quadStart, newPos, *r, *s,texturePercentage);
  325. }
  326. }
  327. else if( _positionType == PositionType::RELATIVE )
  328. {
  329. Vec2 newPos;
  330. float* startX = _particleData.startPosX;
  331. float* startY = _particleData.startPosY;
  332. float* x = _particleData.posx;
  333. float* y = _particleData.posy;
  334. float* s = _particleData.size;
  335. float* r = _particleData.rotation;
  336. V3F_C4B_T2F_Quad* quadStart = startQuad;
  337. Vec4 texturePercentage = _vertexInfo.TexturePercentage;
  338. for (int i = 0 ; i < _particleCount; ++i, ++startX, ++startY, ++x, ++y, ++quadStart, ++s, ++r)
  339. {
  340. newPos.set(*x, *y);
  341. newPos.x = *x - (currentPosition.x - *startX);
  342. newPos.y = *y - (currentPosition.y - *startY);
  343. newPos += pos;
  344. updatePosWithParticle(quadStart, newPos, *r, *s,texturePercentage);
  345. }
  346. }
  347. else
  348. {
  349. Vec2 newPos;
  350. float* startX = _particleData.startPosX;
  351. float* startY = _particleData.startPosY;
  352. float* x = _particleData.posx;
  353. float* y = _particleData.posy;
  354. float* s = _particleData.size;
  355. float* r = _particleData.rotation;
  356. V3F_C4B_T2F_Quad* quadStart = startQuad;
  357. Vec4 texturePercentage = _vertexInfo.TexturePercentage;
  358. for (int i = 0 ; i < _particleCount; ++i, ++startX, ++startY, ++x, ++y, ++quadStart, ++s, ++r)
  359. {
  360. newPos.set(*x + pos.x, *y + pos.y);
  361. updatePosWithParticle(quadStart, newPos, *r, *s,texturePercentage);
  362. }
  363. }
  364. //set color
  365. if(_opacityModifyRGB)
  366. {
  367. V3F_C4B_T2F_Quad* quad = startQuad;
  368. float* r = _particleData.colorR;
  369. float* g = _particleData.colorG;
  370. float* b = _particleData.colorB;
  371. float* a = _particleData.colorA;
  372. for (int i = 0; i < _particleCount; ++i,++quad,++r,++g,++b,++a)
  373. {
  374. GLubyte colorR = *r * *a * 255 * _displayedColor.r / 255 * _displayedOpacity / 255;
  375. GLubyte colorG = *g * *a * 255 * _displayedColor.g / 255 * _displayedOpacity / 255;
  376. GLubyte colorB = *b * *a * 255 * _displayedColor.b / 255 * _displayedOpacity / 255;
  377. GLubyte colorA = *a * 255 * _displayedOpacity / 255;
  378. quad->bl.colors.set(colorR, colorG, colorB, colorA);
  379. quad->br.colors.set(colorR, colorG, colorB, colorA);
  380. quad->tl.colors.set(colorR, colorG, colorB, colorA);
  381. quad->tr.colors.set(colorR, colorG, colorB, colorA);
  382. }
  383. }
  384. else
  385. {
  386. V3F_C4B_T2F_Quad* quad = startQuad;
  387. float* r = _particleData.colorR;
  388. float* g = _particleData.colorG;
  389. float* b = _particleData.colorB;
  390. float* a = _particleData.colorA;
  391. for (int i = 0; i < _particleCount; ++i,++quad,++r,++g,++b,++a)
  392. {
  393. GLubyte colorR = *r * 255 * _displayedColor.r / 255 * _displayedOpacity / 255;
  394. GLubyte colorG = *g * 255 * _displayedColor.g / 255 * _displayedOpacity / 255;
  395. GLubyte colorB = *b * 255 * _displayedColor.b / 255 * _displayedOpacity / 255;
  396. GLubyte colorA = *a * 255 * _displayedOpacity / 255;
  397. quad->bl.colors.set(colorR, colorG, colorB, colorA);
  398. quad->br.colors.set(colorR, colorG, colorB, colorA);
  399. quad->tl.colors.set(colorR, colorG, colorB, colorA);
  400. quad->tr.colors.set(colorR, colorG, colorB, colorA);
  401. }
  402. }
  403. {
  404. //设置顶点
  405. V3F_C4B_T2F_Quad* quad = startQuad;
  406. for (int i = 0; i < _particleCount; ++i, ++quad) {
  407. quad->bl.texCoords.u = _vertexInfo.bl.u;
  408. quad->bl.texCoords.v = _vertexInfo.bl.v;
  409. // bottom-right vertex:
  410. quad->br.texCoords.u = _vertexInfo.br.u;
  411. quad->br.texCoords.v = _vertexInfo.br.v;
  412. // top-left vertex:
  413. quad->tl.texCoords.u = _vertexInfo.tl.u;
  414. quad->tl.texCoords.v = _vertexInfo.tl.v;
  415. // top-right vertex:
  416. quad->tr.texCoords.u = _vertexInfo.tr.u;
  417. quad->tr.texCoords.v = _vertexInfo.tr.v;
  418. }
  419. }
  420. }
  421. void ZMLCCParticleSystemQuad::postStep()
  422. {
  423. glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
  424. // Option 1: Sub Data
  425. glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(_quads[0])*_totalParticles, _quads);
  426. // Option 2: Data
  427. // glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * particleCount, quads_, GL_DYNAMIC_DRAW);
  428. // Option 3: Orphaning + glMapBuffer
  429. // glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0])*_totalParticles, nullptr, GL_STREAM_DRAW);
  430. // void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
  431. // memcpy(buf, _quads, sizeof(_quads[0])*_totalParticles);
  432. // glUnmapBuffer(GL_ARRAY_BUFFER);
  433. glBindBuffer(GL_ARRAY_BUFFER, 0);
  434. CHECK_GL_ERROR_DEBUG();
  435. }
  436. // overriding draw method
  437. void ZMLCCParticleSystemQuad::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
  438. {
  439. //quad command
  440. if(_particleCount > 0)
  441. {
  442. _quadCommand.init(_globalZOrder, _texture, getGLProgramState(), _blendFunc, _quads, _particleCount, transform, flags);
  443. renderer->addCommand(&_quadCommand);
  444. }
  445. }
  446. void ZMLCCParticleSystemQuad::setTotalParticles(int tp)
  447. {
  448. // If we are setting the total number of particles to a number higher
  449. // than what is allocated, we need to allocate new arrays
  450. if( tp > _allocatedParticles )
  451. {
  452. // Allocate new memory
  453. size_t quadsSize = sizeof(_quads[0]) * tp * 1;
  454. size_t indicesSize = sizeof(_indices[0]) * tp * 6 * 1;
  455. _particleData.release();
  456. if (!_particleData.init(tp))
  457. {
  458. CCLOG("Particle system: not enough memory");
  459. return;
  460. }
  461. V3F_C4B_T2F_Quad* quadsNew = (V3F_C4B_T2F_Quad*)realloc(_quads, quadsSize);
  462. GLushort* indicesNew = (GLushort*)realloc(_indices, indicesSize);
  463. if (quadsNew && indicesNew)
  464. {
  465. // Assign pointers
  466. _quads = quadsNew;
  467. _indices = indicesNew;
  468. // Clear the memory
  469. memset(_quads, 0, quadsSize);
  470. memset(_indices, 0, indicesSize);
  471. _allocatedParticles = tp;
  472. }
  473. else
  474. {
  475. // Out of memory, failed to resize some array
  476. if (quadsNew) _quads = quadsNew;
  477. if (indicesNew) _indices = indicesNew;
  478. CCLOG("Particle system: out of memory");
  479. return;
  480. }
  481. _totalParticles = tp;
  482. // Init particles
  483. if (_batchNode)
  484. {
  485. for (int i = 0; i < _totalParticles; i++)
  486. {
  487. _particleData.atlasIndex[i] = i;
  488. }
  489. }
  490. initIndices();
  491. if (Configuration::getInstance()->supportsShareableVAO())
  492. {
  493. setupVBOandVAO();
  494. }
  495. else
  496. {
  497. setupVBO();
  498. }
  499. // fixed http://www.cocos2d-x.org/issues/3990
  500. // Updates texture coords.
  501. updateTexCoords();
  502. }
  503. else
  504. {
  505. _totalParticles = tp;
  506. }
  507. // fixed issue #5762
  508. // reset the emission rate
  509. if(CocosConfig::isCCBParticleUseEmitrate() == false){
  510. setEmissionRate(_totalParticles / _life);
  511. }
  512. resetSystem();
  513. }
  514. void ZMLCCParticleSystemQuad::setupVBOandVAO()
  515. {
  516. // clean VAO
  517. glDeleteBuffers(2, &_buffersVBO[0]);
  518. glDeleteVertexArrays(1, &_VAOname);
  519. GL::bindVAO(0);
  520. glGenVertexArrays(1, &_VAOname);
  521. GL::bindVAO(_VAOname);
  522. #define kQuadSize sizeof(_quads[0].bl)
  523. glGenBuffers(2, &_buffersVBO[0]);
  524. glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
  525. glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _totalParticles, _quads, GL_DYNAMIC_DRAW);
  526. // vertices
  527. glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION);
  528. glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, vertices));
  529. // colors
  530. glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR);
  531. glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, colors));
  532. // tex coords
  533. glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_TEX_COORD);
  534. glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, texCoords));
  535. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
  536. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_indices[0]) * _totalParticles * 6, _indices, GL_STATIC_DRAW);
  537. // Must unbind the VAO before changing the element buffer.
  538. GL::bindVAO(0);
  539. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  540. glBindBuffer(GL_ARRAY_BUFFER, 0);
  541. CHECK_GL_ERROR_DEBUG();
  542. }
  543. void ZMLCCParticleSystemQuad::setupVBO()
  544. {
  545. glDeleteBuffers(2, &_buffersVBO[0]);
  546. glGenBuffers(2, &_buffersVBO[0]);
  547. glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
  548. glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _totalParticles, _quads, GL_DYNAMIC_DRAW);
  549. glBindBuffer(GL_ARRAY_BUFFER, 0);
  550. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
  551. glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_indices[0]) * _totalParticles * 6, _indices, GL_STATIC_DRAW);
  552. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  553. CHECK_GL_ERROR_DEBUG();
  554. }
  555. void ZMLCCParticleSystemQuad::listenRendererRecreated(EventCustom* /*event*/)
  556. {
  557. //when comes to foreground in android, _buffersVBO and _VAOname is a wild handle
  558. //before recreating, we need to reset them to 0
  559. memset(_buffersVBO, 0, sizeof(_buffersVBO));
  560. if (Configuration::getInstance()->supportsShareableVAO())
  561. {
  562. _VAOname = 0;
  563. setupVBOandVAO();
  564. }
  565. else
  566. {
  567. setupVBO();
  568. }
  569. }
  570. bool ZMLCCParticleSystemQuad::allocMemory()
  571. {
  572. CCASSERT( !_batchNode, "Memory should not be alloced when not using batchNode");
  573. CC_SAFE_FREE(_quads);
  574. CC_SAFE_FREE(_indices);
  575. _quads = (V3F_C4B_T2F_Quad*)malloc(_totalParticles * sizeof(V3F_C4B_T2F_Quad));
  576. _indices = (GLushort*)malloc(_totalParticles * 6 * sizeof(GLushort));
  577. if( !_quads || !_indices)
  578. {
  579. CCLOG("cocos2d: Particle system: not enough memory");
  580. CC_SAFE_FREE(_quads);
  581. CC_SAFE_FREE(_indices);
  582. return false;
  583. }
  584. memset(_quads, 0, _totalParticles * sizeof(V3F_C4B_T2F_Quad));
  585. memset(_indices, 0, _totalParticles * 6 * sizeof(GLushort));
  586. return true;
  587. }
  588. void ZMLCCParticleSystemQuad::setBatchNode(ParticleBatchNode * batchNode)
  589. {
  590. if( _batchNode != batchNode )
  591. {
  592. ParticleBatchNode* oldBatch = _batchNode;
  593. ZMLCCParticleSystem::setBatchNode(batchNode);
  594. // NEW: is self render ?
  595. if( ! batchNode )
  596. {
  597. allocMemory();
  598. initIndices();
  599. setTexture(oldBatch->getTexture());
  600. if (Configuration::getInstance()->supportsShareableVAO())
  601. {
  602. setupVBOandVAO();
  603. }
  604. else
  605. {
  606. setupVBO();
  607. }
  608. }
  609. // OLD: was it self render ? cleanup
  610. else if( !oldBatch )
  611. {
  612. // copy current state to batch
  613. V3F_C4B_T2F_Quad *batchQuads = _batchNode->getTextureAtlas()->getQuads();
  614. V3F_C4B_T2F_Quad *quad = &(batchQuads[_atlasIndex] );
  615. memcpy( quad, _quads, _totalParticles * sizeof(_quads[0]) );
  616. CC_SAFE_FREE(_quads);
  617. CC_SAFE_FREE(_indices);
  618. glDeleteBuffers(2, &_buffersVBO[0]);
  619. memset(_buffersVBO, 0, sizeof(_buffersVBO));
  620. if (Configuration::getInstance()->supportsShareableVAO())
  621. {
  622. glDeleteVertexArrays(1, &_VAOname);
  623. GL::bindVAO(0);
  624. _VAOname = 0;
  625. }
  626. }
  627. }
  628. }
  629. ZMLCCParticleSystemQuad * ZMLCCParticleSystemQuad::create() {
  630. ZMLCCParticleSystemQuad *particleSystemQuad = new (std::nothrow) ZMLCCParticleSystemQuad();
  631. if (particleSystemQuad && particleSystemQuad->init())
  632. {
  633. particleSystemQuad->autorelease();
  634. return particleSystemQuad;
  635. }
  636. CC_SAFE_DELETE(particleSystemQuad);
  637. return nullptr;
  638. }
  639. std::string ZMLCCParticleSystemQuad::getDescription() const
  640. {
  641. return StringUtils::format("<ZMLCCParticleSystemQuad | Tag = %d, Total Particles = %d>", _tag, _totalParticles);
  642. }
  643. void ZMLCCParticleSystemQuad::setParticlyKeyInfo(bool isSF,std::string originalName,std::unordered_set<std::string> originaPlist){
  644. _isSpriteFrame = isSF;
  645. _originalName = originalName;
  646. _originalPlistSt = originaPlist;
  647. }
  648. ///根据记录的信息重置纹理
  649. void ZMLCCParticleSystemQuad::resetTextureByKeyInfo(std::unordered_set<std::string> replacePlist){
  650. if (_isSpriteFrame) {
  651. SpriteFrameCache * frameCache = SpriteFrameCache::getInstance();
  652. SpriteFrame * pFrame = frameCache->getSpriteFrameByName(_originalName,replacePlist);
  653. if (!pFrame) {
  654. pFrame = frameCache->getSpriteFrameByName(_originalName,_originalPlistSt);
  655. }
  656. bool isrotated = pFrame->isRotated();
  657. Vec2 offset = pFrame->getOffset();
  658. Vec2 originalSize = pFrame->getOriginalSize();
  659. auto pointRect = pFrame->getRect();
  660. setTextureWithRect(pFrame->getTexture(), pFrame->getRect(),isrotated,offset,originalSize);
  661. }
  662. else{
  663. }
  664. }
  665. NS_CC_END