TiledMapTilesetImporter.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.IO;
  3. using System.Xml.Serialization;
  4. using Microsoft.Xna.Framework.Content.Pipeline;
  5. using MonoGame.Extended.Content.Tiled;
  6. namespace MonoGame.Extended.Content.Pipeline.Tiled
  7. {
  8. [ContentImporter(".tsx", DefaultProcessor = "TiledMapTilesetProcessor", DisplayName = "Tiled Map Tileset Importer - MonoGame.Extended")]
  9. public class TiledMapTilesetImporter : ContentImporter<TiledMapTilesetContentItem>
  10. {
  11. public override TiledMapTilesetContentItem Import(string filePath, ContentImporterContext context)
  12. {
  13. try
  14. {
  15. if (filePath == null)
  16. throw new ArgumentNullException(nameof(filePath));
  17. ContentLogger.Logger = context.Logger;
  18. ContentLogger.Log($"Importing '{filePath}'");
  19. var tileset = DeserializeTiledMapTilesetContent(filePath, context);
  20. ContentLogger.Log($"Imported '{filePath}'");
  21. return new TiledMapTilesetContentItem(tileset);
  22. }
  23. catch (Exception e)
  24. {
  25. context.Logger.LogImportantMessage(e.StackTrace);
  26. throw;
  27. }
  28. }
  29. private TiledMapTilesetContent DeserializeTiledMapTilesetContent(string filePath, ContentImporterContext context)
  30. {
  31. using (var reader = new StreamReader(filePath))
  32. {
  33. var tilesetSerializer = new XmlSerializer(typeof(TiledMapTilesetContent));
  34. var tileset = (TiledMapTilesetContent)tilesetSerializer.Deserialize(reader);
  35. if (tileset.Image is not null)
  36. tileset.Image.Source = context.AddDependencyWithLogging(filePath, tileset.Image.Source);
  37. foreach (var tile in tileset.Tiles)
  38. {
  39. foreach (var obj in tile.Objects)
  40. {
  41. if (!string.IsNullOrWhiteSpace(obj.TemplateSource))
  42. obj.TemplateSource = context.AddDependencyWithLogging(filePath, obj.TemplateSource);
  43. }
  44. if (tile.Image is not null)
  45. tile.Image.Source = context.AddDependencyWithLogging(filePath, tile.Image.Source);
  46. }
  47. return tileset;
  48. }
  49. }
  50. }
  51. }