com.unity.netcode.gameobjects@2.0.0-exp.2
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-exp.2] - 2024-04-02 ### Added - Added updates to all internal messages to account for a distributed authority network session connection. (#2863) - Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863) - For a customized `NetworkRigidbodyBase` class: - `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes. - `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned. - `NetworkRigidbodyBase.Initialize` is a protected method that, when invoked, will initialize the instance. This includes options to: - Set whether using a `RigidbodyTypes.Rigidbody` or `RigidbodyTypes.Rigidbody2D`. - Includes additional optional parameters to set the `NetworkTransform`, `Rigidbody`, and `Rigidbody2d` to use. - Provides additional public methods: - `NetworkRigidbodyBase.GetPosition` to return the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.GetRotation` to return the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.MovePosition` to move to the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.MoveRotation` to move to the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.SetPosition` to set the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.SetRotation` to set the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.ApplyCurrentTransform` to set the position and rotation of the `Rigidbody` or `Rigidbody2d` based on the associated `GameObject` transform (depending upon its initialized setting). - `NetworkRigidbodyBase.WakeIfSleeping` to wake up the rigid body if sleeping. - `NetworkRigidbodyBase.SleepRigidbody` to put the rigid body to sleep. - `NetworkRigidbodyBase.IsKinematic` to determine if the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) is currently kinematic. - `NetworkRigidbodyBase.SetIsKinematic` to set the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) current kinematic state. - `NetworkRigidbodyBase.ResetInterpolation` to reset the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) back to its original interpolation value when initialized. - Now includes a `MonoBehaviour.FixedUpdate` implementation that will update the assigned `NetworkTransform` when `NetworkRigidbodyBase.UseRigidBodyForMotion` is true. (#2863) - Added `RigidbodyContactEventManager` that provides a more optimized way to process collision enter and collision stay events as opposed to the `Monobehaviour` approach. (#2863) - Can be used in client-server and distributed authority modes, but is particularly useful in distributed authority. - Added rigid body motion updates to `NetworkTransform` which allows users to set interolation on rigid bodies. (#2863) - Extrapolation is only allowed on authoritative instances, but custom class derived from `NetworkRigidbodyBase` or `NetworkRigidbody` or `NetworkRigidbody2D` automatically switches non-authoritative instances to interpolation if set to extrapolation. - Added distributed authority mode support to `NetworkAnimator`. (#2863) - Added session mode selection to `NetworkManager` inspector view. (#2863) - Added distributed authority permissions feature. (#2863) - Added distributed authority mode specific `NetworkObject` permissions flags (Distributable, Transferable, and RequestRequired). (#2863) - Added distributed authority mode specific `NetworkObject.SetOwnershipStatus` method that applies one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863) - Added distributed authority mode specific `NetworkObject.RemoveOwnershipStatus` method that removes one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863) - Added distributed authority mode specific `NetworkObject.HasOwnershipStatus` method that will return (true or false) whether one or more ownership flags is set. (#2863) - Added distributed authority mode specific `NetworkObject.SetOwnershipLock` method that locks ownership of a `NetworkObject` to prevent ownership from changing until the current owner releases the lock. (#2863) - Added distributed authority mode specific `NetworkObject.RequestOwnership` method that sends an ownership request to the current owner of a spawned `NetworkObject` instance. (#2863) - Added distributed authority mode specific `NetworkObject.OnOwnershipRequested` callback handler that is invoked on the owner/authoritative side when a non-owner requests ownership. Depending upon the boolean returned value depends upon whether the request is approved or denied. (#2863) - Added distributed authority mode specific `NetworkObject.OnOwnershipRequestResponse` callback handler that is invoked when a non-owner's request has been processed. This callback includes a `NetworkObjet.OwnershipRequestResponseStatus` response parameter that describes whether the request was approved or the reason why it was not approved. (#2863) - Added distributed authority mode specific `NetworkObject.DeferDespawn` method that defers the despawning of `NetworkObject` instances on non-authoritative clients based on the tick offset parameter. (#2863) - Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863) - Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863) - Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863) - Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is authomatically the owner of the spawned object). (#2863) - This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example). - Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863) - Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863) - Added distributed authority mode specific `NetworkManager.OnFetchLocalPlayerPrefabToSpawn` callback that, when assigned, will allow the local client to provide the player prefab to be spawned for the local client. (#2863) - This is only invoked if the `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property is set to true. - Added distributed authority mode specific `NetworkBehaviour.HasAuthority` property that determines if the local client has authority over the associated `NetworkObject` instance (typical use case is within a `NetworkBehaviour` script much like that of `IsServer` or `IsClient`). (#2863) - Added distributed authority mode specific `NetworkBehaviour.IsSessionOwner` property that determines if the local client is the session owner (typical use case would be to determine if the local client can has scene management authority within a `NetworkBehaviour` script). (#2863) - Added support for distributed authority mode scene management where the currently assigned session owner can start scene events (i.e. scene loading and scene unloading). (#2863) ### Fixed - Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822) - Fixed issue where NetworkTransform could potentially attempt to "unregister" a named message prior to it being registered. (#2807) - Fixed issue where in-scene placed `NetworkObject`s with complex nested children `NetworkObject`s (more than one child in depth) would not synchronize properly if WorldPositionStays was set to true. (#2796) ### Changed - Changed client side awareness of other clients is now the same as a server or host. (#2863) - Changed `NetworkManager.ConnectedClients` can now be accessed by both server and clients. (#2863) - Changed `NetworkManager.ConnectedClientsList` can now be accessed by both server and clients. (#2863) - Changed `NetworkTransform` defaults to owner authoritative when connected to a distributed authority session. (#2863) - Changed `NetworkVariable` defaults to owner write and everyone read permissions when connected to a distributed authority session (even if declared with server read or write permissions). (#2863) - Changed `NetworkObject` no longer implements the `MonoBehaviour.Update` method in order to determine whether a `NetworkObject` instance has been migrated to a different scene. Instead, only `NetworkObjects` with the `SceneMigrationSynchronization` property set will be updated internally during the `NetworkUpdateStage.PostLateUpdate` by `NetworkManager`. (#2863) - Changed `NetworkManager` inspector view layout where properties are now organized by category. (#2863) - Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810) - Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807)
This commit is contained in:
769
Runtime/NetworkVariable/CollectionSerializationUtility.cs
Normal file
769
Runtime/NetworkVariable/CollectionSerializationUtility.cs
Normal 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c822ece4e24f4676861e07288a7f8526
|
||||
timeCreated: 1705437250
|
||||
@@ -24,6 +24,7 @@ namespace Unity.Netcode
|
||||
/// The callback to be invoked when the list gets changed
|
||||
/// </summary>
|
||||
public event OnListChangedDelegate OnListChanged;
|
||||
internal override NetworkVariableType Type => NetworkVariableType.NetworkList;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor method for <see cref="NetworkList"/>
|
||||
@@ -98,7 +99,7 @@ namespace Unity.Netcode
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Insert:
|
||||
{
|
||||
writer.WriteValueSafe(element.Index);
|
||||
BytePacker.WriteValueBitPacked(writer, element.Index);
|
||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
||||
}
|
||||
break;
|
||||
@@ -109,12 +110,12 @@ namespace Unity.Netcode
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.RemoveAt:
|
||||
{
|
||||
writer.WriteValueSafe(element.Index);
|
||||
BytePacker.WriteValueBitPacked(writer, element.Index);
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Value:
|
||||
{
|
||||
writer.WriteValueSafe(element.Index);
|
||||
BytePacker.WriteValueBitPacked(writer, element.Index);
|
||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
||||
}
|
||||
break;
|
||||
@@ -130,6 +131,20 @@ namespace Unity.Netcode
|
||||
/// <inheritdoc />
|
||||
public override void WriteField(FastBufferWriter writer)
|
||||
{
|
||||
if (m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
writer.WriteValueSafe(NetworkVariableSerialization<T>.Type);
|
||||
if (NetworkVariableSerialization<T>.Type == CollectionItemType.Unmanaged)
|
||||
{
|
||||
// Write the size of the unmanaged serialized type as it has a fixed size. This allows the CMB runtime to correctly read the unmanged type.
|
||||
var placeholder = new T();
|
||||
var startPos = writer.Position;
|
||||
NetworkVariableSerialization<T>.Write(writer, ref placeholder);
|
||||
var size = writer.Position - startPos;
|
||||
writer.Seek(startPos);
|
||||
BytePacker.WriteValueBitPacked(writer, size);
|
||||
}
|
||||
}
|
||||
writer.WriteValueSafe((ushort)m_List.Length);
|
||||
for (int i = 0; i < m_List.Length; i++)
|
||||
{
|
||||
@@ -141,6 +156,15 @@ namespace Unity.Netcode
|
||||
public override void ReadField(FastBufferReader reader)
|
||||
{
|
||||
m_List.Clear();
|
||||
if (m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
// Collection item type is used by the CMB rust service, drop value here.
|
||||
reader.ReadValueSafe(out CollectionItemType type);
|
||||
if (type == CollectionItemType.Unmanaged)
|
||||
{
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out int _);
|
||||
}
|
||||
}
|
||||
reader.ReadValueSafe(out ushort count);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
@@ -189,7 +213,7 @@ namespace Unity.Netcode
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Insert:
|
||||
{
|
||||
reader.ReadValueSafe(out int index);
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out int index);
|
||||
var value = new T();
|
||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
||||
|
||||
@@ -261,7 +285,7 @@ namespace Unity.Netcode
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.RemoveAt:
|
||||
{
|
||||
reader.ReadValueSafe(out int index);
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out int index);
|
||||
T value = m_List[index];
|
||||
m_List.RemoveAt(index);
|
||||
|
||||
@@ -289,7 +313,7 @@ namespace Unity.Netcode
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Value:
|
||||
{
|
||||
reader.ReadValueSafe(out int index);
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out int index);
|
||||
var value = new T();
|
||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
||||
if (index >= m_List.Length)
|
||||
@@ -367,7 +391,7 @@ namespace Unity.Netcode
|
||||
public void Add(T item)
|
||||
{
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
}
|
||||
@@ -388,7 +412,7 @@ namespace Unity.Netcode
|
||||
public void Clear()
|
||||
{
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
}
|
||||
@@ -414,7 +438,7 @@ namespace Unity.Netcode
|
||||
public bool Remove(T item)
|
||||
{
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
}
|
||||
@@ -449,7 +473,7 @@ namespace Unity.Netcode
|
||||
public void Insert(int index, T item)
|
||||
{
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
}
|
||||
@@ -478,7 +502,7 @@ namespace Unity.Netcode
|
||||
public void RemoveAt(int index)
|
||||
{
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
}
|
||||
@@ -503,7 +527,7 @@ namespace Unity.Netcode
|
||||
set
|
||||
{
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
}
|
||||
@@ -551,6 +575,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
m_List.Dispose();
|
||||
m_DirtyEvents.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ namespace Unity.Netcode
|
||||
/// The callback to be invoked when the value gets changed
|
||||
/// </summary>
|
||||
public OnValueChangedDelegate OnValueChanged;
|
||||
internal override NetworkVariableType Type => NetworkVariableType.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for <see cref="NetworkVariable{T}"/>
|
||||
@@ -43,6 +44,19 @@ namespace Unity.Netcode
|
||||
m_PreviousValue = default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the NetworkVariable when the associated NetworkObject is not spawned
|
||||
/// </summary>
|
||||
/// <param name="value">the value to reset the NetworkVariable to (if none specified it resets to the default)</param>
|
||||
public void Reset(T value = default)
|
||||
{
|
||||
if (m_NetworkBehaviour == null || m_NetworkBehaviour != null && !m_NetworkBehaviour.NetworkObject.IsSpawned)
|
||||
{
|
||||
m_InternalValue = value;
|
||||
m_PreviousValue = default;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The internal value of the NetworkVariable
|
||||
/// </summary>
|
||||
@@ -68,9 +82,9 @@ namespace Unity.Netcode
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_NetworkBehaviour && !CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
|
||||
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkVariable");
|
||||
throw new InvalidOperationException($"[Client-{m_NetworkManager.LocalClientId}][{m_NetworkBehaviour.name}][{Name}] Write permissions ({WritePerm}) for this client instance is not allowed!");
|
||||
}
|
||||
|
||||
Set(value);
|
||||
@@ -104,6 +118,8 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
m_PreviousValue = default;
|
||||
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
~NetworkVariable()
|
||||
@@ -142,16 +158,16 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
public override void ResetDirty()
|
||||
{
|
||||
base.ResetDirty();
|
||||
// Resetting the dirty value declares that the current value is not dirty
|
||||
// Therefore, we set the m_PreviousValue field to a duplicate of the current
|
||||
// field, so that our next dirty check is made against the current "not dirty"
|
||||
// value.
|
||||
if (!m_HasPreviousValue || !NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref m_PreviousValue))
|
||||
if (IsDirty())
|
||||
{
|
||||
m_HasPreviousValue = true;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
||||
}
|
||||
base.ResetDirty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -173,7 +189,7 @@ namespace Unity.Netcode
|
||||
/// <param name="writer">The stream to write the value to</param>
|
||||
public override void WriteDelta(FastBufferWriter writer)
|
||||
{
|
||||
WriteField(writer);
|
||||
NetworkVariableSerialization<T>.WriteDelta(writer, ref m_InternalValue, ref m_PreviousValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -189,7 +205,7 @@ namespace Unity.Netcode
|
||||
// would be stored in different fields
|
||||
|
||||
T previousValue = m_InternalValue;
|
||||
NetworkVariableSerialization<T>.Read(reader, ref m_InternalValue);
|
||||
NetworkVariableSerialization<T>.ReadDelta(reader, ref m_InternalValue);
|
||||
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
|
||||
@@ -18,6 +18,22 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
private protected NetworkBehaviour m_NetworkBehaviour;
|
||||
|
||||
private NetworkManager m_InternalNetworkManager;
|
||||
|
||||
internal virtual NetworkVariableType Type => NetworkVariableType.Custom;
|
||||
|
||||
private protected NetworkManager m_NetworkManager
|
||||
{
|
||||
get
|
||||
{
|
||||
if (m_InternalNetworkManager == null && m_NetworkBehaviour && m_NetworkBehaviour.NetworkObject?.NetworkManager)
|
||||
{
|
||||
m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager;
|
||||
}
|
||||
return m_InternalNetworkManager;
|
||||
}
|
||||
}
|
||||
|
||||
public NetworkBehaviour GetBehaviour()
|
||||
{
|
||||
return m_NetworkBehaviour;
|
||||
@@ -29,7 +45,14 @@ namespace Unity.Netcode
|
||||
/// <param name="networkBehaviour">The NetworkBehaviour the NetworkVariable belongs to</param>
|
||||
public void Initialize(NetworkBehaviour networkBehaviour)
|
||||
{
|
||||
m_InternalNetworkManager = null;
|
||||
m_NetworkBehaviour = networkBehaviour;
|
||||
if (m_NetworkBehaviour && m_NetworkBehaviour.NetworkObject?.NetworkManager)
|
||||
{
|
||||
m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager;
|
||||
// When in distributed authority mode, there is no such thing as server write permissions
|
||||
InternalWritePerm = m_InternalNetworkManager.DistributedAuthorityMode ? NetworkVariableWritePermission.Owner : InternalWritePerm;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -53,7 +76,7 @@ namespace Unity.Netcode
|
||||
NetworkVariableWritePermission writePerm = DefaultWritePerm)
|
||||
{
|
||||
ReadPerm = readPerm;
|
||||
WritePerm = writePerm;
|
||||
InternalWritePerm = writePerm;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -76,7 +99,17 @@ namespace Unity.Netcode
|
||||
/// <summary>
|
||||
/// The write permission for this var
|
||||
/// </summary>
|
||||
public readonly NetworkVariableWritePermission WritePerm;
|
||||
public NetworkVariableWritePermission WritePerm
|
||||
{
|
||||
get
|
||||
{
|
||||
return InternalWritePerm;
|
||||
}
|
||||
}
|
||||
|
||||
// We had to change the Write Permission in distributed authority.
|
||||
// (It is too bad we initially declared it as readonly)
|
||||
internal NetworkVariableWritePermission InternalWritePerm;
|
||||
|
||||
/// <summary>
|
||||
/// Sets whether or not the variable needs to be delta synced
|
||||
@@ -92,12 +125,17 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool IgnoreInitializeWarning;
|
||||
|
||||
protected void MarkNetworkBehaviourDirty()
|
||||
{
|
||||
if (m_NetworkBehaviour == null)
|
||||
{
|
||||
Debug.LogWarning($"NetworkVariable is written to, but doesn't know its NetworkBehaviour yet. " +
|
||||
"Are you modifying a NetworkVariable before the NetworkObject is spawned?");
|
||||
if (!IgnoreInitializeWarning)
|
||||
{
|
||||
Debug.LogWarning($"NetworkVariable is written to, but doesn't know its NetworkBehaviour yet. " +
|
||||
"Are you modifying a NetworkVariable before the NetworkObject is spawned?");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (m_NetworkBehaviour.NetworkManager.ShutdownInProgress)
|
||||
@@ -109,7 +147,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
return;
|
||||
}
|
||||
m_NetworkBehaviour.NetworkManager.BehaviourUpdater.AddForUpdate(m_NetworkBehaviour.NetworkObject);
|
||||
m_NetworkBehaviour.NetworkManager.BehaviourUpdater?.AddForUpdate(m_NetworkBehaviour.NetworkObject);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -136,6 +174,11 @@ namespace Unity.Netcode
|
||||
/// <returns>Whether or not the client has permission to read</returns>
|
||||
public bool CanClientRead(ulong clientId)
|
||||
{
|
||||
// When in distributed authority mode, everyone can read (but only the owner can write)
|
||||
if (m_NetworkManager != null && m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
switch (ReadPerm)
|
||||
{
|
||||
default:
|
||||
@@ -201,6 +244,50 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
public virtual void Dispose()
|
||||
{
|
||||
m_InternalNetworkManager = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enum representing the different types of Network Variables.
|
||||
/// </summary>
|
||||
public enum NetworkVariableType : byte
|
||||
{
|
||||
/// <summary>
|
||||
/// Value
|
||||
/// Used for all of the basic NetworkVariables that contain a single value
|
||||
/// </summary>
|
||||
Value = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Custom
|
||||
/// For any custom implemented extension of the NetworkVariableBase
|
||||
/// </summary>
|
||||
Custom = 1,
|
||||
|
||||
/// <summary>
|
||||
/// NetworkList
|
||||
/// </summary>
|
||||
NetworkList = 2
|
||||
}
|
||||
|
||||
public enum CollectionItemType : byte
|
||||
{
|
||||
/// <summary>
|
||||
/// For any type that is not valid inside a NetworkVariable collection
|
||||
/// </summary>
|
||||
Unknown = 0,
|
||||
|
||||
/// <summary>
|
||||
/// The following types are valid types inside of NetworkVariable collections
|
||||
/// </summary>
|
||||
Short = 1,
|
||||
UShort = 2,
|
||||
Int = 3,
|
||||
UInt = 4,
|
||||
Long = 5,
|
||||
ULong = 6,
|
||||
Unmanaged = 7,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
115
Runtime/NetworkVariable/ResizableBitVector.cs
Normal file
115
Runtime/NetworkVariable/ResizableBitVector.cs
Normal 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<byte> 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
3
Runtime/NetworkVariable/ResizableBitVector.cs.meta
Normal file
3
Runtime/NetworkVariable/ResizableBitVector.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 664696a622e244dfa43b26628c05e4a6
|
||||
timeCreated: 1705437231
|
||||
Reference in New Issue
Block a user