MeshChainRenderer.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. using System;
  2. using UnityEngine;
  3. namespace Unity.XRTools.Rendering
  4. {
  5. /// <summary>
  6. /// A unified base class for the XR Line Renderer and XR Trail Renderer
  7. /// </summary>
  8. [RequireComponent(typeof(MeshRenderer))]
  9. [RequireComponent(typeof(MeshFilter))]
  10. [ExecuteInEditMode]
  11. [DisallowMultipleComponent]
  12. public abstract class MeshChainRenderer : MonoBehaviour
  13. {
  14. static readonly GradientColorKey k_DefaultStartColor = new GradientColorKey(Color.white, 0);
  15. static readonly GradientColorKey k_DefaultEndColor = new GradientColorKey(Color.white, 1);
  16. static readonly GradientAlphaKey k_DefaultStartAlpha = new GradientAlphaKey(1, 0);
  17. static readonly GradientAlphaKey k_DefaultEndAlpha = new GradientAlphaKey(1, 1);
  18. /// <summary>
  19. /// Materials to use when rendering.
  20. /// </summary>
  21. [SerializeField]
  22. [Tooltip("Materials to use when rendering.")]
  23. protected Material[] m_Materials;
  24. /// <summary>
  25. /// The multiplier applied to the curve, describing the width (in world space) along the line.
  26. /// </summary>
  27. [SerializeField]
  28. [Tooltip("The multiplier applied to the curve, describing the width (in world space) along the line.")]
  29. protected float m_Width = 1.0f;
  30. /// <summary>
  31. /// The curve describing the width of the line at various points along its length.
  32. /// </summary>
  33. [SerializeField]
  34. [Tooltip("The curve describing the width of the line at various points along its length.")]
  35. protected AnimationCurve m_WidthCurve = new AnimationCurve();
  36. /// <summary>
  37. /// The gradient describing color along the line.
  38. /// </summary>
  39. [SerializeField]
  40. [Tooltip("The gradient describing color along the line.")]
  41. protected Gradient m_Color = new Gradient();
  42. /// <summary>
  43. /// The MeshRenderer used to render the line
  44. /// </summary>
  45. [SerializeField]
  46. [HideInInspector]
  47. protected MeshRenderer m_MeshRenderer;
  48. /// <summary>
  49. /// Cached mesh data
  50. /// </summary>
  51. protected XRMeshChain m_XRMeshData;
  52. /// <summary>
  53. /// Whether the mesh data needs to be refreshed
  54. /// </summary>
  55. protected bool m_MeshNeedsRefreshing;
  56. /// <summary>
  57. /// The step size
  58. /// </summary>
  59. protected float m_StepSize = 1.0f;
  60. /// <summary>
  61. /// Returns the first instantiated Material assigned to the renderer.
  62. /// </summary>
  63. public virtual Material material
  64. {
  65. get { return m_MeshRenderer.material; }
  66. set { m_MeshRenderer.material = value; }
  67. }
  68. /// <summary>
  69. /// Returns all the instantiated materials of this object.
  70. /// </summary>
  71. public virtual Material[] materials
  72. {
  73. get { return m_MeshRenderer.materials; }
  74. set { m_MeshRenderer.materials = value; }
  75. }
  76. /// <summary>
  77. /// Returns the shared material of this object.
  78. /// </summary>
  79. public virtual Material sharedMaterial
  80. {
  81. get { return m_MeshRenderer.sharedMaterial; }
  82. set { m_MeshRenderer.sharedMaterial = value; }
  83. }
  84. /// <summary>
  85. /// Returns all shared materials of this object.
  86. /// </summary>
  87. public virtual Material[] SharedMaterials
  88. {
  89. get { return m_MeshRenderer.materials; }
  90. set { m_MeshRenderer.sharedMaterials = value; }
  91. }
  92. /// <summary>
  93. /// Set the width at the start of the line.
  94. /// </summary>
  95. public float widthStart
  96. {
  97. get { return m_WidthCurve.Evaluate(0) * m_Width; }
  98. set
  99. {
  100. if (m_Width == 0 || float.IsNaN(m_Width))
  101. return;
  102. var keys = m_WidthCurve.keys;
  103. keys[0].value = value / m_Width;
  104. m_WidthCurve.keys = keys;
  105. UpdateWidth();
  106. }
  107. }
  108. /// <summary>
  109. /// Set the width at the end of the line.
  110. /// </summary>
  111. public float widthEnd
  112. {
  113. get { return m_WidthCurve.Evaluate(1) * m_Width; }
  114. set
  115. {
  116. if (m_Width == 0 || float.IsNaN(m_Width))
  117. return;
  118. var keys = m_WidthCurve.keys;
  119. var lastIndex = keys.Length - 1;
  120. keys[lastIndex].value = value / m_Width;
  121. m_WidthCurve.keys = keys;
  122. UpdateWidth();
  123. }
  124. }
  125. /// <summary>
  126. /// Set an overall multiplier that is applied to the LineRenderer.widthCurve to get the final width of the line.
  127. /// </summary>
  128. public float widthMultiplier
  129. {
  130. get { return m_Width; }
  131. set
  132. {
  133. m_Width = value;
  134. UpdateWidth();
  135. }
  136. }
  137. /// <summary>
  138. /// Set the curve describing the width of the line at various points along its length.
  139. /// </summary>
  140. public AnimationCurve widthCurve
  141. {
  142. get { return m_WidthCurve; }
  143. set
  144. {
  145. m_WidthCurve = value ?? new AnimationCurve(new Keyframe(0, 1.0f));
  146. UpdateWidth();
  147. }
  148. }
  149. /// <summary>
  150. /// Set the color gradient describing the color of the line at various points along its length.
  151. /// </summary>
  152. public Gradient colorGradient
  153. {
  154. get { return m_Color; }
  155. set
  156. {
  157. if (m_Color == value)
  158. {
  159. return;
  160. }
  161. m_Color = value ?? new Gradient
  162. {
  163. alphaKeys = new[] { k_DefaultStartAlpha, k_DefaultEndAlpha },
  164. colorKeys = new[] { k_DefaultStartColor, k_DefaultEndColor },
  165. mode = GradientMode.Blend
  166. };
  167. UpdateColors();
  168. }
  169. }
  170. /// <summary>
  171. /// Set the color at the start of the line.
  172. /// </summary>
  173. public Color colorStart
  174. {
  175. get { return m_Color.Evaluate(0); }
  176. set
  177. {
  178. var colorKeys = m_Color.colorKeys;
  179. var alphaKeys = m_Color.alphaKeys;
  180. var flatColor = value;
  181. flatColor.a = 1.0f;
  182. colorKeys[0].color = flatColor;
  183. alphaKeys[0].alpha = value.a;
  184. m_Color.colorKeys = colorKeys;
  185. m_Color.alphaKeys = alphaKeys;
  186. UpdateColors();
  187. }
  188. }
  189. /// <summary>
  190. /// Set the color at the end of the line.
  191. /// </summary>
  192. public Color colorEnd
  193. {
  194. get { return m_Color.Evaluate(1); }
  195. set
  196. {
  197. var colorKeys = m_Color.colorKeys;
  198. var alphaKeys = m_Color.alphaKeys;
  199. var lastColorIndex = colorKeys.Length - 1;
  200. var lastAlphaIndex = alphaKeys.Length - 1;
  201. var flatColor = value;
  202. flatColor.a = 1.0f;
  203. colorKeys[lastColorIndex].color = flatColor;
  204. alphaKeys[lastAlphaIndex].alpha = value.a;
  205. m_Color.colorKeys = colorKeys;
  206. m_Color.alphaKeys = alphaKeys;
  207. UpdateColors();
  208. }
  209. }
  210. /// <summary>
  211. /// Resets the width to a straight curve at the given value
  212. /// </summary>
  213. /// <param name="newWidth">The new width for the curve to display</param>
  214. public void SetTotalWidth(float newWidth)
  215. {
  216. m_Width = newWidth;
  217. m_WidthCurve = new AnimationCurve(new Keyframe(0, 1.0f));
  218. UpdateWidth();
  219. }
  220. /// <summary>
  221. /// Resets the color to a single value
  222. /// </summary>
  223. /// <param name="newColor">The new color for the curve to display</param>
  224. public void SetTotalColor(Color newColor)
  225. {
  226. var flatColor = newColor;
  227. flatColor.a = 1.0f;
  228. m_Color = new Gradient
  229. {
  230. alphaKeys = new[] { new GradientAlphaKey(newColor.a, 0), new GradientAlphaKey(newColor.a, 1), },
  231. colorKeys = new[] { new GradientColorKey(flatColor, 0), new GradientColorKey(flatColor, 1) },
  232. mode = GradientMode.Blend
  233. };
  234. UpdateColors();
  235. }
  236. void OnValidate()
  237. {
  238. SetupMeshBackend();
  239. if (NeedsReinitialize())
  240. {
  241. #if UNITY_EDITOR
  242. UnityEditor.EditorApplication.delayCall += EditorCheckForUpdate;
  243. #endif
  244. }
  245. else
  246. {
  247. EditorCheckForUpdate();
  248. }
  249. }
  250. /// <summary>
  251. /// Manually trigger the mesh data to be refreshed. This is automatically done in LateUpdate if anything has changed.
  252. /// </summary>
  253. public void RefreshMesh()
  254. {
  255. m_XRMeshData.RefreshMesh();
  256. m_MeshNeedsRefreshing = false;
  257. }
  258. /// <summary>
  259. /// Cleans up the visible interface of the MeshRenderer by hiding unneeded components
  260. /// Also makes sure the animation curves are set up properly to defaults
  261. /// </summary>
  262. void SetupMeshBackend()
  263. {
  264. if (m_MeshRenderer == null)
  265. m_MeshRenderer = GetComponent<MeshRenderer>();
  266. if (m_MeshRenderer.hideFlags == HideFlags.None)
  267. m_MeshRenderer.hideFlags = HideFlags.HideInInspector;
  268. var meshFilter = GetComponent<MeshFilter>();
  269. if (meshFilter.hideFlags == HideFlags.None)
  270. meshFilter.hideFlags = HideFlags.HideInInspector;
  271. if (m_Materials == null || m_Materials.Length == 0)
  272. {
  273. m_Materials = m_MeshRenderer.sharedMaterials;
  274. }
  275. var sharedMaterials = m_MeshRenderer.sharedMaterials;
  276. var length = sharedMaterials.Length;
  277. var materialsEqual = true;
  278. for (var i = 0; i < length; i++)
  279. {
  280. if (sharedMaterials[i] != m_Materials[i])
  281. {
  282. materialsEqual = false;
  283. break;
  284. }
  285. }
  286. if (!materialsEqual)
  287. {
  288. m_MeshRenderer.sharedMaterials = m_Materials;
  289. }
  290. if (m_WidthCurve == null || m_WidthCurve.keys == null || m_WidthCurve.keys.Length == 0)
  291. {
  292. m_WidthCurve = new AnimationCurve(new Keyframe(0, 1.0f));
  293. }
  294. if (m_Color == null)
  295. {
  296. m_Color = new Gradient
  297. {
  298. alphaKeys = new[] { k_DefaultStartAlpha, k_DefaultEndAlpha },
  299. colorKeys = new[] { k_DefaultStartColor, k_DefaultEndColor },
  300. mode = GradientMode.Blend
  301. };
  302. }
  303. }
  304. /// <summary>
  305. /// Makes the sure mesh renderer reference is initialized before any functions try to access it
  306. /// </summary>
  307. protected virtual void Awake()
  308. {
  309. SetupMeshBackend();
  310. Initialize();
  311. }
  312. /// <summary>
  313. /// Makes the sure mesh renderer reference is initialized on reset of the component
  314. /// </summary>
  315. void Reset()
  316. {
  317. SetupMeshBackend();
  318. Initialize();
  319. }
  320. /// <summary>
  321. /// Ensures the lines have all their data precached upon loading
  322. /// </summary>
  323. void Start()
  324. {
  325. Initialize();
  326. }
  327. #if UNITY_EDITOR
  328. /// <summary>
  329. /// Ensures the hidden mesh/meshfilters are destroyed if users are messing with the components in edit mode
  330. /// </summary>
  331. void OnDestroy()
  332. {
  333. if (!Application.isPlaying)
  334. {
  335. var rendererToDestroy = m_MeshRenderer;
  336. var filterToDestroy = gameObject.GetComponent<MeshFilter>();
  337. UnityEditor.EditorApplication.delayCall += () =>
  338. {
  339. if (!Application.isPlaying)
  340. {
  341. if (rendererToDestroy != null)
  342. {
  343. DestroyImmediate(rendererToDestroy);
  344. }
  345. if (filterToDestroy != null)
  346. {
  347. DestroyImmediate(filterToDestroy);
  348. }
  349. }
  350. };
  351. }
  352. }
  353. #endif
  354. /// <summary>
  355. /// Does the actual internal mesh updating as late as possible so nothing ends up a frame behind
  356. /// </summary>
  357. protected virtual void LateUpdate()
  358. {
  359. if (m_MeshNeedsRefreshing == true)
  360. {
  361. m_XRMeshData.RefreshMesh();
  362. m_MeshNeedsRefreshing = false;
  363. }
  364. }
  365. /// <summary>
  366. /// Allows the component to be referenced as a renderer, forwarding the MeshRenderer ahead
  367. /// </summary>
  368. /// <param name="meshChainRenderer"></param>
  369. /// <returns>The MeshChainRenderer's MeshRenderer</returns>
  370. public static implicit operator Renderer(MeshChainRenderer meshChainRenderer)
  371. {
  372. return meshChainRenderer.m_MeshRenderer;
  373. }
  374. /// <summary>
  375. /// Triggered by validation - forced initialization to make sure data changed
  376. /// in the editor is reflected immediately to the user.
  377. /// </summary>
  378. void EditorCheckForUpdate()
  379. {
  380. // Because this gets delay-called, it can be referring to a destroyed component when a scene starts
  381. if (this != null)
  382. {
  383. // If we did not initialize, refresh all the properties instead
  384. Initialize(false);
  385. }
  386. }
  387. /// <summary>
  388. /// Updates any internal variables to represent the new color that has been applied
  389. /// </summary>
  390. protected virtual void UpdateColors() { }
  391. /// <summary>
  392. /// Updates any internal variables to represent the new width that has been applied
  393. /// </summary>
  394. protected virtual void UpdateWidth() { }
  395. /// <summary>
  396. /// Creates or updates the underlying mesh data
  397. /// </summary>
  398. protected virtual void Initialize(bool generate = true) { }
  399. /// <summary>
  400. /// Tests if the mesh data needs to be created or rebuilt
  401. /// </summary>
  402. /// <returns>true if the mesh data needs recreation, false if it is already set up properly</returns>
  403. protected virtual bool NeedsReinitialize()
  404. {
  405. return true;
  406. }
  407. /// <summary>
  408. /// Enables the internal mesh representing the line
  409. /// </summary>
  410. protected virtual void OnEnable()
  411. {
  412. m_MeshRenderer.enabled = true;
  413. }
  414. /// <summary>
  415. /// Disables the internal mesh representing the line
  416. /// </summary>
  417. protected virtual void OnDisable()
  418. {
  419. m_MeshRenderer.enabled = false;
  420. }
  421. }
  422. }