NetworkWriter.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using Unity.Collections.LowLevel.Unsafe;
  4. using UnityEngine;
  5. namespace Mirror
  6. {
  7. /// <summary>Network Writer for most simple types like floats, ints, buffers, structs, etc. Use NetworkWriterPool.GetReader() to avoid allocations.</summary>
  8. public class NetworkWriter
  9. {
  10. public const int MaxStringLength = 1024 * 32;
  11. // create writer immediately with it's own buffer so no one can mess with it and so that we can resize it.
  12. // note: BinaryWriter allocates too much, so we only use a MemoryStream
  13. // => 1500 bytes by default because on average, most packets will be <= MTU
  14. byte[] buffer = new byte[1500];
  15. /// <summary>Next position to write to the buffer</summary>
  16. public int Position;
  17. /// <summary>Reset both the position and length of the stream</summary>
  18. // Leaves the capacity the same so that we can reuse this writer without
  19. // extra allocations
  20. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  21. public void Reset()
  22. {
  23. Position = 0;
  24. }
  25. // NOTE that our runtime resizing comes at no extra cost because:
  26. // 1. 'has space' checks are necessary even for fixed sized writers.
  27. // 2. all writers will eventually be large enough to stop resizing.
  28. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  29. void EnsureCapacity(int value)
  30. {
  31. if (buffer.Length < value)
  32. {
  33. int capacity = Math.Max(value, buffer.Length * 2);
  34. Array.Resize(ref buffer, capacity);
  35. }
  36. }
  37. /// <summary>Copies buffer until 'Position' to a new array.</summary>
  38. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  39. public byte[] ToArray()
  40. {
  41. byte[] data = new byte[Position];
  42. Array.ConstrainedCopy(buffer, 0, data, 0, Position);
  43. return data;
  44. }
  45. /// <summary>Returns allocation-free ArraySegment until 'Position'.</summary>
  46. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  47. public ArraySegment<byte> ToArraySegment()
  48. {
  49. return new ArraySegment<byte>(buffer, 0, Position);
  50. }
  51. // WriteBlittable<T> from DOTSNET.
  52. // this is extremely fast, but only works for blittable types.
  53. //
  54. // Benchmark:
  55. // WriteQuaternion x 100k, Macbook Pro 2015 @ 2.2Ghz, Unity 2018 LTS (debug mode)
  56. //
  57. // | Median | Min | Max | Avg | Std | (ms)
  58. // before | 30.35 | 29.86 | 48.99 | 32.54 | 4.93 |
  59. // blittable* | 5.69 | 5.52 | 27.51 | 7.78 | 5.65 |
  60. //
  61. // * without IsBlittable check
  62. // => 4-6x faster!
  63. //
  64. // WriteQuaternion x 100k, Macbook Pro 2015 @ 2.2Ghz, Unity 2020.1 (release mode)
  65. //
  66. // | Median | Min | Max | Avg | Std | (ms)
  67. // before | 9.41 | 8.90 | 23.02 | 10.72 | 3.07 |
  68. // blittable* | 1.48 | 1.40 | 16.03 | 2.60 | 2.71 |
  69. //
  70. // * without IsBlittable check
  71. // => 6x faster!
  72. //
  73. // Note:
  74. // WriteBlittable assumes same endianness for server & client.
  75. // All Unity 2018+ platforms are little endian.
  76. // => run NetworkWriterTests.BlittableOnThisPlatform() to verify!
  77. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  78. internal unsafe void WriteBlittable<T>(T value)
  79. where T : unmanaged
  80. {
  81. // check if blittable for safety
  82. #if UNITY_EDITOR
  83. if (!UnsafeUtility.IsBlittable(typeof(T)))
  84. {
  85. Debug.LogError($"{typeof(T)} is not blittable!");
  86. return;
  87. }
  88. #endif
  89. // calculate size
  90. // sizeof(T) gets the managed size at compile time.
  91. // Marshal.SizeOf<T> gets the unmanaged size at runtime (slow).
  92. // => our 1mio writes benchmark is 6x slower with Marshal.SizeOf<T>
  93. // => for blittable types, sizeof(T) is even recommended:
  94. // https://docs.microsoft.com/en-us/dotnet/standard/native-interop/best-practices
  95. int size = sizeof(T);
  96. // ensure capacity
  97. // NOTE that our runtime resizing comes at no extra cost because:
  98. // 1. 'has space' checks are necessary even for fixed sized writers.
  99. // 2. all writers will eventually be large enough to stop resizing.
  100. EnsureCapacity(Position + size);
  101. // write blittable
  102. fixed (byte* ptr = &buffer[Position])
  103. {
  104. #if UNITY_ANDROID
  105. // on some android systems, assigning *(T*)ptr throws a NRE if
  106. // the ptr isn't aligned (i.e. if Position is 1,2,3,5, etc.).
  107. // here we have to use memcpy.
  108. //
  109. // => we can't get a pointer of a struct in C# without
  110. // marshalling allocations
  111. // => instead, we stack allocate an array of type T and use that
  112. // => stackalloc avoids GC and is very fast. it only works for
  113. // value types, but all blittable types are anyway.
  114. //
  115. // this way, we can still support blittable reads on android.
  116. // see also: https://github.com/vis2k/Mirror/issues/3044
  117. // (solution discovered by AIIO, FakeByte, mischa)
  118. T* valueBuffer = stackalloc T[1]{value};
  119. UnsafeUtility.MemCpy(ptr, valueBuffer, size);
  120. #else
  121. // cast buffer to T* pointer, then assign value to the area
  122. *(T*)ptr = value;
  123. #endif
  124. }
  125. Position += size;
  126. }
  127. // blittable'?' template for code reuse
  128. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  129. internal void WriteBlittableNullable<T>(T? value)
  130. where T : unmanaged
  131. {
  132. // bool isn't blittable. write as byte.
  133. WriteByte((byte)(value.HasValue ? 0x01 : 0x00));
  134. // only write value if exists. saves bandwidth.
  135. if (value.HasValue)
  136. WriteBlittable(value.Value);
  137. }
  138. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  139. public void WriteByte(byte value) => WriteBlittable(value);
  140. // for byte arrays with consistent size, where the reader knows how many to read
  141. // (like a packet opcode that's always the same)
  142. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  143. public void WriteBytes(byte[] buffer, int offset, int count)
  144. {
  145. EnsureCapacity(Position + count);
  146. Array.ConstrainedCopy(buffer, offset, this.buffer, Position, count);
  147. Position += count;
  148. }
  149. /// <summary>Writes any type that mirror supports. Uses weaver populated Writer(T).write.</summary>
  150. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  151. public void Write<T>(T value)
  152. {
  153. Action<NetworkWriter, T> writeDelegate = Writer<T>.write;
  154. if (writeDelegate == null)
  155. {
  156. Debug.LogError($"No writer found for {typeof(T)}. This happens either if you are missing a NetworkWriter extension for your custom type, or if weaving failed. Try to reimport a script to weave again.");
  157. }
  158. else
  159. {
  160. writeDelegate(this, value);
  161. }
  162. }
  163. }
  164. /// <summary>Helper class that weaver populates with all writer types.</summary>
  165. // Note that c# creates a different static variable for each type
  166. // -> Weaver.ReaderWriterProcessor.InitializeReaderAndWriters() populates it
  167. public static class Writer<T>
  168. {
  169. public static Action<NetworkWriter, T> write;
  170. }
  171. }