CCTMXLayer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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-2016 Chukong Technologies Inc.
  6. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  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/CCTMXLayer.h"
  25. #include "2d/CCTMXTiledMap.h"
  26. #include "2d/CCSprite.h"
  27. #include "base/CCDirector.h"
  28. #include "base/ccUTF8.h"
  29. #include "renderer/CCTextureCache.h"
  30. #include "renderer/CCGLProgram.h"
  31. NS_CC_BEGIN
  32. // TMXLayer - init & alloc & dealloc
  33. TMXLayer * TMXLayer::create(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
  34. {
  35. TMXLayer *ret = new (std::nothrow) TMXLayer();
  36. if (ret->initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo))
  37. {
  38. ret->autorelease();
  39. return ret;
  40. }
  41. CC_SAFE_DELETE(ret);
  42. return nullptr;
  43. }
  44. bool TMXLayer::initWithTilesetInfo(TMXTilesetInfo *tilesetInfo, TMXLayerInfo *layerInfo, TMXMapInfo *mapInfo)
  45. {
  46. // FIXME:: is 35% a good estimate ?
  47. Size size = layerInfo->_layerSize;
  48. float totalNumberOfTiles = size.width * size.height;
  49. float capacity = totalNumberOfTiles * 0.35f + 1; // 35 percent is occupied ?
  50. Texture2D *texture = nullptr;
  51. if( tilesetInfo )
  52. {
  53. texture = Director::getInstance()->getTextureCache()->addImage(tilesetInfo->_sourceImage);
  54. }
  55. if (nullptr == texture)
  56. return false;
  57. if (SpriteBatchNode::initWithTexture(texture, static_cast<ssize_t>(capacity)))
  58. {
  59. // layerInfo
  60. _layerName = layerInfo->_name;
  61. _layerSize = size;
  62. _tiles = layerInfo->_tiles;
  63. _opacity = layerInfo->_opacity;
  64. setProperties(layerInfo->getProperties());
  65. _contentScaleFactor = Director::getInstance()->getContentScaleFactor();
  66. // tilesetInfo
  67. _tileSet = tilesetInfo;
  68. CC_SAFE_RETAIN(_tileSet);
  69. // mapInfo
  70. _mapTileSize = mapInfo->getTileSize();
  71. _layerOrientation = mapInfo->getOrientation();
  72. _staggerAxis = mapInfo->getStaggerAxis();
  73. _staggerIndex = mapInfo->getStaggerIndex();
  74. _hexSideLength = mapInfo->getHexSideLength();
  75. // offset (after layer orientation is set);
  76. Vec2 offset = this->calculateLayerOffset(layerInfo->_offset);
  77. this->setPosition(CC_POINT_PIXELS_TO_POINTS(offset));
  78. _atlasIndexArray = ccCArrayNew(totalNumberOfTiles);
  79. float width = 0;
  80. float height = 0;
  81. if (_layerOrientation == TMXOrientationHex) {
  82. if (_staggerAxis == TMXStaggerAxis_X) {
  83. height = _mapTileSize.height * (_layerSize.height + 0.5);
  84. width = (_mapTileSize.width + _hexSideLength) * ((int)(_layerSize.width / 2)) + _mapTileSize.width * ((int)_layerSize.width % 2);
  85. } else {
  86. width = _mapTileSize.width * (_layerSize.width + 0.5);
  87. height = (_mapTileSize.height + _hexSideLength) * ((int)(_layerSize.height / 2)) + _mapTileSize.height * ((int)_layerSize.height % 2);
  88. }
  89. } else {
  90. width = _layerSize.width * _mapTileSize.width;
  91. height = _layerSize.height * _mapTileSize.height;
  92. }
  93. this->setContentSize(CC_SIZE_PIXELS_TO_POINTS(Size(width, height)));
  94. _useAutomaticVertexZ = false;
  95. _vertexZvalue = 0;
  96. return true;
  97. }
  98. return false;
  99. }
  100. TMXLayer::TMXLayer()
  101. :_layerName("")
  102. ,_opacity(0)
  103. ,_vertexZvalue(0)
  104. ,_useAutomaticVertexZ(false)
  105. ,_reusedTile(nullptr)
  106. ,_atlasIndexArray(nullptr)
  107. ,_contentScaleFactor(1.0f)
  108. ,_layerSize(Size::ZERO)
  109. ,_mapTileSize(Size::ZERO)
  110. ,_tiles(nullptr)
  111. ,_tileSet(nullptr)
  112. ,_layerOrientation(TMXOrientationOrtho)
  113. ,_staggerAxis(TMXStaggerAxis_Y)
  114. ,_staggerIndex(TMXStaggerIndex_Even)
  115. ,_hexSideLength(0)
  116. {}
  117. TMXLayer::~TMXLayer()
  118. {
  119. CC_SAFE_RELEASE(_tileSet);
  120. CC_SAFE_RELEASE(_reusedTile);
  121. if (_atlasIndexArray)
  122. {
  123. ccCArrayFree(_atlasIndexArray);
  124. _atlasIndexArray = nullptr;
  125. }
  126. CC_SAFE_FREE(_tiles);
  127. }
  128. void TMXLayer::releaseMap()
  129. {
  130. if (_tiles)
  131. {
  132. free(_tiles);
  133. _tiles = nullptr;
  134. }
  135. if (_atlasIndexArray)
  136. {
  137. ccCArrayFree(_atlasIndexArray);
  138. _atlasIndexArray = nullptr;
  139. }
  140. }
  141. // TMXLayer - setup Tiles
  142. void TMXLayer::setupTiles()
  143. {
  144. // Optimization: quick hack that sets the image size on the tileset
  145. _tileSet->_imageSize = _textureAtlas->getTexture()->getContentSizeInPixels();
  146. // By default all the tiles are aliased
  147. // pros:
  148. // - easier to render
  149. // cons:
  150. // - difficult to scale / rotate / etc.
  151. _textureAtlas->getTexture()->setAliasTexParameters();
  152. //CFByteOrder o = CFByteOrderGetCurrent();
  153. // Parse cocos2d properties
  154. this->parseInternalProperties();
  155. for (int y=0; y < _layerSize.height; y++)
  156. {
  157. for (int x=0; x < _layerSize.width; x++)
  158. {
  159. int newX = x;
  160. // fix correct render ordering in Hexagonal maps when stagger axis == x
  161. if (_staggerAxis == TMXStaggerAxis_X && _layerOrientation == TMXOrientationHex)
  162. {
  163. if (_staggerIndex == TMXStaggerIndex_Odd)
  164. {
  165. if (x >= _layerSize.width/2)
  166. newX = (x - std::ceil(_layerSize.width/2)) * 2 + 1;
  167. else
  168. newX = x * 2;
  169. } else {
  170. // TMXStaggerIndex_Even
  171. if (x >= static_cast<int>(_layerSize.width/2))
  172. newX = (x - static_cast<int>(_layerSize.width/2)) * 2;
  173. else
  174. newX = x * 2 + 1;
  175. }
  176. }
  177. int pos = static_cast<int>(newX + _layerSize.width * y);
  178. int gid = _tiles[ pos ];
  179. // gid are stored in little endian.
  180. // if host is big endian, then swap
  181. //if( o == CFByteOrderBigEndian )
  182. // gid = CFSwapInt32( gid );
  183. /* We support little endian.*/
  184. // FIXME:: gid == 0 --> empty tile
  185. if (gid != 0)
  186. {
  187. this->appendTileForGID(gid, Vec2(newX, y));
  188. }
  189. }
  190. }
  191. }
  192. // TMXLayer - Properties
  193. Value TMXLayer::getProperty(const std::string& propertyName) const
  194. {
  195. if (_properties.find(propertyName) != _properties.end())
  196. return _properties.at(propertyName);
  197. return Value();
  198. }
  199. void TMXLayer::parseInternalProperties()
  200. {
  201. // if cc_vertex=automatic, then tiles will be rendered using vertexz
  202. auto vertexz = getProperty("cc_vertexz");
  203. if (!vertexz.isNull())
  204. {
  205. std::string vertexZStr = vertexz.asString();
  206. // If "automatic" is on, then parse the "cc_alpha_func" too
  207. if (vertexZStr == "automatic")
  208. {
  209. _useAutomaticVertexZ = true;
  210. auto alphaFuncVal = getProperty("cc_alpha_func");
  211. float alphaFuncValue = alphaFuncVal.asFloat();
  212. setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST));
  213. GLint alphaValueLocation = glGetUniformLocation(getGLProgram()->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);
  214. // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison
  215. // use shader program to set uniform
  216. getGLProgram()->use();
  217. getGLProgram()->setUniformLocationWith1f(alphaValueLocation, alphaFuncValue);
  218. CHECK_GL_ERROR_DEBUG();
  219. }
  220. else
  221. {
  222. _vertexZvalue = vertexz.asInt();
  223. }
  224. }
  225. }
  226. void TMXLayer::setupTileSprite(Sprite* sprite, const Vec2& pos, uint32_t gid)
  227. {
  228. sprite->setPosition(getPositionAt(pos));
  229. sprite->setPositionZ((float)getVertexZForPos(pos));
  230. sprite->setAnchorPoint(Vec2::ZERO);
  231. sprite->setOpacity(_opacity);
  232. //issue 1264, flip can be undone as well
  233. sprite->setFlippedX(false);
  234. sprite->setFlippedY(false);
  235. sprite->setRotation(0.0f);
  236. sprite->setAnchorPoint(Vec2(0,0));
  237. // Rotation in tiled is achieved using 3 flipped states, flipping across the horizontal, vertical, and diagonal axes of the tiles.
  238. if (gid & kTMXTileDiagonalFlag)
  239. {
  240. // put the anchor in the middle for ease of rotation.
  241. sprite->setAnchorPoint(Vec2(0.5f,0.5f));
  242. sprite->setPosition(getPositionAt(pos).x + sprite->getContentSize().height/2,
  243. getPositionAt(pos).y + sprite->getContentSize().width/2 );
  244. auto flag = gid & (kTMXTileHorizontalFlag | kTMXTileVerticalFlag );
  245. // handle the 4 diagonally flipped states.
  246. if (flag == kTMXTileHorizontalFlag)
  247. {
  248. sprite->setRotation(90.0f);
  249. }
  250. else if (flag == kTMXTileVerticalFlag)
  251. {
  252. sprite->setRotation(270.0f);
  253. }
  254. else if (flag == (kTMXTileVerticalFlag | kTMXTileHorizontalFlag) )
  255. {
  256. sprite->setRotation(90.0f);
  257. sprite->setFlippedX(true);
  258. }
  259. else
  260. {
  261. sprite->setRotation(270.0f);
  262. sprite->setFlippedX(true);
  263. }
  264. }
  265. else
  266. {
  267. if (gid & kTMXTileHorizontalFlag)
  268. {
  269. sprite->setFlippedX(true);
  270. }
  271. if (gid & kTMXTileVerticalFlag)
  272. {
  273. sprite->setFlippedY(true);
  274. }
  275. }
  276. }
  277. Sprite* TMXLayer::reusedTileWithRect(const Rect& rect)
  278. {
  279. if (! _reusedTile)
  280. {
  281. _reusedTile = Sprite::createWithTexture(_textureAtlas->getTexture(), rect);
  282. _reusedTile->setBatchNode(this);
  283. _reusedTile->retain();
  284. }
  285. else
  286. {
  287. // FIXME: HACK: Needed because if "batch node" is nil,
  288. // then the Sprite'squad will be reset
  289. _reusedTile->setBatchNode(nullptr);
  290. // Re-init the sprite
  291. _reusedTile->setTextureRect(rect, false, rect.size);
  292. // restore the batch node
  293. _reusedTile->setBatchNode(this);
  294. }
  295. return _reusedTile;
  296. }
  297. // TMXLayer - obtaining tiles/gids
  298. Sprite * TMXLayer::getTileAt(const Vec2& pos)
  299. {
  300. CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
  301. CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
  302. Sprite *tile = nullptr;
  303. int gid = this->getTileGIDAt(pos);
  304. // if GID == 0, then no tile is present
  305. if (gid)
  306. {
  307. int z = (int)(pos.x + pos.y * _layerSize.width);
  308. tile = static_cast<Sprite*>(this->getChildByTag(z));
  309. // tile not created yet. create it
  310. if (! tile)
  311. {
  312. Rect rect = _tileSet->getRectForGID(gid);
  313. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  314. tile = Sprite::createWithTexture(this->getTexture(), rect);
  315. tile->setBatchNode(this);
  316. tile->setPosition(getPositionAt(pos));
  317. tile->setPositionZ((float)getVertexZForPos(pos));
  318. tile->setAnchorPoint(Vec2::ZERO);
  319. tile->setOpacity(_opacity);
  320. ssize_t indexForZ = atlasIndexForExistantZ(z);
  321. this->addSpriteWithoutQuad(tile, static_cast<int>(indexForZ), z);
  322. }
  323. }
  324. return tile;
  325. }
  326. uint32_t TMXLayer::getTileGIDAt(const Vec2& pos, TMXTileFlags* flags/* = nullptr*/)
  327. {
  328. CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
  329. CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
  330. ssize_t idx = static_cast<int>(((int) pos.x + (int) pos.y * _layerSize.width));
  331. // Bits on the far end of the 32-bit global tile ID are used for tile flags
  332. uint32_t tile = _tiles[idx];
  333. // issue1264, flipped tiles can be changed dynamically
  334. if (flags)
  335. {
  336. *flags = (TMXTileFlags)(tile & kTMXFlipedAll);
  337. }
  338. return (tile & kTMXFlippedMask);
  339. }
  340. // TMXLayer - adding helper methods
  341. Sprite * TMXLayer::insertTileForGID(uint32_t gid, const Vec2& pos)
  342. {
  343. if (gid != 0 && (static_cast<int>((gid & kTMXFlippedMask)) - _tileSet->_firstGid) >= 0)
  344. {
  345. Rect rect = _tileSet->getRectForGID(gid);
  346. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  347. intptr_t z = (intptr_t)((int) pos.x + (int) pos.y * _layerSize.width);
  348. Sprite *tile = reusedTileWithRect(rect);
  349. setupTileSprite(tile, pos, gid);
  350. // get atlas index
  351. ssize_t indexForZ = atlasIndexForNewZ(static_cast<int>(z));
  352. // Optimization: add the quad without adding a child
  353. this->insertQuadFromSprite(tile, indexForZ);
  354. // insert it into the local atlasindex array
  355. ccCArrayInsertValueAtIndex(_atlasIndexArray, (void*)z, indexForZ);
  356. // update possible children
  357. for(const auto &child : _children) {
  358. Sprite* sp = static_cast<Sprite*>(child);
  359. ssize_t ai = sp->getAtlasIndex();
  360. if ( ai >= indexForZ )
  361. {
  362. sp->setAtlasIndex(ai+1);
  363. }
  364. }
  365. _tiles[z] = gid;
  366. return tile;
  367. }
  368. return nullptr;
  369. }
  370. Sprite * TMXLayer::updateTileForGID(uint32_t gid, const Vec2& pos)
  371. {
  372. Rect rect = _tileSet->getRectForGID(gid);
  373. rect = Rect(rect.origin.x / _contentScaleFactor, rect.origin.y / _contentScaleFactor, rect.size.width/ _contentScaleFactor, rect.size.height/ _contentScaleFactor);
  374. int z = (int)((int) pos.x + (int) pos.y * _layerSize.width);
  375. Sprite *tile = reusedTileWithRect(rect);
  376. setupTileSprite(tile ,pos ,gid);
  377. // get atlas index
  378. ssize_t indexForZ = atlasIndexForExistantZ(z);
  379. tile->setAtlasIndex(indexForZ);
  380. tile->setDirty(true);
  381. tile->updateTransform();
  382. _tiles[z] = gid;
  383. return tile;
  384. }
  385. intptr_t TMXLayer::getZForPos(const Vec2& pos) const
  386. {
  387. intptr_t z = -1;
  388. // fix correct render ordering in Hexagonal maps when stagger axis == x
  389. if (_staggerAxis == TMXStaggerAxis_X && _layerOrientation == TMXOrientationHex)
  390. {
  391. if (_staggerIndex == TMXStaggerIndex_Odd)
  392. {
  393. if (((int)pos.x % 2) == 0)
  394. z = pos.x / 2 + pos.y * _layerSize.width;
  395. else
  396. z = pos.x / 2 + std::ceil(_layerSize.width / 2) + pos.y * _layerSize.width;
  397. } else {
  398. // TMXStaggerIndex_Even
  399. if (((int)pos.x % 2) == 1)
  400. z = pos.x / 2 + pos.y * _layerSize.width;
  401. else
  402. z = pos.x / 2 + std::floor(_layerSize.width / 2) + pos.y * _layerSize.width;
  403. }
  404. }
  405. else
  406. {
  407. z = (pos.x + pos.y * _layerSize.width);
  408. }
  409. CCASSERT(z != -1, "Invalid Z");
  410. return z;
  411. }
  412. // used only when parsing the map. useless after the map was parsed
  413. // since lot's of assumptions are no longer true
  414. Sprite * TMXLayer::appendTileForGID(uint32_t gid, const Vec2& pos)
  415. {
  416. if (gid != 0 && (static_cast<int>((gid & kTMXFlippedMask)) - _tileSet->_firstGid) >= 0)
  417. {
  418. Rect rect = _tileSet->getRectForGID(gid);
  419. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  420. // Z could be just an integer that gets incremented each time it is called.
  421. // but that wouldn't work on layers with empty tiles.
  422. // and it is IMPORTANT that Z returns an unique and bigger number than the previous one.
  423. // since _atlasIndexArray must be ordered because `bsearch` is used to find the GID for
  424. // a given Z. (github issue #16512)
  425. intptr_t z = getZForPos(pos);
  426. Sprite *tile = reusedTileWithRect(rect);
  427. setupTileSprite(tile ,pos ,gid);
  428. // optimization:
  429. // The difference between appendTileForGID and insertTileforGID is that append is faster, since
  430. // it appends the tile at the end of the texture atlas
  431. ssize_t indexForZ = _atlasIndexArray->num;
  432. // don't add it using the "standard" way.
  433. insertQuadFromSprite(tile, indexForZ);
  434. // append should be after addQuadFromSprite since it modifies the quantity values
  435. ccCArrayInsertValueAtIndex(_atlasIndexArray, (void*)z, indexForZ);
  436. // Validation for issue #16512
  437. CCASSERT(_atlasIndexArray->num == 1 ||
  438. _atlasIndexArray->arr[_atlasIndexArray->num-1] > _atlasIndexArray->arr[_atlasIndexArray->num-2], "Invalid z for _atlasIndexArray");
  439. return tile;
  440. }
  441. return nullptr;
  442. }
  443. // TMXLayer - atlasIndex and Z
  444. static inline int compareInts(const void * a, const void * b)
  445. {
  446. const int ia = *(int*)a;
  447. const int ib = *(int*)b;
  448. return (ia-ib);
  449. }
  450. ssize_t TMXLayer::atlasIndexForExistantZ(int z)
  451. {
  452. int key=z;
  453. int *item = (int*)bsearch((void*)&key, (void*)&_atlasIndexArray->arr[0], _atlasIndexArray->num, sizeof(void*), compareInts);
  454. CCASSERT(item, "TMX atlas index not found. Shall not happen");
  455. ssize_t index = ((size_t)item - (size_t)_atlasIndexArray->arr) / sizeof(void*);
  456. return index;
  457. }
  458. ssize_t TMXLayer::atlasIndexForNewZ(int z)
  459. {
  460. // FIXME:: This can be improved with a sort of binary search
  461. ssize_t i=0;
  462. for (i=0; i< _atlasIndexArray->num ; i++)
  463. {
  464. ssize_t val = (size_t) _atlasIndexArray->arr[i];
  465. if (z < val)
  466. {
  467. break;
  468. }
  469. }
  470. return i;
  471. }
  472. // TMXLayer - adding / remove tiles
  473. void TMXLayer::setTileGID(uint32_t gid, const Vec2& pos)
  474. {
  475. setTileGID(gid, pos, (TMXTileFlags)0);
  476. }
  477. void TMXLayer::setTileGID(uint32_t gid, const Vec2& pos, TMXTileFlags flags)
  478. {
  479. CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
  480. CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
  481. CCASSERT(gid == 0 || (int)gid >= _tileSet->_firstGid, "TMXLayer: invalid gid" );
  482. TMXTileFlags currentFlags;
  483. uint32_t currentGID = getTileGIDAt(pos, &currentFlags);
  484. if (currentGID != gid || currentFlags != flags)
  485. {
  486. uint32_t gidAndFlags = gid | flags;
  487. // setting gid=0 is equal to remove the tile
  488. if (gid == 0)
  489. {
  490. removeTileAt(pos);
  491. }
  492. // empty tile. create a new one
  493. else if (currentGID == 0)
  494. {
  495. insertTileForGID(gidAndFlags, pos);
  496. }
  497. // modifying an existing tile with a non-empty tile
  498. else
  499. {
  500. int z = (int) pos.x + (int) pos.y * _layerSize.width;
  501. Sprite *sprite = static_cast<Sprite*>(getChildByTag(z));
  502. if (sprite)
  503. {
  504. Rect rect = _tileSet->getRectForGID(gid);
  505. rect = CC_RECT_PIXELS_TO_POINTS(rect);
  506. sprite->setTextureRect(rect, false, rect.size);
  507. if (flags)
  508. {
  509. setupTileSprite(sprite, sprite->getPosition(), gidAndFlags);
  510. }
  511. _tiles[z] = gidAndFlags;
  512. }
  513. else
  514. {
  515. updateTileForGID(gidAndFlags, pos);
  516. }
  517. }
  518. }
  519. }
  520. void TMXLayer::addChild(Node* /*child*/, int /*zOrder*/, int /*tag*/)
  521. {
  522. CCASSERT(0, "addChild: is not supported on TMXLayer. Instead use setTileGID:at:/tileAt:");
  523. }
  524. void TMXLayer::removeChild(Node* node, bool cleanup)
  525. {
  526. Sprite *sprite = (Sprite*)node;
  527. // allows removing nil objects
  528. if (! sprite)
  529. {
  530. return;
  531. }
  532. CCASSERT(_children.contains(sprite), "Tile does not belong to TMXLayer");
  533. ssize_t atlasIndex = sprite->getAtlasIndex();
  534. ssize_t zz = (ssize_t)_atlasIndexArray->arr[atlasIndex];
  535. _tiles[zz] = 0;
  536. ccCArrayRemoveValueAtIndex(_atlasIndexArray, atlasIndex);
  537. SpriteBatchNode::removeChild(sprite, cleanup);
  538. }
  539. void TMXLayer::removeTileAt(const Vec2& pos)
  540. {
  541. CCASSERT(pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, "TMXLayer: invalid position");
  542. CCASSERT(_tiles && _atlasIndexArray, "TMXLayer: the tiles map has been released");
  543. int gid = getTileGIDAt(pos);
  544. if (gid)
  545. {
  546. int z = pos.x + pos.y * _layerSize.width;
  547. ssize_t atlasIndex = atlasIndexForExistantZ(z);
  548. // remove tile from GID map
  549. _tiles[z] = 0;
  550. // remove tile from atlas position array
  551. ccCArrayRemoveValueAtIndex(_atlasIndexArray, atlasIndex);
  552. // remove it from sprites and/or texture atlas
  553. Sprite *sprite = (Sprite*)getChildByTag(z);
  554. if (sprite)
  555. {
  556. SpriteBatchNode::removeChild(sprite, true);
  557. }
  558. else
  559. {
  560. _textureAtlas->removeQuadAtIndex(atlasIndex);
  561. // update possible children
  562. for(const auto &obj : _children) {
  563. Sprite* child = static_cast<Sprite*>(obj);
  564. ssize_t ai = child->getAtlasIndex();
  565. if ( ai >= atlasIndex )
  566. {
  567. child->setAtlasIndex(ai-1);
  568. }
  569. }
  570. }
  571. }
  572. }
  573. //CCTMXLayer - obtaining positions, offset
  574. Vec2 TMXLayer::calculateLayerOffset(const Vec2& pos)
  575. {
  576. Vec2 ret;
  577. switch (_layerOrientation)
  578. {
  579. case TMXOrientationOrtho:
  580. ret.set( pos.x * _mapTileSize.width, -pos.y *_mapTileSize.height);
  581. break;
  582. case TMXOrientationIso:
  583. ret.set((_mapTileSize.width /2) * (pos.x - pos.y),
  584. (_mapTileSize.height /2 ) * (-pos.x - pos.y));
  585. break;
  586. case TMXOrientationHex:
  587. {
  588. if(_staggerAxis == TMXStaggerAxis_Y)
  589. {
  590. int diffX = (_staggerIndex == TMXStaggerIndex_Even) ? _mapTileSize.width/2 : 0;
  591. ret.set(pos.x * _mapTileSize.width + diffX, -pos.y * (_mapTileSize.height - (_mapTileSize.width - _hexSideLength) / 2));
  592. }
  593. else if(_staggerAxis == TMXStaggerAxis_X)
  594. {
  595. int diffY = (_staggerIndex == TMXStaggerIndex_Odd) ? _mapTileSize.height/2 : 0;
  596. ret.set(pos.x * (_mapTileSize.width - (_mapTileSize.width - _hexSideLength) / 2), -pos.y * _mapTileSize.height + diffY);
  597. }
  598. break;
  599. }
  600. case TMXOrientationStaggered:
  601. {
  602. float diffX = 0;
  603. if ((int)std::abs(pos.y) % 2 == 1)
  604. {
  605. diffX = _mapTileSize.width/2;
  606. }
  607. ret.set(pos.x * _mapTileSize.width + diffX,
  608. (-pos.y) * _mapTileSize.height/2);
  609. }
  610. break;
  611. }
  612. return ret;
  613. }
  614. Vec2 TMXLayer::getPositionAt(const Vec2& pos)
  615. {
  616. Vec2 ret;
  617. switch (_layerOrientation)
  618. {
  619. case TMXOrientationOrtho:
  620. ret = getPositionForOrthoAt(pos);
  621. break;
  622. case TMXOrientationIso:
  623. ret = getPositionForIsoAt(pos);
  624. break;
  625. case TMXOrientationHex:
  626. ret = getPositionForHexAt(pos);
  627. break;
  628. case TMXOrientationStaggered:
  629. ret = getPositionForStaggeredAt(pos);
  630. break;
  631. }
  632. ret = CC_POINT_PIXELS_TO_POINTS( ret );
  633. return ret;
  634. }
  635. Vec2 TMXLayer::getPositionForOrthoAt(const Vec2& pos)
  636. {
  637. return Vec2(pos.x * _mapTileSize.width,
  638. (_layerSize.height - pos.y - 1) * _mapTileSize.height);
  639. }
  640. Vec2 TMXLayer::getPositionForIsoAt(const Vec2& pos)
  641. {
  642. return Vec2(_mapTileSize.width /2 * (_layerSize.width + pos.x - pos.y - 1),
  643. _mapTileSize.height /2 * ((_layerSize.height * 2 - pos.x - pos.y) - 2));
  644. }
  645. Vec2 TMXLayer::getPositionForHexAt(const Vec2& pos)
  646. {
  647. Vec2 xy;
  648. Vec2 offset = _tileSet->_tileOffset;
  649. int odd_even = (_staggerIndex == TMXStaggerIndex_Odd) ? 1 : -1;
  650. switch (_staggerAxis)
  651. {
  652. case TMXStaggerAxis_Y:
  653. {
  654. float diffX = 0;
  655. if ((int)pos.y % 2 == 1)
  656. {
  657. diffX = _mapTileSize.width/2 * odd_even;
  658. }
  659. xy = Vec2(pos.x * _mapTileSize.width+diffX+offset.x,
  660. (_layerSize.height - pos.y - 1) * (_mapTileSize.height-(_mapTileSize.height-_hexSideLength)/2)-offset.y);
  661. break;
  662. }
  663. case TMXStaggerAxis_X:
  664. {
  665. float diffY = 0;
  666. if ((int)pos.x % 2 == 1)
  667. {
  668. diffY = _mapTileSize.height/2 * -odd_even;
  669. }
  670. xy = Vec2(pos.x * (_mapTileSize.width-(_mapTileSize.width-_hexSideLength)/2)+offset.x,
  671. (_layerSize.height - pos.y - 1) * _mapTileSize.height + diffY-offset.y);
  672. break;
  673. }
  674. }
  675. return xy;
  676. }
  677. Vec2 TMXLayer::getPositionForStaggeredAt(const Vec2 &pos)
  678. {
  679. float diffX = 0;
  680. if ((int)pos.y % 2 == 1)
  681. {
  682. diffX = _mapTileSize.width/2;
  683. }
  684. return Vec2(pos.x * _mapTileSize.width + diffX,
  685. (_layerSize.height - pos.y - 1) * _mapTileSize.height/2);
  686. }
  687. int TMXLayer::getVertexZForPos(const Vec2& pos)
  688. {
  689. int ret = 0;
  690. int maxVal = 0;
  691. if (_useAutomaticVertexZ)
  692. {
  693. switch (_layerOrientation)
  694. {
  695. case TMXOrientationIso:
  696. maxVal = static_cast<int>(_layerSize.width + _layerSize.height);
  697. ret = static_cast<int>(-(maxVal - (pos.x + pos.y)));
  698. break;
  699. case TMXOrientationOrtho:
  700. ret = static_cast<int>(-(_layerSize.height-pos.y));
  701. break;
  702. case TMXOrientationStaggered:
  703. ret = static_cast<int>(-(_layerSize.height-pos.y));
  704. break;
  705. case TMXOrientationHex:
  706. ret = static_cast<int>(-(_layerSize.height-pos.y));
  707. break;
  708. default:
  709. CCASSERT(0, "TMX invalid value");
  710. break;
  711. }
  712. }
  713. else
  714. {
  715. ret = _vertexZvalue;
  716. }
  717. return ret;
  718. }
  719. std::string TMXLayer::getDescription() const
  720. {
  721. return StringUtils::format("<TMXLayer | tag = %d, size = %d,%d>", _tag, (int)_mapTileSize.width, (int)_mapTileSize.height);
  722. }
  723. NS_CC_END