TmxFile2D.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  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 "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Graphics/Texture2D.h"
  25. #include "../IO/FileSystem.h"
  26. #include "../IO/Log.h"
  27. #include "../Resource/ResourceCache.h"
  28. #include "../Resource/XMLFile.h"
  29. #include "../Atomic2D/Sprite2D.h"
  30. #include "../Atomic2D/TmxFile2D.h"
  31. #include "../DebugNew.h"
  32. namespace Atomic
  33. {
  34. extern const float PIXEL_SIZE;
  35. TmxLayer2D::TmxLayer2D(TmxFile2D* tmxFile, TileMapLayerType2D type) :
  36. tmxFile_(tmxFile),
  37. type_(type)
  38. {
  39. }
  40. TmxLayer2D::~TmxLayer2D()
  41. {
  42. }
  43. TmxFile2D* TmxLayer2D::GetTmxFile() const
  44. {
  45. return tmxFile_;
  46. }
  47. bool TmxLayer2D::HasProperty(const String& name) const
  48. {
  49. if (!propertySet_)
  50. return false;
  51. return propertySet_->HasProperty(name);
  52. }
  53. const String& TmxLayer2D::GetProperty(const String& name) const
  54. {
  55. if (!propertySet_)
  56. return String::EMPTY;
  57. return propertySet_->GetProperty(name);
  58. }
  59. void TmxLayer2D::LoadInfo(const XMLElement& element)
  60. {
  61. name_ = element.GetAttribute("name");
  62. width_ = element.GetInt("width");
  63. height_ = element.GetInt("height");
  64. if (element.HasAttribute("visible"))
  65. visible_ = element.GetInt("visible") != 0;
  66. else
  67. visible_ = true;
  68. }
  69. void TmxLayer2D::LoadPropertySet(const XMLElement& element)
  70. {
  71. propertySet_ = new PropertySet2D();
  72. propertySet_->Load(element);
  73. }
  74. TmxTileLayer2D::TmxTileLayer2D(TmxFile2D* tmxFile) :
  75. TmxLayer2D(tmxFile, LT_TILE_LAYER)
  76. {
  77. }
  78. bool TmxTileLayer2D::Load(const XMLElement& element, const TileMapInfo2D& info)
  79. {
  80. LoadInfo(element);
  81. XMLElement dataElem = element.GetChild("data");
  82. if (!dataElem)
  83. {
  84. LOGERROR("Could not find data in layer");
  85. return false;
  86. }
  87. if (dataElem.HasAttribute("encoding") && dataElem.GetAttribute("encoding") != "xml")
  88. {
  89. LOGERROR("Encoding not support now");
  90. return false;
  91. }
  92. XMLElement tileElem = dataElem.GetChild("tile");
  93. tiles_.Resize((unsigned)(width_ * height_));
  94. for (int y = 0; y < height_; ++y)
  95. {
  96. for (int x = 0; x < width_; ++x)
  97. {
  98. if (!tileElem)
  99. return false;
  100. int gid = tileElem.GetInt("gid");
  101. if (gid > 0)
  102. {
  103. SharedPtr<Tile2D> tile(new Tile2D());
  104. tile->gid_ = gid;
  105. tile->sprite_ = tmxFile_->GetTileSprite(gid);
  106. tile->propertySet_ = tmxFile_->GetTilePropertySet(gid);
  107. tile->objectGroup_ = tmxFile_->GetTileObjectGroup(gid);
  108. tiles_[y * width_ + x] = tile;
  109. }
  110. tileElem = tileElem.GetNext("tile");
  111. }
  112. }
  113. if (element.HasChild("properties"))
  114. LoadPropertySet(element.GetChild("properties"));
  115. return true;
  116. }
  117. Tile2D* TmxTileLayer2D::GetTile(int x, int y) const
  118. {
  119. if (x < 0 || x >= width_ || y < 0 || y >= height_)
  120. return 0;
  121. return tiles_[y * width_ + x];
  122. }
  123. TmxObjectGroup2D::TmxObjectGroup2D(TmxFile2D* tmxFile) :
  124. TmxLayer2D(tmxFile, LT_OBJECT_GROUP)
  125. {
  126. }
  127. bool TmxObjectGroup2D::Load(const XMLElement& element, const TileMapInfo2D& info, bool local)
  128. {
  129. LoadInfo(element);
  130. for (XMLElement objectElem = element.GetChild("object"); objectElem; objectElem = objectElem.GetNext("object"))
  131. {
  132. SharedPtr<TileMapObject2D> object(new TileMapObject2D());
  133. if (objectElem.HasAttribute("name"))
  134. object->name_ = objectElem.GetAttribute("name");
  135. else
  136. object->name_ = "Object";
  137. if (objectElem.HasAttribute("type"))
  138. object->type_ = objectElem.GetAttribute("type");
  139. Vector2 position(objectElem.GetFloat("x"), objectElem.GetFloat("y"));
  140. if (objectElem.HasAttribute("width") || objectElem.HasAttribute("height"))
  141. {
  142. if (!objectElem.HasChild("ellipse"))
  143. object->objectType_ = OT_RECTANGLE;
  144. else
  145. object->objectType_ = OT_ELLIPSE;
  146. Vector2 size(objectElem.GetFloat("width"), objectElem.GetFloat("height"));
  147. if (!local)
  148. {
  149. object->position_ = info.ConvertPosition(Vector2(position.x_, position.y_ + size.y_));
  150. object->size_ = Vector2(size.x_ * PIXEL_SIZE, size.y_ * PIXEL_SIZE);
  151. }
  152. else
  153. {
  154. object->size_ = Vector2(size.x_ * PIXEL_SIZE, size.y_ * PIXEL_SIZE);
  155. position.x_ *= PIXEL_SIZE;
  156. position.y_ *= PIXEL_SIZE;
  157. position.x_ = position.x_ + object->size_.x_ / 2.0f;
  158. position.y_ = position.y_ + object->size_.y_ / 2.0f;
  159. position.y_ = info.tileHeight_ - position.y_;
  160. object->position_ = position;
  161. }
  162. }
  163. else if (objectElem.HasAttribute("gid"))
  164. {
  165. object->objectType_ = OT_TILE;
  166. object->position_ = info.ConvertPosition(position);
  167. object->gid_ = objectElem.GetInt("gid");
  168. object->sprite_ = tmxFile_->GetTileSprite(object->gid_);
  169. }
  170. else
  171. {
  172. Vector<String> points;
  173. if (objectElem.HasChild("polygon"))
  174. {
  175. object->objectType_ = OT_POLYGON;
  176. XMLElement polygonElem = objectElem.GetChild("polygon");
  177. points = polygonElem.GetAttribute("points").Split(' ');
  178. }
  179. else if (objectElem.HasChild("polyline"))
  180. {
  181. object->objectType_ = OT_POLYLINE;
  182. XMLElement polylineElem = objectElem.GetChild("polyline");
  183. points = polylineElem.GetAttribute("points").Split(' ');
  184. }
  185. else
  186. return false;
  187. if (points.Size() <= 1)
  188. continue;
  189. object->points_.Resize(points.Size());
  190. for (unsigned i = 0; i < points.Size(); ++i)
  191. {
  192. points[i].Replace(',', ' ');
  193. Vector2 point = position + ToVector2(points[i]);
  194. object->points_[i] = info.ConvertPosition(point);
  195. }
  196. }
  197. if (objectElem.HasChild("properties"))
  198. {
  199. object->propertySet_ = new PropertySet2D();
  200. object->propertySet_->Load(objectElem.GetChild("properties"));
  201. }
  202. objects_.Push(object);
  203. }
  204. if (element.HasChild("properties"))
  205. LoadPropertySet(element.GetChild("properties"));
  206. return true;
  207. }
  208. TileMapObject2D* TmxObjectGroup2D::GetObject(unsigned index) const
  209. {
  210. if (index >= objects_.Size())
  211. return 0;
  212. return objects_[index];
  213. }
  214. TmxImageLayer2D::TmxImageLayer2D(TmxFile2D* tmxFile) :
  215. TmxLayer2D(tmxFile, LT_IMAGE_LAYER)
  216. {
  217. }
  218. bool TmxImageLayer2D::Load(const XMLElement& element, const TileMapInfo2D& info)
  219. {
  220. LoadInfo(element);
  221. XMLElement imageElem = element.GetChild("image");
  222. if (!imageElem)
  223. return false;
  224. position_ = Vector2(0.0f, info.GetMapHeight());
  225. source_ = imageElem.GetAttribute("source");
  226. String textureFilePath = GetParentPath(tmxFile_->GetName()) + source_;
  227. ResourceCache* cache = tmxFile_->GetSubsystem<ResourceCache>();
  228. SharedPtr<Texture2D> texture(cache->GetResource<Texture2D>(textureFilePath));
  229. if (!texture)
  230. {
  231. LOGERROR("Could not load texture " + textureFilePath);
  232. return false;
  233. }
  234. sprite_ = new Sprite2D(tmxFile_->GetContext());
  235. sprite_->SetTexture(texture);
  236. sprite_->SetRectangle(IntRect(0, 0, texture->GetWidth(), texture->GetHeight()));
  237. // Set image hot spot at left top
  238. sprite_->SetHotSpot(Vector2(0.0f, 1.0f));
  239. if (element.HasChild("properties"))
  240. LoadPropertySet(element.GetChild("properties"));
  241. return true;
  242. }
  243. Sprite2D* TmxImageLayer2D::GetSprite() const
  244. {
  245. return sprite_;
  246. }
  247. TmxFile2D::TmxFile2D(Context* context) :
  248. Resource(context)
  249. {
  250. }
  251. TmxFile2D::~TmxFile2D()
  252. {
  253. }
  254. void TmxFile2D::RegisterObject(Context* context)
  255. {
  256. context->RegisterFactory<TmxFile2D>();
  257. }
  258. bool TmxFile2D::BeginLoad(Deserializer& source)
  259. {
  260. if (GetName().Empty())
  261. SetName(source.GetName());
  262. loadXMLFile_ = new XMLFile(context_);
  263. if (!loadXMLFile_->Load(source))
  264. {
  265. LOGERROR("Load XML failed " + source.GetName());
  266. loadXMLFile_.Reset();
  267. return false;
  268. }
  269. XMLElement rootElem = loadXMLFile_->GetRoot("map");
  270. if (!rootElem)
  271. {
  272. LOGERROR("Invalid tmx file " + source.GetName());
  273. loadXMLFile_.Reset();
  274. return false;
  275. }
  276. // If we're async loading, request the texture now. Finish during EndLoad().
  277. if (GetAsyncLoadState() == ASYNC_LOADING)
  278. {
  279. for (XMLElement tileSetElem = rootElem.GetChild("tileset"); tileSetElem; tileSetElem = tileSetElem.GetNext("tileset"))
  280. {
  281. // Tile set defined in TSX file
  282. if (tileSetElem.HasAttribute("source"))
  283. {
  284. String source = tileSetElem.GetAttribute("source");
  285. SharedPtr<XMLFile> tsxXMLFile = LoadTSXFile(source);
  286. if (!tsxXMLFile)
  287. return false;
  288. tsxXMLFiles_[source] = tsxXMLFile;
  289. String textureFilePath =
  290. GetParentPath(GetName()) + tsxXMLFile->GetRoot("tileset").GetChild("image").GetAttribute("source");
  291. GetSubsystem<ResourceCache>()->BackgroundLoadResource<Texture2D>(textureFilePath, true, this);
  292. }
  293. else
  294. {
  295. String textureFilePath = GetParentPath(GetName()) + tileSetElem.GetChild("image").GetAttribute("source");
  296. GetSubsystem<ResourceCache>()->BackgroundLoadResource<Texture2D>(textureFilePath, true, this);
  297. }
  298. }
  299. for (XMLElement imageLayerElem = rootElem.GetChild("imagelayer"); imageLayerElem;
  300. imageLayerElem = imageLayerElem.GetNext("imagelayer"))
  301. {
  302. String textureFilePath = GetParentPath(GetName()) + imageLayerElem.GetChild("image").GetAttribute("source");
  303. GetSubsystem<ResourceCache>()->BackgroundLoadResource<Texture2D>(textureFilePath, true, this);
  304. }
  305. }
  306. return true;
  307. }
  308. bool TmxFile2D::EndLoad()
  309. {
  310. if (!loadXMLFile_)
  311. return false;
  312. XMLElement rootElem = loadXMLFile_->GetRoot("map");
  313. String version = rootElem.GetAttribute("version");
  314. if (version != "1.0")
  315. {
  316. LOGERROR("Invalid version");
  317. return false;
  318. }
  319. String orientation = rootElem.GetAttribute("orientation");
  320. if (orientation == "orthogonal")
  321. info_.orientation_ = O_ORTHOGONAL;
  322. else if (orientation == "isometric")
  323. info_.orientation_ = O_ISOMETRIC;
  324. else if (orientation == "staggered")
  325. info_.orientation_ = O_STAGGERED;
  326. else
  327. {
  328. LOGERROR("Unsupported orientation type " + orientation);
  329. return false;
  330. }
  331. info_.width_ = rootElem.GetInt("width");
  332. info_.height_ = rootElem.GetInt("height");
  333. info_.tileWidth_ = rootElem.GetFloat("tilewidth") * PIXEL_SIZE;
  334. info_.tileHeight_ = rootElem.GetFloat("tileheight") * PIXEL_SIZE;
  335. layers_.Clear();
  336. for (XMLElement childElement = rootElem.GetChild(); childElement; childElement = childElement.GetNext())
  337. {
  338. bool ret = true;
  339. String name = childElement.GetName();
  340. if (name == "tileset")
  341. ret = LoadTileSet(childElement);
  342. else if (name == "layer")
  343. {
  344. SharedPtr<TmxTileLayer2D> tileLayer (new TmxTileLayer2D(this));
  345. ret = tileLayer->Load(childElement, info_);
  346. layers_.Push((SharedPtr<TmxLayer2D>)(tileLayer));
  347. }
  348. else if (name == "objectgroup")
  349. {
  350. SharedPtr<TmxObjectGroup2D> objectGroup (new TmxObjectGroup2D(this));
  351. ret = objectGroup->Load(childElement, info_);
  352. layers_.Push((SharedPtr<TmxLayer2D>)(objectGroup));
  353. }
  354. else if (name == "imagelayer")
  355. {
  356. SharedPtr<TmxImageLayer2D> imageLayer (new TmxImageLayer2D(this));
  357. ret = imageLayer->Load(childElement, info_);
  358. layers_.Push((SharedPtr<TmxLayer2D>)(imageLayer));
  359. }
  360. if (!ret)
  361. {
  362. loadXMLFile_.Reset();
  363. tsxXMLFiles_.Clear();
  364. return false;
  365. }
  366. }
  367. loadXMLFile_.Reset();
  368. tsxXMLFiles_.Clear();
  369. return true;
  370. }
  371. Sprite2D* TmxFile2D::GetTileSprite(int gid) const
  372. {
  373. HashMap<int, SharedPtr<Sprite2D> >::ConstIterator i = gidToSpriteMapping_.Find(gid);
  374. if (i == gidToSpriteMapping_.End())
  375. return 0;
  376. return i->second_;
  377. }
  378. PropertySet2D* TmxFile2D::GetTilePropertySet(int gid) const
  379. {
  380. HashMap<int, SharedPtr<PropertySet2D> >::ConstIterator i = gidToPropertySetMapping_.Find(gid);
  381. if (i == gidToPropertySetMapping_.End())
  382. return 0;
  383. return i->second_;
  384. }
  385. TmxObjectGroup2D* TmxFile2D::GetTileObjectGroup(int gid) const
  386. {
  387. HashMap<int, SharedPtr<TmxObjectGroup2D> >::ConstIterator i = gidToObjectGroupMapping_.Find(gid);
  388. if (i == gidToObjectGroupMapping_.End())
  389. return 0;
  390. return i->second_;
  391. }
  392. const TmxLayer2D* TmxFile2D::GetLayer(unsigned index) const
  393. {
  394. if (index >= layers_.Size())
  395. return 0;
  396. return layers_[index];
  397. }
  398. SharedPtr<XMLFile> TmxFile2D::LoadTSXFile(const String& source)
  399. {
  400. String tsxFilePath = GetParentPath(GetName()) + source;
  401. SharedPtr<File> tsxFile = GetSubsystem<ResourceCache>()->GetFile(tsxFilePath);
  402. SharedPtr<XMLFile> tsxXMLFile(new XMLFile(context_));
  403. if (!tsxFile || !tsxXMLFile->Load(*tsxFile))
  404. {
  405. LOGERROR("Load TSX file failed " + tsxFilePath);
  406. return SharedPtr<XMLFile>();
  407. }
  408. return tsxXMLFile;
  409. }
  410. bool TmxFile2D::LoadTileSet(const XMLElement& element)
  411. {
  412. int firstgid = element.GetInt("firstgid");
  413. XMLElement tileSetElem;
  414. if (element.HasAttribute("source"))
  415. {
  416. String source = element.GetAttribute("source");
  417. HashMap<String, SharedPtr<XMLFile> >::Iterator i = tsxXMLFiles_.Find(source);
  418. if (i == tsxXMLFiles_.End())
  419. {
  420. SharedPtr<XMLFile> tsxXMLFile = LoadTSXFile(source);
  421. if (!tsxXMLFile)
  422. return false;
  423. // Add to mapping to avoid release
  424. tsxXMLFiles_[source] = tsxXMLFile;
  425. tileSetElem = tsxXMLFile->GetRoot("tileset");
  426. }
  427. else
  428. tileSetElem = i->second_->GetRoot("tileset");
  429. }
  430. else
  431. tileSetElem = element;
  432. XMLElement imageElem = tileSetElem.GetChild("image");
  433. String textureFilePath = GetParentPath(GetName()) + imageElem.GetAttribute("source");
  434. ResourceCache* cache = GetSubsystem<ResourceCache>();
  435. SharedPtr<Texture2D> texture(cache->GetResource<Texture2D>(textureFilePath));
  436. if (!texture)
  437. {
  438. LOGERROR("Could not load texture " + textureFilePath);
  439. return false;
  440. }
  441. // reduces border tile sample errors
  442. texture->SetFilterMode(FILTER_NEAREST);
  443. tileSetTextures_.Push(texture);
  444. int tileWidth = tileSetElem.GetInt("tilewidth");
  445. int tileHeight = tileSetElem.GetInt("tileheight");
  446. int spacing = tileSetElem.GetInt("spacing");
  447. int margin = tileSetElem.GetInt("margin");
  448. int imageWidth = imageElem.GetInt("width");
  449. int imageHeight = imageElem.GetInt("height");
  450. // Set hot spot at left bottom
  451. Vector2 hotSpot(0.0f, 0.0f);
  452. if (tileSetElem.HasChild("tileoffset"))
  453. {
  454. XMLElement offsetElem = tileSetElem.GetChild("tileoffset");
  455. hotSpot.x_ += offsetElem.GetFloat("x") / (float)tileWidth;
  456. hotSpot.y_ += offsetElem.GetFloat("y") / (float)tileHeight;
  457. }
  458. int gid = firstgid;
  459. for (int y = margin; y + tileHeight <= imageHeight - margin; y += tileHeight + spacing)
  460. {
  461. for (int x = margin; x + tileWidth <= imageWidth - margin; x += tileWidth + spacing)
  462. {
  463. SharedPtr<Sprite2D> sprite(new Sprite2D(context_));
  464. sprite->SetTexture(texture);
  465. sprite->SetRectangle(IntRect(x, y, x + tileWidth, y + tileHeight));
  466. sprite->SetHotSpot(hotSpot);
  467. gidToSpriteMapping_[gid++] = sprite;
  468. }
  469. }
  470. for (XMLElement tileElem = tileSetElem.GetChild("tile"); tileElem; tileElem = tileElem.GetNext("tile"))
  471. {
  472. if (tileElem.HasChild("properties"))
  473. {
  474. SharedPtr<PropertySet2D> propertySet(new PropertySet2D());
  475. propertySet->Load(tileElem.GetChild("properties"));
  476. gidToPropertySetMapping_[firstgid + tileElem.GetInt("id")] = propertySet;
  477. }
  478. // collision information
  479. if (tileElem.HasChild("objectgroup"))
  480. {
  481. // ok, when you use multiple tile sets the "info"
  482. // numbers can be different, this is a bit of a hack
  483. // if something is wrong, look here... may have to need
  484. // to refactor "info" to be per set
  485. float _tileWidth = info_.tileWidth_;
  486. float _tileHeight = info_.tileHeight_;
  487. info_.tileHeight_ = (float) tileHeight * PIXEL_SIZE;
  488. info_.tileWidth_ = (float) tileWidth * PIXEL_SIZE;
  489. XMLElement groupElem = tileElem.GetChild("objectgroup");
  490. TmxObjectGroup2D* objectGroup = new TmxObjectGroup2D(this);
  491. if (!objectGroup->Load(groupElem, info_, true))
  492. {
  493. LOGERROR("Could not load objectgroup");
  494. objectGroup->ReleaseRef();
  495. }
  496. else
  497. {
  498. gidToObjectGroupMapping_[firstgid + tileElem.GetInt("id")] = objectGroup;
  499. }
  500. info_.tileWidth_ = _tileWidth;
  501. info_.tileHeight_ = _tileHeight;
  502. }
  503. }
  504. return true;
  505. }
  506. }