CanvasRenderTexture.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.Profiling;
  4. namespace Rokid.UXR.Interaction
  5. {
  6. #if UNITY_EDITOR
  7. using UnityEditor;
  8. #endif
  9. [DisallowMultipleComponent]
  10. public class CanvasRenderTexture : MonoBehaviour
  11. {
  12. private class TransformChangeListener : MonoBehaviour
  13. {
  14. public event Action WhenRectTransformDimensionsChanged = delegate { };
  15. private void OnRectTransformDimensionsChange()
  16. {
  17. WhenRectTransformDimensionsChanged();
  18. }
  19. }
  20. public enum DriveMode
  21. {
  22. Auto,
  23. Manual
  24. }
  25. public const int DEFAULT_UI_LAYERMASK = 1 << 5; //Hardcoded as the UI layer in Unity.
  26. private static readonly Vector2Int DEFAULT_TEXTURE_RES = new Vector2Int(128, 128);
  27. [SerializeField]
  28. private Canvas _canvas;
  29. [Tooltip("If you need extra resolution, you can use this as a whole-integer multiplier of the final resolution used to render the texture.")]
  30. [Range(1, 3)]
  31. [Delayed]
  32. [SerializeField]
  33. private int _renderScale = 1;
  34. [SerializeField]
  35. private DriveMode _dimensionsDriveMode = DriveMode.Auto;
  36. [Tooltip("The exact pixel resolution of the texture used for interface rendering. If set to auto this will take the size of the attached " +
  37. "RectTransform into consideration, in addition to the configured pixel-to-meter ratio.")]
  38. [Delayed]
  39. [SerializeField]
  40. private Vector2Int _resolution = DEFAULT_TEXTURE_RES;
  41. [Tooltip("Whether or not mip-maps should be auto-generated for the texture. Can help aliasing if the texture can be " +
  42. "viewed from many difference distances.")]
  43. [SerializeField]
  44. private bool _generateMipMaps = false;
  45. [SerializeField]
  46. private int _pixelsPerUnit = 100;
  47. [Header("Rendering Settings")]
  48. [Tooltip("The layers to render when the rendering texture is created. All child renderers should be part of this mask.")]
  49. [SerializeField]
  50. private LayerMask _renderingLayers = DEFAULT_UI_LAYERMASK;
  51. public LayerMask RenderingLayers => _renderingLayers;
  52. public Action<Texture> OnUpdateRenderTexture = delegate { };
  53. public int RenderScale
  54. {
  55. get
  56. {
  57. return _renderScale;
  58. }
  59. set
  60. {
  61. if (_renderScale < 1 || _renderScale > 3)
  62. {
  63. throw new ArgumentException($"Render scale must be between 1 and 3, but was {value}");
  64. }
  65. if (_renderScale == value)
  66. {
  67. return;
  68. }
  69. _renderScale = value;
  70. if (isActiveAndEnabled && Application.isPlaying)
  71. {
  72. UpdateCamera();
  73. }
  74. }
  75. }
  76. public Camera OverlayCamera => _camera;
  77. public Texture Texture => _tex;
  78. private TransformChangeListener _listener;
  79. private RenderTexture _tex;
  80. private Camera _camera;
  81. public Vector2Int CalcAutoResolution()
  82. {
  83. RKLog.Debug("====CanvasRenderTexture====: CalcAutoResolution");
  84. if (_canvas == null)
  85. {
  86. return DEFAULT_TEXTURE_RES;
  87. }
  88. var rectTransform = _canvas.GetComponent<RectTransform>();
  89. if (rectTransform == null)
  90. {
  91. return DEFAULT_TEXTURE_RES;
  92. }
  93. Vector2 size = rectTransform.sizeDelta;
  94. size.x *= rectTransform.lossyScale.x;
  95. size.y *= rectTransform.lossyScale.y;
  96. int x = Mathf.RoundToInt(UnitsToPixels(size.x));
  97. int y = Mathf.RoundToInt(UnitsToPixels(size.y));
  98. RKLog.Debug($"====CanvasRenderTexture====: CalcAutoResolution {x},{y}");
  99. return new Vector2Int(Mathf.Max(x, 1), Mathf.Max(y, 1));
  100. }
  101. public Vector2Int GetBaseResolutionToUse()
  102. {
  103. if (_dimensionsDriveMode == DriveMode.Auto)
  104. {
  105. return CalcAutoResolution();
  106. }
  107. else
  108. {
  109. return _resolution;
  110. }
  111. }
  112. public Vector2Int GetScaledResolutionToUse()
  113. {
  114. Vector2 resolution = GetBaseResolutionToUse();
  115. return Vector2Int.RoundToInt(resolution * _renderScale);
  116. }
  117. public float PixelsToUnits(float pixels)
  118. {
  119. return (1f / _pixelsPerUnit) * pixels;
  120. }
  121. public float UnitsToPixels(float units)
  122. {
  123. return _pixelsPerUnit * units;
  124. }
  125. protected void OnEnable()
  126. {
  127. if (_listener == null)
  128. {
  129. _listener = _canvas.gameObject.AddComponent<TransformChangeListener>();
  130. }
  131. _listener.WhenRectTransformDimensionsChanged += WhenCanvasRectTransformDimensionsChanged;
  132. UpdateCamera();
  133. }
  134. private void WhenCanvasRectTransformDimensionsChanged()
  135. {
  136. UpdateCamera();
  137. }
  138. protected void OnDisable()
  139. {
  140. if (_camera != null && _camera.gameObject != null)
  141. {
  142. Destroy(_camera.gameObject);
  143. }
  144. if (_tex != null)
  145. {
  146. DestroyImmediate(_tex);
  147. }
  148. if (_listener != null)
  149. {
  150. _listener.WhenRectTransformDimensionsChanged -= WhenCanvasRectTransformDimensionsChanged;
  151. }
  152. }
  153. public void UpdateCamera()
  154. {
  155. if (!Application.isPlaying)
  156. {
  157. return;
  158. }
  159. Profiler.BeginSample("InterfaceRenderer.UpdateCamera");
  160. try
  161. {
  162. if (_camera == null)
  163. {
  164. RKLog.Debug("====CanvasRenderTexture====: UpdateCamera Camera is Null");
  165. GameObject cameraObj = CreateChildObject("__Camera");
  166. _camera = cameraObj.AddComponent<Camera>();
  167. _camera.orthographic = true;
  168. _camera.nearClipPlane = -5;
  169. _camera.farClipPlane = 5f;
  170. _camera.backgroundColor = new Color(0, 0, 0, 0);
  171. _camera.clearFlags = CameraClearFlags.SolidColor;
  172. }
  173. UpdateRenderTexture();
  174. UpdateOrthoSize();
  175. UpdateCameraCullingMask();
  176. }
  177. finally
  178. {
  179. Profiler.EndSample();
  180. }
  181. }
  182. protected void UpdateRenderTexture()
  183. {
  184. RKLog.Debug("====CanvasRenderTexture====: UpdateRenderTexture");
  185. Profiler.BeginSample("InterfaceRenderer.UpdateRenderTexture");
  186. try
  187. {
  188. Vector2Int resolutionToUse = GetScaledResolutionToUse();
  189. if (_tex == null ||
  190. _tex.width != resolutionToUse.x ||
  191. _tex.height != resolutionToUse.y ||
  192. _tex.autoGenerateMips != _generateMipMaps)
  193. {
  194. if (_tex != null)
  195. {
  196. _camera.targetTexture = null;
  197. DestroyImmediate(_tex);
  198. }
  199. _tex = new RenderTexture(resolutionToUse.x, resolutionToUse.y, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
  200. _tex.filterMode = FilterMode.Bilinear;
  201. _tex.autoGenerateMips = _generateMipMaps;
  202. _camera.targetTexture = _tex;
  203. OnUpdateRenderTexture(_tex);
  204. }
  205. }
  206. finally
  207. {
  208. Profiler.EndSample();
  209. }
  210. }
  211. private void UpdateOrthoSize()
  212. {
  213. if (_camera != null)
  214. {
  215. _camera.orthographicSize = PixelsToUnits(GetBaseResolutionToUse().y) * 0.5f;
  216. }
  217. }
  218. private void UpdateCameraCullingMask()
  219. {
  220. if (_camera != null)
  221. {
  222. _camera.cullingMask = _renderingLayers.value;
  223. }
  224. }
  225. protected GameObject CreateChildObject(string name)
  226. {
  227. GameObject obj = new GameObject(name);
  228. obj.transform.SetParent(_canvas.transform);
  229. obj.transform.localPosition = Vector3.zero;
  230. obj.transform.localRotation = Quaternion.identity;
  231. obj.transform.localScale = Vector3.one;
  232. return obj;
  233. }
  234. public static class Properties
  235. {
  236. public static readonly string DimensionDriveMode = nameof(_dimensionsDriveMode);
  237. public static readonly string Resolution = nameof(_resolution);
  238. public static readonly string RenderScale = nameof(_renderScale);
  239. public static readonly string PixelsPerUnit = nameof(_pixelsPerUnit);
  240. public static readonly string RenderLayers = nameof(_renderingLayers);
  241. public static readonly string GenerateMipMaps = nameof(_generateMipMaps);
  242. public static readonly string Canvas = nameof(_canvas);
  243. }
  244. }
  245. }