Compression.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. // Quaternion compression from DOTSNET
  2. using System;
  3. using System.Runtime.CompilerServices;
  4. using UnityEngine;
  5. namespace Mirror
  6. {
  7. /// <summary>Functions to Compress Quaternions and Floats</summary>
  8. public static class Compression
  9. {
  10. // divide by precision (functions backported from Mirror II)
  11. // for example, 0.1 cm precision converts '5.0f' float to '50' long.
  12. //
  13. // 'long' instead of 'int' to allow for large enough worlds.
  14. // value / precision exceeds int.max range too easily.
  15. // Convert.ToInt32/64 would throw.
  16. // https://github.com/vis2k/DOTSNET/issues/59
  17. //
  18. // 'long' and 'int' will result in the same bandwidth though.
  19. // for example, ScaleToLong(10.5, 0.1) = 105.
  20. // int: 0x00000069
  21. // long: 0x0000000000000069
  22. // delta compression will reduce both to 1 byte.
  23. //
  24. // returns
  25. // 'true' if scaling was possible within 'long' bounds.
  26. // 'false' if clamping was necessary.
  27. // never throws. checking result is optional.
  28. public static bool ScaleToLong(float value, float precision, out long result)
  29. {
  30. // user might try to pass precision = 0 to disable rounding.
  31. // this is not supported.
  32. // throw to make the user fix this immediately.
  33. // otherwise we would have to reinterpret-cast if ==0 etc.
  34. // this function should be kept simple.
  35. // if rounding isn't wanted, this function shouldn't be called.
  36. if (precision == 0) throw new DivideByZeroException($"ScaleToLong: precision=0 would cause null division. If rounding isn't wanted, don't call this function.");
  37. // catch OverflowException if value/precision > long.max.
  38. // attackers should never be able to throw exceptions.
  39. try
  40. {
  41. result = Convert.ToInt64(value / precision);
  42. return true;
  43. }
  44. // clamp to .max/.min.
  45. // returning '0' would make far away entities reset to origin.
  46. // returning 'max' would keep them stuck at the end of the world.
  47. // the latter is much easier to debug.
  48. catch (OverflowException)
  49. {
  50. result = value > 0 ? long.MaxValue : long.MinValue;
  51. return false;
  52. }
  53. }
  54. // returns
  55. // 'true' if scaling was possible within 'long' bounds.
  56. // 'false' if clamping was necessary.
  57. // never throws. checking result is optional.
  58. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  59. public static bool ScaleToLong(Vector3 value, float precision, out long x, out long y, out long z)
  60. {
  61. // attempt to convert every component.
  62. // do not return early if one conversion returned 'false'.
  63. // the return value is optional. always attempt to convert all.
  64. bool result = true;
  65. result &= ScaleToLong(value.x, precision, out x);
  66. result &= ScaleToLong(value.y, precision, out y);
  67. result &= ScaleToLong(value.z, precision, out z);
  68. return result;
  69. }
  70. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  71. public static bool ScaleToLong(Vector3 value, float precision, out Vector3Long quantized)
  72. {
  73. quantized = Vector3Long.zero;
  74. return ScaleToLong(value, precision, out quantized.x, out quantized.y, out quantized.z);
  75. }
  76. // multiple by precision.
  77. // for example, 0.1 cm precision converts '50' long to '5.0f' float.
  78. public static float ScaleToFloat(long value, float precision)
  79. {
  80. // user might try to pass precision = 0 to disable rounding.
  81. // this is not supported.
  82. // throw to make the user fix this immediately.
  83. // otherwise we would have to reinterpret-cast if ==0 etc.
  84. // this function should be kept simple.
  85. // if rounding isn't wanted, this function shouldn't be called.
  86. if (precision == 0) throw new DivideByZeroException($"ScaleToLong: precision=0 would cause null division. If rounding isn't wanted, don't call this function.");
  87. return value * precision;
  88. }
  89. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  90. public static Vector3 ScaleToFloat(long x, long y, long z, float precision)
  91. {
  92. Vector3 v;
  93. v.x = ScaleToFloat(x, precision);
  94. v.y = ScaleToFloat(y, precision);
  95. v.z = ScaleToFloat(z, precision);
  96. return v;
  97. }
  98. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  99. public static Vector3 ScaleToFloat(Vector3Long value, float precision) =>
  100. ScaleToFloat(value.x, value.y, value.z, precision);
  101. // scale a float within min/max range to an ushort between min/max range
  102. // note: can also use this for byte range from byte.MinValue to byte.MaxValue
  103. public static ushort ScaleFloatToUShort(float value, float minValue, float maxValue, ushort minTarget, ushort maxTarget)
  104. {
  105. // note: C# ushort - ushort => int, hence so many casts
  106. // max ushort - min ushort only fits into something bigger
  107. int targetRange = maxTarget - minTarget;
  108. float valueRange = maxValue - minValue;
  109. float valueRelative = value - minValue;
  110. return (ushort)(minTarget + (ushort)(valueRelative / valueRange * targetRange));
  111. }
  112. // scale an ushort within min/max range to a float between min/max range
  113. // note: can also use this for byte range from byte.MinValue to byte.MaxValue
  114. public static float ScaleUShortToFloat(ushort value, ushort minValue, ushort maxValue, float minTarget, float maxTarget)
  115. {
  116. // note: C# ushort - ushort => int, hence so many casts
  117. float targetRange = maxTarget - minTarget;
  118. ushort valueRange = (ushort)(maxValue - minValue);
  119. ushort valueRelative = (ushort)(value - minValue);
  120. return minTarget + (valueRelative / (float)valueRange * targetRange);
  121. }
  122. // quaternion compression //////////////////////////////////////////////
  123. // smallest three: https://gafferongames.com/post/snapshot_compression/
  124. // compresses 16 bytes quaternion into 4 bytes
  125. // helper function to find largest absolute element
  126. // returns the index of the largest one
  127. public static int LargestAbsoluteComponentIndex(Vector4 value, out float largestAbs, out Vector3 withoutLargest)
  128. {
  129. // convert to abs
  130. Vector4 abs = new Vector4(Mathf.Abs(value.x), Mathf.Abs(value.y), Mathf.Abs(value.z), Mathf.Abs(value.w));
  131. // set largest to first abs (x)
  132. largestAbs = abs.x;
  133. withoutLargest = new Vector3(value.y, value.z, value.w);
  134. int largestIndex = 0;
  135. // compare to the others, starting at second value
  136. // performance for 100k calls
  137. // for-loop: 25ms
  138. // manual checks: 22ms
  139. if (abs.y > largestAbs)
  140. {
  141. largestIndex = 1;
  142. largestAbs = abs.y;
  143. withoutLargest = new Vector3(value.x, value.z, value.w);
  144. }
  145. if (abs.z > largestAbs)
  146. {
  147. largestIndex = 2;
  148. largestAbs = abs.z;
  149. withoutLargest = new Vector3(value.x, value.y, value.w);
  150. }
  151. if (abs.w > largestAbs)
  152. {
  153. largestIndex = 3;
  154. largestAbs = abs.w;
  155. withoutLargest = new Vector3(value.x, value.y, value.z);
  156. }
  157. return largestIndex;
  158. }
  159. const float QuaternionMinRange = -0.707107f;
  160. const float QuaternionMaxRange = 0.707107f;
  161. const ushort TenBitsMax = 0x3FF;
  162. // helper function to access 'nth' component of quaternion
  163. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  164. static float QuaternionElement(Quaternion q, int element)
  165. {
  166. switch (element)
  167. {
  168. case 0: return q.x;
  169. case 1: return q.y;
  170. case 2: return q.z;
  171. case 3: return q.w;
  172. default: return 0;
  173. }
  174. }
  175. // note: assumes normalized quaternions
  176. public static uint CompressQuaternion(Quaternion q)
  177. {
  178. // note: assuming normalized quaternions is enough. no need to force
  179. // normalize here. we already normalize when decompressing.
  180. // find the largest component index [0,3] + value
  181. int largestIndex = LargestAbsoluteComponentIndex(new Vector4(q.x, q.y, q.z, q.w), out float _, out Vector3 withoutLargest);
  182. // from here on, we work with the 3 components without largest!
  183. // "You might think you need to send a sign bit for [largest] in
  184. // case it is negative, but you don’t, because you can make
  185. // [largest] always positive by negating the entire quaternion if
  186. // [largest] is negative. in quaternion space (x,y,z,w) and
  187. // (-x,-y,-z,-w) represent the same rotation."
  188. if (QuaternionElement(q, largestIndex) < 0)
  189. withoutLargest = -withoutLargest;
  190. // put index & three floats into one integer.
  191. // => index is 2 bits (4 values require 2 bits to store them)
  192. // => the three floats are between [-0.707107,+0.707107] because:
  193. // "If v is the absolute value of the largest quaternion
  194. // component, the next largest possible component value occurs
  195. // when two components have the same absolute value and the
  196. // other two components are zero. The length of that quaternion
  197. // (v,v,0,0) is 1, therefore v^2 + v^2 = 1, 2v^2 = 1,
  198. // v = 1/sqrt(2). This means you can encode the smallest three
  199. // components in [-0.707107,+0.707107] instead of [-1,+1] giving
  200. // you more precision with the same number of bits."
  201. // => the article recommends storing each float in 9 bits
  202. // => our uint has 32 bits, so we might as well store in (32-2)/3=10
  203. // 10 bits max value: 1023=0x3FF (use OSX calc to flip 10 bits)
  204. ushort aScaled = ScaleFloatToUShort(withoutLargest.x, QuaternionMinRange, QuaternionMaxRange, 0, TenBitsMax);
  205. ushort bScaled = ScaleFloatToUShort(withoutLargest.y, QuaternionMinRange, QuaternionMaxRange, 0, TenBitsMax);
  206. ushort cScaled = ScaleFloatToUShort(withoutLargest.z, QuaternionMinRange, QuaternionMaxRange, 0, TenBitsMax);
  207. // now we just need to pack them into one integer
  208. // -> index is 2 bit and needs to be shifted to 31..32
  209. // -> a is 10 bit and needs to be shifted 20..30
  210. // -> b is 10 bit and needs to be shifted 10..20
  211. // -> c is 10 bit and needs to be at 0..10
  212. return (uint)(largestIndex << 30 | aScaled << 20 | bScaled << 10 | cScaled);
  213. }
  214. // Quaternion normalizeSAFE from ECS math.normalizesafe()
  215. // => useful to produce valid quaternions even if client sends invalid
  216. // data
  217. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  218. static Quaternion QuaternionNormalizeSafe(Quaternion value)
  219. {
  220. // The smallest positive normal number representable in a float.
  221. const float FLT_MIN_NORMAL = 1.175494351e-38F;
  222. Vector4 v = new Vector4(value.x, value.y, value.z, value.w);
  223. float length = Vector4.Dot(v, v);
  224. return length > FLT_MIN_NORMAL
  225. ? value.normalized
  226. : Quaternion.identity;
  227. }
  228. // note: gives normalized quaternions
  229. public static Quaternion DecompressQuaternion(uint data)
  230. {
  231. // get cScaled which is at 0..10 and ignore the rest
  232. ushort cScaled = (ushort)(data & TenBitsMax);
  233. // get bScaled which is at 10..20 and ignore the rest
  234. ushort bScaled = (ushort)((data >> 10) & TenBitsMax);
  235. // get aScaled which is at 20..30 and ignore the rest
  236. ushort aScaled = (ushort)((data >> 20) & TenBitsMax);
  237. // get 2 bit largest index, which is at 31..32
  238. int largestIndex = (int)(data >> 30);
  239. // scale back to floats
  240. float a = ScaleUShortToFloat(aScaled, 0, TenBitsMax, QuaternionMinRange, QuaternionMaxRange);
  241. float b = ScaleUShortToFloat(bScaled, 0, TenBitsMax, QuaternionMinRange, QuaternionMaxRange);
  242. float c = ScaleUShortToFloat(cScaled, 0, TenBitsMax, QuaternionMinRange, QuaternionMaxRange);
  243. // calculate the omitted component based on a²+b²+c²+d²=1
  244. float d = Mathf.Sqrt(1 - a*a - b*b - c*c);
  245. // reconstruct based on largest index
  246. Vector4 value;
  247. switch (largestIndex)
  248. {
  249. case 0: value = new Vector4(d, a, b, c); break;
  250. case 1: value = new Vector4(a, d, b, c); break;
  251. case 2: value = new Vector4(a, b, d, c); break;
  252. default: value = new Vector4(a, b, c, d); break;
  253. }
  254. // ECS Rotation only works with normalized quaternions.
  255. // make sure that's always the case here to avoid ECS bugs where
  256. // everything stops moving if the quaternion isn't normalized.
  257. // => NormalizeSafe returns a normalized quaternion even if we pass
  258. // in NaN from deserializing invalid values!
  259. return QuaternionNormalizeSafe(new Quaternion(value.x, value.y, value.z, value.w));
  260. }
  261. // varint compression //////////////////////////////////////////////////
  262. // compress ulong varint.
  263. // same result for ulong, uint, ushort and byte. only need one function.
  264. // NOT an extension. otherwise weaver might accidentally use it.
  265. public static void CompressVarUInt(NetworkWriter writer, ulong value)
  266. {
  267. if (value <= 240)
  268. {
  269. writer.WriteByte((byte)value);
  270. return;
  271. }
  272. if (value <= 2287)
  273. {
  274. writer.WriteByte((byte)(((value - 240) >> 8) + 241));
  275. writer.WriteByte((byte)((value - 240) & 0xFF));
  276. return;
  277. }
  278. if (value <= 67823)
  279. {
  280. writer.WriteByte((byte)249);
  281. writer.WriteByte((byte)((value - 2288) >> 8));
  282. writer.WriteByte((byte)((value - 2288) & 0xFF));
  283. return;
  284. }
  285. if (value <= 16777215)
  286. {
  287. writer.WriteByte((byte)250);
  288. writer.WriteByte((byte)(value & 0xFF));
  289. writer.WriteByte((byte)((value >> 8) & 0xFF));
  290. writer.WriteByte((byte)((value >> 16) & 0xFF));
  291. return;
  292. }
  293. if (value <= 4294967295)
  294. {
  295. writer.WriteByte((byte)251);
  296. writer.WriteByte((byte)(value & 0xFF));
  297. writer.WriteByte((byte)((value >> 8) & 0xFF));
  298. writer.WriteByte((byte)((value >> 16) & 0xFF));
  299. writer.WriteByte((byte)((value >> 24) & 0xFF));
  300. return;
  301. }
  302. if (value <= 1099511627775)
  303. {
  304. writer.WriteByte((byte)252);
  305. writer.WriteByte((byte)(value & 0xFF));
  306. writer.WriteByte((byte)((value >> 8) & 0xFF));
  307. writer.WriteByte((byte)((value >> 16) & 0xFF));
  308. writer.WriteByte((byte)((value >> 24) & 0xFF));
  309. writer.WriteByte((byte)((value >> 32) & 0xFF));
  310. return;
  311. }
  312. if (value <= 281474976710655)
  313. {
  314. writer.WriteByte((byte)253);
  315. writer.WriteByte((byte)(value & 0xFF));
  316. writer.WriteByte((byte)((value >> 8) & 0xFF));
  317. writer.WriteByte((byte)((value >> 16) & 0xFF));
  318. writer.WriteByte((byte)((value >> 24) & 0xFF));
  319. writer.WriteByte((byte)((value >> 32) & 0xFF));
  320. writer.WriteByte((byte)((value >> 40) & 0xFF));
  321. return;
  322. }
  323. if (value <= 72057594037927935)
  324. {
  325. writer.WriteByte((byte)254);
  326. writer.WriteByte((byte)(value & 0xFF));
  327. writer.WriteByte((byte)((value >> 8) & 0xFF));
  328. writer.WriteByte((byte)((value >> 16) & 0xFF));
  329. writer.WriteByte((byte)((value >> 24) & 0xFF));
  330. writer.WriteByte((byte)((value >> 32) & 0xFF));
  331. writer.WriteByte((byte)((value >> 40) & 0xFF));
  332. writer.WriteByte((byte)((value >> 48) & 0xFF));
  333. return;
  334. }
  335. // all others
  336. {
  337. writer.WriteByte((byte)255);
  338. writer.WriteByte((byte)(value & 0xFF));
  339. writer.WriteByte((byte)((value >> 8) & 0xFF));
  340. writer.WriteByte((byte)((value >> 16) & 0xFF));
  341. writer.WriteByte((byte)((value >> 24) & 0xFF));
  342. writer.WriteByte((byte)((value >> 32) & 0xFF));
  343. writer.WriteByte((byte)((value >> 40) & 0xFF));
  344. writer.WriteByte((byte)((value >> 48) & 0xFF));
  345. writer.WriteByte((byte)((value >> 56) & 0xFF));
  346. }
  347. }
  348. // zigzag encoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba
  349. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  350. public static void CompressVarInt(NetworkWriter writer, long i)
  351. {
  352. ulong zigzagged = (ulong)((i >> 63) ^ (i << 1));
  353. CompressVarUInt(writer, zigzagged);
  354. }
  355. // NOT an extension. otherwise weaver might accidentally use it.
  356. public static ulong DecompressVarUInt(NetworkReader reader)
  357. {
  358. byte a0 = reader.ReadByte();
  359. if (a0 < 241)
  360. {
  361. return a0;
  362. }
  363. byte a1 = reader.ReadByte();
  364. if (a0 <= 248)
  365. {
  366. return 240 + ((a0 - (ulong)241) << 8) + a1;
  367. }
  368. byte a2 = reader.ReadByte();
  369. if (a0 == 249)
  370. {
  371. return 2288 + ((ulong)a1 << 8) + a2;
  372. }
  373. byte a3 = reader.ReadByte();
  374. if (a0 == 250)
  375. {
  376. return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16);
  377. }
  378. byte a4 = reader.ReadByte();
  379. if (a0 == 251)
  380. {
  381. return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24);
  382. }
  383. byte a5 = reader.ReadByte();
  384. if (a0 == 252)
  385. {
  386. return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32);
  387. }
  388. byte a6 = reader.ReadByte();
  389. if (a0 == 253)
  390. {
  391. return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32) + (((ulong)a6) << 40);
  392. }
  393. byte a7 = reader.ReadByte();
  394. if (a0 == 254)
  395. {
  396. return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32) + (((ulong)a6) << 40) + (((ulong)a7) << 48);
  397. }
  398. byte a8 = reader.ReadByte();
  399. if (a0 == 255)
  400. {
  401. return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32) + (((ulong)a6) << 40) + (((ulong)a7) << 48) + (((ulong)a8) << 56);
  402. }
  403. throw new IndexOutOfRangeException($"DecompressVarInt failure: {a0}");
  404. }
  405. // zigzag decoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba
  406. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  407. public static long DecompressVarInt(NetworkReader reader)
  408. {
  409. ulong data = DecompressVarUInt(reader);
  410. return ((long)(data >> 1)) ^ -((long)data & 1);
  411. }
  412. }
  413. }