CCProgressTimer.cpp 17 KB

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