Newer
Older
DungeonShooting / DungeonShooting_Godot / src / framework / map / liquid / BrushImageData.cs
@小李xl 小李xl on 7 Dec 2023 3 KB 更新开发日志
  1. using System;
  2. using Godot;
  3. using System.Collections.Generic;
  4. using Config;
  5.  
  6. /// <summary>
  7. /// 液体笔刷数据
  8. /// </summary>
  9. public class BrushImageData
  10. {
  11. /// <summary>
  12. /// 笔刷宽度
  13. /// </summary>
  14. public int Width;
  15. /// <summary>
  16. /// 笔刷高度
  17. /// </summary>
  18. public int Height;
  19. /// <summary>
  20. /// 笔刷所有有效像素点
  21. /// </summary>
  22. public BrushPixelData[] Pixels;
  23.  
  24. //有效像素范围
  25. public int PixelMinX = int.MaxValue;
  26. public int PixelMinY = int.MaxValue;
  27. public int PixelMaxX;
  28. public int PixelMaxY;
  29. /// <summary>
  30. /// 有效像素宽度
  31. /// </summary>
  32. public int PixelWidth;
  33. /// <summary>
  34. /// 有效像素高度
  35. /// </summary>
  36. public int PixelHeight;
  37. /// <summary>
  38. /// 笔刷材质
  39. /// </summary>
  40. public ExcelConfig.LiquidMaterial Material;
  41.  
  42. private static readonly Dictionary<string, Image> _imageData = new Dictionary<string, Image>();
  43.  
  44. public BrushImageData(ExcelConfig.LiquidMaterial material)
  45. {
  46. Material = material;
  47. var image = GetImageData(material.BrushTexture);
  48. var list = new List<BrushPixelData>();
  49. var width = image.GetWidth();
  50. var height = image.GetHeight();
  51. var flag = false;
  52. for (var x = 0; x < width; x++)
  53. {
  54. for (var y = 0; y < height; y++)
  55. {
  56. var pixel = image.GetPixel(x, y);
  57. if (pixel.A > 0)
  58. {
  59. flag = true;
  60. list.Add(new BrushPixelData()
  61. {
  62. X = x,
  63. Y = y,
  64. Color = pixel,
  65. Material = material
  66. });
  67. if (x < PixelMinX)
  68. {
  69. PixelMinX = x;
  70. }
  71. else if (x > PixelMaxX)
  72. {
  73. PixelMaxX = x;
  74. }
  75.  
  76. if (y < PixelMinY)
  77. {
  78. PixelMinY = y;
  79. }
  80. else if (y > PixelMaxY)
  81. {
  82. PixelMaxY = y;
  83. }
  84. }
  85. }
  86. }
  87.  
  88. if (!flag)
  89. {
  90. throw new Exception("不能使用完全透明的图片作为笔刷!");
  91. }
  92.  
  93. Pixels = list.ToArray();
  94. Width = width;
  95. Height = height;
  96.  
  97. PixelWidth = PixelMaxX - PixelMinX;
  98. PixelHeight = PixelMaxY - PixelMinY;
  99. }
  100.  
  101. private static Image GetImageData(string path)
  102. {
  103. if (!_imageData.TryGetValue(path, out var image))
  104. {
  105. var texture = ResourceManager.LoadTexture2D(path);
  106. image = texture.GetImage();
  107. }
  108.  
  109. return image;
  110. }
  111.  
  112. /// <summary>
  113. /// 清除笔刷缓存数据
  114. /// </summary>
  115. public static void ClearBrushData()
  116. {
  117. foreach (var keyValuePair in _imageData)
  118. {
  119. keyValuePair.Value.Dispose();
  120. }
  121. _imageData.Clear();
  122. }
  123. }