CCFastTMXLayer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2010-2012 cocos2d-x.org
  4. Copyright (c) 2011 Zynga Inc.
  5. Copyright (c) 2013-2017 Chukong Technologies Inc.
  6. Copyright (c) 2011 HKASoftware
  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. /*
  25. Original rewrite of TMXLayer was based on HKTMXTiledMap by HKASoftware http://hkasoftware.com
  26. Further info: http://www.cocos2d-iphone.org/forums/topic/hktmxtiledmap/
  27. It was rewritten again, and only a small part of the original HK ideas/code remains in this implementation
  28. */
  29. #include "2d/CCFastTMXLayer.h"
  30. #include "2d/CCFastTMXTiledMap.h"
  31. #include "2d/CCSprite.h"
  32. #include "2d/CCCamera.h"
  33. #include "renderer/CCTextureCache.h"
  34. #include "renderer/CCGLProgramCache.h"
  35. #include "renderer/ccGLStateCache.h"
  36. #include "renderer/CCRenderer.h"
  37. #include "renderer/CCVertexIndexBuffer.h"
  38. #include "base/CCDirector.h"
  39. #include "base/ccUTF8.h"
  40. NS_CC_BEGIN
  41. namespace experimental {
  42. const int TMXLayer::FAST_TMX_ORIENTATION_ORTHO = 0;
  43. const int TMXLayer::FAST_TMX_ORIENTATION_HEX = 1;
  44. const int TMXLayer::FAST_TMX_ORIENTATION_ISO = 2;
  45. // FastTMXLayer - init & alloc & dealloc
  46. TMXLayer * TMXLayer::create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
  47. {
  48. TMXLayer *ret = new (std::nothrow) TMXLayer();
  49. if (ret->initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo))
  50. {
  51. ret->autorelease();
  52. return ret;
  53. }
  54. CC_SAFE_DELETE(ret);
  55. return nullptr;
  56. }
  57. bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
  58. {
  59. if( tilesetInfo )
  60. {
  61. _texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage);
  62. _texture->retain();
  63. }
  64. // layerInfo
  65. _layerName = layerInfo->_name;
  66. _layerSize = layerInfo->_layerSize;
  67. _tiles = layerInfo->_tiles;
  68. _quadsDirty = true;
  69. setOpacity( layerInfo->_opacity );
  70. setProperties(layerInfo->getProperties());
  71. // tilesetInfo
  72. _tileSet = tilesetInfo;
  73. CC_SAFE_RETAIN(_tileSet);
  74. // mapInfo
  75. _mapTileSize = mapInfo->getTileSize();
  76. _layerOrientation = mapInfo->getOrientation();
  77. // offset (after layer orientation is set);
  78. Vec2 offset = this->calculateLayerOffset(layerInfo->_offset);
  79. this->setPosition(CC_POINT_PIXELS_TO_POINTS(offset));
  80. this->setContentSize(CC_SIZE_PIXELS_TO_POINTS(Size(_layerSize.width * _mapTileSize.width, _layerSize.height * _mapTileSize.height)));
  81. this->tileToNodeTransform();
  82. // shader, and other stuff
  83. setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
  84. _useAutomaticVertexZ = false;
  85. _vertexZvalue = 0;
  86. return true;
  87. }
  88. TMXLayer::TMXLayer()
  89. : _layerName("")
  90. , _layerSize(Size::ZERO)
  91. , _mapTileSize(Size::ZERO)
  92. , _tiles(nullptr)
  93. , _tileSet(nullptr)
  94. , _layerOrientation(FAST_TMX_ORIENTATION_ORTHO)
  95. , _texture(nullptr)
  96. , _vertexZvalue(0)
  97. , _useAutomaticVertexZ(false)
  98. , _quadsDirty(true)
  99. , _dirty(true)
  100. , _vertexBuffer(nullptr)
  101. , _vData(nullptr)
  102. , _indexBuffer(nullptr)
  103. {
  104. }
  105. TMXLayer::~TMXLayer()
  106. {
  107. CC_SAFE_RELEASE(_tileSet);
  108. CC_SAFE_RELEASE(_texture);
  109. CC_SAFE_FREE(_tiles);
  110. CC_SAFE_RELEASE(_vData);
  111. CC_SAFE_RELEASE(_vertexBuffer);
  112. CC_SAFE_RELEASE(_indexBuffer);
  113. }
  114. void TMXLayer::draw(Renderer *renderer, const Mat4& transform, uint32_t flags)
  115. {
  116. updateTotalQuads();
  117. bool isViewProjectionUpdated = true;
  118. auto visitingCamera = Camera::getVisitingCamera();
  119. auto defaultCamera = Camera::getDefaultCamera();
  120. if (visitingCamera == defaultCamera) {
  121. isViewProjectionUpdated = visitingCamera->isViewProjectionUpdated();
  122. }
  123. if( flags != 0 || _dirty || _quadsDirty || isViewProjectionUpdated)
  124. {
  125. Size s = Director::getInstance()->getVisibleSize();
  126. auto rect = Rect(Camera::getVisitingCamera()->getPositionX() - s.width * 0.5f,
  127. Camera::getVisitingCamera()->getPositionY() - s.height * 0.5f,
  128. s.width,
  129. s.height);
  130. Mat4 inv = transform;
  131. inv.inverse();
  132. rect = RectApplyTransform(rect, inv);
  133. updateTiles(rect);
  134. updateIndexBuffer();
  135. updatePrimitives();
  136. _dirty = false;
  137. }
  138. if(_renderCommands.size() < static_cast<size_t>(_primitives.size()))
  139. {
  140. _renderCommands.resize(_primitives.size());
  141. }
  142. int index = 0;
  143. for(const auto& iter : _primitives)
  144. {
  145. if(iter.second->getCount() > 0)
  146. {
  147. auto& cmd = _renderCommands[index++];
  148. auto blendfunc = _texture->hasPremultipliedAlpha() ? BlendFunc::ALPHA_PREMULTIPLIED : BlendFunc::ALPHA_NON_PREMULTIPLIED;
  149. cmd.init(iter.first, _texture->getName(), getGLProgramState(), blendfunc, iter.second, _modelViewTransform, flags);
  150. renderer->addCommand(&cmd);
  151. }
  152. }
  153. }
  154. void TMXLayer::onDraw(Primitive *primitive)
  155. {
  156. GL::bindTexture2D(_texture->getName());
  157. getGLProgramState()->apply(_modelViewTransform);
  158. GL::bindVAO(0);
  159. primitive->draw();
  160. glBindBuffer(GL_ARRAY_BUFFER, 0);
  161. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  162. CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, primitive->getCount() * 4);
  163. }
  164. void TMXLayer::updateTiles(const Rect& culledRect)
  165. {
  166. Rect visibleTiles = Rect(culledRect.origin, culledRect.size * Director::getInstance()->getContentScaleFactor());
  167. Size mapTileSize = CC_SIZE_PIXELS_TO_POINTS(_mapTileSize);
  168. Size tileSize = CC_SIZE_PIXELS_TO_POINTS(_tileSet->_tileSize);
  169. Mat4 nodeToTileTransform = _tileToNodeTransform.getInversed();
  170. //transform to tile
  171. visibleTiles = RectApplyTransform(visibleTiles, nodeToTileTransform);
  172. // tile coordinate is upside-down, so we need to make the tile coordinate use top-left for the start point.
  173. visibleTiles.origin.y += 1;
  174. // if x=0.7, width=9.5, we need to draw number 0~10 of tiles, and so is height.
  175. visibleTiles.size.width = ceil(visibleTiles.origin.x + visibleTiles.size.width) - floor(visibleTiles.origin.x);
  176. visibleTiles.size.height = ceil(visibleTiles.origin.y + visibleTiles.size.height) - floor(visibleTiles.origin.y);
  177. visibleTiles.origin.x = floor(visibleTiles.origin.x);
  178. visibleTiles.origin.y = floor(visibleTiles.origin.y);
  179. // for the bigger tiles.
  180. int tilesOverX = 0;
  181. int tilesOverY = 0;
  182. // for diagonal orientation tiles
  183. float tileSizeMax = std::max(tileSize.width, tileSize.height);
  184. if (_layerOrientation == FAST_TMX_ORIENTATION_ORTHO)
  185. {
  186. tilesOverX = ceil(tileSizeMax / mapTileSize.width) - 1;
  187. tilesOverY = ceil(tileSizeMax / mapTileSize.height) - 1;
  188. if (tilesOverX < 0) tilesOverX = 0;
  189. if (tilesOverY < 0) tilesOverY = 0;
  190. }
  191. else if(_layerOrientation == FAST_TMX_ORIENTATION_ISO)
  192. {
  193. Rect overTileRect(0, 0, tileSizeMax - mapTileSize.width, tileSizeMax - mapTileSize.height);
  194. if (overTileRect.size.width < 0) overTileRect.size.width = 0;
  195. if (overTileRect.size.height < 0) overTileRect.size.height = 0;
  196. overTileRect = RectApplyTransform(overTileRect, nodeToTileTransform);
  197. tilesOverX = ceil(overTileRect.origin.x + overTileRect.size.width) - floor(overTileRect.origin.x);
  198. tilesOverY = ceil(overTileRect.origin.y + overTileRect.size.height) - floor(overTileRect.origin.y);
  199. }
  200. else
  201. {
  202. //do nothing, do not support
  203. //CCASSERT(0, "TMX invalid value");
  204. }
  205. _indicesVertexZNumber.clear();
  206. for(const auto& iter : _indicesVertexZOffsets)
  207. {
  208. _indicesVertexZNumber[iter.first] = iter.second;
  209. }
  210. int yBegin = std::max(0.f,visibleTiles.origin.y - tilesOverY);
  211. int yEnd = std::min(_layerSize.height,visibleTiles.origin.y + visibleTiles.size.height + tilesOverY);
  212. int xBegin = std::max(0.f,visibleTiles.origin.x - tilesOverX);
  213. int xEnd = std::min(_layerSize.width,visibleTiles.origin.x + visibleTiles.size.width + tilesOverX);
  214. for (int y = yBegin; y < yEnd; ++y)
  215. {
  216. for (int x = xBegin; x < xEnd; ++x)
  217. {
  218. int tileIndex = getTileIndexByPos(x, y);
  219. if(_tiles[tileIndex] == 0) continue;
  220. int vertexZ = getVertexZForPos(Vec2(x,y));
  221. auto iter = _indicesVertexZNumber.find(vertexZ);
  222. int offset = iter->second;
  223. iter->second++;
  224. int quadIndex = _tileToQuadIndex[tileIndex];
  225. CC_ASSERT(-1 != quadIndex);
  226. _indices[6 * offset + 0] = quadIndex * 4 + 0;
  227. _indices[6 * offset + 1] = quadIndex * 4 + 1;
  228. _indices[6 * offset + 2] = quadIndex * 4 + 2;
  229. _indices[6 * offset + 3] = quadIndex * 4 + 3;
  230. _indices[6 * offset + 4] = quadIndex * 4 + 2;
  231. _indices[6 * offset + 5] = quadIndex * 4 + 1;
  232. } // for x
  233. } // for y
  234. for(const auto& iter : _indicesVertexZOffsets)
  235. {
  236. _indicesVertexZNumber[iter.first] -= iter.second;
  237. if(_indicesVertexZNumber[iter.first] == 0)
  238. {
  239. _indicesVertexZNumber.erase(iter.first);
  240. }
  241. }
  242. }
  243. void TMXLayer::updateVertexBuffer()
  244. {
  245. GL::bindVAO(0);
  246. if(nullptr == _vData)
  247. {
  248. _vertexBuffer = VertexBuffer::create(sizeof(V3F_C4B_T2F), (int)_totalQuads.size() * 4);
  249. _vData = VertexData::create();
  250. _vData->setStream(_vertexBuffer, VertexStreamAttribute(0, GLProgram::VERTEX_ATTRIB_POSITION, GL_FLOAT, 3));
  251. _vData->setStream(_vertexBuffer, VertexStreamAttribute(offsetof(V3F_C4B_T2F, colors), GLProgram::VERTEX_ATTRIB_COLOR, GL_UNSIGNED_BYTE, 4, true));
  252. _vData->setStream(_vertexBuffer, VertexStreamAttribute(offsetof(V3F_C4B_T2F, texCoords), GLProgram::VERTEX_ATTRIB_TEX_COORD, GL_FLOAT, 2));
  253. CC_SAFE_RETAIN(_vData);
  254. CC_SAFE_RETAIN(_vertexBuffer);
  255. }
  256. if(_vertexBuffer)
  257. {
  258. _vertexBuffer->updateVertices((void*)&_totalQuads[0], (int)_totalQuads.size() * 4, 0);
  259. }
  260. }
  261. void TMXLayer::updateIndexBuffer()
  262. {
  263. if(nullptr == _indexBuffer)
  264. {
  265. #ifdef CC_FAST_TILEMAP_32_BIT_INDICES
  266. _indexBuffer = IndexBuffer::create(IndexBuffer::IndexType::INDEX_TYPE_UINT_32, (int)_indices.size());
  267. #else
  268. _indexBuffer = IndexBuffer::create(IndexBuffer::IndexType::INDEX_TYPE_SHORT_16, (int)_indices.size());
  269. #endif
  270. CC_SAFE_RETAIN(_indexBuffer);
  271. }
  272. _indexBuffer->updateIndices(&_indices[0], (int)_indices.size(), 0);
  273. }
  274. // FastTMXLayer - setup Tiles
  275. void TMXLayer::setupTiles()
  276. {
  277. // Optimization: quick hack that sets the image size on the tileset
  278. _tileSet->_imageSize = _texture->getContentSizeInPixels();
  279. // By default all the tiles are aliased
  280. // pros: easier to render
  281. // cons: difficult to scale / rotate / etc.
  282. _texture->setAliasTexParameters();
  283. //CFByteOrder o = CFByteOrderGetCurrent();
  284. // Parse cocos2d properties
  285. this->parseInternalProperties();
  286. Size screenSize = Director::getInstance()->getWinSize();
  287. switch (_layerOrientation)
  288. {
  289. case FAST_TMX_ORIENTATION_ORTHO:
  290. _screenGridSize.width = ceil(screenSize.width / _mapTileSize.width) + 1;
  291. _screenGridSize.height = ceil(screenSize.height / _mapTileSize.height) + 1;
  292. // tiles could be bigger than the grid, add additional rows if needed
  293. _screenGridSize.height += _tileSet->_tileSize.height / _mapTileSize.height;
  294. break;
  295. case FAST_TMX_ORIENTATION_ISO:
  296. _screenGridSize.width = ceil(screenSize.width / _mapTileSize.width) + 2;
  297. _screenGridSize.height = ceil(screenSize.height / (_mapTileSize.height/2)) + 4;
  298. break;
  299. case FAST_TMX_ORIENTATION_HEX:
  300. default:
  301. CCLOGERROR("FastTMX does not support type %d", _layerOrientation);
  302. break;
  303. }
  304. _screenTileCount = _screenGridSize.width * _screenGridSize.height;
  305. }
  306. Mat4 TMXLayer::tileToNodeTransform()
  307. {
  308. float w = _mapTileSize.width / CC_CONTENT_SCALE_FACTOR();
  309. float h = _mapTileSize.height / CC_CONTENT_SCALE_FACTOR();
  310. float offY = (_layerSize.height - 1) * h;
  311. switch(_layerOrientation)
  312. {
  313. case FAST_TMX_ORIENTATION_ORTHO:
  314. {
  315. _tileToNodeTransform = Mat4
  316. (
  317. w, 0.0f, 0.0f, 0.0f,
  318. 0.0f, -h, 0.0f, offY,
  319. 0.0f, 0.0f, 1.0f, 0.0f,
  320. 0.0f, 0.0, 0.0f, 1.0f
  321. );
  322. return _tileToNodeTransform;
  323. }
  324. case FAST_TMX_ORIENTATION_ISO:
  325. {
  326. float offX = (_layerSize.width - 1) * w / 2;
  327. _tileToNodeTransform = Mat4
  328. (
  329. w/2, -w/2, 0.0f, offX,
  330. -h/2, -h/2, 0.0f, offY,
  331. 0.0f, 0.0f, 1.0f, 0.0f,
  332. 0.0f, 0.0f, 0.0f, 1.0f
  333. );
  334. return _tileToNodeTransform;
  335. }
  336. case FAST_TMX_ORIENTATION_HEX:
  337. {
  338. _tileToNodeTransform = Mat4
  339. (
  340. h * sqrtf(0.75), 0, 0, 0,
  341. -h/2, -h, 0, offY,
  342. 0, 0, 1, 0,
  343. 0, 0, 0, 1
  344. );
  345. return _tileToNodeTransform;
  346. }
  347. default:
  348. {
  349. _tileToNodeTransform = Mat4::IDENTITY;
  350. return _tileToNodeTransform;
  351. }
  352. }
  353. }
  354. void TMXLayer::updatePrimitives()
  355. {
  356. for(const auto& iter : _indicesVertexZNumber)
  357. {
  358. int start = _indicesVertexZOffsets.at(iter.first);
  359. auto primitiveIter= _primitives.find(iter.first);
  360. if(primitiveIter == _primitives.end())
  361. {
  362. auto primitive = Primitive::create(_vData, _indexBuffer, GL_TRIANGLES);
  363. primitive->setCount(iter.second * 6);
  364. primitive->setStart(start * 6);
  365. _primitives.insert(iter.first, primitive);
  366. }
  367. else
  368. {
  369. primitiveIter->second->setCount(iter.second * 6);
  370. primitiveIter->second->setStart(start * 6);
  371. }
  372. }
  373. }
  374. void TMXLayer::updateTotalQuads()
  375. {
  376. if(_quadsDirty)
  377. {
  378. Size tileSize = CC_SIZE_PIXELS_TO_POINTS(_tileSet->_tileSize);
  379. Size texSize = _tileSet->_imageSize;
  380. _tileToQuadIndex.clear();
  381. _totalQuads.resize(int(_layerSize.width * _layerSize.height));
  382. _indices.resize(6 * int(_layerSize.width * _layerSize.height));
  383. _tileToQuadIndex.resize(int(_layerSize.width * _layerSize.height),-1);
  384. _indicesVertexZOffsets.clear();
  385. int quadIndex = 0;
  386. for(int y = 0; y < _layerSize.height; ++y)
  387. {
  388. for(int x =0; x < _layerSize.width; ++x)
  389. {
  390. int tileIndex = getTileIndexByPos(x, y);
  391. int tileGID = _tiles[tileIndex];
  392. if(tileGID == 0) continue;
  393. _tileToQuadIndex[tileIndex] = quadIndex;
  394. auto& quad = _totalQuads[quadIndex];
  395. Vec3 nodePos(float(x), float(y), 0);
  396. _tileToNodeTransform.transformPoint(&nodePos);
  397. float left, right, top, bottom, z;
  398. z = getVertexZForPos(Vec2(x, y));
  399. auto iter = _indicesVertexZOffsets.find(z);
  400. if(iter == _indicesVertexZOffsets.end())
  401. {
  402. _indicesVertexZOffsets[z] = 1;
  403. }
  404. else
  405. {
  406. iter->second++;
  407. }
  408. // vertices
  409. if (tileGID & kTMXTileDiagonalFlag)
  410. {
  411. left = nodePos.x;
  412. right = nodePos.x + tileSize.height;
  413. bottom = nodePos.y + tileSize.width;
  414. top = nodePos.y;
  415. }
  416. else
  417. {
  418. left = nodePos.x;
  419. right = nodePos.x + tileSize.width;
  420. bottom = nodePos.y + tileSize.height;
  421. top = nodePos.y;
  422. }
  423. if(tileGID & kTMXTileVerticalFlag)
  424. std::swap(top, bottom);
  425. if(tileGID & kTMXTileHorizontalFlag)
  426. std::swap(left, right);
  427. if(tileGID & kTMXTileDiagonalFlag)
  428. {
  429. // FIXME: not working correctly
  430. quad.bl.vertices.x = left;
  431. quad.bl.vertices.y = bottom;
  432. quad.bl.vertices.z = z;
  433. quad.br.vertices.x = left;
  434. quad.br.vertices.y = top;
  435. quad.br.vertices.z = z;
  436. quad.tl.vertices.x = right;
  437. quad.tl.vertices.y = bottom;
  438. quad.tl.vertices.z = z;
  439. quad.tr.vertices.x = right;
  440. quad.tr.vertices.y = top;
  441. quad.tr.vertices.z = z;
  442. }
  443. else
  444. {
  445. quad.bl.vertices.x = left;
  446. quad.bl.vertices.y = bottom;
  447. quad.bl.vertices.z = z;
  448. quad.br.vertices.x = right;
  449. quad.br.vertices.y = bottom;
  450. quad.br.vertices.z = z;
  451. quad.tl.vertices.x = left;
  452. quad.tl.vertices.y = top;
  453. quad.tl.vertices.z = z;
  454. quad.tr.vertices.x = right;
  455. quad.tr.vertices.y = top;
  456. quad.tr.vertices.z = z;
  457. }
  458. // texcoords
  459. Rect tileTexture = _tileSet->getRectForGID(tileGID);
  460. left = (tileTexture.origin.x / texSize.width);
  461. right = left + (tileTexture.size.width / texSize.width);
  462. bottom = (tileTexture.origin.y / texSize.height);
  463. top = bottom + (tileTexture.size.height / texSize.height);
  464. quad.bl.texCoords.u = left;
  465. quad.bl.texCoords.v = bottom;
  466. quad.br.texCoords.u = right;
  467. quad.br.texCoords.v = bottom;
  468. quad.tl.texCoords.u = left;
  469. quad.tl.texCoords.v = top;
  470. quad.tr.texCoords.u = right;
  471. quad.tr.texCoords.v = top;
  472. quad.bl.colors = Color4B::WHITE;
  473. quad.br.colors = Color4B::WHITE;
  474. quad.tl.colors = Color4B::WHITE;
  475. quad.tr.colors = Color4B::WHITE;
  476. ++quadIndex;
  477. }
  478. }
  479. int offset = 0;
  480. for(auto& vertexZOffset : _indicesVertexZOffsets)
  481. {
  482. std::swap(offset, vertexZOffset.second);
  483. offset += vertexZOffset.second;
  484. }
  485. updateVertexBuffer();
  486. _quadsDirty = false;
  487. }
  488. }
  489. // removing / getting tiles
  490. Sprite* TMXLayer::getTileAt(const Vec2& tileCoordinate)
  491. {
  492. CCASSERT( tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
  493. CCASSERT( _tiles, "TMXLayer: the tiles map has been released");
  494. Sprite *tile = nullptr;
  495. int gid = this->getTileGIDAt(tileCoordinate);
  496. // if GID == 0, then no tile is present
  497. if( gid ) {
  498. int index = (int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width;
  499. auto it = _spriteContainer.find(index);
  500. if (it != _spriteContainer.end())
  501. {
  502. tile = it->second.first;
  503. }
  504. else
  505. {
  506. // tile not created yet. create it
  507. Rect rect = _tileSet->getRectForGID(gid);
  508. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  509. tile = Sprite::createWithTexture(_texture, rect);
  510. Vec2 p = this->getPositionAt(tileCoordinate);
  511. tile->setAnchorPoint(Vec2::ZERO);
  512. tile->setPosition(p);
  513. tile->setPositionZ((float)getVertexZForPos(tileCoordinate));
  514. tile->setOpacity(this->getOpacity());
  515. tile->setTag(index);
  516. this->addChild(tile, index);
  517. _spriteContainer.insert(std::pair<int, std::pair<Sprite*, int> >(index, std::pair<Sprite*, int>(tile, gid)));
  518. // tile is converted to sprite.
  519. setFlaggedTileGIDByIndex(index, 0);
  520. }
  521. }
  522. return tile;
  523. }
  524. int TMXLayer::getTileGIDAt(const Vec2& tileCoordinate, TMXTileFlags* flags/* = nullptr*/)
  525. {
  526. CCASSERT(tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
  527. CCASSERT(_tiles, "TMXLayer: the tiles map has been released");
  528. int idx = static_cast<int>(((int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width));
  529. // Bits on the far end of the 32-bit global tile ID are used for tile flags
  530. int tile = _tiles[idx];
  531. auto it = _spriteContainer.find(idx);
  532. // converted to sprite.
  533. if (tile == 0 && it != _spriteContainer.end())
  534. {
  535. tile = it->second.second;
  536. }
  537. // issue1264, flipped tiles can be changed dynamically
  538. if (flags)
  539. {
  540. *flags = (TMXTileFlags)(tile & kTMXFlipedAll);
  541. }
  542. return (tile & kTMXFlippedMask);
  543. }
  544. Vec2 TMXLayer::getPositionAt(const Vec2& pos)
  545. {
  546. return PointApplyTransform(pos, _tileToNodeTransform);
  547. }
  548. int TMXLayer::getVertexZForPos(const Vec2& pos)
  549. {
  550. int ret = 0;
  551. int maxVal = 0;
  552. if (_useAutomaticVertexZ)
  553. {
  554. switch (_layerOrientation)
  555. {
  556. case FAST_TMX_ORIENTATION_ISO:
  557. maxVal = static_cast<int>(_layerSize.width + _layerSize.height);
  558. ret = static_cast<int>(-(maxVal - (pos.x + pos.y)));
  559. break;
  560. case FAST_TMX_ORIENTATION_ORTHO:
  561. ret = static_cast<int>(-(_layerSize.height-pos.y));
  562. break;
  563. case FAST_TMX_ORIENTATION_HEX:
  564. CCASSERT(0, "TMX Hexa vertexZ not supported");
  565. break;
  566. default:
  567. CCASSERT(0, "TMX invalid value");
  568. break;
  569. }
  570. }
  571. else
  572. {
  573. ret = _vertexZvalue;
  574. }
  575. return ret;
  576. }
  577. void TMXLayer::removeTileAt(const Vec2& tileCoordinate)
  578. {
  579. CCASSERT( tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
  580. int gid = this->getTileGIDAt(tileCoordinate);
  581. if( gid ) {
  582. int z = (int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width;
  583. // remove tile from GID map
  584. setFlaggedTileGIDByIndex(z, 0);
  585. // remove it from sprites
  586. auto it = _spriteContainer.find(z);
  587. if (it != _spriteContainer.end())
  588. {
  589. this->removeChild(it->second.first);
  590. }
  591. }
  592. }
  593. void TMXLayer::setFlaggedTileGIDByIndex(int index, uint32_t gid)
  594. {
  595. if(gid == _tiles[index]) return;
  596. _tiles[index] = gid;
  597. _quadsDirty = true;
  598. _dirty = true;
  599. }
  600. void TMXLayer::removeChild(Node* node, bool cleanup)
  601. {
  602. int tag = node->getTag();
  603. auto it = _spriteContainer.find(tag);
  604. if (it != _spriteContainer.end() && it->second.first == node)
  605. {
  606. _spriteContainer.erase(it);
  607. }
  608. Node::removeChild(node, cleanup);
  609. }
  610. // TMXLayer - Properties
  611. Value TMXLayer::getProperty(const std::string& propertyName) const
  612. {
  613. if (_properties.find(propertyName) != _properties.end())
  614. return _properties.at(propertyName);
  615. return Value();
  616. }
  617. void TMXLayer::parseInternalProperties()
  618. {
  619. auto vertexz = getProperty("cc_vertexz");
  620. if (vertexz.isNull()) return;
  621. std::string vertexZStr = vertexz.asString();
  622. // If "automatic" is on, then parse the "cc_alpha_func" too
  623. if (vertexZStr == "automatic")
  624. {
  625. _useAutomaticVertexZ = true;
  626. auto alphaFuncVal = getProperty("cc_alpha_func");
  627. float alphaFuncValue = alphaFuncVal.asFloat();
  628. setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST));
  629. GLint alphaValueLocation = glGetUniformLocation(getGLProgram()->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);
  630. // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison
  631. // use shader program to set uniform
  632. getGLProgram()->use();
  633. getGLProgram()->setUniformLocationWith1f(alphaValueLocation, alphaFuncValue);
  634. CHECK_GL_ERROR_DEBUG();
  635. }
  636. else
  637. {
  638. _vertexZvalue = vertexz.asInt();
  639. }
  640. }
  641. //CCTMXLayer2 - obtaining positions, offset
  642. Vec2 TMXLayer::calculateLayerOffset(const Vec2& pos)
  643. {
  644. Vec2 ret;
  645. switch (_layerOrientation)
  646. {
  647. case FAST_TMX_ORIENTATION_ORTHO:
  648. ret.set( pos.x * _mapTileSize.width, -pos.y *_mapTileSize.height);
  649. break;
  650. case FAST_TMX_ORIENTATION_ISO:
  651. ret.set((_mapTileSize.width /2) * (pos.x - pos.y),
  652. (_mapTileSize.height /2 ) * (-pos.x - pos.y));
  653. break;
  654. case FAST_TMX_ORIENTATION_HEX:
  655. default:
  656. CCASSERT(pos.isZero(), "offset for this map not implemented yet");
  657. break;
  658. }
  659. return ret;
  660. }
  661. // TMXLayer - adding / remove tiles
  662. void TMXLayer::setTileGID(int gid, const Vec2& tileCoordinate)
  663. {
  664. setTileGID(gid, tileCoordinate, (TMXTileFlags)0);
  665. }
  666. void TMXLayer::setTileGID(int gid, const Vec2& tileCoordinate, TMXTileFlags flags)
  667. {
  668. CCASSERT(tileCoordinate.x < _layerSize.width && tileCoordinate.y < _layerSize.height && tileCoordinate.x >=0 && tileCoordinate.y >=0, "TMXLayer: invalid position");
  669. CCASSERT(_tiles, "TMXLayer: the tiles map has been released");
  670. CCASSERT(gid == 0 || gid >= _tileSet->_firstGid, "TMXLayer: invalid gid" );
  671. TMXTileFlags currentFlags;
  672. int currentGID = getTileGIDAt(tileCoordinate, &currentFlags);
  673. if (currentGID == gid && currentFlags == flags) return;
  674. uint32_t gidAndFlags = gid | flags;
  675. // setting gid=0 is equal to remove the tile
  676. if (gid == 0)
  677. {
  678. removeTileAt(tileCoordinate);
  679. }
  680. // empty tile. create a new one
  681. else if (currentGID == 0)
  682. {
  683. int z = (int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width;
  684. setFlaggedTileGIDByIndex(z, gidAndFlags);
  685. }
  686. // modifying an existing tile with a non-empty tile
  687. else
  688. {
  689. int z = (int) tileCoordinate.x + (int) tileCoordinate.y * _layerSize.width;
  690. auto it = _spriteContainer.find(z);
  691. if (it != _spriteContainer.end())
  692. {
  693. Sprite *sprite = it->second.first;
  694. Rect rect = _tileSet->getRectForGID(gid);
  695. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  696. sprite->setTextureRect(rect, false, rect.size);
  697. this->reorderChild(sprite, z);
  698. if (flags)
  699. {
  700. setupTileSprite(sprite, sprite->getPosition(), gidAndFlags);
  701. }
  702. it->second.second = gidAndFlags;
  703. }
  704. else
  705. {
  706. setFlaggedTileGIDByIndex(z, gidAndFlags);
  707. }
  708. }
  709. }
  710. void TMXLayer::setupTileSprite(Sprite* sprite, const Vec2& pos, uint32_t gid)
  711. {
  712. sprite->setPosition(getPositionAt(pos));
  713. sprite->setPositionZ((float)getVertexZForPos(pos));
  714. sprite->setAnchorPoint(Vec2::ZERO);
  715. sprite->setOpacity(this->getOpacity());
  716. //issue 1264, flip can be undone as well
  717. sprite->setFlippedX(false);
  718. sprite->setFlippedY(false);
  719. sprite->setRotation(0.0f);
  720. // Rotation in tiled is achieved using 3 flipped states, flipping across the horizontal, vertical, and diagonal axes of the tiles.
  721. if (gid & kTMXTileDiagonalFlag)
  722. {
  723. // put the anchor in the middle for ease of rotation.
  724. sprite->setAnchorPoint(Vec2(0.5f,0.5f));
  725. sprite->setPosition(getPositionAt(pos).x + sprite->getContentSize().height/2,
  726. getPositionAt(pos).y + sprite->getContentSize().width/2 );
  727. uint32_t flag = gid & (kTMXTileHorizontalFlag | kTMXTileVerticalFlag );
  728. // handle the 4 diagonally flipped states.
  729. if (flag == kTMXTileHorizontalFlag)
  730. {
  731. sprite->setRotation(90.0f);
  732. }
  733. else if (flag == kTMXTileVerticalFlag)
  734. {
  735. sprite->setRotation(270.0f);
  736. }
  737. else if (flag == (kTMXTileVerticalFlag | kTMXTileHorizontalFlag) )
  738. {
  739. sprite->setRotation(90.0f);
  740. sprite->setFlippedX(true);
  741. }
  742. else
  743. {
  744. sprite->setRotation(270.0f);
  745. sprite->setFlippedX(true);
  746. }
  747. }
  748. else
  749. {
  750. if (gid & kTMXTileHorizontalFlag)
  751. {
  752. sprite->setFlippedX(true);
  753. }
  754. if (gid & kTMXTileVerticalFlag)
  755. {
  756. sprite->setFlippedY(true);
  757. }
  758. }
  759. }
  760. std::string TMXLayer::getDescription() const
  761. {
  762. return StringUtils::format("<FastTMXLayer | tag = %d, size = %d,%d>", _tag, (int)_mapTileSize.width, (int)_mapTileSize.height);
  763. }
  764. } //end of namespace experimental
  765. NS_CC_END