TmxFile2D.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. //
  2. // Copyright (c) 2008-2016 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 "../Urho2D/Sprite2D.h"
  30. #include "../Urho2D/TmxFile2D.h"
  31. #include "../DebugNew.h"
  32. namespace Urho3D
  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. URHO3D_LOGERROR("Could not find data in layer");
  85. return false;
  86. }
  87. if (dataElem.HasAttribute("encoding") && dataElem.GetAttribute("encoding") != "xml")
  88. {
  89. URHO3D_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. tiles_[y * width_ + x] = tile;
  108. }
  109. tileElem = tileElem.GetNext("tile");
  110. }
  111. }
  112. if (element.HasChild("properties"))
  113. LoadPropertySet(element.GetChild("properties"));
  114. return true;
  115. }
  116. Tile2D* TmxTileLayer2D::GetTile(int x, int y) const
  117. {
  118. if (x < 0 || x >= width_ || y < 0 || y >= height_)
  119. return 0;
  120. return tiles_[y * width_ + x];
  121. }
  122. TmxObjectGroup2D::TmxObjectGroup2D(TmxFile2D* tmxFile) :
  123. TmxLayer2D(tmxFile, LT_OBJECT_GROUP)
  124. {
  125. }
  126. bool TmxObjectGroup2D::Load(const XMLElement& element, const TileMapInfo2D& info)
  127. {
  128. LoadInfo(element);
  129. for (XMLElement objectElem = element.GetChild("object"); objectElem; objectElem = objectElem.GetNext("object"))
  130. {
  131. SharedPtr<TileMapObject2D> object(new TileMapObject2D());
  132. if (objectElem.HasAttribute("name"))
  133. object->name_ = objectElem.GetAttribute("name");
  134. if (objectElem.HasAttribute("type"))
  135. object->type_ = objectElem.GetAttribute("type");
  136. if (objectElem.HasAttribute("gid"))
  137. object->objectType_ = OT_TILE;
  138. else if (objectElem.HasChild("polygon"))
  139. object->objectType_ = OT_POLYGON;
  140. else if (objectElem.HasChild("polyline"))
  141. object->objectType_ = OT_POLYLINE;
  142. else if (objectElem.HasChild("ellipse"))
  143. object->objectType_ = OT_ELLIPSE;
  144. else
  145. object->objectType_ = OT_RECTANGLE;
  146. const Vector2 position(objectElem.GetFloat("x"), objectElem.GetFloat("y"));
  147. const Vector2 size(objectElem.GetFloat("width"), objectElem.GetFloat("height"));
  148. switch (object->objectType_)
  149. {
  150. case OT_RECTANGLE:
  151. case OT_ELLIPSE:
  152. object->position_ = info.ConvertPosition(Vector2(position.x_, position.y_ + size.y_));
  153. object->size_ = Vector2(size.x_ * PIXEL_SIZE, size.y_ * PIXEL_SIZE);
  154. break;
  155. case OT_TILE:
  156. object->position_ = info.ConvertPosition(position);
  157. object->gid_ = objectElem.GetInt("gid");
  158. object->sprite_ = tmxFile_->GetTileSprite(object->gid_);
  159. if (objectElem.HasAttribute("width") || objectElem.HasAttribute("height"))
  160. {
  161. object->size_ = Vector2(size.x_ * PIXEL_SIZE, size.y_ * PIXEL_SIZE);
  162. }
  163. else if (object->sprite_)
  164. {
  165. IntVector2 spriteSize = object->sprite_->GetRectangle().Size();
  166. object->size_ = Vector2(spriteSize.x_, spriteSize.y_);
  167. }
  168. break;
  169. case OT_POLYGON:
  170. case OT_POLYLINE:
  171. {
  172. Vector<String> points;
  173. const char* name = object->objectType_ == OT_POLYGON ? "polygon" : "polyline";
  174. XMLElement polygonElem = objectElem.GetChild(name);
  175. points = polygonElem.GetAttribute("points").Split(' ');
  176. if (points.Size() <= 1)
  177. continue;
  178. object->points_.Resize(points.Size());
  179. for (unsigned i = 0; i < points.Size(); ++i)
  180. {
  181. points[i].Replace(',', ' ');
  182. Vector2 point = position + ToVector2(points[i]);
  183. object->points_[i] = info.ConvertPosition(point);
  184. }
  185. }
  186. break;
  187. default: break;
  188. }
  189. if (objectElem.HasChild("properties"))
  190. {
  191. object->propertySet_ = new PropertySet2D();
  192. object->propertySet_->Load(objectElem.GetChild("properties"));
  193. }
  194. objects_.Push(object);
  195. }
  196. if (element.HasChild("properties"))
  197. LoadPropertySet(element.GetChild("properties"));
  198. return true;
  199. }
  200. TileMapObject2D* TmxObjectGroup2D::GetObject(unsigned index) const
  201. {
  202. if (index >= objects_.Size())
  203. return 0;
  204. return objects_[index];
  205. }
  206. TmxImageLayer2D::TmxImageLayer2D(TmxFile2D* tmxFile) :
  207. TmxLayer2D(tmxFile, LT_IMAGE_LAYER)
  208. {
  209. }
  210. bool TmxImageLayer2D::Load(const XMLElement& element, const TileMapInfo2D& info)
  211. {
  212. LoadInfo(element);
  213. XMLElement imageElem = element.GetChild("image");
  214. if (!imageElem)
  215. return false;
  216. position_ = Vector2(0.0f, info.GetMapHeight());
  217. source_ = imageElem.GetAttribute("source");
  218. String textureFilePath = GetParentPath(tmxFile_->GetName()) + source_;
  219. ResourceCache* cache = tmxFile_->GetSubsystem<ResourceCache>();
  220. SharedPtr<Texture2D> texture(cache->GetResource<Texture2D>(textureFilePath));
  221. if (!texture)
  222. {
  223. URHO3D_LOGERROR("Could not load texture " + textureFilePath);
  224. return false;
  225. }
  226. sprite_ = new Sprite2D(tmxFile_->GetContext());
  227. sprite_->SetTexture(texture);
  228. sprite_->SetRectangle(IntRect(0, 0, texture->GetWidth(), texture->GetHeight()));
  229. // Set image hot spot at left top
  230. sprite_->SetHotSpot(Vector2(0.0f, 1.0f));
  231. if (element.HasChild("properties"))
  232. LoadPropertySet(element.GetChild("properties"));
  233. return true;
  234. }
  235. Sprite2D* TmxImageLayer2D::GetSprite() const
  236. {
  237. return sprite_;
  238. }
  239. TmxFile2D::TmxFile2D(Context* context) :
  240. Resource(context)
  241. {
  242. }
  243. TmxFile2D::~TmxFile2D()
  244. {
  245. for (unsigned i = 0; i < layers_.Size(); ++i)
  246. delete layers_[i];
  247. }
  248. void TmxFile2D::RegisterObject(Context* context)
  249. {
  250. context->RegisterFactory<TmxFile2D>();
  251. }
  252. bool TmxFile2D::BeginLoad(Deserializer& source)
  253. {
  254. if (GetName().Empty())
  255. SetName(source.GetName());
  256. loadXMLFile_ = new XMLFile(context_);
  257. if (!loadXMLFile_->Load(source))
  258. {
  259. URHO3D_LOGERROR("Load XML failed " + source.GetName());
  260. loadXMLFile_.Reset();
  261. return false;
  262. }
  263. XMLElement rootElem = loadXMLFile_->GetRoot("map");
  264. if (!rootElem)
  265. {
  266. URHO3D_LOGERROR("Invalid tmx file " + source.GetName());
  267. loadXMLFile_.Reset();
  268. return false;
  269. }
  270. // If we're async loading, request the texture now. Finish during EndLoad().
  271. if (GetAsyncLoadState() == ASYNC_LOADING)
  272. {
  273. for (XMLElement tileSetElem = rootElem.GetChild("tileset"); tileSetElem; tileSetElem = tileSetElem.GetNext("tileset"))
  274. {
  275. // Tile set defined in TSX file
  276. if (tileSetElem.HasAttribute("source"))
  277. {
  278. String source = tileSetElem.GetAttribute("source");
  279. SharedPtr<XMLFile> tsxXMLFile = LoadTSXFile(source);
  280. if (!tsxXMLFile)
  281. return false;
  282. tsxXMLFiles_[source] = tsxXMLFile;
  283. String textureFilePath =
  284. GetParentPath(GetName()) + tsxXMLFile->GetRoot("tileset").GetChild("image").GetAttribute("source");
  285. GetSubsystem<ResourceCache>()->BackgroundLoadResource<Texture2D>(textureFilePath, true, this);
  286. }
  287. else
  288. {
  289. String textureFilePath = GetParentPath(GetName()) + tileSetElem.GetChild("image").GetAttribute("source");
  290. GetSubsystem<ResourceCache>()->BackgroundLoadResource<Texture2D>(textureFilePath, true, this);
  291. }
  292. }
  293. for (XMLElement imageLayerElem = rootElem.GetChild("imagelayer"); imageLayerElem;
  294. imageLayerElem = imageLayerElem.GetNext("imagelayer"))
  295. {
  296. String textureFilePath = GetParentPath(GetName()) + imageLayerElem.GetChild("image").GetAttribute("source");
  297. GetSubsystem<ResourceCache>()->BackgroundLoadResource<Texture2D>(textureFilePath, true, this);
  298. }
  299. }
  300. return true;
  301. }
  302. bool TmxFile2D::EndLoad()
  303. {
  304. if (!loadXMLFile_)
  305. return false;
  306. XMLElement rootElem = loadXMLFile_->GetRoot("map");
  307. String version = rootElem.GetAttribute("version");
  308. if (version != "1.0")
  309. {
  310. URHO3D_LOGERROR("Invalid version");
  311. return false;
  312. }
  313. String orientation = rootElem.GetAttribute("orientation");
  314. if (orientation == "orthogonal")
  315. info_.orientation_ = O_ORTHOGONAL;
  316. else if (orientation == "isometric")
  317. info_.orientation_ = O_ISOMETRIC;
  318. else if (orientation == "staggered")
  319. info_.orientation_ = O_STAGGERED;
  320. else if (orientation == "hexagonal")
  321. info_.orientation_ = O_HEXAGONAL;
  322. else
  323. {
  324. URHO3D_LOGERROR("Unsupported orientation type " + orientation);
  325. return false;
  326. }
  327. info_.width_ = rootElem.GetInt("width");
  328. info_.height_ = rootElem.GetInt("height");
  329. info_.tileWidth_ = rootElem.GetFloat("tilewidth") * PIXEL_SIZE;
  330. info_.tileHeight_ = rootElem.GetFloat("tileheight") * PIXEL_SIZE;
  331. for (unsigned i = 0; i < layers_.Size(); ++i)
  332. delete layers_[i];
  333. layers_.Clear();
  334. for (XMLElement childElement = rootElem.GetChild(); childElement; childElement = childElement.GetNext())
  335. {
  336. bool ret = true;
  337. String name = childElement.GetName();
  338. if (name == "tileset")
  339. ret = LoadTileSet(childElement);
  340. else if (name == "layer")
  341. {
  342. TmxTileLayer2D* tileLayer = new TmxTileLayer2D(this);
  343. ret = tileLayer->Load(childElement, info_);
  344. layers_.Push(tileLayer);
  345. }
  346. else if (name == "objectgroup")
  347. {
  348. TmxObjectGroup2D* objectGroup = new TmxObjectGroup2D(this);
  349. ret = objectGroup->Load(childElement, info_);
  350. layers_.Push(objectGroup);
  351. }
  352. else if (name == "imagelayer")
  353. {
  354. TmxImageLayer2D* imageLayer = new TmxImageLayer2D(this);
  355. ret = imageLayer->Load(childElement, info_);
  356. layers_.Push(imageLayer);
  357. }
  358. if (!ret)
  359. {
  360. loadXMLFile_.Reset();
  361. tsxXMLFiles_.Clear();
  362. return false;
  363. }
  364. }
  365. loadXMLFile_.Reset();
  366. tsxXMLFiles_.Clear();
  367. return true;
  368. }
  369. bool TmxFile2D::SetInfo(Orientation2D orientation, int width, int height, float tileWidth, float tileHeight)
  370. {
  371. if (layers_.Size() > 0)
  372. return false;
  373. info_.orientation_ = orientation;
  374. info_.width_ = width;
  375. info_.height_ = height;
  376. info_.tileWidth_ = tileWidth * PIXEL_SIZE;
  377. info_.tileHeight_ = tileHeight * PIXEL_SIZE;
  378. return true;
  379. }
  380. void TmxFile2D::AddLayer(unsigned index, TmxLayer2D *layer)
  381. {
  382. if (index > layers_.Size())
  383. layers_.Push(layer);
  384. else // index <= layers_.size()
  385. layers_.Insert(index, layer);
  386. }
  387. void TmxFile2D::AddLayer(TmxLayer2D *layer)
  388. {
  389. layers_.Push(layer);
  390. }
  391. Sprite2D* TmxFile2D::GetTileSprite(int gid) const
  392. {
  393. HashMap<int, SharedPtr<Sprite2D> >::ConstIterator i = gidToSpriteMapping_.Find(gid);
  394. if (i == gidToSpriteMapping_.End())
  395. return 0;
  396. return i->second_;
  397. }
  398. PropertySet2D* TmxFile2D::GetTilePropertySet(int gid) const
  399. {
  400. HashMap<int, SharedPtr<PropertySet2D> >::ConstIterator i = gidToPropertySetMapping_.Find(gid);
  401. if (i == gidToPropertySetMapping_.End())
  402. return 0;
  403. return i->second_;
  404. }
  405. const TmxLayer2D* TmxFile2D::GetLayer(unsigned index) const
  406. {
  407. if (index >= layers_.Size())
  408. return 0;
  409. return layers_[index];
  410. }
  411. SharedPtr<XMLFile> TmxFile2D::LoadTSXFile(const String& source)
  412. {
  413. String tsxFilePath = GetParentPath(GetName()) + source;
  414. SharedPtr<File> tsxFile = GetSubsystem<ResourceCache>()->GetFile(tsxFilePath);
  415. SharedPtr<XMLFile> tsxXMLFile(new XMLFile(context_));
  416. if (!tsxFile || !tsxXMLFile->Load(*tsxFile))
  417. {
  418. URHO3D_LOGERROR("Load TSX file failed " + tsxFilePath);
  419. return SharedPtr<XMLFile>();
  420. }
  421. return tsxXMLFile;
  422. }
  423. bool TmxFile2D::LoadTileSet(const XMLElement& element)
  424. {
  425. int firstgid = element.GetInt("firstgid");
  426. XMLElement tileSetElem;
  427. if (element.HasAttribute("source"))
  428. {
  429. String source = element.GetAttribute("source");
  430. HashMap<String, SharedPtr<XMLFile> >::Iterator i = tsxXMLFiles_.Find(source);
  431. if (i == tsxXMLFiles_.End())
  432. {
  433. SharedPtr<XMLFile> tsxXMLFile = LoadTSXFile(source);
  434. if (!tsxXMLFile)
  435. return false;
  436. // Add to napping to avoid release
  437. tsxXMLFiles_[source] = tsxXMLFile;
  438. tileSetElem = tsxXMLFile->GetRoot("tileset");
  439. }
  440. else
  441. tileSetElem = i->second_->GetRoot("tileset");
  442. }
  443. else
  444. tileSetElem = element;
  445. XMLElement imageElem = tileSetElem.GetChild("image");
  446. String textureFilePath = GetParentPath(GetName()) + imageElem.GetAttribute("source");
  447. ResourceCache* cache = GetSubsystem<ResourceCache>();
  448. SharedPtr<Texture2D> texture(cache->GetResource<Texture2D>(textureFilePath));
  449. if (!texture)
  450. {
  451. URHO3D_LOGERROR("Could not load texture " + textureFilePath);
  452. return false;
  453. }
  454. tileSetTextures_.Push(texture);
  455. int tileWidth = tileSetElem.GetInt("tilewidth");
  456. int tileHeight = tileSetElem.GetInt("tileheight");
  457. int spacing = tileSetElem.GetInt("spacing");
  458. int margin = tileSetElem.GetInt("margin");
  459. int imageWidth = imageElem.GetInt("width");
  460. int imageHeight = imageElem.GetInt("height");
  461. // Set hot spot at left bottom
  462. Vector2 hotSpot(0.0f, 0.0f);
  463. if (tileSetElem.HasChild("tileoffset"))
  464. {
  465. XMLElement offsetElem = tileSetElem.GetChild("tileoffset");
  466. hotSpot.x_ += offsetElem.GetFloat("x") / (float)tileWidth;
  467. hotSpot.y_ += offsetElem.GetFloat("y") / (float)tileHeight;
  468. }
  469. int gid = firstgid;
  470. for (int y = margin; y + tileHeight <= imageHeight - margin; y += tileHeight + spacing)
  471. {
  472. for (int x = margin; x + tileWidth <= imageWidth - margin; x += tileWidth + spacing)
  473. {
  474. SharedPtr<Sprite2D> sprite(new Sprite2D(context_));
  475. sprite->SetTexture(texture);
  476. sprite->SetRectangle(IntRect(x, y, x + tileWidth, y + tileHeight));
  477. sprite->SetHotSpot(hotSpot);
  478. gidToSpriteMapping_[gid++] = sprite;
  479. }
  480. }
  481. for (XMLElement tileElem = tileSetElem.GetChild("tile"); tileElem; tileElem = tileElem.GetNext("tile"))
  482. {
  483. if (tileElem.HasChild("properties"))
  484. {
  485. SharedPtr<PropertySet2D> propertySet(new PropertySet2D());
  486. propertySet->Load(tileElem.GetChild("properties"));
  487. gidToPropertySetMapping_[firstgid + tileElem.GetInt("id")] = propertySet;
  488. }
  489. }
  490. return true;
  491. }
  492. }