NetworkLoop.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // our ideal update looks like this:
  2. // transport.process_incoming()
  3. // update_world()
  4. // transport.process_outgoing()
  5. //
  6. // this way we avoid unnecessary latency for low-ish server tick rates.
  7. // for example, if we were to use this tick:
  8. // transport.process_incoming/outgoing()
  9. // update_world()
  10. //
  11. // then anything sent in update_world wouldn't be actually sent out by the
  12. // transport until the next frame. if server runs at 60Hz, then this can add
  13. // 16ms latency for every single packet.
  14. //
  15. // => instead we process incoming, update world, process_outgoing in the same
  16. // frame. it's more clear (no race conditions) and lower latency.
  17. // => we need to add custom Update functions to the Unity engine:
  18. // NetworkEarlyUpdate before Update()/FixedUpdate()
  19. // NetworkLateUpdate after LateUpdate()
  20. // this way the user can update the world in Update/FixedUpdate/LateUpdate
  21. // and networking still runs before/after those functions no matter what!
  22. // => see also: https://docs.unity3d.com/Manual/ExecutionOrder.html
  23. // => update order:
  24. // * we add to the end of EarlyUpdate so it runs after any Unity initializations
  25. // * we add to the end of PreLateUpdate so it runs after LateUpdate(). adding
  26. // to the beginning of PostLateUpdate doesn't actually work.
  27. using System;
  28. using UnityEngine;
  29. // PlayerLoop and LowLevel were in the Experimental namespace until 2019.3
  30. // https://docs.unity3d.com/2019.2/Documentation/ScriptReference/Experimental.LowLevel.PlayerLoop.html
  31. // https://docs.unity3d.com/2019.3/Documentation/ScriptReference/LowLevel.PlayerLoop.html
  32. #if UNITY_2019_3_OR_NEWER
  33. using UnityEngine.LowLevel;
  34. using UnityEngine.PlayerLoop;
  35. #else
  36. using UnityEngine.Experimental.LowLevel;
  37. using UnityEngine.Experimental.PlayerLoop;
  38. #endif
  39. namespace Mirror
  40. {
  41. public static class NetworkLoop
  42. {
  43. // helper enum to add loop to begin/end of subSystemList
  44. internal enum AddMode { Beginning, End }
  45. // callbacks in case someone needs to use early/lateupdate too.
  46. public static Action OnEarlyUpdate;
  47. public static Action OnLateUpdate;
  48. // helper function to find an update function's index in a player loop
  49. // type. this is used for testing to guarantee our functions are added
  50. // at the beginning/end properly.
  51. internal static int FindPlayerLoopEntryIndex(PlayerLoopSystem.UpdateFunction function, PlayerLoopSystem playerLoop, Type playerLoopSystemType)
  52. {
  53. // did we find the type? e.g. EarlyUpdate/PreLateUpdate/etc.
  54. if (playerLoop.type == playerLoopSystemType)
  55. return Array.FindIndex(playerLoop.subSystemList, (elem => elem.updateDelegate == function));
  56. // recursively keep looking
  57. if (playerLoop.subSystemList != null)
  58. {
  59. for(int i = 0; i < playerLoop.subSystemList.Length; ++i)
  60. {
  61. int index = FindPlayerLoopEntryIndex(function, playerLoop.subSystemList[i], playerLoopSystemType);
  62. if (index != -1) return index;
  63. }
  64. }
  65. return -1;
  66. }
  67. // MODIFIED AddSystemToPlayerLoopList from Unity.Entities.ScriptBehaviourUpdateOrder (ECS)
  68. //
  69. // => adds an update function to the Unity internal update type.
  70. // => Unity has different update loops:
  71. // https://medium.com/@thebeardphantom/unity-2018-and-playerloop-5c46a12a677
  72. // EarlyUpdate
  73. // FixedUpdate
  74. // PreUpdate
  75. // Update
  76. // PreLateUpdate
  77. // PostLateUpdate
  78. //
  79. // function: the custom update function to add
  80. // IMPORTANT: according to a comment in Unity.Entities.ScriptBehaviourUpdateOrder,
  81. // the UpdateFunction can not be virtual because
  82. // Mono 4.6 has problems invoking virtual methods
  83. // as delegates from native!
  84. // ownerType: the .type to fill in so it's obvious who the new function
  85. // belongs to. seems to be mostly for debugging. pass any.
  86. // addMode: prepend or append to update list
  87. internal static bool AddToPlayerLoop(PlayerLoopSystem.UpdateFunction function, Type ownerType, ref PlayerLoopSystem playerLoop, Type playerLoopSystemType, AddMode addMode)
  88. {
  89. // did we find the type? e.g. EarlyUpdate/PreLateUpdate/etc.
  90. if (playerLoop.type == playerLoopSystemType)
  91. {
  92. // debugging
  93. //Debug.Log($"Found playerLoop of type {playerLoop.type} with {playerLoop.subSystemList.Length} Functions:");
  94. //foreach (PlayerLoopSystem sys in playerLoop.subSystemList)
  95. // Debug.Log($" ->{sys.type}");
  96. // resize & expand subSystemList to fit one more entry
  97. int oldListLength = (playerLoop.subSystemList != null) ? playerLoop.subSystemList.Length : 0;
  98. Array.Resize(ref playerLoop.subSystemList, oldListLength + 1);
  99. // IMPORTANT: always insert a FRESH PlayerLoopSystem!
  100. // We CAN NOT resize and then OVERWRITE an entry's type/loop.
  101. // => PlayerLoopSystem has native IntPtr loop members
  102. // => forgetting to clear those would cause undefined behaviour!
  103. // see also: https://github.com/vis2k/Mirror/pull/2652
  104. PlayerLoopSystem system = new PlayerLoopSystem {
  105. type = ownerType,
  106. updateDelegate = function
  107. };
  108. // prepend our custom loop to the beginning
  109. if (addMode == AddMode.Beginning)
  110. {
  111. // shift to the right, write into first array element
  112. Array.Copy(playerLoop.subSystemList, 0, playerLoop.subSystemList, 1, playerLoop.subSystemList.Length - 1);
  113. playerLoop.subSystemList[0] = system;
  114. }
  115. // append our custom loop to the end
  116. else if (addMode == AddMode.End)
  117. {
  118. // simply write into last array element
  119. playerLoop.subSystemList[oldListLength] = system;
  120. }
  121. // debugging
  122. //Debug.Log($"New playerLoop of type {playerLoop.type} with {playerLoop.subSystemList.Length} Functions:");
  123. //foreach (PlayerLoopSystem sys in playerLoop.subSystemList)
  124. // Debug.Log($" ->{sys.type}");
  125. return true;
  126. }
  127. // recursively keep looking
  128. if (playerLoop.subSystemList != null)
  129. {
  130. for(int i = 0; i < playerLoop.subSystemList.Length; ++i)
  131. {
  132. if (AddToPlayerLoop(function, ownerType, ref playerLoop.subSystemList[i], playerLoopSystemType, addMode))
  133. return true;
  134. }
  135. }
  136. return false;
  137. }
  138. // hook into Unity runtime to actually add our custom functions
  139. [RuntimeInitializeOnLoadMethod]
  140. static void RuntimeInitializeOnLoad()
  141. {
  142. //Debug.Log("Mirror: adding Network[Early/Late]Update to Unity...");
  143. // get loop
  144. // 2019 has GetCURRENTPlayerLoop which is safe to use without
  145. // breaking other custom system's custom loops.
  146. // see also: https://github.com/vis2k/Mirror/pull/2627/files
  147. PlayerLoopSystem playerLoop =
  148. #if UNITY_2019_3_OR_NEWER
  149. PlayerLoop.GetCurrentPlayerLoop();
  150. #else
  151. PlayerLoop.GetDefaultPlayerLoop();
  152. #endif
  153. // add NetworkEarlyUpdate to the end of EarlyUpdate so it runs after
  154. // any Unity initializations but before the first Update/FixedUpdate
  155. AddToPlayerLoop(NetworkEarlyUpdate, typeof(NetworkLoop), ref playerLoop, typeof(EarlyUpdate), AddMode.End);
  156. // add NetworkLateUpdate to the end of PreLateUpdate so it runs after
  157. // LateUpdate(). adding to the beginning of PostLateUpdate doesn't
  158. // actually work.
  159. AddToPlayerLoop(NetworkLateUpdate, typeof(NetworkLoop), ref playerLoop, typeof(PreLateUpdate), AddMode.End);
  160. // set the new loop
  161. PlayerLoop.SetPlayerLoop(playerLoop);
  162. }
  163. static void NetworkEarlyUpdate()
  164. {
  165. //Debug.Log($"NetworkEarlyUpdate {Time.time}");
  166. NetworkServer.NetworkEarlyUpdate();
  167. NetworkClient.NetworkEarlyUpdate();
  168. // invoke event after mirror has done it's early updating.
  169. OnEarlyUpdate?.Invoke();
  170. }
  171. static void NetworkLateUpdate()
  172. {
  173. //Debug.Log($"NetworkLateUpdate {Time.time}");
  174. // invoke event before mirror does its final late updating.
  175. OnLateUpdate?.Invoke();
  176. NetworkServer.NetworkLateUpdate();
  177. NetworkClient.NetworkLateUpdate();
  178. }
  179. }
  180. }