NetworkLoop.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. internal static class NetworkLoop
  42. {
  43. // helper enum to add loop to begin/end of subSystemList
  44. internal enum AddMode { Beginning, End }
  45. // helper function to find an update function's index in a player loop
  46. // type. this is used for testing to guarantee our functions are added
  47. // at the beginning/end properly.
  48. internal static int FindPlayerLoopEntryIndex(PlayerLoopSystem.UpdateFunction function, PlayerLoopSystem playerLoop, Type playerLoopSystemType)
  49. {
  50. // did we find the type? e.g. EarlyUpdate/PreLateUpdate/etc.
  51. if (playerLoop.type == playerLoopSystemType)
  52. return Array.FindIndex(playerLoop.subSystemList, (elem => elem.updateDelegate == function));
  53. // recursively keep looking
  54. if (playerLoop.subSystemList != null)
  55. {
  56. for(int i = 0; i < playerLoop.subSystemList.Length; ++i)
  57. {
  58. int index = FindPlayerLoopEntryIndex(function, playerLoop.subSystemList[i], playerLoopSystemType);
  59. if (index != -1) return index;
  60. }
  61. }
  62. return -1;
  63. }
  64. // MODIFIED AddSystemToPlayerLoopList from Unity.Entities.ScriptBehaviourUpdateOrder (ECS)
  65. //
  66. // => adds an update function to the Unity internal update type.
  67. // => Unity has different update loops:
  68. // https://medium.com/@thebeardphantom/unity-2018-and-playerloop-5c46a12a677
  69. // EarlyUpdate
  70. // FixedUpdate
  71. // PreUpdate
  72. // Update
  73. // PreLateUpdate
  74. // PostLateUpdate
  75. //
  76. // function: the custom update function to add
  77. // IMPORTANT: according to a comment in Unity.Entities.ScriptBehaviourUpdateOrder,
  78. // the UpdateFunction can not be virtual because
  79. // Mono 4.6 has problems invoking virtual methods
  80. // as delegates from native!
  81. // ownerType: the .type to fill in so it's obvious who the new function
  82. // belongs to. seems to be mostly for debugging. pass any.
  83. // addMode: prepend or append to update list
  84. internal static bool AddToPlayerLoop(PlayerLoopSystem.UpdateFunction function, Type ownerType, ref PlayerLoopSystem playerLoop, Type playerLoopSystemType, AddMode addMode)
  85. {
  86. // did we find the type? e.g. EarlyUpdate/PreLateUpdate/etc.
  87. if (playerLoop.type == playerLoopSystemType)
  88. {
  89. // debugging
  90. //Debug.Log($"Found playerLoop of type {playerLoop.type} with {playerLoop.subSystemList.Length} Functions:");
  91. //foreach (PlayerLoopSystem sys in playerLoop.subSystemList)
  92. // Debug.Log($" ->{sys.type}");
  93. // resize & expand subSystemList to fit one more entry
  94. int oldListLength = (playerLoop.subSystemList != null) ? playerLoop.subSystemList.Length : 0;
  95. Array.Resize(ref playerLoop.subSystemList, oldListLength + 1);
  96. // IMPORTANT: always insert a FRESH PlayerLoopSystem!
  97. // We CAN NOT resize and then OVERWRITE an entry's type/loop.
  98. // => PlayerLoopSystem has native IntPtr loop members
  99. // => forgetting to clear those would cause undefined behaviour!
  100. // see also: https://github.com/vis2k/Mirror/pull/2652
  101. PlayerLoopSystem system = new PlayerLoopSystem {
  102. type = ownerType,
  103. updateDelegate = function
  104. };
  105. // prepend our custom loop to the beginning
  106. if (addMode == AddMode.Beginning)
  107. {
  108. // shift to the right, write into first array element
  109. Array.Copy(playerLoop.subSystemList, 0, playerLoop.subSystemList, 1, playerLoop.subSystemList.Length - 1);
  110. playerLoop.subSystemList[0] = system;
  111. }
  112. // append our custom loop to the end
  113. else if (addMode == AddMode.End)
  114. {
  115. // simply write into last array element
  116. playerLoop.subSystemList[oldListLength] = system;
  117. }
  118. // debugging
  119. //Debug.Log($"New playerLoop of type {playerLoop.type} with {playerLoop.subSystemList.Length} Functions:");
  120. //foreach (PlayerLoopSystem sys in playerLoop.subSystemList)
  121. // Debug.Log($" ->{sys.type}");
  122. return true;
  123. }
  124. // recursively keep looking
  125. if (playerLoop.subSystemList != null)
  126. {
  127. for(int i = 0; i < playerLoop.subSystemList.Length; ++i)
  128. {
  129. if (AddToPlayerLoop(function, ownerType, ref playerLoop.subSystemList[i], playerLoopSystemType, addMode))
  130. return true;
  131. }
  132. }
  133. return false;
  134. }
  135. // hook into Unity runtime to actually add our custom functions
  136. [RuntimeInitializeOnLoadMethod]
  137. static void RuntimeInitializeOnLoad()
  138. {
  139. //Debug.Log("Mirror: adding Network[Early/Late]Update to Unity...");
  140. // get loop
  141. // 2019 has GetCURRENTPlayerLoop which is safe to use without
  142. // breaking other custom system's custom loops.
  143. // see also: https://github.com/vis2k/Mirror/pull/2627/files
  144. PlayerLoopSystem playerLoop =
  145. #if UNITY_2019_3_OR_NEWER
  146. PlayerLoop.GetCurrentPlayerLoop();
  147. #else
  148. PlayerLoop.GetDefaultPlayerLoop();
  149. #endif
  150. // add NetworkEarlyUpdate to the end of EarlyUpdate so it runs after
  151. // any Unity initializations but before the first Update/FixedUpdate
  152. AddToPlayerLoop(NetworkEarlyUpdate, typeof(NetworkLoop), ref playerLoop, typeof(EarlyUpdate), AddMode.End);
  153. // add NetworkLateUpdate to the end of PreLateUpdate so it runs after
  154. // LateUpdate(). adding to the beginning of PostLateUpdate doesn't
  155. // actually work.
  156. AddToPlayerLoop(NetworkLateUpdate, typeof(NetworkLoop), ref playerLoop, typeof(PreLateUpdate), AddMode.End);
  157. // set the new loop
  158. PlayerLoop.SetPlayerLoop(playerLoop);
  159. }
  160. static void NetworkEarlyUpdate()
  161. {
  162. //Debug.Log("NetworkEarlyUpdate @ " + Time.time);
  163. NetworkServer.NetworkEarlyUpdate();
  164. NetworkClient.NetworkEarlyUpdate();
  165. }
  166. static void NetworkLateUpdate()
  167. {
  168. //Debug.Log("NetworkLateUpdate @ " + Time.time);
  169. NetworkServer.NetworkLateUpdate();
  170. NetworkClient.NetworkLateUpdate();
  171. }
  172. }
  173. }