Newer
Older
DungeonShooting / DungeonShooting_Godot / src / game / manager / EditorTileSetManager.cs
@小李xl 小李xl on 8 Jan 2024 2 KB 生成Godot.TileSet, 开发中
  1.  
  2. using System.IO;
  3. using System.Text.Json;
  4. using Godot;
  5.  
  6. public static class EditorTileSetManager
  7. {
  8. /// <summary>
  9. /// 扫描路径
  10. /// </summary>
  11. public static string CustomTileSetPath { get; private set; }
  12. private static bool _init;
  13. public static void Init()
  14. {
  15. if (_init)
  16. {
  17. return;
  18. }
  19.  
  20. _init = true;
  21. #if TOOLS
  22. CustomTileSetPath = GameConfig.RoomTileSetDir;
  23. #else
  24. CustomTileSetPath = GameConfig.RoomTileSetDir;
  25. #endif
  26. EventManager.AddEventListener(EventEnum.OnTileSetSave, OnTileSetSave);
  27. }
  28.  
  29. /// <summary>
  30. /// 保存TileSetConfig数据
  31. /// </summary>
  32. public static void SaveTileSetConfig()
  33. {
  34. var options = new JsonSerializerOptions();
  35. options.WriteIndented = true;
  36. var jsonText = JsonSerializer.Serialize(GameApplication.Instance.TileSetConfig, options);
  37. File.WriteAllText(GameConfig.RoomTileSetDir + GameConfig.TileSetConfigFile, jsonText);
  38. }
  39.  
  40. /// <summary>
  41. /// 保存TileSetInfo数据
  42. /// </summary>
  43. public static void SaveTileSetInfo(TileSetInfo tileSetInfo)
  44. {
  45. var dir = CustomTileSetPath + tileSetInfo.Name;
  46. if (Directory.Exists(dir))
  47. {
  48. //删除多余文件
  49. if (tileSetInfo.Sources == null)
  50. {
  51. Directory.Delete(dir, true);
  52. Directory.CreateDirectory(dir);
  53. }
  54. else
  55. {
  56. var directoryInfo = new DirectoryInfo(dir);
  57. var fileInfos = directoryInfo.GetFiles();
  58. foreach (var fileInfo in fileInfos)
  59. {
  60. if (fileInfo.Name.EndsWith(".png"))
  61. {
  62. var name = fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
  63. if (tileSetInfo.Sources.FindIndex(info => info.Name == name) < 0)
  64. {
  65. fileInfo.Delete();
  66. }
  67. }
  68. }
  69. }
  70. }
  71. else
  72. {
  73. Directory.CreateDirectory(dir);
  74. }
  75.  
  76. var path = dir + "/TileSet.json";
  77.  
  78. //保存json
  79. var options = new JsonSerializerOptions();
  80. options.WriteIndented = true;
  81. var jsonText = JsonSerializer.Serialize(tileSetInfo, options);
  82. File.WriteAllText(path, jsonText);
  83.  
  84. //保存资源
  85. if (tileSetInfo.Sources != null)
  86. {
  87. foreach (var sourceInfo in tileSetInfo.Sources)
  88. {
  89. var image = sourceInfo.GetSourceImage();
  90. if (image != null)
  91. {
  92. image.SavePng(dir + "/" + sourceInfo.Name + ".png");
  93. }
  94. }
  95. }
  96. }
  97.  
  98. //保存图块集
  99. private static void OnTileSetSave(object o)
  100. {
  101. if (o is TileSetSplit tileSetSplit)
  102. {
  103. var tileSetInfo = tileSetSplit.TileSetInfo;
  104. SaveTileSetInfo(tileSetInfo);
  105. }
  106. }
  107. }