TiledMapTileset.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.Xna.Framework;
  5. using Microsoft.Xna.Framework.Graphics;
  6. using MonoGame.Extended.Graphics;
  7. namespace MonoGame.Extended.Tiled
  8. {
  9. public interface ITileset
  10. {
  11. int ActualWidth { get; }
  12. int Columns { get; }
  13. int ActualHeight { get; }
  14. int Rows { get; }
  15. int TileWidth { get; }
  16. int TileHeight { get; }
  17. Texture2D Texture { get; }
  18. Texture2DRegion GetRegion(int column, int row);
  19. }
  20. public class TiledMapTileset : ITileset
  21. {
  22. public TiledMapTileset(Texture2D texture, string type, int tileWidth, int tileHeight, int tileCount, int spacing, int margin, int columns)
  23. {
  24. Texture = texture;
  25. Type = type;
  26. TileWidth = tileWidth;
  27. TileHeight = tileHeight;
  28. TileCount = tileCount;
  29. Spacing = spacing;
  30. Margin = margin;
  31. Columns = columns;
  32. Properties = new TiledMapProperties();
  33. Tiles = new List<TiledMapTilesetTile>();
  34. }
  35. public string Name => Texture.Name;
  36. public Texture2D Texture { get; }
  37. public Texture2DRegion GetRegion(int column, int row)
  38. {
  39. var x = Margin + column * (TileWidth + Spacing);
  40. var y = Margin + row * (TileHeight + Spacing);
  41. return new Texture2DRegion(Texture, x, y, TileWidth, TileHeight);
  42. }
  43. public string Type { get; }
  44. public int TileWidth { get; }
  45. public int TileHeight { get; }
  46. public int Spacing { get; }
  47. public int Margin { get; }
  48. public int TileCount { get; }
  49. public int Columns { get; }
  50. public List<TiledMapTilesetTile> Tiles { get; }
  51. public TiledMapProperties Properties { get; }
  52. public int Rows => (int)Math.Ceiling((double) TileCount / Columns);
  53. public int ActualWidth => TileWidth * Columns;
  54. public int ActualHeight => TileHeight * Rows;
  55. public Rectangle GetTileRegion(int localTileIdentifier)
  56. {
  57. return Texture is not null
  58. ? TiledMapHelper.GetTileSourceRectangle(localTileIdentifier, TileWidth, TileHeight, Columns, Margin,
  59. Spacing)
  60. : Tiles.FirstOrDefault(x => x.LocalTileIdentifier == localTileIdentifier).Texture.Bounds;
  61. }
  62. }
  63. }