SnapshotInterpolation.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. // snapshot interpolation algorithms only,
  2. // independent from Unity/NetworkTransform/MonoBehaviour/Mirror/etc.
  3. // the goal is to remove all the magic from it.
  4. // => a standalone snapshot interpolation algorithm
  5. // => that can be simulated with unit tests easily
  6. //
  7. // BOXING: in C#, uses <T> does not box! passing the interface would box!
  8. using System;
  9. using System.Collections.Generic;
  10. namespace Mirror
  11. {
  12. public static class SnapshotInterpolation
  13. {
  14. // insert into snapshot buffer if newer than first entry
  15. // this should ALWAYS be used when inserting into a snapshot buffer!
  16. public static void InsertIfNewEnough<T>(T snapshot, SortedList<double, T> buffer)
  17. where T : Snapshot
  18. {
  19. // we need to drop any snapshot which is older ('<=')
  20. // the snapshots we are already working with.
  21. double timestamp = snapshot.remoteTimestamp;
  22. // if size == 1, then only add snapshots that are newer.
  23. // for example, a snapshot before the first one might have been
  24. // lagging.
  25. if (buffer.Count == 1 &&
  26. timestamp <= buffer.Values[0].remoteTimestamp)
  27. return;
  28. // for size >= 2, we are already interpolating between the first two
  29. // so only add snapshots that are newer than the second entry.
  30. // aka the 'ACB' problem:
  31. // if we have a snapshot A at t=0 and C at t=2,
  32. // we start interpolating between them.
  33. // if suddenly B at t=1 comes in unexpectely,
  34. // we should NOT suddenly steer towards B.
  35. if (buffer.Count >= 2 &&
  36. timestamp <= buffer.Values[1].remoteTimestamp)
  37. return;
  38. // otherwise sort it into the list
  39. // an UDP messages might arrive twice sometimes.
  40. // SortedList throws if key already exists, so check.
  41. if (!buffer.ContainsKey(timestamp))
  42. buffer.Add(timestamp, snapshot);
  43. }
  44. // helper function to check if we have >= n old enough snapshots.
  45. // NOTE: we check LOCAL timestamp here.
  46. // not REMOTE timestamp.
  47. // we buffer for 'bufferTime' locally.
  48. // it has nothing to do with remote timestamp.
  49. // and we wouldn't know the current remoteTime either.
  50. public static bool HasAmountOlderThan<T>(SortedList<double, T> buffer, double threshold, int amount)
  51. where T : Snapshot =>
  52. buffer.Count >= amount &&
  53. buffer.Values[amount - 1].localTimestamp <= threshold;
  54. // calculate catchup.
  55. // the goal is to buffer 'bufferTime' snapshots.
  56. // for whatever reason, we might see growing buffers.
  57. // in which case we should speed up to avoid ever growing delay.
  58. // -> everything after 'threshold' is multiplied by 'multiplier'
  59. public static double CalculateCatchup<T>(SortedList<double, T> buffer, int catchupThreshold, double catchupMultiplier)
  60. where T : Snapshot
  61. {
  62. // NOTE: we count ALL buffer entires > threshold as excess.
  63. // not just the 'old enough' ones.
  64. // if buffer keeps growing, we have to catch up no matter what.
  65. int excess = buffer.Count - catchupThreshold;
  66. return excess > 0 ? excess * catchupMultiplier : 0;
  67. }
  68. // get first & second buffer entries and delta between them.
  69. // helper function because we use this several times.
  70. // => assumes at least two entries in buffer.
  71. public static void GetFirstSecondAndDelta<T>(SortedList<double, T> buffer, out T first, out T second, out double delta)
  72. where T : Snapshot
  73. {
  74. // get first & second
  75. first = buffer.Values[0];
  76. second = buffer.Values[1];
  77. // delta between first & second is needed a lot
  78. delta = second.remoteTimestamp - first.remoteTimestamp;
  79. }
  80. // the core snapshot interpolation algorithm.
  81. // for a given remoteTime, interpolationTime and buffer,
  82. // we tick the snapshot simulation once.
  83. // => it's the same one on server and client
  84. // => should be called every Update() depending on authority
  85. //
  86. // time: LOCAL time since startup in seconds. like Unity's Time.time.
  87. // deltaTime: Time.deltaTime from Unity. parameter for easier tests.
  88. // interpolationTime: time in interpolation. moved along deltaTime.
  89. // between [0, delta] where delta is snapshot
  90. // B.timestamp - A.timestamp.
  91. // IMPORTANT:
  92. // => we use actual time instead of a relative
  93. // t [0,1] because overshoot is easier to handle.
  94. // if relative t overshoots but next snapshots are
  95. // further apart than the current ones, it's not
  96. // obvious how to calculate it.
  97. // => for example, if t = 3 every time we skip we would have to
  98. // make sure to adjust the subtracted value relative to the
  99. // skipped delta. way too complex.
  100. // => actual time can overshoot without problems.
  101. // we know it's always by actual time.
  102. // bufferTime: time in seconds that we buffer snapshots.
  103. // buffer: our buffer of snapshots.
  104. // Compute() assumes full integrity of the snapshots.
  105. // for example, when interpolating between A=0 and C=2,
  106. // make sure that you don't add B=1 between A and C if that
  107. // snapshot arrived after we already started interpolating.
  108. // => InsertIfNewEnough needs to protect against the 'ACB' problem
  109. // catchupThreshold: amount of buffer entries after which we start to
  110. // accelerate to catch up.
  111. // if 'bufferTime' is 'sendInterval * 3', then try
  112. // a value > 3 like 6.
  113. // catchupMultiplier: catchup by % per additional excess buffer entry
  114. // over the amount of 'catchupThreshold'.
  115. // Interpolate: interpolates one snapshot to another, returns the result
  116. // T Interpolate(T from, T to, double t);
  117. // => needs to be Func<T> instead of a function in the Snapshot
  118. // interface because that would require boxing.
  119. // => make sure to only allocate that function once.
  120. //
  121. // returns
  122. // 'true' if it spit out a snapshot to apply.
  123. // 'false' means computation moved along, but nothing to apply.
  124. public static bool Compute<T>(
  125. double time,
  126. double deltaTime,
  127. ref double interpolationTime,
  128. double bufferTime,
  129. SortedList<double, T> buffer,
  130. int catchupThreshold,
  131. float catchupMultiplier,
  132. Func<T, T, double, T> Interpolate,
  133. out T computed)
  134. where T : Snapshot
  135. {
  136. // we buffer snapshots for 'bufferTime'
  137. // for example:
  138. // * we buffer for 3 x sendInterval = 300ms
  139. // * the idea is to wait long enough so we at least have a few
  140. // snapshots to interpolate between
  141. // * we process anything older 100ms immediately
  142. //
  143. // IMPORTANT: snapshot timestamps are _remote_ time
  144. // we need to interpolate and calculate buffer lifetimes based on it.
  145. // -> we don't know remote's current time
  146. // -> NetworkTime.time fluctuates too much, that's no good
  147. // -> we _could_ calculate an offset when the first snapshot arrives,
  148. // but if there was high latency then we'll always calculate time
  149. // with high latency
  150. // -> at any given time, we are interpolating from snapshot A to B
  151. // => seems like A.timestamp += deltaTime is a good way to do it
  152. computed = default;
  153. //Debug.Log($"{name} snapshotbuffer={buffer.Count}");
  154. // we always need two OLD ENOUGH snapshots to interpolate.
  155. // otherwise there's nothing to do.
  156. double threshold = time - bufferTime;
  157. if (!HasAmountOlderThan(buffer, threshold, 2))
  158. return false;
  159. // multiply deltaTime by catchup.
  160. // for example, assuming a catch up of 50%:
  161. // - deltaTime = 1s => 1.5s
  162. // - deltaTime = 0.1s => 0.15s
  163. // in other words, variations in deltaTime don't matter.
  164. // simply multiply. that's just how time works.
  165. // (50% catch up means 0.5, so we multiply by 1.5)
  166. //
  167. // if '0' catchup then we multiply by '1', which changes nothing.
  168. // (faster branch prediction)
  169. double catchup = CalculateCatchup(buffer, catchupThreshold, catchupMultiplier);
  170. deltaTime *= (1 + catchup);
  171. // interpolationTime starts at 0 and we add deltaTime to move
  172. // along the interpolation.
  173. //
  174. // ONLY while we have snapshots to interpolate.
  175. // otherwise we might increase it to infinity which would lead
  176. // to skipping the next snapshots entirely.
  177. //
  178. // IMPORTANT: interpolationTime as actual time instead of
  179. // t [0,1] allows us to overshoot and subtract easily.
  180. // if t was [0,1], and we overshoot by 0.1, that's a
  181. // RELATIVE overshoot for the delta between B.time - A.time.
  182. // => if the next C.time - B.time is not the same delta,
  183. // then the relative overshoot would speed up or slow
  184. // down the interpolation! CAREFUL.
  185. //
  186. // IMPORTANT: we NEVER add deltaTime to 'time'.
  187. // 'time' is already NOW. that's how Unity works.
  188. interpolationTime += deltaTime;
  189. // get first & second & delta
  190. GetFirstSecondAndDelta(buffer, out T first, out T second, out double delta);
  191. // reached goal and have more old enough snapshots in buffer?
  192. // then skip and move to next.
  193. // for example, if we have snapshots at t=1,2,3
  194. // and we are at interpolationTime = 2.5, then
  195. // we should skip the first one, subtract delta and interpolate
  196. // between 2,3 instead.
  197. //
  198. // IMPORTANT: we only ever use old enough snapshots.
  199. // if we wouldn't check for old enough, then we would
  200. // move to the next one, interpolate a little bit,
  201. // and then in next compute() wait again because it
  202. // wasn't old enough yet.
  203. while (interpolationTime >= delta &&
  204. HasAmountOlderThan(buffer, threshold, 3))
  205. {
  206. // subtract exactly delta from interpolation time
  207. // instead of setting to '0', where we would lose the
  208. // overshoot part and see jitter again.
  209. //
  210. // IMPORTANT: subtracting delta TIME works perfectly.
  211. // subtracting '1' from a ratio of t [0,1] would
  212. // leave the overshoot as relative between the
  213. // next delta. if next delta is different, then
  214. // overshoot would be bigger than planned and
  215. // speed up the interpolation.
  216. interpolationTime -= delta;
  217. //Debug.LogWarning($"{name} overshot and is now at: {interpolationTime}");
  218. // remove first, get first, second & delta again after change.
  219. buffer.RemoveAt(0);
  220. GetFirstSecondAndDelta(buffer, out first, out second, out delta);
  221. // NOTE: it's worth consider spitting out all snapshots
  222. // that we skipped, in case someone still wants to move
  223. // along them to avoid physics collisions.
  224. // * for NetworkTransform it's unnecessary as we always
  225. // set transform.position, which can go anywhere.
  226. // * for CharacterController it's worth considering
  227. }
  228. // interpolationTime is actual time, NOT a 't' ratio [0,1].
  229. // we need 't' between [0,1] relative.
  230. // InverseLerp calculates just that.
  231. // InverseLerp CLAMPS between [0,1] and DOES NOT extrapolate!
  232. // => we already skipped ahead as many as possible above.
  233. // => we do NOT extrapolate for the reasons below.
  234. //
  235. // IMPORTANT:
  236. // we should NOT extrapolate & predict while waiting for more
  237. // snapshots as this would introduce a whole range of issues:
  238. // * player might be extrapolated WAY out if we wait for long
  239. // * player might be extrapolated behind walls
  240. // * once we receive a new snapshot, we would interpolate
  241. // not from the last valid position, but from the
  242. // extrapolated position. this could be ANYWHERE. the
  243. // player might get stuck in walls, etc.
  244. // => we are NOT doing client side prediction & rollback here
  245. // => we are simply interpolating with known, valid positions
  246. //
  247. // SEE TEST: Compute_Step5_OvershootWithoutEnoughSnapshots_NeverExtrapolates()
  248. double t = Mathd.InverseLerp(first.remoteTimestamp, second.remoteTimestamp, first.remoteTimestamp + interpolationTime);
  249. //Debug.Log($"InverseLerp({first.remoteTimestamp:F2}, {second.remoteTimestamp:F2}, {first.remoteTimestamp} + {interpolationTime:F2}) = {t:F2} snapshotbuffer={buffer.Count}");
  250. // interpolate snapshot, return true to indicate we computed one
  251. computed = Interpolate(first, second, t);
  252. // interpolationTime:
  253. // overshooting is ONLY allowed for smooth transitions when
  254. // immediately moving to the NEXT snapshot afterwards.
  255. //
  256. // if there is ANY break, for example:
  257. // * reached second snapshot and waiting for more
  258. // * reached second snapshot and next one isn't old enough yet
  259. //
  260. // then we SHOULD NOT overshoot because:
  261. // * increasing interpolationTime by deltaTime while waiting
  262. // would make it grow HUGE to 100+.
  263. // * once we have more snapshots, we would skip most of them
  264. // instantly instead of actually interpolating through them.
  265. //
  266. // in other words, if we DON'T have >= 3 old enough.
  267. if (!HasAmountOlderThan(buffer, threshold, 3))
  268. {
  269. // interpolationTime is always from 0..delta.
  270. // so we cap it at delta.
  271. // DO NOT cap it at second.remoteTimestamp.
  272. // (that's why when interpolating the third parameter is
  273. // first.time + interpolationTime)
  274. // => covered with test:
  275. // Compute_Step5_OvershootWithEnoughSnapshots_NextIsntOldEnough()
  276. interpolationTime = Math.Min(interpolationTime, delta);
  277. }
  278. return true;
  279. }
  280. }
  281. }