SnapshotInterpolation.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // snapshot interpolation V2 by mischa
  2. //
  3. // Unity independent to be engine agnostic & easy to test.
  4. // boxing: in C#, uses <T> does not box! passing the interface would box!
  5. //
  6. // credits:
  7. // glenn fiedler: https://gafferongames.com/post/snapshot_interpolation/
  8. // fholm: netcode streams
  9. // fakebyte: standard deviation for dynamic adjustment
  10. // ninjakicka: math & debugging
  11. using System.Collections.Generic;
  12. using System.Runtime.CompilerServices;
  13. namespace Mirror
  14. {
  15. public static class SortedListExtensions
  16. {
  17. // removes the first 'amount' elements from the sorted list
  18. public static void RemoveRange<T, U>(this SortedList<T, U> list, int amount)
  19. {
  20. // remove the first element 'amount' times.
  21. // handles -1 and > count safely.
  22. for (int i = 0; i < amount && i < list.Count; ++i)
  23. list.RemoveAt(0);
  24. }
  25. }
  26. public static class SnapshotInterpolation
  27. {
  28. // calculate timescale for catch-up / slow-down
  29. // note that negative threshold should be <0.
  30. // caller should verify (i.e. Unity OnValidate).
  31. // improves branch prediction.
  32. public static double Timescale(
  33. double drift, // how far we are off from bufferTime
  34. double catchupSpeed, // in % [0,1]
  35. double slowdownSpeed, // in % [0,1]
  36. double catchupNegativeThreshold, // in % of sendInteral (careful, we may run out of snapshots)
  37. double catchupPositiveThreshold) // in % of sendInterval)
  38. {
  39. // if the drift time is too large, it means we are behind more time.
  40. // so we need to speed up the timescale.
  41. // note the threshold should be sendInterval * catchupThreshold.
  42. if (drift > catchupPositiveThreshold)
  43. {
  44. // localTimeline += 0.001; // too simple, this would ping pong
  45. return 1 + catchupSpeed; // n% faster
  46. }
  47. // if the drift time is too small, it means we are ahead of time.
  48. // so we need to slow down the timescale.
  49. // note the threshold should be sendInterval * catchupThreshold.
  50. if (drift < catchupNegativeThreshold)
  51. {
  52. // localTimeline -= 0.001; // too simple, this would ping pong
  53. return 1 - slowdownSpeed; // n% slower
  54. }
  55. // keep constant timescale while within threshold.
  56. // this way we have perfectly smooth speed most of the time.
  57. return 1;
  58. }
  59. // calculate dynamic buffer time adjustment
  60. public static double DynamicAdjustment(
  61. double sendInterval,
  62. double jitterStandardDeviation,
  63. double dynamicAdjustmentTolerance)
  64. {
  65. // jitter is equal to delivery time standard variation.
  66. // delivery time is made up of 'sendInterval+jitter'.
  67. // .Average would be dampened by the constant sendInterval
  68. // .StandardDeviation is the changes in 'jitter' that we want
  69. // so add it to send interval again.
  70. double intervalWithJitter = sendInterval + jitterStandardDeviation;
  71. // how many multiples of sendInterval is that?
  72. // we want to convert to bufferTimeMultiplier later.
  73. double multiples = intervalWithJitter / sendInterval;
  74. // add the tolerance
  75. double safezone = multiples + dynamicAdjustmentTolerance;
  76. // UnityEngine.Debug.Log($"sendInterval={sendInterval:F3} jitter std={jitterStandardDeviation:F3} => that is ~{multiples:F1} x sendInterval + {dynamicAdjustmentTolerance} => dynamic bufferTimeMultiplier={safezone}");
  77. return safezone;
  78. }
  79. // helper function to insert a snapshot if it doesn't exist yet.
  80. // extra function so we can use it for both cases:
  81. // NetworkClient global timeline insertions & adjustments via Insert<T>.
  82. // NetworkBehaviour local insertion without any time adjustments.
  83. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  84. public static bool InsertIfNotExists<T>(
  85. SortedList<double, T> buffer, // snapshot buffer
  86. T snapshot) // the newly received snapshot
  87. where T : Snapshot
  88. {
  89. // SortedList does not allow duplicates.
  90. // we don't need to check ContainsKey (which is expensive).
  91. // simply add and compare count before/after for the return value.
  92. //if (buffer.ContainsKey(snapshot.remoteTime)) return false; // too expensive
  93. // buffer.Add(snapshot.remoteTime, snapshot); // throws if key exists
  94. int before = buffer.Count;
  95. buffer[snapshot.remoteTime] = snapshot; // overwrites if key exists
  96. return buffer.Count > before;
  97. }
  98. // call this for every received snapshot.
  99. // adds / inserts it to the list & initializes local time if needed.
  100. public static void InsertAndAdjust<T>(
  101. SortedList<double, T> buffer, // snapshot buffer
  102. T snapshot, // the newly received snapshot
  103. ref double localTimeline, // local interpolation time based on server time
  104. ref double localTimescale, // timeline multiplier to apply catchup / slowdown over time
  105. float sendInterval, // for debugging
  106. double bufferTime, // offset for buffering
  107. double catchupSpeed, // in % [0,1]
  108. double slowdownSpeed, // in % [0,1]
  109. ref ExponentialMovingAverage driftEma, // for catchup / slowdown
  110. float catchupNegativeThreshold, // in % of sendInteral (careful, we may run out of snapshots)
  111. float catchupPositiveThreshold, // in % of sendInterval
  112. ref ExponentialMovingAverage deliveryTimeEma) // for dynamic buffer time adjustment
  113. where T : Snapshot
  114. {
  115. // first snapshot?
  116. // initialize local timeline.
  117. // we want it to be behind by 'offset'.
  118. //
  119. // note that the first snapshot may be a lagging packet.
  120. // so we would always be behind by that lag.
  121. // this requires catchup later.
  122. if (buffer.Count == 0)
  123. localTimeline = snapshot.remoteTime - bufferTime;
  124. // insert into the buffer.
  125. //
  126. // note that we might insert it between our current interpolation
  127. // which is fine, it adds another data point for accuracy.
  128. //
  129. // note that insert may be called twice for the same key.
  130. // by default, this would throw.
  131. // need to handle it silently.
  132. if (InsertIfNotExists(buffer, snapshot))
  133. {
  134. // dynamic buffer adjustment needs delivery interval jitter
  135. if (buffer.Count >= 2)
  136. {
  137. // note that this is not entirely accurate for scrambled inserts.
  138. //
  139. // we always use the last two, not what we just inserted
  140. // even if we were to use the diff for what we just inserted,
  141. // a scrambled insert would still not be 100% accurate:
  142. // => assume a buffer of AC, with delivery time C-A
  143. // => we then insert B, with delivery time B-A
  144. // => but then technically the first C-A wasn't correct,
  145. // as it would have to be C-B
  146. //
  147. // in practice, scramble is rare and won't make much difference
  148. double previousLocalTime = buffer.Values[buffer.Count - 2].localTime;
  149. double lastestLocalTime = buffer.Values[buffer.Count - 1].localTime;
  150. // this is the delivery time since last snapshot
  151. double localDeliveryTime = lastestLocalTime - previousLocalTime;
  152. // feed the local delivery time to the EMA.
  153. // this is what the original stream did too.
  154. // our final dynamic buffer adjustment is different though.
  155. // we use standard deviation instead of average.
  156. deliveryTimeEma.Add(localDeliveryTime);
  157. }
  158. // adjust timescale to catch up / slow down after each insertion
  159. // because that is when we add new values to our EMA.
  160. // we want localTimeline to be about 'bufferTime' behind.
  161. // for that, we need the delivery time EMA.
  162. // snapshots may arrive out of order, we can not use last-timeline.
  163. // we need to use the inserted snapshot's time - timeline.
  164. double latestRemoteTime = snapshot.remoteTime;
  165. double timeDiff = latestRemoteTime - localTimeline;
  166. // next, calculate average of a few seconds worth of timediffs.
  167. // this gives smoother results.
  168. //
  169. // to calculate the average, we could simply loop through the
  170. // last 'n' seconds worth of timediffs, but:
  171. // - our buffer may only store a few snapshots (bufferTime)
  172. // - looping through seconds worth of snapshots every time is
  173. // expensive
  174. //
  175. // to solve this, we use an exponential moving average.
  176. // https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  177. // which is basically fancy math to do the same but faster.
  178. // additionally, it allows us to look at more timeDiff values
  179. // than we sould have access to in our buffer :)
  180. driftEma.Add(timeDiff);
  181. // next up, calculate how far we are currently away from bufferTime
  182. double drift = driftEma.Value - bufferTime;
  183. // convert relative thresholds to absolute values based on sendInterval
  184. double absoluteNegativeThreshold = sendInterval * catchupNegativeThreshold;
  185. double absolutePositiveThreshold = sendInterval * catchupPositiveThreshold;
  186. // next, set localTimescale to catchup consistently in Update().
  187. // we quantize between default/catchup/slowdown,
  188. // this way we have 'default' speed most of the time(!).
  189. // and only catch up / slow down for a little bit occasionally.
  190. // a consistent multiplier would never be exactly 1.0.
  191. localTimescale = Timescale(drift, catchupSpeed, slowdownSpeed, absoluteNegativeThreshold, absolutePositiveThreshold);
  192. // debug logging
  193. // UnityEngine.Debug.Log($"sendInterval={sendInterval:F3} bufferTime={bufferTime:F3} drift={drift:F3} driftEma={driftEma.Value:F3} timescale={localTimescale:F3} deliveryIntervalEma={deliveryTimeEma.Value:F3}");
  194. }
  195. }
  196. // sample snapshot buffer to find the pair around the given time.
  197. // returns indices so we can use it with RemoveRange to clear old snaps.
  198. // make sure to use use buffer.Values[from/to], not buffer[from/to].
  199. // make sure to only call this is we have > 0 snapshots.
  200. public static void Sample<T>(
  201. SortedList<double, T> buffer, // snapshot buffer
  202. double localTimeline, // local interpolation time based on server time
  203. out int from, // the snapshot <= time
  204. out int to, // the snapshot >= time
  205. out double t) // interpolation factor
  206. where T : Snapshot
  207. {
  208. from = -1;
  209. to = -1;
  210. t = 0;
  211. // sample from [0,count-1] so we always have two at 'i' and 'i+1'.
  212. for (int i = 0; i < buffer.Count - 1; ++i)
  213. {
  214. // is local time between these two?
  215. T first = buffer.Values[i];
  216. T second = buffer.Values[i + 1];
  217. if (localTimeline >= first.remoteTime &&
  218. localTimeline <= second.remoteTime)
  219. {
  220. // use these two snapshots
  221. from = i;
  222. to = i + 1;
  223. t = Mathd.InverseLerp(first.remoteTime, second.remoteTime, localTimeline);
  224. return;
  225. }
  226. }
  227. // didn't find two snapshots around local time.
  228. // so pick either the first or last, depending on which is closer.
  229. // oldest snapshot ahead of local time?
  230. if (buffer.Values[0].remoteTime > localTimeline)
  231. {
  232. from = to = 0;
  233. t = 0;
  234. }
  235. // otherwise initialize both to the last one
  236. else
  237. {
  238. from = to = buffer.Count - 1;
  239. t = 0;
  240. }
  241. }
  242. // progress local timeline every update.
  243. //
  244. // ONLY CALL IF SNAPSHOTS.COUNT > 0!
  245. //
  246. // decoupled from Step<T> for easier testing and so we can progress
  247. // time only once in NetworkClient, while stepping for each component.
  248. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  249. public static void StepTime(
  250. double deltaTime, // engine delta time (unscaled)
  251. ref double localTimeline, // local interpolation time based on server time
  252. double localTimescale) // catchup / slowdown is applied to time every update)
  253. {
  254. // move local forward in time, scaled with catchup / slowdown applied
  255. localTimeline += deltaTime * localTimescale;
  256. }
  257. // sample, clear old.
  258. // call this every update.
  259. //
  260. // ONLY CALL IF SNAPSHOTS.COUNT > 0!
  261. //
  262. // returns true if there is anything to apply (requires at least 1 snap)
  263. // from/to/t are out parameters instead of an interpolated 'computed'.
  264. // this allows us to store from/to/t globally (i.e. in NetworkClient)
  265. // and have each component apply the interpolation manually.
  266. // besides, passing "Func Interpolate" would allocate anyway.
  267. public static void StepInterpolation<T>(
  268. SortedList<double, T> buffer, // snapshot buffer
  269. double localTimeline, // local interpolation time based on server time
  270. out T fromSnapshot, // we interpolate 'from' this snapshot
  271. out T toSnapshot, // 'to' this snapshot
  272. out double t) // at ratio 't' [0,1]
  273. where T : Snapshot
  274. {
  275. // check this in caller:
  276. // nothing to do if there are no snapshots at all yet
  277. // if (buffer.Count == 0) return false;
  278. // sample snapshot buffer at local interpolation time
  279. Sample(buffer, localTimeline, out int from, out int to, out t);
  280. // save from/to
  281. fromSnapshot = buffer.Values[from];
  282. toSnapshot = buffer.Values[to];
  283. // remove older snapshots that we definitely don't need anymore.
  284. // after(!) using the indices.
  285. //
  286. // if we have 3 snapshots and we are between 2nd and 3rd:
  287. // from = 1, to = 2
  288. // then we need to remove the first one, which is exactly 'from'.
  289. // because 'from-1' = 0 would remove none.
  290. buffer.RemoveRange(from);
  291. }
  292. // update time, sample, clear old.
  293. // call this every update.
  294. //
  295. // ONLY CALL IF SNAPSHOTS.COUNT > 0!
  296. //
  297. // returns true if there is anything to apply (requires at least 1 snap)
  298. // from/to/t are out parameters instead of an interpolated 'computed'.
  299. // this allows us to store from/to/t globally (i.e. in NetworkClient)
  300. // and have each component apply the interpolation manually.
  301. // besides, passing "Func Interpolate" would allocate anyway.
  302. public static void Step<T>(
  303. SortedList<double, T> buffer, // snapshot buffer
  304. double deltaTime, // engine delta time (unscaled)
  305. ref double localTimeline, // local interpolation time based on server time
  306. double localTimescale, // catchup / slowdown is applied to time every update
  307. out T fromSnapshot, // we interpolate 'from' this snapshot
  308. out T toSnapshot, // 'to' this snapshot
  309. out double t) // at ratio 't' [0,1]
  310. where T : Snapshot
  311. {
  312. StepTime(deltaTime, ref localTimeline, localTimescale);
  313. StepInterpolation(buffer, localTimeline, out fromSnapshot, out toSnapshot, out t);
  314. }
  315. }
  316. }