CCProgressTimer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /****************************************************************************
  2. Copyright (c) 2010 Lam Pham
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2013-2017 Chukong Technologies Inc
  5. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  6. http://www.cocos2d-x.org
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. #include "2d/CCProgressTimer.h"
  24. #include <algorithm>
  25. #include "base/ccMacros.h"
  26. #include "base/CCDirector.h"
  27. #include "2d/CCSprite.h"
  28. #include "renderer/ccGLStateCache.h"
  29. #include "renderer/CCRenderer.h"
  30. NS_CC_BEGIN
  31. #define kProgressTextureCoordsCount 4
  32. // kProgressTextureCoords holds points {0,1} {0,0} {1,0} {1,1} we can represent it as bits
  33. const char kProgressTextureCoords = 0x4b;
  34. ProgressTimer::ProgressTimer()
  35. :_type(Type::RADIAL)
  36. ,_midpoint(0,0)
  37. ,_barChangeRate(0,0)
  38. ,_percentage(0.0f)
  39. ,_sprite(nullptr)
  40. ,_vertexDataCount(0)
  41. ,_vertexData(nullptr)
  42. ,_reverseDirection(false)
  43. {}
  44. ProgressTimer* ProgressTimer::create(Sprite* sp)
  45. {
  46. ProgressTimer *progressTimer = new (std::nothrow) ProgressTimer();
  47. if (progressTimer && progressTimer->initWithSprite(sp))
  48. {
  49. progressTimer->autorelease();
  50. return progressTimer;
  51. }
  52. delete progressTimer;
  53. return nullptr;
  54. }
  55. bool ProgressTimer::initWithSprite(Sprite* sp)
  56. {
  57. setPercentage(0.0f);
  58. _vertexData = nullptr;
  59. _vertexDataCount = 0;
  60. setAnchorPoint(Vec2(0.5f,0.5f));
  61. _type = Type::RADIAL;
  62. _reverseDirection = false;
  63. setMidpoint(Vec2(0.5f, 0.5f));
  64. setBarChangeRate(Vec2(1,1));
  65. setSprite(sp);
  66. // shader state
  67. setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR, sp->getTexture()));
  68. return true;
  69. }
  70. ProgressTimer::~ProgressTimer(void)
  71. {
  72. CC_SAFE_FREE(_vertexData);
  73. CC_SAFE_RELEASE(_sprite);
  74. }
  75. void ProgressTimer::setPercentage(float percentage)
  76. {
  77. if (_percentage != percentage)
  78. {
  79. _percentage = clampf(percentage, 0, 100);
  80. updateProgress();
  81. }
  82. }
  83. void ProgressTimer::setSprite(Sprite *sprite)
  84. {
  85. if (_sprite != sprite)
  86. {
  87. #if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  88. auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  89. if (sEngine)
  90. {
  91. if (_sprite)
  92. sEngine->releaseScriptObject(this, _sprite);
  93. if (sprite)
  94. sEngine->retainScriptObject(this, sprite);
  95. }
  96. #endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  97. CC_SAFE_RETAIN(sprite);
  98. CC_SAFE_RELEASE(_sprite);
  99. _sprite = sprite;
  100. setContentSize(_sprite->getContentSize());
  101. // Every time we set a new sprite, we free the current vertex data
  102. if (_vertexData)
  103. {
  104. CC_SAFE_FREE(_vertexData);
  105. _vertexDataCount = 0;
  106. updateProgress();
  107. }
  108. }
  109. }
  110. void ProgressTimer::setType(Type type)
  111. {
  112. if (type != _type)
  113. {
  114. // release all previous information
  115. if (_vertexData)
  116. {
  117. CC_SAFE_FREE(_vertexData);
  118. _vertexData = nullptr;
  119. _vertexDataCount = 0;
  120. }
  121. _type = type;
  122. }
  123. }
  124. void ProgressTimer::setReverseDirection(bool reverse)
  125. {
  126. if( _reverseDirection != reverse ) {
  127. _reverseDirection = reverse;
  128. // release all previous information
  129. CC_SAFE_FREE(_vertexData);
  130. _vertexDataCount = 0;
  131. }
  132. }
  133. // Interval
  134. ///
  135. // @returns the vertex position from the texture coordinate
  136. ///
  137. Tex2F ProgressTimer::textureCoordFromAlphaPoint(Vec2 alpha)
  138. {
  139. Tex2F ret(0.0f, 0.0f);
  140. if (!_sprite) {
  141. return ret;
  142. }
  143. V3F_C4B_T2F_Quad quad = _sprite->getQuad();
  144. Vec2 min(quad.bl.texCoords.u,quad.bl.texCoords.v);
  145. Vec2 max(quad.tr.texCoords.u,quad.tr.texCoords.v);
  146. // Fix bug #1303 so that progress timer handles sprite frame texture rotation
  147. if (_sprite->isTextureRectRotated()) {
  148. std::swap(alpha.x, alpha.y);
  149. }
  150. return Tex2F(min.x * (1.f - alpha.x) + max.x * alpha.x, min.y * (1.f - alpha.y) + max.y * alpha.y);
  151. }
  152. Vec2 ProgressTimer::vertexFromAlphaPoint(Vec2 alpha)
  153. {
  154. Vec2 ret(0.0f, 0.0f);
  155. if (!_sprite) {
  156. return ret;
  157. }
  158. V3F_C4B_T2F_Quad quad = _sprite->getQuad();
  159. Vec2 min(quad.bl.vertices.x,quad.bl.vertices.y);
  160. Vec2 max(quad.tr.vertices.x,quad.tr.vertices.y);
  161. ret.x = min.x * (1.f - alpha.x) + max.x * alpha.x;
  162. ret.y = min.y * (1.f - alpha.y) + max.y * alpha.y;
  163. return ret;
  164. }
  165. void ProgressTimer::updateColor(void)
  166. {
  167. if (!_sprite) {
  168. return;
  169. }
  170. if (_vertexData)
  171. {
  172. Color4B sc = _sprite->getQuad().tl.colors;
  173. for (int i = 0; i < _vertexDataCount; ++i)
  174. {
  175. _vertexData[i].colors = sc;
  176. }
  177. }
  178. }
  179. void ProgressTimer::updateProgress(void)
  180. {
  181. switch (_type)
  182. {
  183. case Type::RADIAL:
  184. updateRadial();
  185. break;
  186. case Type::BAR:
  187. updateBar();
  188. break;
  189. default:
  190. break;
  191. }
  192. }
  193. void ProgressTimer::setAnchorPoint(const Vec2& anchorPoint)
  194. {
  195. Node::setAnchorPoint(anchorPoint);
  196. }
  197. Vec2 ProgressTimer::getMidpoint() const
  198. {
  199. return _midpoint;
  200. }
  201. void ProgressTimer::setColor(const Color3B &color)
  202. {
  203. _sprite->setColor(color);
  204. updateColor();
  205. }
  206. const Color3B& ProgressTimer::getColor() const
  207. {
  208. return _sprite->getColor();
  209. }
  210. void ProgressTimer::setOpacity(GLubyte opacity)
  211. {
  212. _sprite->setOpacity(opacity);
  213. updateColor();
  214. }
  215. GLubyte ProgressTimer::getOpacity() const
  216. {
  217. return _sprite->getOpacity();
  218. }
  219. void ProgressTimer::setMidpoint(const Vec2& midPoint)
  220. {
  221. _midpoint = midPoint.getClampPoint(Vec2::ZERO, Vec2(1, 1));
  222. }
  223. ///
  224. // Update does the work of mapping the texture onto the triangles
  225. // It now doesn't occur the cost of free/alloc data every update cycle.
  226. // It also only changes the percentage point but no other points if they have not
  227. // been modified.
  228. //
  229. // It now deals with flipped texture. If you run into this problem, just use the
  230. // sprite property and enable the methods flipX, flipY.
  231. ///
  232. void ProgressTimer::updateRadial(void)
  233. {
  234. if (!_sprite) {
  235. return;
  236. }
  237. float alpha = _percentage / 100.f;
  238. float angle = 2.f*((float)M_PI) * ( _reverseDirection ? alpha : 1.0f - alpha);
  239. // We find the vector to do a hit detection based on the percentage
  240. // We know the first vector is the one @ 12 o'clock (top,mid) so we rotate
  241. // from that by the progress angle around the _midpoint pivot
  242. Vec2 topMid(_midpoint.x, 1.f);
  243. Vec2 percentagePt = topMid.rotateByAngle(_midpoint, angle);
  244. int index = 0;
  245. Vec2 hit;
  246. if (alpha == 0.f) {
  247. // More efficient since we don't always need to check intersection
  248. // If the alpha is zero then the hit point is top mid and the index is 0.
  249. hit = topMid;
  250. index = 0;
  251. } else if (alpha == 1.f) {
  252. // More efficient since we don't always need to check intersection
  253. // If the alpha is one then the hit point is top mid and the index is 4.
  254. hit = topMid;
  255. index = 4;
  256. } else {
  257. // We run a for loop checking the edges of the texture to find the
  258. // intersection point
  259. // We loop through five points since the top is split in half
  260. float min_t = FLT_MAX;
  261. for (int i = 0; i <= kProgressTextureCoordsCount; ++i) {
  262. int pIndex = (i + (kProgressTextureCoordsCount - 1))%kProgressTextureCoordsCount;
  263. Vec2 edgePtA = boundaryTexCoord(i % kProgressTextureCoordsCount);
  264. Vec2 edgePtB = boundaryTexCoord(pIndex);
  265. // Remember that the top edge is split in half for the 12 o'clock position
  266. // Let's deal with that here by finding the correct endpoints
  267. if(i == 0){
  268. edgePtB = edgePtA.lerp(edgePtB, 1-_midpoint.x);
  269. } else if(i == 4){
  270. edgePtA = edgePtA.lerp(edgePtB, 1-_midpoint.x);
  271. }
  272. // s and t are returned by ccpLineIntersect
  273. float s = 0, t = 0;
  274. if(Vec2::isLineIntersect(edgePtA, edgePtB, _midpoint, percentagePt, &s, &t))
  275. {
  276. // Since our hit test is on rays we have to deal with the top edge
  277. // being in split in half so we have to test as a segment
  278. if ((i == 0 || i == 4)) {
  279. // s represents the point between edgePtA--edgePtB
  280. if (!(0.f <= s && s <= 1.f)) {
  281. continue;
  282. }
  283. }
  284. // As long as our t isn't negative we are at least finding a
  285. // correct hitpoint from _midpoint to percentagePt.
  286. if (t >= 0.f) {
  287. // Because the percentage line and all the texture edges are
  288. // rays we should only account for the shortest intersection
  289. if (t < min_t) {
  290. min_t = t;
  291. index = i;
  292. }
  293. }
  294. }
  295. }
  296. // Now that we have the minimum magnitude we can use that to find our intersection
  297. hit = _midpoint+ ((percentagePt - _midpoint) * min_t);
  298. }
  299. // The size of the vertex data is the index from the hitpoint
  300. // the 3 is for the _midpoint, 12 o'clock point and hitpoint position.
  301. bool sameIndexCount = true;
  302. if(_vertexDataCount != index + 3){
  303. sameIndexCount = false;
  304. CC_SAFE_FREE(_vertexData);
  305. _vertexDataCount = 0;
  306. }
  307. if(!_vertexData) {
  308. _vertexDataCount = index + 3;
  309. _vertexData = (V2F_C4B_T2F*)malloc(_vertexDataCount * sizeof(V2F_C4B_T2F));
  310. CCASSERT( _vertexData, "CCProgressTimer. Not enough memory");
  311. }
  312. updateColor();
  313. if (!sameIndexCount) {
  314. // First we populate the array with the _midpoint, then all
  315. // vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint
  316. _vertexData[0].texCoords = textureCoordFromAlphaPoint(_midpoint);
  317. _vertexData[0].vertices = vertexFromAlphaPoint(_midpoint);
  318. _vertexData[1].texCoords = textureCoordFromAlphaPoint(topMid);
  319. _vertexData[1].vertices = vertexFromAlphaPoint(topMid);
  320. for(int i = 0; i < index; ++i){
  321. Vec2 alphaPoint = boundaryTexCoord(i);
  322. _vertexData[i+2].texCoords = textureCoordFromAlphaPoint(alphaPoint);
  323. _vertexData[i+2].vertices = vertexFromAlphaPoint(alphaPoint);
  324. }
  325. }
  326. // hitpoint will go last
  327. _vertexData[_vertexDataCount - 1].texCoords = textureCoordFromAlphaPoint(hit);
  328. _vertexData[_vertexDataCount - 1].vertices = vertexFromAlphaPoint(hit);
  329. }
  330. ///
  331. // Update does the work of mapping the texture onto the triangles for the bar
  332. // It now doesn't occur the cost of free/alloc data every update cycle.
  333. // It also only changes the percentage point but no other points if they have not
  334. // been modified.
  335. //
  336. // It now deals with flipped texture. If you run into this problem, just use the
  337. // sprite property and enable the methods flipX, flipY.
  338. ///
  339. void ProgressTimer::updateBar(void)
  340. {
  341. if (!_sprite) {
  342. return;
  343. }
  344. float alpha = _percentage / 100.0f;
  345. Vec2 alphaOffset = Vec2(1.0f * (1.0f - _barChangeRate.x) + alpha * _barChangeRate.x, 1.0f * (1.0f - _barChangeRate.y) + alpha * _barChangeRate.y) * 0.5f;
  346. Vec2 min = _midpoint - alphaOffset;
  347. Vec2 max = _midpoint + alphaOffset;
  348. if (min.x < 0.f) {
  349. max.x += -min.x;
  350. min.x = 0.f;
  351. }
  352. if (max.x > 1.f) {
  353. min.x -= max.x - 1.f;
  354. max.x = 1.f;
  355. }
  356. if (min.y < 0.f) {
  357. max.y += -min.y;
  358. min.y = 0.f;
  359. }
  360. if (max.y > 1.f) {
  361. min.y -= max.y - 1.f;
  362. max.y = 1.f;
  363. }
  364. if (!_reverseDirection) {
  365. if(!_vertexData) {
  366. _vertexDataCount = 4;
  367. _vertexData = (V2F_C4B_T2F*)malloc(_vertexDataCount * sizeof(V2F_C4B_T2F));
  368. CCASSERT( _vertexData, "CCProgressTimer. Not enough memory");
  369. }
  370. // TOPLEFT
  371. _vertexData[0].texCoords = textureCoordFromAlphaPoint(Vec2(min.x,max.y));
  372. _vertexData[0].vertices = vertexFromAlphaPoint(Vec2(min.x,max.y));
  373. // BOTLEFT
  374. _vertexData[1].texCoords = textureCoordFromAlphaPoint(Vec2(min.x,min.y));
  375. _vertexData[1].vertices = vertexFromAlphaPoint(Vec2(min.x,min.y));
  376. // TOPRIGHT
  377. _vertexData[2].texCoords = textureCoordFromAlphaPoint(Vec2(max.x,max.y));
  378. _vertexData[2].vertices = vertexFromAlphaPoint(Vec2(max.x,max.y));
  379. // BOTRIGHT
  380. _vertexData[3].texCoords = textureCoordFromAlphaPoint(Vec2(max.x,min.y));
  381. _vertexData[3].vertices = vertexFromAlphaPoint(Vec2(max.x,min.y));
  382. } else {
  383. if(!_vertexData) {
  384. _vertexDataCount = 8;
  385. _vertexData = (V2F_C4B_T2F*)malloc(_vertexDataCount * sizeof(V2F_C4B_T2F));
  386. CCASSERT( _vertexData, "CCProgressTimer. Not enough memory");
  387. // TOPLEFT 1
  388. _vertexData[0].texCoords = textureCoordFromAlphaPoint(Vec2(0,1));
  389. _vertexData[0].vertices = vertexFromAlphaPoint(Vec2(0,1));
  390. // BOTLEFT 1
  391. _vertexData[1].texCoords = textureCoordFromAlphaPoint(Vec2(0,0));
  392. _vertexData[1].vertices = vertexFromAlphaPoint(Vec2(0,0));
  393. // TOPRIGHT 2
  394. _vertexData[6].texCoords = textureCoordFromAlphaPoint(Vec2(1,1));
  395. _vertexData[6].vertices = vertexFromAlphaPoint(Vec2(1,1));
  396. // BOTRIGHT 2
  397. _vertexData[7].texCoords = textureCoordFromAlphaPoint(Vec2(1,0));
  398. _vertexData[7].vertices = vertexFromAlphaPoint(Vec2(1,0));
  399. }
  400. // TOPRIGHT 1
  401. _vertexData[2].texCoords = textureCoordFromAlphaPoint(Vec2(min.x,max.y));
  402. _vertexData[2].vertices = vertexFromAlphaPoint(Vec2(min.x,max.y));
  403. // BOTRIGHT 1
  404. _vertexData[3].texCoords = textureCoordFromAlphaPoint(Vec2(min.x,min.y));
  405. _vertexData[3].vertices = vertexFromAlphaPoint(Vec2(min.x,min.y));
  406. // TOPLEFT 2
  407. _vertexData[4].texCoords = textureCoordFromAlphaPoint(Vec2(max.x,max.y));
  408. _vertexData[4].vertices = vertexFromAlphaPoint(Vec2(max.x,max.y));
  409. // BOTLEFT 2
  410. _vertexData[5].texCoords = textureCoordFromAlphaPoint(Vec2(max.x,min.y));
  411. _vertexData[5].vertices = vertexFromAlphaPoint(Vec2(max.x,min.y));
  412. }
  413. updateColor();
  414. }
  415. Vec2 ProgressTimer::boundaryTexCoord(char index)
  416. {
  417. if (index < kProgressTextureCoordsCount) {
  418. if (_reverseDirection) {
  419. return Vec2((kProgressTextureCoords>>(7-(index<<1)))&1,(kProgressTextureCoords>>(7-((index<<1)+1)))&1);
  420. } else {
  421. return Vec2((kProgressTextureCoords>>((index<<1)+1))&1,(kProgressTextureCoords>>(index<<1))&1);
  422. }
  423. }
  424. return Vec2::ZERO;
  425. }
  426. void ProgressTimer::onDraw(const Mat4 &transform, uint32_t /*flags*/)
  427. {
  428. getGLProgram()->use();
  429. getGLProgram()->setUniformsForBuiltins(transform);
  430. GL::blendFunc( _sprite->getBlendFunc().src, _sprite->getBlendFunc().dst );
  431. GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX );
  432. GL::bindTexture2D( _sprite->getTexture() );
  433. glVertexAttribPointer( GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(_vertexData[0]) , &_vertexData[0].vertices);
  434. glVertexAttribPointer( GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, sizeof(_vertexData[0]), &_vertexData[0].texCoords);
  435. glVertexAttribPointer( GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(_vertexData[0]), &_vertexData[0].colors);
  436. if(_type == Type::RADIAL)
  437. {
  438. glDrawArrays(GL_TRIANGLE_FAN, 0, _vertexDataCount);
  439. CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,_vertexDataCount);
  440. }
  441. else if (_type == Type::BAR)
  442. {
  443. if (!_reverseDirection)
  444. {
  445. glDrawArrays(GL_TRIANGLE_STRIP, 0, _vertexDataCount);
  446. CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,_vertexDataCount);
  447. }
  448. else
  449. {
  450. glDrawArrays(GL_TRIANGLE_STRIP, 0, _vertexDataCount/2);
  451. glDrawArrays(GL_TRIANGLE_STRIP, 4, _vertexDataCount/2);
  452. // 2 draw calls
  453. CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(2,_vertexDataCount);
  454. }
  455. }
  456. }
  457. void ProgressTimer::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
  458. {
  459. if( ! _vertexData || ! _sprite)
  460. return;
  461. _customCommand.init(_globalZOrder, transform, flags);
  462. _customCommand.func = CC_CALLBACK_0(ProgressTimer::onDraw, this, transform, flags);
  463. renderer->addCommand(&_customCommand);
  464. }
  465. NS_CC_END