CanvasUpdateRegistry.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.UI.Collections;
  4. namespace UnityEngine.UI
  5. {
  6. /// <summary>
  7. /// Values of 'update' called on a Canvas update.
  8. /// </summary>
  9. /// <remarks> If modifying also modify m_CanvasUpdateProfilerStrings to match.</remarks>
  10. public enum CanvasUpdate
  11. {
  12. /// <summary>
  13. /// Called before layout.
  14. /// </summary>
  15. Prelayout = 0,
  16. /// <summary>
  17. /// Called for layout.
  18. /// </summary>
  19. Layout = 1,
  20. /// <summary>
  21. /// Called after layout.
  22. /// </summary>
  23. PostLayout = 2,
  24. /// <summary>
  25. /// Called before rendering.
  26. /// </summary>
  27. PreRender = 3,
  28. /// <summary>
  29. /// Called late, before render.
  30. /// </summary>
  31. LatePreRender = 4,
  32. /// <summary>
  33. /// Max enum value. Always last.
  34. /// </summary>
  35. MaxUpdateValue = 5
  36. }
  37. /// <summary>
  38. /// This is an element that can live on a Canvas.
  39. /// </summary>
  40. public interface ICanvasElement
  41. {
  42. /// <summary>
  43. /// Rebuild the element for the given stage.
  44. /// </summary>
  45. /// <param name="executing">The current CanvasUpdate stage being rebuild.</param>
  46. void Rebuild(CanvasUpdate executing);
  47. /// <summary>
  48. /// Get the transform associated with the ICanvasElement.
  49. /// </summary>
  50. Transform transform { get; }
  51. /// <summary>
  52. /// Callback sent when this ICanvasElement has completed layout.
  53. /// </summary>
  54. void LayoutComplete();
  55. /// <summary>
  56. /// Callback sent when this ICanvasElement has completed Graphic rebuild.
  57. /// </summary>
  58. void GraphicUpdateComplete();
  59. /// <summary>
  60. /// Used if the native representation has been destroyed.
  61. /// </summary>
  62. /// <returns>Return true if the element is considered destroyed.</returns>
  63. bool IsDestroyed();
  64. }
  65. /// <summary>
  66. /// A place where CanvasElements can register themselves for rebuilding.
  67. /// </summary>
  68. public class CanvasUpdateRegistry
  69. {
  70. private static CanvasUpdateRegistry s_Instance;
  71. private bool m_PerformingLayoutUpdate;
  72. private bool m_PerformingGraphicUpdate;
  73. // This list matches the CanvasUpdate enum above. Keep in sync
  74. private string[] m_CanvasUpdateProfilerStrings = new string[] { "CanvasUpdate.Prelayout", "CanvasUpdate.Layout", "CanvasUpdate.PostLayout", "CanvasUpdate.PreRender", "CanvasUpdate.LatePreRender" };
  75. private const string m_CullingUpdateProfilerString = "ClipperRegistry.Cull";
  76. private readonly IndexedSet<ICanvasElement> m_LayoutRebuildQueue = new IndexedSet<ICanvasElement>();
  77. private readonly IndexedSet<ICanvasElement> m_GraphicRebuildQueue = new IndexedSet<ICanvasElement>();
  78. protected CanvasUpdateRegistry()
  79. {
  80. Canvas.willRenderCanvases += PerformUpdate;
  81. }
  82. /// <summary>
  83. /// Get the singleton registry instance.
  84. /// </summary>
  85. public static CanvasUpdateRegistry instance
  86. {
  87. get
  88. {
  89. if (s_Instance == null)
  90. s_Instance = new CanvasUpdateRegistry();
  91. return s_Instance;
  92. }
  93. }
  94. private bool ObjectValidForUpdate(ICanvasElement element)
  95. {
  96. var valid = element != null;
  97. var isUnityObject = element is Object;
  98. if (isUnityObject)
  99. valid = (element as Object) != null; //Here we make use of the overloaded UnityEngine.Object == null, that checks if the native object is alive.
  100. return valid;
  101. }
  102. private void CleanInvalidItems()
  103. {
  104. // So MB's override the == operator for null equality, which checks
  105. // if they are destroyed. This is fine if you are looking at a concrete
  106. // mb, but in this case we are looking at a list of ICanvasElement
  107. // this won't forward the == operator to the MB, but just check if the
  108. // interface is null. IsDestroyed will return if the backend is destroyed.
  109. var layoutRebuildQueueCount = m_LayoutRebuildQueue.Count;
  110. for (int i = layoutRebuildQueueCount - 1; i >= 0; --i)
  111. {
  112. var item = m_LayoutRebuildQueue[i];
  113. if (item == null)
  114. {
  115. m_LayoutRebuildQueue.RemoveAt(i);
  116. continue;
  117. }
  118. if (item.IsDestroyed())
  119. {
  120. m_LayoutRebuildQueue.RemoveAt(i);
  121. item.LayoutComplete();
  122. }
  123. }
  124. var graphicRebuildQueueCount = m_GraphicRebuildQueue.Count;
  125. for (int i = graphicRebuildQueueCount - 1; i >= 0; --i)
  126. {
  127. var item = m_GraphicRebuildQueue[i];
  128. if (item == null)
  129. {
  130. m_GraphicRebuildQueue.RemoveAt(i);
  131. continue;
  132. }
  133. if (item.IsDestroyed())
  134. {
  135. m_GraphicRebuildQueue.RemoveAt(i);
  136. item.GraphicUpdateComplete();
  137. }
  138. }
  139. }
  140. private static readonly Comparison<ICanvasElement> s_SortLayoutFunction = SortLayoutList;
  141. private void PerformUpdate()
  142. {
  143. UISystemProfilerApi.BeginSample(UISystemProfilerApi.SampleType.Layout);
  144. CleanInvalidItems();
  145. m_PerformingLayoutUpdate = true;
  146. m_LayoutRebuildQueue.Sort(s_SortLayoutFunction);
  147. for (int i = 0; i <= (int)CanvasUpdate.PostLayout; i++)
  148. {
  149. UnityEngine.Profiling.Profiler.BeginSample(m_CanvasUpdateProfilerStrings[i]);
  150. for (int j = 0; j < m_LayoutRebuildQueue.Count; j++)
  151. {
  152. var rebuild = m_LayoutRebuildQueue[j];
  153. try
  154. {
  155. if (ObjectValidForUpdate(rebuild))
  156. rebuild.Rebuild((CanvasUpdate)i);
  157. }
  158. catch (Exception e)
  159. {
  160. Debug.LogException(e, rebuild.transform);
  161. }
  162. }
  163. UnityEngine.Profiling.Profiler.EndSample();
  164. }
  165. for (int i = 0; i < m_LayoutRebuildQueue.Count; ++i)
  166. m_LayoutRebuildQueue[i].LayoutComplete();
  167. m_LayoutRebuildQueue.Clear();
  168. m_PerformingLayoutUpdate = false;
  169. UISystemProfilerApi.EndSample(UISystemProfilerApi.SampleType.Layout);
  170. UISystemProfilerApi.BeginSample(UISystemProfilerApi.SampleType.Render);
  171. // now layout is complete do culling...
  172. UnityEngine.Profiling.Profiler.BeginSample(m_CullingUpdateProfilerString);
  173. ClipperRegistry.instance.Cull();
  174. UnityEngine.Profiling.Profiler.EndSample();
  175. m_PerformingGraphicUpdate = true;
  176. for (var i = (int)CanvasUpdate.PreRender; i < (int)CanvasUpdate.MaxUpdateValue; i++)
  177. {
  178. UnityEngine.Profiling.Profiler.BeginSample(m_CanvasUpdateProfilerStrings[i]);
  179. for (var k = 0; k < m_GraphicRebuildQueue.Count; k++)
  180. {
  181. try
  182. {
  183. var element = m_GraphicRebuildQueue[k];
  184. if (ObjectValidForUpdate(element))
  185. element.Rebuild((CanvasUpdate)i);
  186. }
  187. catch (Exception e)
  188. {
  189. Debug.LogException(e, m_GraphicRebuildQueue[k].transform);
  190. }
  191. }
  192. UnityEngine.Profiling.Profiler.EndSample();
  193. }
  194. for (int i = 0; i < m_GraphicRebuildQueue.Count; ++i)
  195. m_GraphicRebuildQueue[i].GraphicUpdateComplete();
  196. m_GraphicRebuildQueue.Clear();
  197. m_PerformingGraphicUpdate = false;
  198. UISystemProfilerApi.EndSample(UISystemProfilerApi.SampleType.Render);
  199. }
  200. private static int ParentCount(Transform child)
  201. {
  202. if (child == null)
  203. return 0;
  204. var parent = child.parent;
  205. int count = 0;
  206. while (parent != null)
  207. {
  208. count++;
  209. parent = parent.parent;
  210. }
  211. return count;
  212. }
  213. private static int SortLayoutList(ICanvasElement x, ICanvasElement y)
  214. {
  215. Transform t1 = x.transform;
  216. Transform t2 = y.transform;
  217. return ParentCount(t1) - ParentCount(t2);
  218. }
  219. /// <summary>
  220. /// Try and add the given element to the layout rebuild list.
  221. /// Will not return if successfully added.
  222. /// </summary>
  223. /// <param name="element">The element that is needing rebuilt.</param>
  224. public static void RegisterCanvasElementForLayoutRebuild(ICanvasElement element)
  225. {
  226. instance.InternalRegisterCanvasElementForLayoutRebuild(element);
  227. }
  228. /// <summary>
  229. /// Try and add the given element to the layout rebuild list.
  230. /// </summary>
  231. /// <param name="element">The element that is needing rebuilt.</param>
  232. /// <returns>
  233. /// True if the element was successfully added to the rebuilt list.
  234. /// False if either already inside a Graphic Update loop OR has already been added to the list.
  235. /// </returns>
  236. public static bool TryRegisterCanvasElementForLayoutRebuild(ICanvasElement element)
  237. {
  238. return instance.InternalRegisterCanvasElementForLayoutRebuild(element);
  239. }
  240. private bool InternalRegisterCanvasElementForLayoutRebuild(ICanvasElement element)
  241. {
  242. if (m_LayoutRebuildQueue.Contains(element))
  243. return false;
  244. /* TODO: this likely should be here but causes the error to show just resizing the game view (case 739376)
  245. if (m_PerformingLayoutUpdate)
  246. {
  247. Debug.LogError(string.Format("Trying to add {0} for layout rebuild while we are already inside a layout rebuild loop. This is not supported.", element));
  248. return false;
  249. }*/
  250. return m_LayoutRebuildQueue.AddUnique(element);
  251. }
  252. /// <summary>
  253. /// Try and add the given element to the rebuild list.
  254. /// Will not return if successfully added.
  255. /// </summary>
  256. /// <param name="element">The element that is needing rebuilt.</param>
  257. public static void RegisterCanvasElementForGraphicRebuild(ICanvasElement element)
  258. {
  259. instance.InternalRegisterCanvasElementForGraphicRebuild(element);
  260. }
  261. /// <summary>
  262. /// Try and add the given element to the rebuild list.
  263. /// </summary>
  264. /// <param name="element">The element that is needing rebuilt.</param>
  265. /// <returns>
  266. /// True if the element was successfully added to the rebuilt list.
  267. /// False if either already inside a Graphic Update loop OR has already been added to the list.
  268. /// </returns>
  269. public static bool TryRegisterCanvasElementForGraphicRebuild(ICanvasElement element)
  270. {
  271. return instance.InternalRegisterCanvasElementForGraphicRebuild(element);
  272. }
  273. private bool InternalRegisterCanvasElementForGraphicRebuild(ICanvasElement element)
  274. {
  275. if (m_PerformingGraphicUpdate)
  276. {
  277. Debug.LogError(string.Format("Trying to add {0} for graphic rebuild while we are already inside a graphic rebuild loop. This is not supported.", element));
  278. return false;
  279. }
  280. return m_GraphicRebuildQueue.AddUnique(element);
  281. }
  282. /// <summary>
  283. /// Remove the given element from both the graphic and the layout rebuild lists.
  284. /// </summary>
  285. /// <param name="element"></param>
  286. public static void UnRegisterCanvasElementForRebuild(ICanvasElement element)
  287. {
  288. instance.InternalUnRegisterCanvasElementForLayoutRebuild(element);
  289. instance.InternalUnRegisterCanvasElementForGraphicRebuild(element);
  290. }
  291. private void InternalUnRegisterCanvasElementForLayoutRebuild(ICanvasElement element)
  292. {
  293. if (m_PerformingLayoutUpdate)
  294. {
  295. Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element));
  296. return;
  297. }
  298. element.LayoutComplete();
  299. instance.m_LayoutRebuildQueue.Remove(element);
  300. }
  301. private void InternalUnRegisterCanvasElementForGraphicRebuild(ICanvasElement element)
  302. {
  303. if (m_PerformingGraphicUpdate)
  304. {
  305. Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element));
  306. return;
  307. }
  308. element.GraphicUpdateComplete();
  309. instance.m_GraphicRebuildQueue.Remove(element);
  310. }
  311. /// <summary>
  312. /// Are graphics layouts currently being calculated..
  313. /// </summary>
  314. /// <returns>True if the rebuild loop is CanvasUpdate.Prelayout, CanvasUpdate.Layout or CanvasUpdate.Postlayout</returns>
  315. public static bool IsRebuildingLayout()
  316. {
  317. return instance.m_PerformingLayoutUpdate;
  318. }
  319. /// <summary>
  320. /// Are graphics currently being rebuild.
  321. /// </summary>
  322. /// <returns>True if the rebuild loop is CanvasUpdate.PreRender or CanvasUpdate.Render</returns>
  323. public static bool IsRebuildingGraphics()
  324. {
  325. return instance.m_PerformingGraphicUpdate;
  326. }
  327. }
  328. }