TiledTmxParser.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Xml;
  5. using System.Xml.Serialization;
  6. using Microsoft.Xna.Framework.Graphics;
  7. using MonoGame.Extended.Tilemaps.Parsers;
  8. using MonoGame.Extended.Tilemaps.Tiled.Converters;
  9. namespace MonoGame.Extended.Tilemaps.Tiled;
  10. /// <summary>
  11. /// Parser for Tiled TMX (Tile Map XML) files.
  12. /// </summary>
  13. public class TiledTmxParser : ITilemapParser
  14. {
  15. private readonly string _baseDirectory;
  16. /// <summary>
  17. /// Initializes a new instance of the <see cref="TiledTmxParser"/> class.
  18. /// </summary>
  19. /// <param name="baseDirectory">
  20. /// Optional base directory for resolving relative file paths. If provided, file paths in
  21. /// <see cref="ParseFromFile"/> will be resolved relative to this directory.
  22. /// If <see langword="null"/>, paths are resolved from the file's own location.
  23. /// </param>
  24. public TiledTmxParser(string baseDirectory = null)
  25. {
  26. _baseDirectory = baseDirectory;
  27. }
  28. /// <inheritdoc/>
  29. public IReadOnlyList<string> SupportedExtensions => new[] { ".tmx" };
  30. /// <summary>
  31. /// Parses a Tiled TMX file from disk.
  32. /// </summary>
  33. /// <param name="path">The path to the TMX file.</param>
  34. /// <param name="graphicsDevice">The graphics device for loading textures.</param>
  35. /// <returns>The parsed tilemap.</returns>
  36. /// <exception cref="ArgumentNullException">Thrown when path or graphicsDevice is null.</exception>
  37. /// <exception cref="FileNotFoundException">Thrown when the file does not exist.</exception>
  38. /// <exception cref="TilemapParseException">Thrown when parsing fails.</exception>
  39. public Tilemap ParseFromFile(string path, GraphicsDevice graphicsDevice)
  40. {
  41. if (string.IsNullOrEmpty(path))
  42. {
  43. throw new ArgumentNullException(nameof(path));
  44. }
  45. if (graphicsDevice == null)
  46. {
  47. throw new ArgumentNullException(nameof(graphicsDevice));
  48. }
  49. // Resolve full path using base directory if provided
  50. string fullPath = _baseDirectory != null
  51. ? Path.Combine(_baseDirectory, path)
  52. : path;
  53. if (!File.Exists(fullPath))
  54. {
  55. throw new FileNotFoundException($"Tilemap file not found: {fullPath}", fullPath);
  56. }
  57. try
  58. {
  59. // Get the directory of the TMX file for resolving relative paths
  60. string baseDirectory = Path.GetDirectoryName(Path.GetFullPath(fullPath));
  61. // Load and deserialize TMX file
  62. TiledMapXml mapXml;
  63. using (Stream stream = File.OpenRead(fullPath))
  64. {
  65. mapXml = DeserializeMap(stream);
  66. }
  67. // Load external tilesets (TSX files)
  68. LoadExternalTilesets(mapXml, baseDirectory);
  69. // Load textures for tilesets
  70. LoadTilesetTextures(mapXml, baseDirectory, graphicsDevice);
  71. // Load textures for image layers
  72. LoadImageLayerTextures(mapXml, baseDirectory, graphicsDevice);
  73. // Convert to public API
  74. Tilemap tilemap = TilemapConverter.Convert(mapXml);
  75. return tilemap;
  76. }
  77. catch (TilemapParseException)
  78. {
  79. throw;
  80. }
  81. catch (Exception ex)
  82. {
  83. throw new TilemapParseException($"Failed to parse TMX file: {fullPath}", ex);
  84. }
  85. }
  86. /// <summary>
  87. /// Parses a Tiled TMX file from a stream.
  88. /// </summary>
  89. /// <param name="stream">The stream containing TMX data.</param>
  90. /// <param name="graphicsDevice">The graphics device for loading textures.</param>
  91. /// <param name="basePath">
  92. /// Optional base path for resolving relative file references. If not provided,
  93. /// uses the base directory from the constructor, or the current directory if neither is set.
  94. /// </param>
  95. /// <returns>The parsed tilemap.</returns>
  96. /// <exception cref="ArgumentNullException">Thrown when stream or graphicsDevice is null.</exception>
  97. /// <exception cref="TilemapParseException">Thrown when parsing fails.</exception>
  98. public Tilemap ParseFromStream(Stream stream, GraphicsDevice graphicsDevice, string basePath = null)
  99. {
  100. if (stream == null)
  101. {
  102. throw new ArgumentNullException(nameof(stream));
  103. }
  104. if (graphicsDevice == null)
  105. {
  106. throw new ArgumentNullException(nameof(graphicsDevice));
  107. }
  108. try
  109. {
  110. // Use provided basePath, fall back to constructor base directory, then current directory
  111. string baseDirectory = basePath ?? _baseDirectory ?? Directory.GetCurrentDirectory();
  112. // Deserialize TMX from stream
  113. TiledMapXml mapXml = DeserializeMap(stream);
  114. // Load external tilesets
  115. LoadExternalTilesets(mapXml, baseDirectory);
  116. // Load textures
  117. LoadTilesetTextures(mapXml, baseDirectory, graphicsDevice);
  118. LoadImageLayerTextures(mapXml, baseDirectory, graphicsDevice);
  119. // Convert to public API
  120. Tilemap tilemap = TilemapConverter.Convert(mapXml);
  121. return tilemap;
  122. }
  123. catch (TilemapParseException)
  124. {
  125. throw;
  126. }
  127. catch (Exception ex)
  128. {
  129. throw new TilemapParseException("Failed to parse TMX from stream", ex);
  130. }
  131. }
  132. private TiledMapXml DeserializeMap(Stream stream)
  133. {
  134. try
  135. {
  136. XmlSerializer serializer = new XmlSerializer(typeof(TiledMapXml));
  137. // Configure XML reader to ignore DTD (Document Type Definition)
  138. // TMX files often include DTD declarations which can cause security warnings
  139. XmlReaderSettings settings = new XmlReaderSettings
  140. {
  141. DtdProcessing = DtdProcessing.Ignore,
  142. XmlResolver = null
  143. };
  144. using (XmlReader reader = XmlReader.Create(stream, settings))
  145. {
  146. return (TiledMapXml)serializer.Deserialize(reader);
  147. }
  148. }
  149. catch (Exception ex)
  150. {
  151. throw new TilemapParseException("Failed to deserialize TMX XML", ex);
  152. }
  153. }
  154. private void LoadExternalTilesets(TiledMapXml mapXml, string baseDirectory)
  155. {
  156. if (mapXml.Tilesets == null)
  157. {
  158. return;
  159. }
  160. foreach (TiledTilesetRefXml tilesetRef in mapXml.Tilesets)
  161. {
  162. // Skip if not an external tileset
  163. if (string.IsNullOrEmpty(tilesetRef.Source))
  164. {
  165. continue;
  166. }
  167. // Resolve TSX file path
  168. string tsxPath = Path.Combine(baseDirectory, tilesetRef.Source);
  169. if (!File.Exists(tsxPath))
  170. {
  171. throw new TilemapParseException($"External tileset file not found: {tsxPath}");
  172. }
  173. // Load and deserialize TSX file
  174. TiledTilesetXml tilesetXml;
  175. using (Stream stream = File.OpenRead(tsxPath))
  176. {
  177. try
  178. {
  179. XmlSerializer serializer = new XmlSerializer(typeof(TiledTilesetXml));
  180. // Configure XML reader to ignore DTD
  181. XmlReaderSettings settings = new XmlReaderSettings
  182. {
  183. DtdProcessing = DtdProcessing.Ignore,
  184. XmlResolver = null
  185. };
  186. using (XmlReader reader = XmlReader.Create(stream, settings))
  187. {
  188. tilesetXml = (TiledTilesetXml)serializer.Deserialize(reader);
  189. }
  190. }
  191. catch (Exception ex)
  192. {
  193. throw new TilemapParseException($"Failed to parse TSX file: {tsxPath}", ex);
  194. }
  195. }
  196. // Store the tileset data (firstgid comes from the map, rest from TSX)
  197. tilesetXml.FirstGlobalId = tilesetRef.FirstGlobalId;
  198. tilesetRef.TilesetData = tilesetXml;
  199. }
  200. }
  201. private void LoadTilesetTextures(TiledMapXml mapXml, string baseDirectory, GraphicsDevice graphicsDevice)
  202. {
  203. if (mapXml.Tilesets == null)
  204. {
  205. return;
  206. }
  207. foreach (TiledTilesetRefXml tilesetRef in mapXml.Tilesets)
  208. {
  209. // Get the actual tileset data (from external TSX or inline)
  210. // TilesetData is non-null for external tilesets, null for inline
  211. TiledTilesetXml tilesetXml = tilesetRef.TilesetData ?? tilesetRef;
  212. // Load main tileset image
  213. if (tilesetXml.Image != null && !string.IsNullOrEmpty(tilesetXml.Image.Source))
  214. {
  215. string imagePath = Path.Combine(baseDirectory, tilesetXml.Image.Source);
  216. tilesetXml.Image.Texture = LoadTexture(imagePath, graphicsDevice);
  217. }
  218. // Load individual tile images (for image collection tilesets)
  219. if (tilesetXml.Tiles != null)
  220. {
  221. foreach (TiledTileXml tile in tilesetXml.Tiles)
  222. {
  223. if (tile.Image != null && !string.IsNullOrEmpty(tile.Image.Source))
  224. {
  225. string imagePath = Path.Combine(baseDirectory, tile.Image.Source);
  226. tile.Image.Texture = LoadTexture(imagePath, graphicsDevice);
  227. }
  228. }
  229. }
  230. }
  231. }
  232. private void LoadImageLayerTextures(TiledMapXml mapXml, string baseDirectory, GraphicsDevice graphicsDevice)
  233. {
  234. if (mapXml.Layers == null)
  235. {
  236. return;
  237. }
  238. foreach (TiledLayerXml layer in mapXml.Layers)
  239. {
  240. LoadImageLayerTexturesRecursive(layer, baseDirectory, graphicsDevice);
  241. }
  242. }
  243. private void LoadImageLayerTexturesRecursive(TiledLayerXml layer, string baseDirectory, GraphicsDevice graphicsDevice)
  244. {
  245. // Handle image layers
  246. if (layer is TiledImageLayerXml imageLayer)
  247. {
  248. if (imageLayer.Image != null && !string.IsNullOrEmpty(imageLayer.Image.Source))
  249. {
  250. string imagePath = Path.Combine(baseDirectory, imageLayer.Image.Source);
  251. imageLayer.Image.Texture = LoadTexture(imagePath, graphicsDevice);
  252. }
  253. }
  254. // Recursively handle group layers
  255. if (layer is TiledGroupLayerXml groupLayer && groupLayer.Layers != null)
  256. {
  257. foreach (TiledLayerXml childLayer in groupLayer.Layers)
  258. {
  259. LoadImageLayerTexturesRecursive(childLayer, baseDirectory, graphicsDevice);
  260. }
  261. }
  262. }
  263. private Texture2D LoadTexture(string filePath, GraphicsDevice graphicsDevice)
  264. {
  265. if (!File.Exists(filePath))
  266. {
  267. throw new TilemapParseException($"Texture file not found: {filePath}");
  268. }
  269. try
  270. {
  271. using (var stream = File.OpenRead(filePath))
  272. {
  273. return Texture2D.FromStream(graphicsDevice, stream);
  274. }
  275. }
  276. catch (Exception ex)
  277. {
  278. throw new TilemapParseException($"Failed to load texture: {filePath}", ex);
  279. }
  280. }
  281. }