Triangles.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System;
  2. using UnityEngine;
  3. using Object = UnityEngine.Object;
  4. namespace UnityStandardAssets.ImageEffects
  5. {
  6. class Triangles
  7. {
  8. private static Mesh[] meshes;
  9. private static int currentTris = 0;
  10. static bool HasMeshes()
  11. {
  12. if (meshes == null)
  13. return false;
  14. for (int i = 0; i < meshes.Length; i++)
  15. if (null == meshes[i])
  16. return false;
  17. return true;
  18. }
  19. static void Cleanup()
  20. {
  21. if (meshes == null)
  22. return;
  23. for (int i = 0; i < meshes.Length; i++)
  24. {
  25. if (null != meshes[i])
  26. {
  27. Object.DestroyImmediate(meshes[i]);
  28. meshes[i] = null;
  29. }
  30. }
  31. meshes = null;
  32. }
  33. static Mesh[] GetMeshes(int totalWidth, int totalHeight)
  34. {
  35. if (HasMeshes() && (currentTris == (totalWidth * totalHeight)))
  36. {
  37. return meshes;
  38. }
  39. int maxTris = 65000 / 3;
  40. int totalTris = totalWidth * totalHeight;
  41. currentTris = totalTris;
  42. int meshCount = Mathf.CeilToInt((1.0f * totalTris) / (1.0f * maxTris));
  43. meshes = new Mesh[meshCount];
  44. int i = 0;
  45. int index = 0;
  46. for (i = 0; i < totalTris; i += maxTris)
  47. {
  48. int tris = Mathf.FloorToInt(Mathf.Clamp((totalTris - i), 0, maxTris));
  49. meshes[index] = GetMesh(tris, i, totalWidth, totalHeight);
  50. index++;
  51. }
  52. return meshes;
  53. }
  54. static Mesh GetMesh(int triCount, int triOffset, int totalWidth, int totalHeight)
  55. {
  56. var mesh = new Mesh();
  57. mesh.hideFlags = HideFlags.DontSave;
  58. var verts = new Vector3[triCount * 3];
  59. var uvs = new Vector2[triCount * 3];
  60. var uvs2 = new Vector2[triCount * 3];
  61. var tris = new int[triCount * 3];
  62. for (int i = 0; i < triCount; i++)
  63. {
  64. int i3 = i * 3;
  65. int vertexWithOffset = triOffset + i;
  66. float x = Mathf.Floor(vertexWithOffset % totalWidth) / totalWidth;
  67. float y = Mathf.Floor(vertexWithOffset / totalWidth) / totalHeight;
  68. Vector3 position = new Vector3(x * 2 - 1, y * 2 - 1, 1.0f);
  69. verts[i3 + 0] = position;
  70. verts[i3 + 1] = position;
  71. verts[i3 + 2] = position;
  72. uvs[i3 + 0] = new Vector2(0.0f, 0.0f);
  73. uvs[i3 + 1] = new Vector2(1.0f, 0.0f);
  74. uvs[i3 + 2] = new Vector2(0.0f, 1.0f);
  75. uvs2[i3 + 0] = new Vector2(x, y);
  76. uvs2[i3 + 1] = new Vector2(x, y);
  77. uvs2[i3 + 2] = new Vector2(x, y);
  78. tris[i3 + 0] = i3 + 0;
  79. tris[i3 + 1] = i3 + 1;
  80. tris[i3 + 2] = i3 + 2;
  81. }
  82. mesh.vertices = verts;
  83. mesh.triangles = tris;
  84. mesh.uv = uvs;
  85. mesh.uv2 = uvs2;
  86. return mesh;
  87. }
  88. }
  89. }