CCTMXXMLParser.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. /****************************************************************************
  2. Copyright (c) 2011 Максим Аксенов
  3. Copyright (c) 2009-2010 Ricardo Quesada
  4. Copyright (c) 2010-2012 cocos2d-x.org
  5. Copyright (c) 2011 Zynga Inc.
  6. Copyright (c) 2013-2017 Chukong Technologies Inc.
  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/CCTMXXMLParser.h"
  25. #include <unordered_map>
  26. #include <sstream>
  27. #include "2d/CCTMXTiledMap.h"
  28. #include "base/ZipUtils.h"
  29. #include "base/base64.h"
  30. #include "base/CCDirector.h"
  31. #include "platform/CCFileUtils.h"
  32. using namespace std;
  33. NS_CC_BEGIN
  34. // implementation TMXLayerInfo
  35. TMXLayerInfo::TMXLayerInfo()
  36. : _name("")
  37. , _tiles(nullptr)
  38. , _ownTiles(true)
  39. {
  40. }
  41. TMXLayerInfo::~TMXLayerInfo()
  42. {
  43. CCLOGINFO("deallocing TMXLayerInfo: %p", this);
  44. if (_ownTiles && _tiles)
  45. {
  46. free(_tiles);
  47. _tiles = nullptr;
  48. }
  49. }
  50. ValueMap& TMXLayerInfo::getProperties()
  51. {
  52. return _properties;
  53. }
  54. void TMXLayerInfo::setProperties(ValueMap var)
  55. {
  56. _properties = var;
  57. }
  58. // implementation TMXTilesetInfo
  59. TMXTilesetInfo::TMXTilesetInfo()
  60. :_firstGid(0)
  61. ,_tileSize(Size::ZERO)
  62. ,_spacing(0)
  63. ,_margin(0)
  64. ,_imageSize(Size::ZERO)
  65. {
  66. }
  67. TMXTilesetInfo::~TMXTilesetInfo()
  68. {
  69. CCLOGINFO("deallocing TMXTilesetInfo: %p", this);
  70. }
  71. Rect TMXTilesetInfo::getRectForGID(uint32_t gid)
  72. {
  73. Rect rect;
  74. rect.size = _tileSize;
  75. gid &= kTMXFlippedMask;
  76. gid = gid - _firstGid;
  77. // max_x means the column count in tile map
  78. // in the origin:
  79. // max_x = (int)((_imageSize.width - _margin*2 + _spacing) / (_tileSize.width + _spacing));
  80. // but in editor "Tiled", _margin variable only effect the left side
  81. // for compatible with "Tiled", change the max_x calculation
  82. int max_x = (int)((_imageSize.width - _margin + _spacing) / (_tileSize.width + _spacing));
  83. rect.origin.x = (gid % max_x) * (_tileSize.width + _spacing) + _margin;
  84. rect.origin.y = (gid / max_x) * (_tileSize.height + _spacing) + _margin;
  85. return rect;
  86. }
  87. // implementation TMXMapInfo
  88. TMXMapInfo * TMXMapInfo::create(const std::string& tmxFile)
  89. {
  90. TMXMapInfo *ret = new (std::nothrow) TMXMapInfo();
  91. if (ret->initWithTMXFile(tmxFile))
  92. {
  93. ret->autorelease();
  94. return ret;
  95. }
  96. CC_SAFE_DELETE(ret);
  97. return nullptr;
  98. }
  99. TMXMapInfo * TMXMapInfo::createWithXML(const std::string& tmxString, const std::string& resourcePath)
  100. {
  101. TMXMapInfo *ret = new (std::nothrow) TMXMapInfo();
  102. if (ret->initWithXML(tmxString, resourcePath))
  103. {
  104. ret->autorelease();
  105. return ret;
  106. }
  107. CC_SAFE_DELETE(ret);
  108. return nullptr;
  109. }
  110. void TMXMapInfo::internalInit(const std::string& tmxFileName, const std::string& resourcePath)
  111. {
  112. if (!tmxFileName.empty())
  113. {
  114. _TMXFileName = FileUtils::getInstance()->fullPathForFilename(tmxFileName);
  115. }
  116. if (!resourcePath.empty())
  117. {
  118. _resources = resourcePath;
  119. }
  120. _objectGroups.reserve(4);
  121. // tmp vars
  122. _currentString = "";
  123. _storingCharacters = false;
  124. _layerAttribs = TMXLayerAttribNone;
  125. _parentElement = TMXPropertyNone;
  126. _currentFirstGID = -1;
  127. }
  128. bool TMXMapInfo::initWithXML(const std::string& tmxString, const std::string& resourcePath)
  129. {
  130. internalInit("", resourcePath);
  131. return parseXMLString(tmxString);
  132. }
  133. bool TMXMapInfo::initWithTMXFile(const std::string& tmxFile)
  134. {
  135. internalInit(tmxFile, "");
  136. return parseXMLFile(_TMXFileName);
  137. }
  138. TMXMapInfo::TMXMapInfo()
  139. : _orientation(TMXOrientationOrtho)
  140. , _staggerAxis(TMXStaggerAxis_Y)
  141. , _staggerIndex(TMXStaggerIndex_Even)
  142. , _hexSideLength(0)
  143. , _parentElement(0)
  144. , _parentGID(0)
  145. , _mapSize(Size::ZERO)
  146. , _tileSize(Size::ZERO)
  147. , _layerAttribs(0)
  148. , _storingCharacters(false)
  149. , _xmlTileIndex(0)
  150. , _currentFirstGID(-1)
  151. , _recordFirstGID(true)
  152. {
  153. }
  154. TMXMapInfo::~TMXMapInfo()
  155. {
  156. CCLOGINFO("deallocing TMXMapInfo: %p", this);
  157. }
  158. bool TMXMapInfo::parseXMLString(const std::string& xmlString)
  159. {
  160. size_t len = xmlString.size();
  161. if (len <= 0)
  162. return false;
  163. SAXParser parser;
  164. if (false == parser.init("UTF-8") )
  165. {
  166. return false;
  167. }
  168. parser.setDelegator(this);
  169. return parser.parse(xmlString.c_str(), len);
  170. }
  171. bool TMXMapInfo::parseXMLFile(const std::string& xmlFilename)
  172. {
  173. SAXParser parser;
  174. if (false == parser.init("UTF-8") )
  175. {
  176. return false;
  177. }
  178. parser.setDelegator(this);
  179. return parser.parse(FileUtils::getInstance()->fullPathForFilename(xmlFilename));
  180. }
  181. // the XML parser calls here with all the elements
  182. void TMXMapInfo::startElement(void* /*ctx*/, const char *name, const char **atts)
  183. {
  184. TMXMapInfo *tmxMapInfo = this;
  185. std::string elementName = name;
  186. ValueMap attributeDict;
  187. if (atts && atts[0])
  188. {
  189. for (int i = 0; atts[i]; i += 2)
  190. {
  191. std::string key = atts[i];
  192. std::string value = atts[i+1];
  193. attributeDict.emplace(key, Value(value));
  194. }
  195. }
  196. if (elementName == "map")
  197. {
  198. std::string version = attributeDict["version"].asString();
  199. if ( version != "1.0")
  200. {
  201. CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %s", version.c_str());
  202. }
  203. std::string orientationStr = attributeDict["orientation"].asString();
  204. if (orientationStr == "orthogonal") {
  205. tmxMapInfo->setOrientation(TMXOrientationOrtho);
  206. }
  207. else if (orientationStr == "isometric") {
  208. tmxMapInfo->setOrientation(TMXOrientationIso);
  209. }
  210. else if (orientationStr == "hexagonal") {
  211. tmxMapInfo->setOrientation(TMXOrientationHex);
  212. }
  213. else if (orientationStr == "staggered") {
  214. tmxMapInfo->setOrientation(TMXOrientationStaggered);
  215. }
  216. else {
  217. CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", tmxMapInfo->getOrientation());
  218. }
  219. std::string staggerAxisStr = attributeDict["staggeraxis"].asString();
  220. if (staggerAxisStr == "x") {
  221. tmxMapInfo->setStaggerAxis(TMXStaggerAxis_X);
  222. }
  223. else if (staggerAxisStr == "y") {
  224. tmxMapInfo->setStaggerAxis(TMXStaggerAxis_Y);
  225. }
  226. std::string staggerIndex = attributeDict["staggerindex"].asString();
  227. if (staggerIndex == "odd") {
  228. tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Odd);
  229. }
  230. else if (staggerIndex == "even") {
  231. tmxMapInfo->setStaggerIndex(TMXStaggerIndex_Even);
  232. }
  233. float hexSideLength = attributeDict["hexsidelength"].asFloat();
  234. tmxMapInfo->setHexSideLength(hexSideLength);
  235. Size s;
  236. s.width = attributeDict["width"].asFloat();
  237. s.height = attributeDict["height"].asFloat();
  238. tmxMapInfo->setMapSize(s);
  239. s.width = attributeDict["tilewidth"].asFloat();
  240. s.height = attributeDict["tileheight"].asFloat();
  241. tmxMapInfo->setTileSize(s);
  242. // The parent element is now "map"
  243. tmxMapInfo->setParentElement(TMXPropertyMap);
  244. }
  245. else if (elementName == "tileset")
  246. {
  247. // If this is an external tileset then start parsing that
  248. std::string externalTilesetFilename = attributeDict["source"].asString();
  249. if (externalTilesetFilename != "")
  250. {
  251. _externalTilesetFilename = externalTilesetFilename;
  252. // Tileset file will be relative to the map file. So we need to convert it to an absolute path
  253. if (_TMXFileName.find_last_of("/") != string::npos)
  254. {
  255. string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1);
  256. externalTilesetFilename = dir + externalTilesetFilename;
  257. }
  258. else
  259. {
  260. externalTilesetFilename = _resources + "/" + externalTilesetFilename;
  261. }
  262. externalTilesetFilename = FileUtils::getInstance()->fullPathForFilename(externalTilesetFilename);
  263. _currentFirstGID = attributeDict["firstgid"].asInt();
  264. if (_currentFirstGID < 0)
  265. {
  266. _currentFirstGID = 0;
  267. }
  268. _recordFirstGID = false;
  269. tmxMapInfo->parseXMLFile(externalTilesetFilename);
  270. }
  271. else
  272. {
  273. TMXTilesetInfo *tileset = new (std::nothrow) TMXTilesetInfo();
  274. tileset->_name = attributeDict["name"].asString();
  275. if (_recordFirstGID)
  276. {
  277. // unset before, so this is tmx file.
  278. tileset->_firstGid = attributeDict["firstgid"].asInt();
  279. if (tileset->_firstGid < 0)
  280. {
  281. tileset->_firstGid = 0;
  282. }
  283. }
  284. else
  285. {
  286. tileset->_firstGid = _currentFirstGID;
  287. _currentFirstGID = 0;
  288. }
  289. tileset->_spacing = attributeDict["spacing"].asInt();
  290. tileset->_margin = attributeDict["margin"].asInt();
  291. Size s;
  292. s.width = attributeDict["tilewidth"].asFloat();
  293. s.height = attributeDict["tileheight"].asFloat();
  294. tileset->_tileSize = s;
  295. tmxMapInfo->getTilesets().pushBack(tileset);
  296. tileset->release();
  297. }
  298. }
  299. else if (elementName == "tile")
  300. {
  301. if (tmxMapInfo->getParentElement() == TMXPropertyLayer)
  302. {
  303. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  304. Size layerSize = layer->_layerSize;
  305. uint32_t gid = static_cast<uint32_t>(attributeDict["gid"].asUnsignedInt());
  306. int tilesAmount = layerSize.width*layerSize.height;
  307. if (_xmlTileIndex < tilesAmount)
  308. {
  309. layer->_tiles[_xmlTileIndex++] = gid;
  310. }
  311. }
  312. else
  313. {
  314. TMXTilesetInfo* info = tmxMapInfo->getTilesets().back();
  315. tmxMapInfo->setParentGID(info->_firstGid + attributeDict["id"].asInt());
  316. tmxMapInfo->getTileProperties()[tmxMapInfo->getParentGID()] = Value(ValueMap());
  317. tmxMapInfo->setParentElement(TMXPropertyTile);
  318. }
  319. }
  320. else if (elementName == "layer")
  321. {
  322. TMXLayerInfo *layer = new (std::nothrow) TMXLayerInfo();
  323. layer->_name = attributeDict["name"].asString();
  324. Size s;
  325. s.width = attributeDict["width"].asFloat();
  326. s.height = attributeDict["height"].asFloat();
  327. layer->_layerSize = s;
  328. Value& visibleValue = attributeDict["visible"];
  329. layer->_visible = visibleValue.isNull() ? true : visibleValue.asBool();
  330. Value& opacityValue = attributeDict["opacity"];
  331. layer->_opacity = opacityValue.isNull() ? 255 : (unsigned char)(255.0f * opacityValue.asFloat());
  332. float x = attributeDict["x"].asFloat();
  333. float y = attributeDict["y"].asFloat();
  334. layer->_offset.set(x, y);
  335. tmxMapInfo->getLayers().pushBack(layer);
  336. layer->release();
  337. // The parent element is now "layer"
  338. tmxMapInfo->setParentElement(TMXPropertyLayer);
  339. }
  340. else if (elementName == "objectgroup")
  341. {
  342. TMXObjectGroup *objectGroup = new (std::nothrow) TMXObjectGroup();
  343. objectGroup->setGroupName(attributeDict["name"].asString());
  344. Vec2 positionOffset;
  345. positionOffset.x = attributeDict["x"].asFloat() * tmxMapInfo->getTileSize().width;
  346. positionOffset.y = attributeDict["y"].asFloat() * tmxMapInfo->getTileSize().height;
  347. objectGroup->setPositionOffset(positionOffset);
  348. tmxMapInfo->getObjectGroups().pushBack(objectGroup);
  349. objectGroup->release();
  350. // The parent element is now "objectgroup"
  351. tmxMapInfo->setParentElement(TMXPropertyObjectGroup);
  352. }
  353. else if (elementName == "tileoffset")
  354. {
  355. TMXTilesetInfo* tileset = tmxMapInfo->getTilesets().back();
  356. double tileOffsetX = attributeDict["x"].asDouble();
  357. double tileOffsetY = attributeDict["y"].asDouble();
  358. tileset->_tileOffset = Vec2(tileOffsetX, tileOffsetY);
  359. }
  360. else if (elementName == "image")
  361. {
  362. TMXTilesetInfo* tileset = tmxMapInfo->getTilesets().back();
  363. // build full path
  364. std::string imagename = attributeDict["source"].asString();
  365. tileset->_originSourceImage = imagename;
  366. if (_TMXFileName.find_last_of("/") != string::npos)
  367. {
  368. string dir = _TMXFileName.substr(0, _TMXFileName.find_last_of("/") + 1);
  369. tileset->_sourceImage = dir + imagename;
  370. }
  371. else
  372. {
  373. tileset->_sourceImage = _resources + (_resources.size() ? "/" : "") + imagename;
  374. }
  375. }
  376. else if (elementName == "data")
  377. {
  378. std::string encoding = attributeDict["encoding"].asString();
  379. std::string compression = attributeDict["compression"].asString();
  380. if (encoding == "")
  381. {
  382. tmxMapInfo->setLayerAttribs(tmxMapInfo->getLayerAttribs() | TMXLayerAttribNone);
  383. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  384. Size layerSize = layer->_layerSize;
  385. int tilesAmount = layerSize.width*layerSize.height;
  386. uint32_t *tiles = (uint32_t*) malloc(tilesAmount*sizeof(uint32_t));
  387. // set all value to 0
  388. memset(tiles, 0, tilesAmount*sizeof(int));
  389. layer->_tiles = tiles;
  390. }
  391. else if (encoding == "base64")
  392. {
  393. int layerAttribs = tmxMapInfo->getLayerAttribs();
  394. tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribBase64);
  395. tmxMapInfo->setStoringCharacters(true);
  396. if (compression == "gzip")
  397. {
  398. layerAttribs = tmxMapInfo->getLayerAttribs();
  399. tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribGzip);
  400. } else
  401. if (compression == "zlib")
  402. {
  403. layerAttribs = tmxMapInfo->getLayerAttribs();
  404. tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribZlib);
  405. }
  406. CCASSERT( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" );
  407. }
  408. else if (encoding == "csv")
  409. {
  410. int layerAttribs = tmxMapInfo->getLayerAttribs();
  411. tmxMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribCSV);
  412. tmxMapInfo->setStoringCharacters(true);
  413. }
  414. }
  415. else if (elementName == "object")
  416. {
  417. TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back();
  418. // The value for "type" was blank or not a valid class name
  419. // Create an instance of TMXObjectInfo to store the object and its properties
  420. ValueMap dict;
  421. // Parse everything automatically
  422. const char* keys[] = {"name", "type", "width", "height", "gid", "id"};
  423. for (const auto& key : keys)
  424. {
  425. Value value = attributeDict[key];
  426. dict[key] = value;
  427. }
  428. // But X and Y since they need special treatment
  429. // X
  430. int x = attributeDict["x"].asInt();
  431. // Y
  432. int y = attributeDict["y"].asInt();
  433. Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().y - attributeDict["height"].asInt());
  434. p = CC_POINT_PIXELS_TO_POINTS(p);
  435. dict["x"] = Value(p.x);
  436. dict["y"] = Value(p.y);
  437. int width = attributeDict["width"].asInt();
  438. int height = attributeDict["height"].asInt();
  439. Size s(width, height);
  440. s = CC_SIZE_PIXELS_TO_POINTS(s);
  441. dict["width"] = Value(s.width);
  442. dict["height"] = Value(s.height);
  443. // Add the object to the objectGroup
  444. objectGroup->getObjects().push_back(Value(dict));
  445. // The parent element is now "object"
  446. tmxMapInfo->setParentElement(TMXPropertyObject);
  447. }
  448. else if (elementName == "property")
  449. {
  450. if ( tmxMapInfo->getParentElement() == TMXPropertyNone )
  451. {
  452. CCLOG( "TMX tile map: Parent element is unsupported. Cannot add property named '%s' with value '%s'",
  453. attributeDict["name"].asString().c_str(), attributeDict["value"].asString().c_str() );
  454. }
  455. else if ( tmxMapInfo->getParentElement() == TMXPropertyMap )
  456. {
  457. // The parent element is the map
  458. Value value = attributeDict["value"];
  459. std::string key = attributeDict["name"].asString();
  460. tmxMapInfo->getProperties().emplace(key, value);
  461. }
  462. else if ( tmxMapInfo->getParentElement() == TMXPropertyLayer )
  463. {
  464. // The parent element is the last layer
  465. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  466. Value value = attributeDict["value"];
  467. std::string key = attributeDict["name"].asString();
  468. // Add the property to the layer
  469. layer->getProperties().emplace(key, value);
  470. }
  471. else if ( tmxMapInfo->getParentElement() == TMXPropertyObjectGroup )
  472. {
  473. // The parent element is the last object group
  474. TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back();
  475. Value value = attributeDict["value"];
  476. std::string key = attributeDict["name"].asString();
  477. objectGroup->getProperties().emplace(key, value);
  478. }
  479. else if ( tmxMapInfo->getParentElement() == TMXPropertyObject )
  480. {
  481. // The parent element is the last object
  482. TMXObjectGroup* objectGroup = tmxMapInfo->getObjectGroups().back();
  483. ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
  484. std::string propertyName = attributeDict["name"].asString();
  485. dict[propertyName] = attributeDict["value"];
  486. }
  487. else if ( tmxMapInfo->getParentElement() == TMXPropertyTile )
  488. {
  489. ValueMap& dict = tmxMapInfo->getTileProperties().at(tmxMapInfo->getParentGID()).asValueMap();
  490. std::string propertyName = attributeDict["name"].asString();
  491. dict[propertyName] = attributeDict["value"];
  492. }
  493. }
  494. else if (elementName == "polygon")
  495. {
  496. // find parent object's dict and add polygon-points to it
  497. TMXObjectGroup* objectGroup = _objectGroups.back();
  498. ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
  499. // get points value string
  500. std::string value = attributeDict["points"].asString();
  501. if (!value.empty())
  502. {
  503. ValueVector pointsArray;
  504. pointsArray.reserve(10);
  505. // parse points string into a space-separated set of points
  506. stringstream pointsStream(value);
  507. string pointPair;
  508. while (std::getline(pointsStream, pointPair, ' '))
  509. {
  510. // parse each point combo into a comma-separated x,y point
  511. stringstream pointStream(pointPair);
  512. string xStr, yStr;
  513. ValueMap pointDict;
  514. // set x
  515. if (std::getline(pointStream, xStr, ','))
  516. {
  517. int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
  518. pointDict["x"] = Value(x);
  519. }
  520. // set y
  521. if (std::getline(pointStream, yStr, ','))
  522. {
  523. int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
  524. pointDict["y"] = Value(y);
  525. }
  526. // add to points array
  527. pointsArray.push_back(Value(pointDict));
  528. }
  529. dict["points"] = Value(pointsArray);
  530. }
  531. }
  532. else if (elementName == "polyline")
  533. {
  534. // find parent object's dict and add polyline-points to it
  535. TMXObjectGroup* objectGroup = _objectGroups.back();
  536. ValueMap& dict = objectGroup->getObjects().rbegin()->asValueMap();
  537. // get points value string
  538. std::string value = attributeDict["points"].asString();
  539. if (!value.empty())
  540. {
  541. ValueVector pointsArray;
  542. pointsArray.reserve(10);
  543. // parse points string into a space-separated set of points
  544. stringstream pointsStream(value);
  545. string pointPair;
  546. while (std::getline(pointsStream, pointPair, ' '))
  547. {
  548. // parse each point combo into a comma-separated x,y point
  549. stringstream pointStream(pointPair);
  550. string xStr, yStr;
  551. ValueMap pointDict;
  552. // set x
  553. if (std::getline(pointStream, xStr, ','))
  554. {
  555. int x = atoi(xStr.c_str()) + (int)objectGroup->getPositionOffset().x;
  556. pointDict["x"] = Value(x);
  557. }
  558. // set y
  559. if (std::getline(pointStream, yStr, ','))
  560. {
  561. int y = atoi(yStr.c_str()) + (int)objectGroup->getPositionOffset().y;
  562. pointDict["y"] = Value(y);
  563. }
  564. // add to points array
  565. pointsArray.push_back(Value(pointDict));
  566. }
  567. dict["polylinePoints"] = Value(pointsArray);
  568. }
  569. }
  570. }
  571. void TMXMapInfo::endElement(void* /*ctx*/, const char *name)
  572. {
  573. TMXMapInfo *tmxMapInfo = this;
  574. std::string elementName = name;
  575. if (elementName == "data")
  576. {
  577. if (tmxMapInfo->getLayerAttribs() & TMXLayerAttribBase64)
  578. {
  579. tmxMapInfo->setStoringCharacters(false);
  580. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  581. std::string currentString = tmxMapInfo->getCurrentString();
  582. unsigned char *buffer;
  583. auto len = base64Decode((unsigned char*)currentString.c_str(), (unsigned int)currentString.length(), &buffer);
  584. if (!buffer)
  585. {
  586. CCLOG("cocos2d: TiledMap: decode data error");
  587. return;
  588. }
  589. if (tmxMapInfo->getLayerAttribs() & (TMXLayerAttribGzip | TMXLayerAttribZlib))
  590. {
  591. unsigned char *deflated = nullptr;
  592. Size s = layer->_layerSize;
  593. // int sizeHint = s.width * s.height * sizeof(uint32_t);
  594. ssize_t sizeHint = s.width * s.height * sizeof(unsigned int);
  595. ssize_t CC_UNUSED inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint);
  596. CCASSERT(inflatedLen == sizeHint, "inflatedLen should be equal to sizeHint!");
  597. free(buffer);
  598. buffer = nullptr;
  599. if (!deflated)
  600. {
  601. CCLOG("cocos2d: TiledMap: inflate data error");
  602. return;
  603. }
  604. layer->_tiles = reinterpret_cast<uint32_t*>(deflated);
  605. }
  606. else
  607. {
  608. layer->_tiles = reinterpret_cast<uint32_t*>(buffer);
  609. }
  610. tmxMapInfo->setCurrentString("");
  611. }
  612. else if (tmxMapInfo->getLayerAttribs() & TMXLayerAttribCSV)
  613. {
  614. unsigned char *buffer;
  615. TMXLayerInfo* layer = tmxMapInfo->getLayers().back();
  616. tmxMapInfo->setStoringCharacters(false);
  617. std::string currentString = tmxMapInfo->getCurrentString();
  618. vector<string> gidTokens;
  619. istringstream filestr(currentString);
  620. string sRow;
  621. while(getline(filestr, sRow, '\n')) {
  622. string sGID;
  623. istringstream rowstr(sRow);
  624. while (getline(rowstr, sGID, ',')) {
  625. gidTokens.push_back(sGID);
  626. }
  627. }
  628. // 32-bits per gid
  629. buffer = (unsigned char*)malloc(gidTokens.size() * 4);
  630. if (!buffer)
  631. {
  632. CCLOG("cocos2d: TiledMap: CSV buffer not allocated.");
  633. return;
  634. }
  635. uint32_t* bufferPtr = reinterpret_cast<uint32_t*>(buffer);
  636. for(auto gidToken : gidTokens) {
  637. auto tileGid = (uint32_t)strtoul(gidToken.c_str(), nullptr, 10);
  638. *bufferPtr = tileGid;
  639. bufferPtr++;
  640. }
  641. layer->_tiles = reinterpret_cast<uint32_t*>(buffer);
  642. tmxMapInfo->setCurrentString("");
  643. }
  644. else if (tmxMapInfo->getLayerAttribs() & TMXLayerAttribNone)
  645. {
  646. _xmlTileIndex = 0;
  647. }
  648. }
  649. else if (elementName == "map")
  650. {
  651. // The map element has ended
  652. tmxMapInfo->setParentElement(TMXPropertyNone);
  653. }
  654. else if (elementName == "layer")
  655. {
  656. // The layer element has ended
  657. tmxMapInfo->setParentElement(TMXPropertyNone);
  658. }
  659. else if (elementName == "objectgroup")
  660. {
  661. // The objectgroup element has ended
  662. tmxMapInfo->setParentElement(TMXPropertyNone);
  663. }
  664. else if (elementName == "object")
  665. {
  666. // The object element has ended
  667. tmxMapInfo->setParentElement(TMXPropertyNone);
  668. }
  669. else if (elementName == "tileset")
  670. {
  671. _recordFirstGID = true;
  672. }
  673. }
  674. void TMXMapInfo::textHandler(void* /*ctx*/, const char *ch, size_t len)
  675. {
  676. TMXMapInfo *tmxMapInfo = this;
  677. std::string text(ch, 0, len);
  678. if (tmxMapInfo->isStoringCharacters())
  679. {
  680. std::string currentString = tmxMapInfo->getCurrentString();
  681. currentString += text;
  682. tmxMapInfo->setCurrentString(currentString);
  683. }
  684. }
  685. NS_CC_END