ParameterizedShape.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. namespace Bitsplash.Vector
  6. {
  7. public class ParameterizedShape : MaskableGraphic
  8. {
  9. public Sprite sprite;
  10. public int EdgeCount=3;
  11. public float EdgeRoundingOffset;
  12. public int EdgeRoundingSegments;
  13. public float Rotation = 0;
  14. // Update is called once per frame
  15. void Update()
  16. {
  17. }
  18. public override Texture mainTexture
  19. {
  20. get
  21. {
  22. if (sprite == null)
  23. return base.mainTexture;
  24. return sprite.texture;
  25. }
  26. }
  27. protected override void OnPopulateMesh(VertexHelper vh)
  28. {
  29. if (EdgeCount < 3)
  30. return;
  31. var rect = GetPixelAdjustedRect();
  32. float radius = Mathf.Min(rect.width, rect.height) * 0.5f;
  33. var list = CommonVectors.mTmpList;
  34. list.Clear();
  35. CommonVectors.NPolygon(EdgeCount, radius, radius, list);
  36. if (EdgeRoundingOffset > 0f)
  37. {
  38. var smoothList = CommonVectors.mTmpSmoothList;
  39. smoothList.Clear();
  40. CommonVectors.SmoothCorners(list, EdgeRoundingOffset, EdgeRoundingSegments, smoothList);
  41. list = smoothList;
  42. }
  43. Matrix4x4 m = Matrix4x4.Rotate(Quaternion.Euler(0f, 0f, Rotation));
  44. for (int i = 0; i < list.Count; i++)
  45. list[i] = m*list[i];
  46. Vector2 centroid = new Vector2();
  47. float minX = float.PositiveInfinity;
  48. float minY = float.PositiveInfinity;
  49. float maxX = float.NegativeInfinity;
  50. float maxY = float.NegativeInfinity;
  51. for(int i=0; i<list.Count; i++)
  52. {
  53. var v = list[i];
  54. centroid += v;
  55. minX = Mathf.Min(minX, v.x);
  56. minY = Mathf.Min(minY, v.y);
  57. maxX = Mathf.Max(maxX, v.x);
  58. maxY = Mathf.Max(maxY, v.y);
  59. }
  60. Vector2 minV = new Vector2(minX, minY);
  61. Vector2 sizeV = new Vector2(maxX - minX, maxY - minY);
  62. centroid *= 1f / list.Count;
  63. vh.Clear();
  64. Vector2 add = rect.center - centroid;
  65. vh.AddVert(rect.center, color, CommonVectors.InterpolateUV(centroid, minV, sizeV));
  66. for (int i=0; i<list.Count; i++)
  67. {
  68. vh.AddTriangle(0, i+1, ((i+1) % list.Count) +1);
  69. vh.AddVert(list[i] + add, color, CommonVectors.InterpolateUV(list[i], minV, sizeV));
  70. }
  71. }
  72. }
  73. }