CCPURibbonTrail.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /****************************************************************************
  2. Copyright (C) 2013 Henry van Merode. All rights reserved.
  3. Copyright (c) 2015-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  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 "extensions/Particle3D/PU/CCPURibbonTrail.h"
  23. #include "extensions/Particle3D/PU/CCPUParticleSystem3D.h"
  24. #include "base/CCDirector.h"
  25. #include "renderer/CCMeshCommand.h"
  26. #include "renderer/CCRenderer.h"
  27. #include "renderer/CCTextureCache.h"
  28. #include "renderer/CCGLProgramState.h"
  29. #include "renderer/CCGLProgramCache.h"
  30. #include "renderer/CCVertexIndexBuffer.h"
  31. #include "2d/CCCamera.h"
  32. #include "3d/CCSprite3D.h"
  33. NS_CC_BEGIN
  34. PURibbonTrail::PURibbonTrail(const std::string& name, const std::string &texFile, size_t maxElements,
  35. size_t numberOfChains, bool useTextureCoords, bool useColours)
  36. :PUBillboardChain(name, texFile, maxElements, 0, useTextureCoords, useColours, true),
  37. _parentNode(nullptr),
  38. _needTimeUpdate(false)
  39. {
  40. setTrailLength(100);
  41. setNumberOfChains(numberOfChains);
  42. // use V as varying texture coord, so we can use 1D textures to 'smear'
  43. setTextureCoordDirection(TCD_V);
  44. }
  45. //-----------------------------------------------------------------------
  46. PURibbonTrail::~PURibbonTrail()
  47. {
  48. }
  49. //-----------------------------------------------------------------------
  50. void PURibbonTrail::addNode(Node* n)
  51. {
  52. if (_nodeList.size() == _chainCount)
  53. {
  54. CCASSERT(false, " cannot monitor any more nodes, chain count exceeded");
  55. }
  56. //if (n->getListener())
  57. //{
  58. // OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
  59. // mName + " cannot monitor node " + n->getName() + " since it already has a listener.",
  60. // "RibbonTrail::addNode");
  61. //}
  62. // get chain index
  63. size_t chainIndex = _freeChains.back();
  64. _freeChains.pop_back();
  65. _nodeToChainSegment.push_back(chainIndex);
  66. _nodeToSegMap[n] = chainIndex;
  67. // initialise the chain
  68. resetTrail(chainIndex, n);
  69. _nodeList.push_back(n);
  70. //n->setListener(this);
  71. }
  72. //-----------------------------------------------------------------------
  73. size_t PURibbonTrail::getChainIndexForNode(const Node* n)
  74. {
  75. NodeToChainSegmentMap::const_iterator i = _nodeToSegMap.find(n);
  76. if (i == _nodeToSegMap.end())
  77. {
  78. CCASSERT(false, "This node is not being tracked");
  79. }
  80. return i->second;
  81. }
  82. //-----------------------------------------------------------------------
  83. void PURibbonTrail::removeNode(Node* n)
  84. {
  85. NodeList::iterator i = std::find(_nodeList.begin(), _nodeList.end(), n);
  86. if (i != _nodeList.end())
  87. {
  88. // also get matching chain segment
  89. size_t index = std::distance(_nodeList.begin(), i);
  90. IndexVector::iterator mi = _nodeToChainSegment.begin();
  91. std::advance(mi, index);
  92. size_t chainIndex = *mi;
  93. PUBillboardChain::clearChain(chainIndex);
  94. // mark as free now
  95. _freeChains.push_back(chainIndex);
  96. //n->setListener(0);
  97. _nodeList.erase(i);
  98. _nodeToChainSegment.erase(mi);
  99. _nodeToSegMap.erase(_nodeToSegMap.find(n));
  100. }
  101. }
  102. //-----------------------------------------------------------------------
  103. void PURibbonTrail::setTrailLength(float len)
  104. {
  105. _trailLength = len;
  106. _elemLength = _trailLength / _maxElementsPerChain;
  107. _squaredElemLength = _elemLength * _elemLength;
  108. }
  109. //-----------------------------------------------------------------------
  110. void PURibbonTrail::setMaxChainElements(size_t maxElements)
  111. {
  112. PUBillboardChain::setMaxChainElements(maxElements);
  113. _elemLength = _trailLength / _maxElementsPerChain;
  114. _squaredElemLength = _elemLength * _elemLength;
  115. resetAllTrails();
  116. }
  117. //-----------------------------------------------------------------------
  118. void PURibbonTrail::setNumberOfChains(size_t numChains)
  119. {
  120. CCASSERT(numChains >= _nodeList.size(), "Can't shrink the number of chains less than number of tracking nodes");
  121. size_t oldChains = getNumberOfChains();
  122. PUBillboardChain::setNumberOfChains(numChains);
  123. _initialColor.resize(numChains, Vec4::ONE);
  124. _deltaColor.resize(numChains, Vec4::ZERO);
  125. _initialWidth.resize(numChains, 10);
  126. _deltaWidth.resize(numChains, 0);
  127. if (oldChains > numChains)
  128. {
  129. // remove free chains
  130. for (IndexVector::iterator i = _freeChains.begin(); i != _freeChains.end();)
  131. {
  132. if (*i >= numChains)
  133. i = _freeChains.erase(i);
  134. else
  135. ++i;
  136. }
  137. }
  138. else if (oldChains < numChains)
  139. {
  140. // add new chains, at front to preserve previous ordering (pop_back)
  141. for (size_t i = oldChains; i < numChains; ++i)
  142. _freeChains.insert(_freeChains.begin(), i);
  143. }
  144. resetAllTrails();
  145. }
  146. //-----------------------------------------------------------------------
  147. void PURibbonTrail::clearChain(size_t chainIndex)
  148. {
  149. PUBillboardChain::clearChain(chainIndex);
  150. // Reset if we are tracking for this chain
  151. IndexVector::iterator i = std::find(_nodeToChainSegment.begin(), _nodeToChainSegment.end(), chainIndex);
  152. if (i != _nodeToChainSegment.end())
  153. {
  154. size_t nodeIndex = std::distance(_nodeToChainSegment.begin(), i);
  155. resetTrail(*i, _nodeList[nodeIndex]);
  156. }
  157. }
  158. //-----------------------------------------------------------------------
  159. void PURibbonTrail::setInitialColour(size_t chainIndex, const Vec4& col)
  160. {
  161. setInitialColour(chainIndex, col.x, col.y, col.z, col.w);
  162. }
  163. //-----------------------------------------------------------------------
  164. void PURibbonTrail::setInitialColour(size_t chainIndex, float r, float g, float b, float a)
  165. {
  166. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  167. _initialColor[chainIndex].x = r;
  168. _initialColor[chainIndex].y = g;
  169. _initialColor[chainIndex].z = b;
  170. _initialColor[chainIndex].w = a;
  171. }
  172. //-----------------------------------------------------------------------
  173. const Vec4& PURibbonTrail::getInitialColour(size_t chainIndex) const
  174. {
  175. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  176. return _initialColor[chainIndex];
  177. }
  178. //-----------------------------------------------------------------------
  179. void PURibbonTrail::setInitialWidth(size_t chainIndex, float width)
  180. {
  181. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  182. _initialWidth[chainIndex] = width;
  183. }
  184. //-----------------------------------------------------------------------
  185. float PURibbonTrail::getInitialWidth(size_t chainIndex) const
  186. {
  187. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  188. return _initialWidth[chainIndex];
  189. }
  190. //-----------------------------------------------------------------------
  191. void PURibbonTrail::setColourChange(size_t chainIndex, const Vec4& valuePerSecond)
  192. {
  193. setColourChange(chainIndex,
  194. valuePerSecond.x, valuePerSecond.y, valuePerSecond.z, valuePerSecond.w);
  195. }
  196. //-----------------------------------------------------------------------
  197. void PURibbonTrail::setColourChange(size_t chainIndex, float r, float g, float b, float a)
  198. {
  199. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  200. _deltaColor[chainIndex].x = r;
  201. _deltaColor[chainIndex].y = g;
  202. _deltaColor[chainIndex].z = b;
  203. _deltaColor[chainIndex].w = a;
  204. manageController();
  205. }
  206. //-----------------------------------------------------------------------
  207. const Vec4& PURibbonTrail::getColourChange(size_t chainIndex) const
  208. {
  209. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  210. return _deltaColor[chainIndex];
  211. }
  212. //-----------------------------------------------------------------------
  213. void PURibbonTrail::setWidthChange(size_t chainIndex, float widthDeltaPerSecond)
  214. {
  215. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  216. _deltaWidth[chainIndex] = widthDeltaPerSecond;
  217. manageController();
  218. }
  219. //-----------------------------------------------------------------------
  220. float PURibbonTrail::getWidthChange(size_t chainIndex) const
  221. {
  222. CCASSERT(chainIndex < _chainCount, "chainIndex out of bounds");
  223. return _deltaWidth[chainIndex];
  224. }
  225. //-----------------------------------------------------------------------
  226. void PURibbonTrail::manageController(void)
  227. {
  228. _needTimeUpdate = false;
  229. for (size_t i = 0; i < _chainCount; ++i)
  230. {
  231. if (_deltaWidth[i] != 0 || _deltaColor[i] != Vec4::ZERO)
  232. {
  233. _needTimeUpdate = true;
  234. break;
  235. }
  236. }
  237. }
  238. //-----------------------------------------------------------------------
  239. void PURibbonTrail::nodeUpdated(const Node* node)
  240. {
  241. size_t chainIndex = getChainIndexForNode(node);
  242. updateTrail(chainIndex, node);
  243. }
  244. //-----------------------------------------------------------------------
  245. void PURibbonTrail::nodeDestroyed(const Node* node)
  246. {
  247. removeNode(const_cast<Node*>(node));
  248. }
  249. //-----------------------------------------------------------------------
  250. void PURibbonTrail::updateTrail(size_t index, const Node* node)
  251. {
  252. // Repeat this entire process if chain is stretched beyond its natural length
  253. bool done = false;
  254. while (!done)
  255. {
  256. // Node has changed somehow, we're only interested in the derived position
  257. ChainSegment& seg = _chainSegmentList[index];
  258. Element& headElem = _chainElementList[seg.start + seg.head];
  259. size_t nextElemIdx = seg.head + 1;
  260. // wrap
  261. if (nextElemIdx == _maxElementsPerChain)
  262. nextElemIdx = 0;
  263. Element& nextElem = _chainElementList[seg.start + nextElemIdx];
  264. // Vary the head elem, but bake new version if that exceeds element len
  265. Vec3 newPos = node->getPosition3D();
  266. if (_parentNode)
  267. {
  268. // Transform position to ourself space
  269. _parentNode->getWorldToNodeTransform().transformPoint(newPos, &newPos);
  270. }
  271. Vec3 diff = newPos - nextElem.position;
  272. float sqlen = diff.lengthSquared();
  273. if (sqlen >= _squaredElemLength)
  274. {
  275. // Move existing head to mElemLength
  276. Vec3 scaledDiff = diff * (_elemLength / sqrtf(sqlen));
  277. headElem.position = nextElem.position + scaledDiff;
  278. // Add a new element to be the new head
  279. Element newElem( newPos, _initialWidth[index], 0.0f,
  280. _initialColor[index], node->getRotationQuat() );
  281. addChainElement(index, newElem);
  282. // alter diff to represent new head size
  283. diff = newPos - headElem.position;
  284. // check whether another step is needed or not
  285. if (diff.lengthSquared() <= _squaredElemLength)
  286. done = true;
  287. }
  288. else
  289. {
  290. // Extend existing head
  291. headElem.position = newPos;
  292. done = true;
  293. }
  294. // Is this segment full?
  295. if ((seg.tail + 1) % _maxElementsPerChain == seg.head)
  296. {
  297. // If so, shrink tail gradually to match head extension
  298. Element& tailElem = _chainElementList[seg.start + seg.tail];
  299. size_t preTailIdx;
  300. if (seg.tail == 0)
  301. preTailIdx = _maxElementsPerChain - 1;
  302. else
  303. preTailIdx = seg.tail - 1;
  304. Element& preTailElem = _chainElementList[seg.start + preTailIdx];
  305. // Measure tail diff from pretail to tail
  306. Vec3 taildiff = tailElem.position - preTailElem.position;
  307. float taillen = taildiff.length();
  308. if (taillen > 1e-06)
  309. {
  310. float tailsize = _elemLength - diff.length();
  311. taildiff *= tailsize / taillen;
  312. tailElem.position = preTailElem.position + taildiff;
  313. }
  314. }
  315. } // end while
  316. _vertexContentDirty = true;
  317. // Need to dirty the parent node, but can't do it using needUpdate() here
  318. // since we're in the middle of the scene graph update (node listener),
  319. // so re-entrant calls don't work. Queue.
  320. //if (mParentNode)
  321. //{
  322. // Node::queueNeedUpdate(getParentSceneNode());
  323. //}
  324. }
  325. //-----------------------------------------------------------------------
  326. void PURibbonTrail::timeUpdate(float time)
  327. {
  328. // Apply all segment effects
  329. for (size_t s = 0; s < _chainSegmentList.size(); ++s)
  330. {
  331. ChainSegment& seg = _chainSegmentList[s];
  332. if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail)
  333. {
  334. for(size_t e = seg.head + 1;; ++e) // until break
  335. {
  336. e = e % _maxElementsPerChain;
  337. Element& elem = _chainElementList[seg.start + e];
  338. elem.width = elem.width - (time * _deltaWidth[s]);
  339. elem.width = 0.0f < elem.width? elem.width: 0.0f;
  340. elem.color = elem.color - (_deltaColor[s] * time);
  341. elem.color.clamp(Vec4(0.0f, 0.0f, 0.0f, 0.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f));
  342. if (e == seg.tail)
  343. break;
  344. }
  345. }
  346. }
  347. }
  348. //-----------------------------------------------------------------------
  349. void PURibbonTrail::resetTrail(size_t index, const Node* node)
  350. {
  351. assert(index < _chainCount);
  352. ChainSegment& seg = _chainSegmentList[index];
  353. // set up this segment
  354. seg.head = seg.tail = SEGMENT_EMPTY;
  355. // Create new element, v coord is always 0.0f
  356. // need to convert to take parent node's position into account
  357. Vec3 position = node->getPosition3D();
  358. if (_parentNode)
  359. {
  360. // Transform position to ourself space
  361. _parentNode->getWorldToNodeTransform().transformPoint(position, &position);
  362. }
  363. Element e(position,
  364. _initialWidth[index], 0.0f, _initialColor[index], node->getRotationQuat());
  365. // Add the start position
  366. addChainElement(index, e);
  367. // Add another on the same spot, this will extend
  368. addChainElement(index, e);
  369. }
  370. //-----------------------------------------------------------------------
  371. void PURibbonTrail::resetAllTrails(void)
  372. {
  373. for (size_t i = 0; i < _nodeList.size(); ++i)
  374. {
  375. resetTrail(i, _nodeList[i]);
  376. }
  377. }
  378. void PURibbonTrail::update( float deltaTime )
  379. {
  380. if (_needTimeUpdate){
  381. static float lastUpdateTime = 0.0f;
  382. if (0.5f < lastUpdateTime){
  383. timeUpdate(deltaTime);
  384. lastUpdateTime = 0.0f;
  385. }
  386. lastUpdateTime += deltaTime;
  387. }
  388. for (auto iter : _nodeToSegMap){
  389. updateTrail(iter.second, iter.first);
  390. }
  391. }
  392. NS_CC_END