com.unity.netcode.gameobjects@2.0.0-pre.1

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).

## [2.0.0-pre.1] - 2024-06-17

### Added

- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)
- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)
- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)

### Fixed

- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)
- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)
- Fixed issue where Rigidbody micro-motion (i.e. relatively small velocities) would result in non-authority instances slightly stuttering as the body would come to a rest (i.e. no motion). Now, the threshold value can increase at higher velocities and can decrease slightly below the provided threshold to account for this. (#2948)

### Changed

- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)
- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)
- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)
This commit is contained in:
Unity Technologies
2024-06-17 00:00:00 +00:00
parent 36d539e265
commit ed38a4dcc2
47 changed files with 2758 additions and 2248 deletions

View File

@@ -0,0 +1,769 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
namespace Unity.Netcode
{
internal static class CollectionSerializationUtility
{
public static void WriteNativeArrayDelta<T>(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) where T : unmanaged
{
// This bit vector serializes the list of which fields have changed using 1 bit per field.
// This will always be 1 bit per field of the whole array (rounded up to the nearest 8 bits)
// even if there is only one change, so as compared to serializing the index with each item,
// this will use more bandwidth when the overall bandwidth usage is small and the array is large,
// but less when the overall bandwidth usage is large. So it optimizes for the worst case while accepting
// some reduction in efficiency in the best case.
using var changes = new ResizableBitVector(Allocator.Temp);
int minLength = math.min(value.Length, previousValue.Length);
var numChanges = 0;
// Iterate the array, checking which values have changed and marking that in the bit vector
for (var i = 0; i < minLength; ++i)
{
var val = value[i];
var prevVal = previousValue[i];
if (!NetworkVariableSerialization<T>.AreEqual(ref val, ref prevVal))
{
++numChanges;
changes.Set(i);
}
}
// Mark any newly added items as well
// We don't need to mark removed items because they are captured by serializing the length
for (var i = previousValue.Length; i < value.Length; ++i)
{
++numChanges;
changes.Set(i);
}
// If the size of serializing the dela is greater than the size of serializing the whole array (i.e.,
// because almost the entire array has changed and the overhead of the change set increases bandwidth),
// then we just do a normal full serialization instead of a delta.
if (changes.GetSerializedSize() + FastBufferWriter.GetWriteSize<T>() * numChanges > FastBufferWriter.GetWriteSize<T>() * value.Length)
{
// 1 = full serialization
writer.WriteByteSafe(1);
writer.WriteValueSafe(value);
return;
}
// 0 = delta serialization
writer.WriteByte(0);
// Write the length, which will be used on the read side to resize the array
BytePacker.WriteValuePacked(writer, value.Length);
writer.WriteValueSafe(changes);
unsafe
{
var ptr = (T*)value.GetUnsafePtr();
var prevPtr = (T*)previousValue.GetUnsafePtr();
for (int i = 0; i < value.Length; ++i)
{
if (changes.IsSet(i))
{
if (i < previousValue.Length)
{
// If we have an item in the previous array for this index, we can do nested deltas!
NetworkVariableSerialization<T>.WriteDelta(writer, ref ptr[i], ref prevPtr[i]);
}
else
{
// If not, just write it normally
NetworkVariableSerialization<T>.Write(writer, ref ptr[i]);
}
}
}
}
}
public static void ReadNativeArrayDelta<T>(FastBufferReader reader, ref NativeArray<T> value) where T : unmanaged
{
// 1 = full serialization, 0 = delta serialization
reader.ReadByteSafe(out byte full);
if (full == 1)
{
// If we're doing full serialization, we fall back on reading the whole array.
value.Dispose();
reader.ReadValueSafe(out value, Allocator.Persistent);
return;
}
// If not, first read the length and the change bits
ByteUnpacker.ReadValuePacked(reader, out int length);
var changes = new ResizableBitVector(Allocator.Temp);
using var toDispose = changes;
{
reader.ReadNetworkSerializableInPlace(ref changes);
// If the length has changed, we need to resize.
// NativeArray is not resizeable, so we have to dispose and allocate a new one.
var previousLength = value.Length;
if (length != value.Length)
{
var newArray = new NativeArray<T>(length, Allocator.Persistent);
unsafe
{
UnsafeUtility.MemCpy(newArray.GetUnsafePtr(), value.GetUnsafePtr(), math.min(newArray.Length * sizeof(T), value.Length * sizeof(T)));
}
value.Dispose();
value = newArray;
}
unsafe
{
var ptr = (T*)value.GetUnsafePtr();
for (var i = 0; i < value.Length; ++i)
{
if (changes.IsSet(i))
{
if (i < previousLength)
{
// If we have an item to read a delta into, read it as a delta
NetworkVariableSerialization<T>.ReadDelta(reader, ref ptr[i]);
}
else
{
// If not, read as a standard element
NetworkVariableSerialization<T>.Read(reader, ref ptr[i]);
}
}
}
}
}
}
public static void WriteListDelta<T>(FastBufferWriter writer, ref List<T> value, ref List<T> previousValue)
{
// Lists can be null, so we have to handle that case.
// We do that by marking this as a full serialization and using the existing null handling logic
// in NetworkVariableSerialization<List<T>>
if (value == null || previousValue == null)
{
writer.WriteByteSafe(1);
NetworkVariableSerialization<List<T>>.Write(writer, ref value);
return;
}
// This bit vector serializes the list of which fields have changed using 1 bit per field.
// This will always be 1 bit per field of the whole array (rounded up to the nearest 8 bits)
// even if there is only one change, so as compared to serializing the index with each item,
// this will use more bandwidth when the overall bandwidth usage is small and the array is large,
// but less when the overall bandwidth usage is large. So it optimizes for the worst case while accepting
// some reduction in efficiency in the best case.
using var changes = new ResizableBitVector(Allocator.Temp);
int minLength = math.min(value.Count, previousValue.Count);
var numChanges = 0;
// Iterate the list, checking which values have changed and marking that in the bit vector
for (var i = 0; i < minLength; ++i)
{
var val = value[i];
var prevVal = previousValue[i];
if (!NetworkVariableSerialization<T>.AreEqual(ref val, ref prevVal))
{
++numChanges;
changes.Set(i);
}
}
// Mark any newly added items as well
// We don't need to mark removed items because they are captured by serializing the length
for (var i = previousValue.Count; i < value.Count; ++i)
{
++numChanges;
changes.Set(i);
}
// If the size of serializing the dela is greater than the size of serializing the whole array (i.e.,
// because almost the entire array has changed and the overhead of the change set increases bandwidth),
// then we just do a normal full serialization instead of a delta.
// In the case of List<T>, it's difficult to know exactly what the serialized size is going to be before
// we serialize it, so we fudge it.
if (numChanges >= value.Count * 0.9)
{
// 1 = full serialization
writer.WriteByteSafe(1);
NetworkVariableSerialization<List<T>>.Write(writer, ref value);
return;
}
// 0 = delta serialization
writer.WriteByteSafe(0);
// Write the length, which will be used on the read side to resize the list
BytePacker.WriteValuePacked(writer, value.Count);
writer.WriteValueSafe(changes);
for (int i = 0; i < value.Count; ++i)
{
if (changes.IsSet(i))
{
var reffable = value[i];
if (i < previousValue.Count)
{
// If we have an item in the previous array for this index, we can do nested deltas!
var prevReffable = previousValue[i];
NetworkVariableSerialization<T>.WriteDelta(writer, ref reffable, ref prevReffable);
}
else
{
// If not, just write it normally.
NetworkVariableSerialization<T>.Write(writer, ref reffable);
}
}
}
}
public static void ReadListDelta<T>(FastBufferReader reader, ref List<T> value)
{
// 1 = full serialization, 0 = delta serialization
reader.ReadByteSafe(out byte full);
if (full == 1)
{
// If we're doing full serialization, we fall back on reading the whole list.
NetworkVariableSerialization<List<T>>.Read(reader, ref value);
return;
}
// If not, first read the length and the change bits
ByteUnpacker.ReadValuePacked(reader, out int length);
var changes = new ResizableBitVector(Allocator.Temp);
using var toDispose = changes;
{
reader.ReadNetworkSerializableInPlace(ref changes);
// If the list shrank, we need to resize it down.
// List<T> has no method to reserve space for future elements,
// so if we have to grow it, we just do that using Add() below.
if (length < value.Count)
{
value.RemoveRange(length, value.Count - length);
}
for (var i = 0; i < length; ++i)
{
if (changes.IsSet(i))
{
if (i < value.Count)
{
// If we have an item to read a delta into, read it as a delta
T item = value[i];
NetworkVariableSerialization<T>.ReadDelta(reader, ref item);
value[i] = item;
}
else
{
// If not, just read it as a standard item.
T item = default;
NetworkVariableSerialization<T>.Read(reader, ref item);
value.Add(item);
}
}
}
}
}
// For HashSet and Dictionary, we need to have some local space to hold lists we need to serialize.
// We don't want to do allocations all the time and we know each one needs a maximum of three lists,
// so we're going to keep static lists that we can reuse in these methods.
private static class ListCache<T>
{
private static List<T> s_AddedList = new List<T>();
private static List<T> s_RemovedList = new List<T>();
private static List<T> s_ChangedList = new List<T>();
public static List<T> GetAddedList()
{
s_AddedList.Clear();
return s_AddedList;
}
public static List<T> GetRemovedList()
{
s_RemovedList.Clear();
return s_RemovedList;
}
public static List<T> GetChangedList()
{
s_ChangedList.Clear();
return s_ChangedList;
}
}
public static void WriteHashSetDelta<T>(FastBufferWriter writer, ref HashSet<T> value, ref HashSet<T> previousValue) where T : IEquatable<T>
{
// HashSets can be null, so we have to handle that case.
// We do that by marking this as a full serialization and using the existing null handling logic
// in NetworkVariableSerialization<HashSet<T>>
if (value == null || previousValue == null)
{
writer.WriteByteSafe(1);
NetworkVariableSerialization<HashSet<T>>.Write(writer, ref value);
return;
}
// No changed array because a set can't have a "changed" element, only added and removed.
var added = ListCache<T>.GetAddedList();
var removed = ListCache<T>.GetRemovedList();
// collect the new elements
foreach (var item in value)
{
if (!previousValue.Contains(item))
{
added.Add(item);
}
}
// collect the removed elements
foreach (var item in previousValue)
{
if (!value.Contains(item))
{
removed.Add(item);
}
}
// If we've got more changes than total items, we just do a full serialization
if (added.Count + removed.Count >= value.Count)
{
writer.WriteByteSafe(1);
NetworkVariableSerialization<HashSet<T>>.Write(writer, ref value);
return;
}
writer.WriteByteSafe(0);
// Write out the added and removed arrays.
writer.WriteValueSafe(added.Count);
for (var i = 0; i < added.Count; ++i)
{
var item = added[i];
NetworkVariableSerialization<T>.Write(writer, ref item);
}
writer.WriteValueSafe(removed.Count);
for (var i = 0; i < removed.Count; ++i)
{
var item = removed[i];
NetworkVariableSerialization<T>.Write(writer, ref item);
}
}
public static void ReadHashSetDelta<T>(FastBufferReader reader, ref HashSet<T> value) where T : IEquatable<T>
{
// 1 = full serialization, 0 = delta serialization
reader.ReadByteSafe(out byte full);
if (full != 0)
{
NetworkVariableSerialization<HashSet<T>>.Read(reader, ref value);
return;
}
// Read in the added and removed values
reader.ReadValueSafe(out int addedCount);
for (var i = 0; i < addedCount; ++i)
{
T item = default;
NetworkVariableSerialization<T>.Read(reader, ref item);
value.Add(item);
}
reader.ReadValueSafe(out int removedCount);
for (var i = 0; i < removedCount; ++i)
{
T item = default;
NetworkVariableSerialization<T>.Read(reader, ref item);
value.Remove(item);
}
}
public static void WriteDictionaryDelta<TKey, TVal>(FastBufferWriter writer, ref Dictionary<TKey, TVal> value, ref Dictionary<TKey, TVal> previousValue)
where TKey : IEquatable<TKey>
{
if (value == null || previousValue == null)
{
writer.WriteByteSafe(1);
NetworkVariableSerialization<Dictionary<TKey, TVal>>.Write(writer, ref value);
return;
}
var added = ListCache<KeyValuePair<TKey, TVal>>.GetAddedList();
var changed = ListCache<KeyValuePair<TKey, TVal>>.GetRemovedList();
var removed = ListCache<KeyValuePair<TKey, TVal>>.GetChangedList();
// Collect items that have been added or have changed
foreach (var item in value)
{
var val = item.Value;
var hasPrevVal = previousValue.TryGetValue(item.Key, out var prevVal);
if (!hasPrevVal)
{
added.Add(item);
}
else if (!NetworkVariableSerialization<TVal>.AreEqual(ref val, ref prevVal))
{
changed.Add(item);
}
}
// collect the items that have been removed
foreach (var item in previousValue)
{
if (!value.ContainsKey(item.Key))
{
removed.Add(item);
}
}
// If there are more changes than total values, just do a full serialization
if (added.Count + removed.Count + changed.Count >= value.Count)
{
writer.WriteByteSafe(1);
NetworkVariableSerialization<Dictionary<TKey, TVal>>.Write(writer, ref value);
return;
}
writer.WriteByteSafe(0);
// Else, write out the added, removed, and changed arrays
writer.WriteValueSafe(added.Count);
for (var i = 0; i < added.Count; ++i)
{
(var key, var val) = (added[i].Key, added[i].Value);
NetworkVariableSerialization<TKey>.Write(writer, ref key);
NetworkVariableSerialization<TVal>.Write(writer, ref val);
}
writer.WriteValueSafe(removed.Count);
for (var i = 0; i < removed.Count; ++i)
{
var key = removed[i].Key;
NetworkVariableSerialization<TKey>.Write(writer, ref key);
}
writer.WriteValueSafe(changed.Count);
for (var i = 0; i < changed.Count; ++i)
{
(var key, var val) = (changed[i].Key, changed[i].Value);
NetworkVariableSerialization<TKey>.Write(writer, ref key);
NetworkVariableSerialization<TVal>.Write(writer, ref val);
}
}
public static void ReadDictionaryDelta<TKey, TVal>(FastBufferReader reader, ref Dictionary<TKey, TVal> value)
where TKey : IEquatable<TKey>
{
// 1 = full serialization, 0 = delta serialization
reader.ReadByteSafe(out byte full);
if (full != 0)
{
NetworkVariableSerialization<Dictionary<TKey, TVal>>.Read(reader, ref value);
return;
}
// Added
reader.ReadValueSafe(out int length);
for (var i = 0; i < length; ++i)
{
(TKey key, TVal val) = (default, default);
NetworkVariableSerialization<TKey>.Read(reader, ref key);
NetworkVariableSerialization<TVal>.Read(reader, ref val);
value.Add(key, val);
}
// Removed
reader.ReadValueSafe(out length);
for (var i = 0; i < length; ++i)
{
TKey key = default;
NetworkVariableSerialization<TKey>.Read(reader, ref key);
value.Remove(key);
}
// Changed
reader.ReadValueSafe(out length);
for (var i = 0; i < length; ++i)
{
(TKey key, TVal val) = (default, default);
NetworkVariableSerialization<TKey>.Read(reader, ref key);
NetworkVariableSerialization<TVal>.Read(reader, ref val);
value[key] = val;
}
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
public static void WriteNativeListDelta<T>(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) where T : unmanaged
{
// See WriteListDelta and WriteNativeArrayDelta to understand most of this. It's basically the same,
// just adjusted for the NativeList API
using var changes = new ResizableBitVector(Allocator.Temp);
int minLength = math.min(value.Length, previousValue.Length);
var numChanges = 0;
for (var i = 0; i < minLength; ++i)
{
var val = value[i];
var prevVal = previousValue[i];
if (!NetworkVariableSerialization<T>.AreEqual(ref val, ref prevVal))
{
++numChanges;
changes.Set(i);
}
}
for (var i = previousValue.Length; i < value.Length; ++i)
{
++numChanges;
changes.Set(i);
}
if (changes.GetSerializedSize() + FastBufferWriter.GetWriteSize<T>() * numChanges > FastBufferWriter.GetWriteSize<T>() * value.Length)
{
writer.WriteByteSafe(1);
writer.WriteValueSafe(value);
return;
}
writer.WriteByte(0);
BytePacker.WriteValuePacked(writer, value.Length);
writer.WriteValueSafe(changes);
unsafe
{
#if UTP_TRANSPORT_2_0_ABOVE
var ptr = value.GetUnsafePtr();
var prevPtr = previousValue.GetUnsafePtr();
#else
var ptr = (T*)value.GetUnsafePtr();
var prevPtr = (T*)previousValue.GetUnsafePtr();
#endif
for (int i = 0; i < value.Length; ++i)
{
if (changes.IsSet(i))
{
if (i < previousValue.Length)
{
NetworkVariableSerialization<T>.WriteDelta(writer, ref ptr[i], ref prevPtr[i]);
}
else
{
NetworkVariableSerialization<T>.Write(writer, ref ptr[i]);
}
}
}
}
}
public static void ReadNativeListDelta<T>(FastBufferReader reader, ref NativeList<T> value) where T : unmanaged
{
// See ReadListDelta and ReadNativeArrayDelta to understand most of this. It's basically the same,
// just adjusted for the NativeList API
reader.ReadByteSafe(out byte full);
if (full == 1)
{
reader.ReadValueSafeInPlace(ref value);
return;
}
ByteUnpacker.ReadValuePacked(reader, out int length);
var changes = new ResizableBitVector(Allocator.Temp);
using var toDispose = changes;
{
reader.ReadNetworkSerializableInPlace(ref changes);
var previousLength = value.Length;
// The one big difference between this and NativeArray/List is that NativeList supports
// easy and fast resizing and reserving space.
if (length != value.Length)
{
value.Resize(length, NativeArrayOptions.UninitializedMemory);
}
unsafe
{
#if UTP_TRANSPORT_2_0_ABOVE
var ptr = value.GetUnsafePtr();
#else
var ptr = (T*)value.GetUnsafePtr();
#endif
for (var i = 0; i < value.Length; ++i)
{
if (changes.IsSet(i))
{
if (i < previousLength)
{
NetworkVariableSerialization<T>.ReadDelta(reader, ref ptr[i]);
}
else
{
NetworkVariableSerialization<T>.Read(reader, ref ptr[i]);
}
}
}
}
}
}
public static unsafe void WriteNativeHashSetDelta<T>(FastBufferWriter writer, ref NativeHashSet<T> value, ref NativeHashSet<T> previousValue) where T : unmanaged, IEquatable<T>
{
// See WriteHashSet; this is the same algorithm, adjusted for the NativeHashSet API
var added = stackalloc T[value.Count];
var removed = stackalloc T[previousValue.Count];
var addedCount = 0;
var removedCount = 0;
foreach (var item in value)
{
if (!previousValue.Contains(item))
{
added[addedCount] = item;
++addedCount;
}
}
foreach (var item in previousValue)
{
if (!value.Contains(item))
{
removed[removedCount] = item;
++removedCount;
}
}
#if UTP_TRANSPORT_2_0_ABOVE
if (addedCount + removedCount >= value.Count)
#else
if (addedCount + removedCount >= value.Count())
#endif
{
writer.WriteByteSafe(1);
writer.WriteValueSafe(value);
return;
}
writer.WriteByteSafe(0);
writer.WriteValueSafe(addedCount);
for (var i = 0; i < addedCount; ++i)
{
NetworkVariableSerialization<T>.Write(writer, ref added[i]);
}
writer.WriteValueSafe(removedCount);
for (var i = 0; i < removedCount; ++i)
{
NetworkVariableSerialization<T>.Write(writer, ref removed[i]);
}
}
public static void ReadNativeHashSetDelta<T>(FastBufferReader reader, ref NativeHashSet<T> value) where T : unmanaged, IEquatable<T>
{
// See ReadHashSet; this is the same algorithm, adjusted for the NativeHashSet API
reader.ReadByteSafe(out byte full);
if (full != 0)
{
reader.ReadValueSafeInPlace(ref value);
return;
}
reader.ReadValueSafe(out int addedCount);
for (var i = 0; i < addedCount; ++i)
{
T item = default;
NetworkVariableSerialization<T>.Read(reader, ref item);
value.Add(item);
}
reader.ReadValueSafe(out int removedCount);
for (var i = 0; i < removedCount; ++i)
{
T item = default;
NetworkVariableSerialization<T>.Read(reader, ref item);
value.Remove(item);
}
}
public static unsafe void WriteNativeHashMapDelta<TKey, TVal>(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value, ref NativeHashMap<TKey, TVal> previousValue)
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
// See WriteDictionary; this is the same algorithm, adjusted for the NativeHashMap API
#if UTP_TRANSPORT_2_0_ABOVE
var added = stackalloc KVPair<TKey, TVal>[value.Count];
var changed = stackalloc KVPair<TKey, TVal>[value.Count];
var removed = stackalloc KVPair<TKey, TVal>[previousValue.Count];
#else
var added = stackalloc KeyValue<TKey, TVal>[value.Count()];
var changed = stackalloc KeyValue<TKey, TVal>[value.Count()];
var removed = stackalloc KeyValue<TKey, TVal>[previousValue.Count()];
#endif
var addedCount = 0;
var changedCount = 0;
var removedCount = 0;
foreach (var item in value)
{
var hasPrevVal = previousValue.TryGetValue(item.Key, out var prevVal);
if (!hasPrevVal)
{
added[addedCount] = item;
++addedCount;
}
else if (!NetworkVariableSerialization<TVal>.AreEqual(ref item.Value, ref prevVal))
{
changed[changedCount] = item;
++changedCount;
}
}
foreach (var item in previousValue)
{
if (!value.ContainsKey(item.Key))
{
removed[removedCount] = item;
++removedCount;
}
}
#if UTP_TRANSPORT_2_0_ABOVE
if (addedCount + removedCount + changedCount >= value.Count)
#else
if (addedCount + removedCount + changedCount >= value.Count())
#endif
{
writer.WriteByteSafe(1);
writer.WriteValueSafe(value);
return;
}
writer.WriteByteSafe(0);
writer.WriteValueSafe(addedCount);
for (var i = 0; i < addedCount; ++i)
{
(var key, var val) = (added[i].Key, added[i].Value);
NetworkVariableSerialization<TKey>.Write(writer, ref key);
NetworkVariableSerialization<TVal>.Write(writer, ref val);
}
writer.WriteValueSafe(removedCount);
for (var i = 0; i < removedCount; ++i)
{
var key = removed[i].Key;
NetworkVariableSerialization<TKey>.Write(writer, ref key);
}
writer.WriteValueSafe(changedCount);
for (var i = 0; i < changedCount; ++i)
{
(var key, var val) = (changed[i].Key, changed[i].Value);
NetworkVariableSerialization<TKey>.Write(writer, ref key);
NetworkVariableSerialization<TVal>.Write(writer, ref val);
}
}
public static void ReadNativeHashMapDelta<TKey, TVal>(FastBufferReader reader, ref NativeHashMap<TKey, TVal> value)
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
// See ReadDictionary; this is the same algorithm, adjusted for the NativeHashMap API
reader.ReadByteSafe(out byte full);
if (full != 0)
{
reader.ReadValueSafeInPlace(ref value);
return;
}
// Added
reader.ReadValueSafe(out int length);
for (var i = 0; i < length; ++i)
{
(TKey key, TVal val) = (default, default);
NetworkVariableSerialization<TKey>.Read(reader, ref key);
NetworkVariableSerialization<TVal>.Read(reader, ref val);
value.Add(key, val);
}
// Removed
reader.ReadValueSafe(out length);
for (var i = 0; i < length; ++i)
{
TKey key = default;
NetworkVariableSerialization<TKey>.Read(reader, ref key);
value.Remove(key);
}
// Changed
reader.ReadValueSafe(out length);
for (var i = 0; i < length; ++i)
{
(TKey key, TVal val) = (default, default);
NetworkVariableSerialization<TKey>.Read(reader, ref key);
NetworkVariableSerialization<TVal>.Read(reader, ref val);
value[key] = val;
}
}
#endif
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c822ece4e24f4676861e07288a7f8526
timeCreated: 1705437250

View File

@@ -0,0 +1,99 @@
using System;
using Unity.Collections;
namespace Unity.Netcode
{
/// <summary>
/// This class is instantiated for types that we can't determine ahead of time are serializable - types
/// that don't meet any of the constraints for methods that are available on FastBufferReader and
/// FastBufferWriter. These types may or may not be serializable through extension methods. To ensure
/// the user has time to pass in the delegates to UserNetworkVariableSerialization, the existence
/// of user serialization isn't checked until it's used, so if no serialization is provided, this
/// will throw an exception when an object containing the relevant NetworkVariable is spawned.
/// </summary>
/// <typeparam name="T"></typeparam>
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
{
private void ThrowArgumentError()
{
throw new ArgumentException($"Serialization has not been generated for type {typeof(T).FullName}. This can be addressed by adding a [{nameof(GenerateSerializationForGenericParameterAttribute)}] to your generic class that serializes this value (if you are using one), adding [{nameof(GenerateSerializationForTypeAttribute)}(typeof({typeof(T).FullName})] to the class or method that is attempting to serialize it, or creating a field on a {nameof(NetworkBehaviour)} of type {nameof(NetworkVariable<T>)}. If this error continues to appear after doing one of those things and this is a type you can change, then either implement {nameof(INetworkSerializable)} or mark it as serializable by memcpy by adding {nameof(INetworkSerializeByMemcpy)} to its interface list to enable automatic serialization generation. If not, assign serialization code to {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.WriteValue)}, {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.ReadValue)}, and {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.DuplicateValue)}, or if it's serializable by memcpy (contains no pointers), wrap it in {typeof(ForceNetworkSerializeByMemcpy<>).Name}.");
}
public void Write(FastBufferWriter writer, ref T value)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
UserNetworkVariableSerialization<T>.WriteValue(writer, value);
}
public void Read(FastBufferReader reader, ref T value)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
UserNetworkVariableSerialization<T>.ReadValue(reader, out value);
}
public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
if (UserNetworkVariableSerialization<T>.WriteDelta == null || UserNetworkVariableSerialization<T>.ReadDelta == null)
{
UserNetworkVariableSerialization<T>.WriteValue(writer, value);
return;
}
UserNetworkVariableSerialization<T>.WriteDelta(writer, value, previousValue);
}
public void ReadDelta(FastBufferReader reader, ref T value)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
if (UserNetworkVariableSerialization<T>.WriteDelta == null || UserNetworkVariableSerialization<T>.ReadDelta == null)
{
UserNetworkVariableSerialization<T>.ReadValue(reader, out value);
return;
}
UserNetworkVariableSerialization<T>.ReadDelta(reader, ref value);
}
void INetworkVariableSerializer<T>.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator)
{
throw new NotImplementedException();
}
public void Duplicate(in T value, ref T duplicatedValue)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
UserNetworkVariableSerialization<T>.DuplicateValue(value, ref duplicatedValue);
}
}
// RuntimeAccessModifiersILPP will make this `public`
// This is just pass-through to NetworkVariableSerialization<T> but is here because I could not get ILPP
// to generate code that would successfully call Type<T>.Method(T), but it has no problem calling Type.Method<T>(T)
internal class RpcFallbackSerialization
{
public static void Write<T>(FastBufferWriter writer, ref T value)
{
NetworkVariableSerialization<T>.Write(writer, ref value);
}
public static void Read<T>(FastBufferReader reader, ref T value)
{
NetworkVariableSerialization<T>.Read(reader, ref value);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 288dbe7d1ff74860ae3552c034485538
timeCreated: 1718219109

View File

@@ -0,0 +1,26 @@
using Unity.Collections;
namespace Unity.Netcode
{
/// <summary>
/// Interface used by NetworkVariables to serialize them
/// </summary>
///
/// <typeparam name="T"></typeparam>
internal interface INetworkVariableSerializer<T>
{
// Write has to be taken by ref here because of INetworkSerializable
// Open Instance Delegates (pointers to methods without an instance attached to them)
// require the first parameter passed to them (the instance) to be passed by ref.
// So foo.Bar() becomes BarDelegate(ref foo);
// Taking T as an in parameter like we do in other places would require making a copy
// of it to pass it as a ref parameter.,
public void Write(FastBufferWriter writer, ref T value);
public void Read(FastBufferReader reader, ref T value);
public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue);
public void ReadDelta(FastBufferReader reader, ref T value);
internal void ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator);
public void Duplicate(in T value, ref T duplicatedValue);
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f78e258ef55f4ee89bc3f24d67b8d242
timeCreated: 1718218205

View File

@@ -0,0 +1,357 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Netcode;
namespace Unity.Netcode
{
internal static class NetworkVariableEquality<T>
{
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool ValueEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : unmanaged
{
// get unmanaged pointers
var aptr = UnsafeUtility.AddressOf(ref a);
var bptr = UnsafeUtility.AddressOf(ref b);
// compare addresses
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType)) == 0;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool ValueEqualsList<TValueType>(ref NativeList<TValueType> a, ref NativeList<TValueType> b) where TValueType : unmanaged
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
if (a.Length != b.Length)
{
return false;
}
#if UTP_TRANSPORT_2_0_ABOVE
var aptr = a.GetUnsafePtr();
var bptr = b.GetUnsafePtr();
#else
var aptr = (TValueType*)a.GetUnsafePtr();
var bptr = (TValueType*)b.GetUnsafePtr();
#endif
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType) * a.Length) == 0;
}
#endif
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool ValueEqualsArray<TValueType>(ref NativeArray<TValueType> a, ref NativeArray<TValueType> b) where TValueType : unmanaged
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
if (a.Length != b.Length)
{
return false;
}
var aptr = (TValueType*)a.GetUnsafePtr();
var bptr = (TValueType*)b.GetUnsafePtr();
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType) * a.Length) == 0;
}
internal static bool EqualityEqualsObject<TValueType>(ref TValueType a, ref TValueType b) where TValueType : class, IEquatable<TValueType>
{
if (a == null)
{
return b == null;
}
if (b == null)
{
return false;
}
return a.Equals(b);
}
internal static bool EqualityEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : unmanaged, IEquatable<TValueType>
{
return a.Equals(b);
}
internal static bool EqualityEqualsList<TValueType>(ref List<TValueType> a, ref List<TValueType> b)
{
if (a == null != (b == null))
{
return false;
}
if (a == null)
{
return true;
}
if (a.Count != b.Count)
{
return false;
}
for (var i = 0; i < a.Count; ++i)
{
var aItem = a[i];
var bItem = b[i];
if (!NetworkVariableSerialization<TValueType>.AreEqual(ref aItem, ref bItem))
{
return false;
}
}
return true;
}
internal static bool EqualityEqualsHashSet<TValueType>(ref HashSet<TValueType> a, ref HashSet<TValueType> b) where TValueType : IEquatable<TValueType>
{
if (a == null != (b == null))
{
return false;
}
if (a == null)
{
return true;
}
if (a.Count != b.Count)
{
return false;
}
foreach (var item in a)
{
if (!b.Contains(item))
{
return false;
}
}
return true;
}
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool EqualityEqualsArray<TValueType>(ref NativeArray<TValueType> a, ref NativeArray<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
if (a.Length != b.Length)
{
return false;
}
var aptr = (TValueType*)a.GetUnsafePtr();
var bptr = (TValueType*)b.GetUnsafePtr();
for (var i = 0; i < a.Length; ++i)
{
if (!EqualityEquals(ref aptr[i], ref bptr[i]))
{
return false;
}
}
return true;
}
internal static bool ClassEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : class
{
return a == b;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool EqualityEqualsNativeList<TValueType>(ref NativeList<TValueType> a, ref NativeList<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
if (a.Length != b.Length)
{
return false;
}
#if UTP_TRANSPORT_2_0_ABOVE
var aptr = a.GetUnsafePtr();
var bptr = b.GetUnsafePtr();
#else
var aptr = (TValueType*)a.GetUnsafePtr();
var bptr = (TValueType*)b.GetUnsafePtr();
#endif
for (var i = 0; i < a.Length; ++i)
{
if (!EqualityEquals(ref aptr[i], ref bptr[i]))
{
return false;
}
}
return true;
}
internal static bool EqualityEqualsNativeHashSet<TValueType>(ref NativeHashSet<TValueType> a, ref NativeHashSet<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
#if UTP_TRANSPORT_2_0_ABOVE
if (a.Count != b.Count)
#else
if (a.Count() != b.Count())
#endif
{
return false;
}
foreach (var item in a)
{
if (!b.Contains(item))
{
return false;
}
}
return true;
}
#endif
}
}
/// <summary>
/// Support methods for equality of NetworkVariable collection types.
/// Because there are multiple overloads of WriteValue/ReadValue based on different generic constraints,
/// but there's no way to achieve the same thing with a class, this sets up various read/write schemes
/// based on which constraints are met by `T` using reflection, which is done at module load time.
/// </summary>
/// <typeparam name="TKey">The type the associated NetworkVariable dictionary collection key templated on</typeparam>
/// <typeparam name="TVal">The type the associated NetworkVariable dictionary collection value templated on</typeparam>
internal class NetworkVariableDictionarySerialization<TKey, TVal>
where TKey : IEquatable<TKey>
{
internal static bool GenericEqualsDictionary(ref Dictionary<TKey, TVal> a, ref Dictionary<TKey, TVal> b)
{
if (a == null != (b == null))
{
return false;
}
if (a == null)
{
return true;
}
if (a.Count != b.Count)
{
return false;
}
foreach (var item in a)
{
var hasKey = b.TryGetValue(item.Key, out var val);
if (!hasKey)
{
return false;
}
var bVal = item.Value;
if (!NetworkVariableSerialization<TVal>.AreEqual(ref bVal, ref val))
{
return false;
}
}
return true;
}
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
internal class NetworkVariableMapSerialization<TKey, TVal>
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
internal static bool GenericEqualsNativeHashMap(ref NativeHashMap<TKey, TVal> a, ref NativeHashMap<TKey, TVal> b)
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
#if UTP_TRANSPORT_2_0_ABOVE
if (a.Count != b.Count)
#else
if (a.Count() != b.Count())
#endif
{
return false;
}
foreach (var item in a)
{
var hasKey = b.TryGetValue(item.Key, out var val);
if (!hasKey || !NetworkVariableSerialization<TVal>.AreEqual(ref item.Value, ref val))
{
return false;
}
}
return true;
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 24b8352a975044509931bf684ccfdb82
timeCreated: 1718219366

View File

@@ -0,0 +1,161 @@
using System;
namespace Unity.Netcode
{
/// <summary>
/// Support methods for reading/writing NetworkVariables
/// Because there are multiple overloads of WriteValue/ReadValue based on different generic constraints,
/// but there's no way to achieve the same thing with a class, this sets up various read/write schemes
/// based on which constraints are met by `T` using reflection, which is done at module load time.
/// </summary>
/// <typeparam name="T">The type the associated NetworkVariable is templated on</typeparam>
[Serializable]
public static class NetworkVariableSerialization<T>
{
internal static INetworkVariableSerializer<T> Serializer = new FallbackSerializer<T>();
internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority;
/// <summary>
/// The collection item type tells the CMB server how to read the bytes of each item in the collection
/// </summary>
/// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server
internal static CollectionItemType Type = CollectionItemType.Unknown;
/// <summary>
/// A callback to check if two values are equal.
/// </summary>
public delegate bool EqualsDelegate(ref T a, ref T b);
/// <summary>
/// Uses the most efficient mechanism for a given type to determine if two values are equal.
/// For types that implement <see cref="IEquatable{T}"/>, it will call the Equals() method.
/// For unmanaged types, it will do a bytewise memory comparison.
/// For other types, it will call the == operator.
/// <br/>
/// <br/>
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute"/> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to check their equality yourself.
/// </summary>
public static EqualsDelegate AreEqual { get; internal set; }
/// <summary>
/// Serialize a value using the best-known serialization method for a generic value.
/// Will reliably serialize any value that is passed to it correctly with no boxing.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to use FastBufferWriter directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.WriteValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user serialization callback to it at runtime.
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
public static void Write(FastBufferWriter writer, ref T value)
{
Serializer.Write(writer, ref value);
}
/// <summary>
/// Deserialize a value using the best-known serialization method for a generic value.
/// Will reliably deserialize any value that is passed to it correctly with no boxing.
/// For types whose deserialization can be determined by codegen (which is most types),
/// GC will only be incurred if the type is a managed type and the ref value passed in is `null`,
/// in which case a new value is created; otherwise, it will be deserialized in-place.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to use FastBufferReader directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.ReadValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user deserialization callback to it at runtime.
/// </summary>
/// <param name="reader"></param>
/// <param name="value"></param>
public static void Read(FastBufferReader reader, ref T value)
{
Serializer.Read(reader, ref value);
}
/// <summary>
/// Serialize a value using the best-known serialization method for a generic value.
/// Will reliably serialize any value that is passed to it correctly with no boxing.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to use FastBufferWriter directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.WriteValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user serialization callback to it at runtime.
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
{
Serializer.WriteDelta(writer, ref value, ref previousValue);
}
/// <summary>
/// Deserialize a value using the best-known serialization method for a generic value.
/// Will reliably deserialize any value that is passed to it correctly with no boxing.
/// For types whose deserialization can be determined by codegen (which is most types),
/// GC will only be incurred if the type is a managed type and the ref value passed in is `null`,
/// in which case a new value is created; otherwise, it will be deserialized in-place.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to use FastBufferReader directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.ReadValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user deserialization callback to it at runtime.
/// </summary>
/// <param name="reader"></param>
/// <param name="value"></param>
public static void ReadDelta(FastBufferReader reader, ref T value)
{
Serializer.ReadDelta(reader, ref value);
}
/// <summary>
/// Duplicates a value using the most efficient means of creating a complete copy.
/// For most types this is a simple assignment or memcpy.
/// For managed types, this is will serialize and then deserialize the value to ensure
/// a correct copy.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to duplicate it directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.DuplicateValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user duplication callback to it at runtime.
/// </summary>
/// <param name="value"></param>
/// <param name="duplicatedValue"></param>
public static void Duplicate(in T value, ref T duplicatedValue)
{
Serializer.Duplicate(value, ref duplicatedValue);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7a943170e35746e8913dd494d79bb63d
timeCreated: 1718215899

View File

@@ -0,0 +1,115 @@
using System;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Netcode
{
/// <summary>
/// This is a simple resizable bit vector - i.e., a list of flags that use 1 bit each and can
/// grow to an indefinite size. This is backed by a NativeList&lt;byte&gt; instead of a single
/// integer value, allowing it to contain any size of memory. Contains built-in serialization support.
/// </summary>
internal struct ResizableBitVector : INetworkSerializable, IDisposable
{
private NativeList<byte> m_Bits;
private const int k_Divisor = sizeof(byte) * 8;
public ResizableBitVector(Allocator allocator)
{
m_Bits = new NativeList<byte>(allocator);
}
public void Dispose()
{
m_Bits.Dispose();
}
public int GetSerializedSize()
{
return sizeof(int) + m_Bits.Length;
}
private (int, int) GetBitData(int i)
{
var index = i / k_Divisor;
var bitWithinIndex = i % k_Divisor;
return (index, bitWithinIndex);
}
/// <summary>
/// Set bit 'i' - i.e., bit 0 is 00000001, bit 1 is 00000010, and so on.
/// There is no upper bound on i except for the memory available in the system.
/// </summary>
/// <param name="i"></param>
public void Set(int i)
{
var (index, bitWithinIndex) = GetBitData(i);
if (index >= m_Bits.Length)
{
m_Bits.Resize(index + 1, NativeArrayOptions.ClearMemory);
}
m_Bits[index] |= (byte)(1 << bitWithinIndex);
}
/// <summary>
/// Unset bit 'i' - i.e., bit 0 is 00000001, bit 1 is 00000010, and so on.
/// There is no upper bound on i except for the memory available in the system.
/// Note that once a BitVector has grown to a certain size, it will not shrink back down,
/// so if you set and unset every bit, it will still serialize at its high watermark size.
/// </summary>
/// <param name="i"></param>
public void Unset(int i)
{
var (index, bitWithinIndex) = GetBitData(i);
if (index >= m_Bits.Length)
{
return;
}
m_Bits[index] &= (byte)~(1 << bitWithinIndex);
}
/// <summary>
/// Check if bit 'i' is set - i.e., bit 0 is 00000001, bit 1 is 00000010, and so on.
/// There is no upper bound on i except for the memory available in the system.
/// </summary>
/// <param name="i"></param>
public bool IsSet(int i)
{
var (index, bitWithinIndex) = GetBitData(i);
if (index >= m_Bits.Length)
{
return false;
}
return (m_Bits[index] & (byte)(1 << bitWithinIndex)) != 0;
}
public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
var length = m_Bits.Length;
serializer.SerializeValue(ref length);
m_Bits.ResizeUninitialized(length);
var ptr = m_Bits.GetUnsafePtr();
{
if (serializer.IsReader)
{
#if UTP_TRANSPORT_2_0_ABOVE
serializer.GetFastBufferReader().ReadBytesSafe(ptr, length);
#else
serializer.GetFastBufferReader().ReadBytesSafe((byte*)ptr, length);
#endif
}
else
{
#if UTP_TRANSPORT_2_0_ABOVE
serializer.GetFastBufferWriter().WriteBytesSafe(ptr, length);
#else
serializer.GetFastBufferWriter().WriteBytesSafe((byte*)ptr, length);
#endif
}
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 664696a622e244dfa43b26628c05e4a6
timeCreated: 1705437231

View File

@@ -0,0 +1,325 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
using UnityEditor;
using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// This class contains initialization functions for various different types used in NetworkVariables.
/// Generally speaking, these methods are called by a module initializer created by codegen (NetworkBehaviourILPP)
/// and do not need to be called manually.
///
/// There are two types of initializers: Serializers and EqualityCheckers. Every type must have an EqualityChecker
/// registered to it in order to be used in NetworkVariable; however, not all types need a Serializer. Types without
/// a serializer registered will fall back to using the delegates in <see cref="UserNetworkVariableSerialization{T}"/>.
/// If no such delegate has been registered, a type without a serializer will throw an exception on the first attempt
/// to serialize or deserialize it. (Again, however, codegen handles this automatically and this registration doesn't
/// typically need to be performed manually.)
/// </summary>
public static class NetworkVariableSerializationTypedInitializers
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
#if UNITY_EDITOR
[InitializeOnLoadMethod]
#endif
internal static void InitializeIntegerSerialization()
{
NetworkVariableSerialization<short>.Serializer = new ShortSerializer();
NetworkVariableSerialization<short>.AreEqual = NetworkVariableEquality<short>.ValueEquals;
NetworkVariableSerialization<ushort>.Serializer = new UshortSerializer();
NetworkVariableSerialization<ushort>.AreEqual = NetworkVariableEquality<ushort>.ValueEquals;
NetworkVariableSerialization<int>.Serializer = new IntSerializer();
NetworkVariableSerialization<int>.AreEqual = NetworkVariableEquality<int>.ValueEquals;
NetworkVariableSerialization<uint>.Serializer = new UintSerializer();
NetworkVariableSerialization<uint>.AreEqual = NetworkVariableEquality<uint>.ValueEquals;
NetworkVariableSerialization<long>.Serializer = new LongSerializer();
NetworkVariableSerialization<long>.AreEqual = NetworkVariableEquality<long>.ValueEquals;
NetworkVariableSerialization<ulong>.Serializer = new UlongSerializer();
NetworkVariableSerialization<ulong>.AreEqual = NetworkVariableEquality<ulong>.ValueEquals;
// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server
NetworkVariableSerialization<short>.Type = CollectionItemType.Short;
NetworkVariableSerialization<ushort>.Type = CollectionItemType.UShort;
NetworkVariableSerialization<int>.Type = CollectionItemType.Int;
NetworkVariableSerialization<uint>.Type = CollectionItemType.UInt;
NetworkVariableSerialization<long>.Type = CollectionItemType.Long;
NetworkVariableSerialization<ulong>.Type = CollectionItemType.ULong;
}
/// <summary>
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedByMemcpy<T>() where T : unmanaged
{
NetworkVariableSerialization<T>.Serializer = new UnmanagedTypeSerializer<T>();
// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server
NetworkVariableSerialization<T>.Type = CollectionItemType.Unmanaged;
}
/// <summary>
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedByMemcpyArray<T>() where T : unmanaged
{
NetworkVariableSerialization<NativeArray<T>>.Serializer = new UnmanagedArraySerializer<T>();
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedByMemcpyList<T>() where T : unmanaged
{
NetworkVariableSerialization<NativeList<T>>.Serializer = new UnmanagedListSerializer<T>();
}
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_NativeHashSet<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<NativeHashSet<T>>.Serializer = new NativeHashSetSerializer<T>();
}
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_NativeHashMap<TKey, TVal>()
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
NetworkVariableSerialization<NativeHashMap<TKey, TVal>>.Serializer = new NativeHashMapSerializer<TKey, TVal>();
}
#endif
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_List<T>()
{
NetworkVariableSerialization<List<T>>.Serializer = new ListSerializer<T>();
}
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_HashSet<T>() where T : IEquatable<T>
{
NetworkVariableSerialization<HashSet<T>>.Serializer = new HashSetSerializer<T>();
}
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_Dictionary<TKey, TVal>() where TKey : IEquatable<TKey>
{
NetworkVariableSerialization<Dictionary<TKey, TVal>>.Serializer = new DictionarySerializer<TKey, TVal>();
}
/// <summary>
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
/// NetworkSerialize
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedINetworkSerializable<T>() where T : unmanaged, INetworkSerializable
{
NetworkVariableSerialization<T>.Serializer = new UnmanagedNetworkSerializableSerializer<T>();
}
/// <summary>
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
/// NetworkSerialize
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedINetworkSerializableArray<T>() where T : unmanaged, INetworkSerializable
{
NetworkVariableSerialization<NativeArray<T>>.Serializer = new UnmanagedNetworkSerializableArraySerializer<T>();
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
/// NetworkSerialize
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedINetworkSerializableList<T>() where T : unmanaged, INetworkSerializable
{
NetworkVariableSerialization<NativeList<T>>.Serializer = new UnmanagedNetworkSerializableListSerializer<T>();
}
#endif
/// <summary>
/// Registers a managed type that implements INetworkSerializable and will be serialized through a call to
/// NetworkSerialize
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_ManagedINetworkSerializable<T>() where T : class, INetworkSerializable, new()
{
NetworkVariableSerialization<T>.Serializer = new ManagedNetworkSerializableSerializer<T>();
}
/// <summary>
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
/// serializers
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_FixedString<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
NetworkVariableSerialization<T>.Serializer = new FixedStringSerializer<T>();
}
/// <summary>
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
/// serializers
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_FixedStringArray<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
NetworkVariableSerialization<NativeArray<T>>.Serializer = new FixedStringArraySerializer<T>();
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
/// serializers
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_FixedStringList<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
NetworkVariableSerialization<NativeList<T>>.Serializer = new FixedStringListSerializer<T>();
}
#endif
/// <summary>
/// Registers a managed type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_ManagedIEquatable<T>() where T : class, IEquatable<T>
{
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsObject;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedIEquatable<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.EqualityEquals;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedIEquatableArray<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<NativeArray<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsArray;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_List<T>()
{
NetworkVariableSerialization<List<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsList;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_HashSet<T>() where T : IEquatable<T>
{
NetworkVariableSerialization<HashSet<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsHashSet;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_Dictionary<TKey, TVal>()
where TKey : IEquatable<TKey>
{
NetworkVariableSerialization<Dictionary<TKey, TVal>>.AreEqual = NetworkVariableDictionarySerialization<TKey, TVal>.GenericEqualsDictionary;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedIEquatableList<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<NativeList<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsNativeList;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_NativeHashSet<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<NativeHashSet<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsNativeHashSet;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_NativeHashMap<TKey, TVal>()
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
NetworkVariableSerialization<NativeHashMap<TKey, TVal>>.AreEqual = NetworkVariableMapSerialization<TKey, TVal>.GenericEqualsNativeHashMap;
}
#endif
/// <summary>
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
/// equal if they are bitwise equivalent in memory
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedValueEquals<T>() where T : unmanaged
{
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.ValueEquals;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
/// equal if they are bitwise equivalent in memory
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedValueEqualsArray<T>() where T : unmanaged
{
NetworkVariableSerialization<NativeArray<T>>.AreEqual = NetworkVariableEquality<T>.ValueEqualsArray;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
/// equal if they are bitwise equivalent in memory
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedValueEqualsList<T>() where T : unmanaged
{
NetworkVariableSerialization<NativeList<T>>.AreEqual = NetworkVariableEquality<T>.ValueEqualsList;
}
#endif
/// <summary>
/// Registers a managed type that will be checked for equality using the == operator
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_ManagedClassEquals<T>() where T : class
{
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.ClassEquals;
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 65bdb3e11a9a412ab5e936a9c96a3da0
timeCreated: 1718216842

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: bbfa170e9dd448bbbe381ce38d5c139d
timeCreated: 1718216671

View File

@@ -0,0 +1,73 @@
namespace Unity.Netcode
{
/// <summary>
/// This class is used to register user serialization with NetworkVariables for types
/// that are serialized via user serialization, such as with FastBufferReader and FastBufferWriter
/// extension methods. Finding those methods isn't achievable efficiently at runtime, so this allows
/// users to tell NetworkVariable about those extension methods (or simply pass in a lambda)
/// </summary>
/// <typeparam name="T"></typeparam>
public class UserNetworkVariableSerialization<T>
{
/// <summary>
/// The write value delegate handler definition
/// </summary>
/// <param name="writer">The <see cref="FastBufferWriter"/> to write the value of type `T`</param>
/// <param name="value">The value of type `T` to be written</param>
public delegate void WriteValueDelegate(FastBufferWriter writer, in T value);
/// <summary>
/// The write value delegate handler definition
/// </summary>
/// <param name="writer">The <see cref="FastBufferWriter"/> to write the value of type `T`</param>
/// <param name="value">The value of type `T` to be written</param>
public delegate void WriteDeltaDelegate(FastBufferWriter writer, in T value, in T previousValue);
/// <summary>
/// The read value delegate handler definition
/// </summary>
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
/// <param name="value">The value of type `T` to be read</param>
public delegate void ReadValueDelegate(FastBufferReader reader, out T value);
/// <summary>
/// The read value delegate handler definition
/// </summary>
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
/// <param name="value">The value of type `T` to be read</param>
public delegate void ReadDeltaDelegate(FastBufferReader reader, ref T value);
/// <summary>
/// The read value delegate handler definition
/// </summary>
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
/// <param name="value">The value of type `T` to be read</param>
public delegate void DuplicateValueDelegate(in T value, ref T duplicatedValue);
/// <summary>
/// Callback to write a value
/// </summary>
public static WriteValueDelegate WriteValue;
/// <summary>
/// Callback to read a value
/// </summary>
public static ReadValueDelegate ReadValue;
/// <summary>
/// Callback to write a delta between two values, based on computing the difference between the previous and
/// current values.
/// </summary>
public static WriteDeltaDelegate WriteDelta;
/// <summary>
/// Callback to read a delta, applying only select changes to the current value.
/// </summary>
public static ReadDeltaDelegate ReadDelta;
/// <summary>
/// Callback to create a duplicate of a value, used to check for dirty status.
/// </summary>
public static DuplicateValueDelegate DuplicateValue;
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b295a6756640488b9824d2ec6e26ddae
timeCreated: 1718218272