CanvasMesh.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. namespace Rokid.UXR.Interaction {
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Assertions;
  5. using UnityEngine.Profiling;
  6. [DisallowMultipleComponent]
  7. public abstract class CanvasMesh : MonoBehaviour
  8. {
  9. [SerializeField]
  10. protected CanvasRenderTexture _canvasRenderTexture;
  11. [SerializeField]
  12. protected MeshFilter _meshFilter;
  13. [SerializeField, Optional]
  14. protected MeshCollider _meshCollider = null;
  15. protected abstract Vector3 MeshInverseTransform(Vector3 localPosition);
  16. protected abstract void GenerateMesh(out List<Vector3> verts, out List<int> tris, out List<Vector2> uvs);
  17. /// <summary>
  18. /// Transform a position in world space relative to the imposter to an associated position relative
  19. /// to the original canvas in world space.
  20. /// </summary>
  21. public Vector3 ImposterToCanvasTransformPoint(Vector3 worldPosition)
  22. {
  23. Vector3 localToImposter =
  24. _meshFilter.transform.InverseTransformPoint(worldPosition);
  25. Vector3 canvasLocalPosition = MeshInverseTransform(localToImposter) /
  26. _canvasRenderTexture.transform.localScale.x;
  27. Vector3 transformedWorldPosition = _canvasRenderTexture.transform.TransformPoint(canvasLocalPosition);
  28. return transformedWorldPosition;//
  29. }
  30. protected virtual void Start()
  31. {
  32. Assert.IsNotNull(_meshFilter);
  33. Assert.IsNotNull(_canvasRenderTexture);
  34. }
  35. protected virtual void OnEnable()
  36. {
  37. UpdateImposter();
  38. _canvasRenderTexture.OnUpdateRenderTexture += HandleUpdateRenderTexture;
  39. if (_canvasRenderTexture.Texture != null)
  40. {
  41. HandleUpdateRenderTexture(_canvasRenderTexture.Texture);
  42. }
  43. }
  44. protected virtual void OnDisable()
  45. {
  46. _canvasRenderTexture.OnUpdateRenderTexture -= HandleUpdateRenderTexture;
  47. }
  48. protected virtual void HandleUpdateRenderTexture(Texture texture)
  49. {
  50. UpdateImposter();
  51. }
  52. public virtual void UpdateImposter()
  53. {
  54. Profiler.BeginSample("InterfaceRenderer.UpdateImposter");
  55. try
  56. {
  57. GenerateMesh(out List<Vector3> verts, out List<int> tris, out List<Vector2> uvs);
  58. Mesh mesh = new Mesh();
  59. mesh.SetVertices(verts);
  60. mesh.SetUVs(0, uvs);
  61. mesh.SetTriangles(tris, 0);
  62. mesh.RecalculateBounds();
  63. mesh.RecalculateNormals();
  64. _meshFilter.mesh = mesh;
  65. if (_meshCollider != null)
  66. {
  67. _meshCollider.sharedMesh = _meshFilter.sharedMesh;
  68. }
  69. }
  70. finally
  71. {
  72. Profiler.EndSample();
  73. }
  74. }
  75. }
  76. }