From ed38a4dcc25e964dec031398a6b3c4bf945b79a8 Mon Sep 17 00:00:00 2001 From: Unity Technologies <@unity> Date: Mon, 17 Jun 2024 00:00:00 +0000 Subject: [PATCH] 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) --- CHANGELOG.md | 28 + Components.meta | 8 - Editor/CodeGen/NetworkBehaviourILPP.cs | 58 +- Editor/NetworkManagerEditor.cs | 37 +- Editor/NetworkObjectEditor.cs | 4 +- Editor/NetworkTransformEditor.cs | 11 +- Editor/com.unity.netcode.editor.asmdef | 2 +- Runtime/Components/NetworkRigidBodyBase.cs | 142 ++ Runtime/Components/NetworkTransform.cs | 95 +- Runtime/Connection/NetworkClient.cs | 11 +- .../Connection/NetworkConnectionManager.cs | 3 + Runtime/Core/NetworkManager.cs | 65 +- Runtime/Core/NetworkObject.cs | 2 +- .../Messages/ConnectionApprovedMessage.cs | 18 + .../Messages/NetworkTransformMessage.cs | 5 +- Runtime/Messaging/NetworkMessageManager.cs | 18 +- .../Messaging/RpcTargets/EveryoneRpcTarget.cs | 18 +- .../NetworkVariableSerialization.cs | 2065 ----------------- .../NetworkVariableSerialization.cs.meta | 3 - Runtime/NetworkVariable/Serialization.meta | 3 + .../CollectionSerializationUtility.cs | 0 .../CollectionSerializationUtility.cs.meta | 0 .../Serialization/FallbackSerializer.cs | 99 + .../Serialization/FallbackSerializer.cs.meta | 3 + .../INetworkVariableSerializer.cs | 26 + .../INetworkVariableSerializer.cs.meta | 3 + .../Serialization/NetworkVariableEquality.cs | 357 +++ .../NetworkVariableEquality.cs.meta | 3 + .../NetworkVariableSerialization.cs | 161 ++ .../NetworkVariableSerialization.cs.meta | 3 + .../{ => Serialization}/ResizableBitVector.cs | 0 .../ResizableBitVector.cs.meta | 0 .../Serialization/TypedILPPInitializers.cs | 325 +++ .../TypedILPPInitializers.cs.meta | 3 + .../TypedSerializerImplementations.cs | 1120 +++++++++ .../TypedSerializerImplementations.cs.meta | 3 + .../UserNetworkVariableSerialization.cs | 73 + .../UserNetworkVariableSerialization.cs.meta | 3 + Runtime/Serialization/FastBufferReader.cs | 71 +- Runtime/Serialization/FastBufferWriter.cs | 87 +- Runtime/Spawning/NetworkSpawnManager.cs | 10 +- Runtime/Transports/NetworkTransport.cs | 16 + Runtime/Transports/UTP/UnityTransport.cs | 5 + Runtime/com.unity.netcode.runtime.asmdef | 16 +- TestHelpers/Runtime/MockTransport.cs | 5 + .../NetworkObjectOwnershipTests.cs | 6 +- package.json | 8 +- 47 files changed, 2756 insertions(+), 2246 deletions(-) delete mode 100644 Components.meta delete mode 100644 Runtime/NetworkVariable/NetworkVariableSerialization.cs delete mode 100644 Runtime/NetworkVariable/NetworkVariableSerialization.cs.meta create mode 100644 Runtime/NetworkVariable/Serialization.meta rename Runtime/NetworkVariable/{ => Serialization}/CollectionSerializationUtility.cs (100%) rename Runtime/NetworkVariable/{ => Serialization}/CollectionSerializationUtility.cs.meta (100%) create mode 100644 Runtime/NetworkVariable/Serialization/FallbackSerializer.cs create mode 100644 Runtime/NetworkVariable/Serialization/FallbackSerializer.cs.meta create mode 100644 Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs create mode 100644 Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs.meta create mode 100644 Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs create mode 100644 Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs.meta create mode 100644 Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs create mode 100644 Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs.meta rename Runtime/NetworkVariable/{ => Serialization}/ResizableBitVector.cs (100%) rename Runtime/NetworkVariable/{ => Serialization}/ResizableBitVector.cs.meta (100%) create mode 100644 Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs create mode 100644 Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs.meta create mode 100644 Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs create mode 100644 Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs.meta create mode 100644 Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs create mode 100644 Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs.meta diff --git a/CHANGELOG.md b/CHANGELOG.md index 02c15ec..5909e66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,12 +6,40 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) 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) + + ## [2.0.0-exp.5] - 2024-06-03 +### Added + + ### Fixed - Fixed issue where SessionOwner message was being treated as a new entry for the new message indexing when it should have been ordinally sorted with the legacy message indices. (#2942) +### Changed +- Changed `FastBufferReader` and `FastBufferWriter` so that they always ensure the length of items serialized is always serialized as an `uint` and added a check before casting for safe reading and writing.(#2946) + + ## [2.0.0-exp.4] - 2024-05-31 ### Added diff --git a/Components.meta b/Components.meta deleted file mode 100644 index d4eb0da..0000000 --- a/Components.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 8b267eb841a574dc083ac248a95d4443 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/CodeGen/NetworkBehaviourILPP.cs b/Editor/CodeGen/NetworkBehaviourILPP.cs index f750f78..fb583e2 100644 --- a/Editor/CodeGen/NetworkBehaviourILPP.cs +++ b/Editor/CodeGen/NetworkBehaviourILPP.cs @@ -721,7 +721,7 @@ private bool ImportReferences(ModuleDefinition moduleDefinition, string[] assemb continue; } - if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypes)) + if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypedInitializers)) { networkVariableSerializationTypesTypeDef = netcodeTypeDef; continue; @@ -1007,103 +1007,103 @@ private bool ImportReferences(ModuleDefinition moduleDefinition, string[] assemb switch (method.Name) { - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpy): m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyArray): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyArray): m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyArray_MethodRef = method; break; #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyList): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyList): m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyList_MethodRef = method; break; #endif - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializable): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializable): m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableArray): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableArray): m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableArray_MethodRef = method; break; #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableList): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableList): m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableList_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashSet): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashSet): m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashMap): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashMap): m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef = method; break; #endif - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_List): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_List): m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_HashSet): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_HashSet): m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_Dictionary): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_Dictionary): m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_ManagedINetworkSerializable): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_ManagedINetworkSerializable): m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedString): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedString): m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringArray): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringArray): m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringArray_MethodRef = method; break; #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringList): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringList): m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringList_MethodRef = method; break; #endif - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedIEquatable): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedIEquatable): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatable): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableArray): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableArray): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableArray_MethodRef = method; break; #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableList): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableList): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableList_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashSet): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashSet): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashMap): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashMap): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef = method; break; #endif - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_List): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_List): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_HashSet): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_HashSet): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_Dictionary): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_Dictionary): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEquals): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef = method; break; - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsArray): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsArray): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsArray_MethodRef = method; break; #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsList): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsList): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsList_MethodRef = method; break; #endif - case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedClassEquals): + case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedClassEquals): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef = method; break; } diff --git a/Editor/NetworkManagerEditor.cs b/Editor/NetworkManagerEditor.cs index f420592..0db3a65 100644 --- a/Editor/NetworkManagerEditor.cs +++ b/Editor/NetworkManagerEditor.cs @@ -30,7 +30,7 @@ public class NetworkManagerEditor : UnityEditor.Editor private SerializedProperty m_ProtocolVersionProperty; private SerializedProperty m_NetworkTransportProperty; private SerializedProperty m_TickRateProperty; -#if MULTIPLAYER_SDK_INSTALLED +#if MULTIPLAYER_SERVICES_SDK_INSTALLED private SerializedProperty m_NetworkTopologyProperty; #endif private SerializedProperty m_ClientConnectionBufferTimeoutProperty; @@ -102,7 +102,7 @@ private void Initialize() m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); -#if MULTIPLAYER_SDK_INSTALLED +#if MULTIPLAYER_SERVICES_SDK_INSTALLED m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology"); #endif m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); @@ -142,7 +142,7 @@ private void CheckNullProperties() m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); -#if MULTIPLAYER_SDK_INSTALLED +#if MULTIPLAYER_SERVICES_SDK_INSTALLED m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology"); #endif m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); @@ -186,7 +186,7 @@ public override void OnInspectorGUI() EditorGUILayout.Space(); EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel); -#if MULTIPLAYER_SDK_INSTALLED +#if MULTIPLAYER_SERVICES_SDK_INSTALLED EditorGUILayout.PropertyField(m_NetworkTopologyProperty); #endif EditorGUILayout.PropertyField(m_ProtocolVersionProperty); @@ -310,21 +310,32 @@ public override void OnInspectorGUI() GUI.enabled = false; } - if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix))) + if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer) { - m_NetworkManager.StartHost(); - } + if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix))) + { + m_NetworkManager.StartHost(); + } - if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix))) - { - m_NetworkManager.StartServer(); - } + if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix))) + { + m_NetworkManager.StartServer(); + } - if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix))) + if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix))) + { + m_NetworkManager.StartClient(); + } + } + else { - m_NetworkManager.StartClient(); + if (GUILayout.Button(new GUIContent("Start Client", "Starts a distributed authority client instance" + buttonDisabledReasonSuffix))) + { + m_NetworkManager.StartClient(); + } } + if (!EditorApplication.isPlaying) { GUI.enabled = true; diff --git a/Editor/NetworkObjectEditor.cs b/Editor/NetworkObjectEditor.cs index 9975482..ef6ea58 100644 --- a/Editor/NetworkObjectEditor.cs +++ b/Editor/NetworkObjectEditor.cs @@ -1,5 +1,5 @@ using System.Collections.Generic; -#if MULTIPLAYER_SDK_INSTALLED +#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED using System.Linq; #endif using UnityEditor; @@ -148,7 +148,7 @@ private void OnDestroy() // Keeping this here just in case, but it appears that in Unity 6 the visual bugs with // enum flags is resolved -#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SDK_INSTALLED +#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED [CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))] public class NetworkObjectOwnership : PropertyDrawer { diff --git a/Editor/NetworkTransformEditor.cs b/Editor/NetworkTransformEditor.cs index 4e7831d..0dbab88 100644 --- a/Editor/NetworkTransformEditor.cs +++ b/Editor/NetworkTransformEditor.cs @@ -30,6 +30,7 @@ public class NetworkTransformEditor : UnityEditor.Editor private SerializedProperty m_UseQuaternionCompression; private SerializedProperty m_UseHalfFloatPrecision; private SerializedProperty m_SlerpPosition; + private SerializedProperty m_AuthorityMode; private static int s_ToggleOffset = 45; private static float s_MaxRowWidth = EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + 5; @@ -38,7 +39,7 @@ public class NetworkTransformEditor : UnityEditor.Editor private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale"); /// - public void OnEnable() + public virtual void OnEnable() { m_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas)); m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX)); @@ -59,12 +60,13 @@ public void OnEnable() m_UseQuaternionCompression = serializedObject.FindProperty(nameof(NetworkTransform.UseQuaternionCompression)); m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision)); m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition)); + m_AuthorityMode = serializedObject.FindProperty(nameof(NetworkTransform.AuthorityMode)); } /// public override void OnInspectorGUI() { - EditorGUILayout.LabelField("Syncing", EditorStyles.boldLabel); + EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel); { GUILayout.BeginHorizontal(); @@ -126,6 +128,11 @@ public override void OnInspectorGUI() GUILayout.EndHorizontal(); } + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Authority", EditorStyles.boldLabel); + { + EditorGUILayout.PropertyField(m_AuthorityMode); + } EditorGUILayout.Space(); EditorGUILayout.LabelField("Thresholds", EditorStyles.boldLabel); EditorGUILayout.PropertyField(m_PositionThresholdProperty); diff --git a/Editor/com.unity.netcode.editor.asmdef b/Editor/com.unity.netcode.editor.asmdef index fb85b90..e80328c 100644 --- a/Editor/com.unity.netcode.editor.asmdef +++ b/Editor/com.unity.netcode.editor.asmdef @@ -57,7 +57,7 @@ { "name": "com.unity.services.multiplayer", "expression": "0.2.0", - "define": "MULTIPLAYER_SDK_INSTALLED" + "define": "MULTIPLAYER_SERVICES_SDK_INSTALLED" } ], "noEngineReferences": false diff --git a/Runtime/Components/NetworkRigidBodyBase.cs b/Runtime/Components/NetworkRigidBodyBase.cs index c2a24eb..17ebaf7 100644 --- a/Runtime/Components/NetworkRigidBodyBase.cs +++ b/Runtime/Components/NetworkRigidBodyBase.cs @@ -45,6 +45,9 @@ public abstract class NetworkRigidbodyBase : NetworkBehaviour private Rigidbody m_Rigidbody; private Rigidbody2D m_Rigidbody2D; internal NetworkTransform NetworkTransform; + private float m_TickFrequency; + private float m_TickRate; + private enum InterpolationTypes { None, @@ -120,6 +123,129 @@ protected void Initialize(RigidbodyTypes rigidbodyType, NetworkTransform network } } + internal Vector3 GetAdjustedPositionThreshold() + { + // Since the threshold is a measurement of unity world space units per tick, we will allow for the maximum threshold + // to be no greater than the threshold measured in unity world space units per second + var thresholdMax = NetworkTransform.PositionThreshold * m_TickRate; + // Get the velocity in unity world space units per tick + var perTickVelocity = GetLinearVelocity() * m_TickFrequency; + // Since a rigid body can have "micro-motion" when allowed to come to rest (based on friction etc), we will allow for + // no less than 1/10th the threshold value. + var minThreshold = NetworkTransform.PositionThreshold * 0.1f; + + // Finally, we adjust the threshold based on the body's current velocity + perTickVelocity.x = Mathf.Clamp(Mathf.Abs(perTickVelocity.x), minThreshold, thresholdMax); + perTickVelocity.y = Mathf.Clamp(Mathf.Abs(perTickVelocity.y), minThreshold, thresholdMax); + // 2D Rigidbody only moves on x & y axis + if (!m_IsRigidbody2D) + { + perTickVelocity.z = Mathf.Clamp(Mathf.Abs(perTickVelocity.z), minThreshold, thresholdMax); + } + + return perTickVelocity; + } + + internal Vector3 GetAdjustedRotationThreshold() + { + // Since the rotation threshold is a measurement pf degrees per tick, we get the maximum threshold + // by calculating the threshold in degrees per second. + var thresholdMax = NetworkTransform.RotAngleThreshold * m_TickRate; + // Angular velocity is expressed in radians per second where as the rotation being checked is in degrees. + // Convert the angular velocity to degrees per second and then convert that to degrees per tick. + var rotationPerTick = (GetAngularVelocity() * Mathf.Rad2Deg) * m_TickFrequency; + var minThreshold = NetworkTransform.RotAngleThreshold * m_TickFrequency; + + // 2D Rigidbody only rotates around Z axis + if (!m_IsRigidbody2D) + { + rotationPerTick.x = Mathf.Clamp(Mathf.Abs(rotationPerTick.x), minThreshold, thresholdMax); + rotationPerTick.y = Mathf.Clamp(Mathf.Abs(rotationPerTick.y), minThreshold, thresholdMax); + } + rotationPerTick.z = Mathf.Clamp(Mathf.Abs(rotationPerTick.z), minThreshold, thresholdMax); + + return rotationPerTick; + } + + /// + /// Sets the linear velocity of the Rigidbody. + /// + /// + /// For , only the x and y components of the are applied. + /// + public void SetLinearVelocity(Vector3 linearVelocity) + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.velocity = linearVelocity; + } + else + { + m_Rigidbody.linearVelocity = linearVelocity; + } + } + + /// + /// Gets the linear velocity of the Rigidbody. + /// + /// + /// For , the velocity returned is only applied to the x and y components. + /// + /// as the linear velocity + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3 GetLinearVelocity() + { + if (m_IsRigidbody2D) + { + return m_Rigidbody2D.velocity; + } + else + { + return m_Rigidbody.linearVelocity; + } + } + + /// + /// Sets the angular velocity for the Rigidbody. + /// + /// + /// For , the z component of is only used to set the angular velocity. + /// A quick way to pass in a 2D angular velocity component is: * angularVelocity (where angularVelocity is a float) + /// + /// the angular velocity to apply to the body + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetAngularVelocity(Vector3 angularVelocity) + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.angularVelocity = angularVelocity.z; + } + else + { + m_Rigidbody.angularVelocity = angularVelocity; + } + } + + /// + /// Gets the angular velocity for the Rigidbody. + /// + /// + /// For , the z component of the returned is the angular velocity of the object. + /// + /// angular velocity as a + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3 GetAngularVelocity() + { + if (m_IsRigidbody2D) + { + return Vector3.forward * m_Rigidbody2D.velocity; + } + else + { + return m_Rigidbody.angularVelocity; + } + } + /// /// Gets the position of the Rigidbody /// @@ -210,6 +336,9 @@ public void ApplyCurrentTransform() } } + // Used for Rigidbody only (see info on normalized below) + private Vector4 m_QuaternionCheck = Vector4.zero; + /// /// Rotatates the Rigidbody towards a specified rotation /// @@ -227,6 +356,17 @@ public void MoveRotation(Quaternion rotation) } else { + // Evidently we need to check to make sure the quaternion is a perfect + // magnitude of 1.0f when applying the rotation to a rigid body. + m_QuaternionCheck.x = rotation.x; + m_QuaternionCheck.y = rotation.y; + m_QuaternionCheck.z = rotation.z; + m_QuaternionCheck.w = rotation.w; + // If the magnitude is greater than 1.0f (even by a very small fractional value), then normalize the quaternion + if (m_QuaternionCheck.magnitude != 1.0f) + { + rotation.Normalize(); + } m_Rigidbody.MoveRotation(rotation); } } @@ -501,6 +641,8 @@ internal void UpdateOwnershipAuthority() /// public override void OnNetworkSpawn() { + m_TickFrequency = 1.0f / NetworkManager.NetworkConfig.TickRate; + m_TickRate = NetworkManager.NetworkConfig.TickRate; UpdateOwnershipAuthority(); } diff --git a/Runtime/Components/NetworkTransform.cs b/Runtime/Components/NetworkTransform.cs index 5635194..db3e9b8 100644 --- a/Runtime/Components/NetworkTransform.cs +++ b/Runtime/Components/NetworkTransform.cs @@ -920,6 +920,22 @@ public void NetworkSerialize(BufferSerializer serializer) where T : IReade #endregion #region PROPERTIES AND GENERAL METHODS + + + public enum AuthorityModes + { + Server, + Owner, + } +#if MULTIPLAYER_SERVICES_SDK_INSTALLED + [Tooltip("Selects who has authority (sends state updates) over the transform. When the network topology is set to distributed authority, this always defaults to owner authority. If server (the default), then only server-side adjustments to the " + + "transform will be synchronized with clients. If owner (or client), then only the owner-side adjustments to the transform will be synchronized with both the server and other clients.")] +#else + [Tooltip("Selects who has authority (sends state updates) over the transform. If server (the default), then only server-side adjustments to the transform will be synchronized with clients. If owner (or client), " + + "then only the owner-side adjustments to the transform will be synchronized with both the server and other clients.")] +#endif + public AuthorityModes AuthorityMode; + /// /// The default position change threshold value. /// Any changes above this threshold will be replicated. @@ -1487,7 +1503,7 @@ protected override void OnSynchronize(ref BufferSerializer serializer) /// /// the transform to be committed /// time it was marked dirty - protected void TryCommitTransformToServer(Transform transformToCommit, double dirtyTime) + internal void TryCommitTransformToServer(Transform transformToCommit, double dirtyTime) { if (!IsSpawned) { @@ -1568,8 +1584,6 @@ private void TryCommitTransform(ref Transform transformToCommit, bool synchroniz // If the transform has deltas (returns dirty) or if an explicitly set state is pending if (m_LocalAuthoritativeNetworkState.ExplicitSet || CheckForStateChange(ref m_LocalAuthoritativeNetworkState, ref transformToCommit, synchronize)) { - m_LocalAuthoritativeNetworkState.LastSerializedSize = m_OldState.LastSerializedSize; - // If the state was explicitly set, then update the network tick to match the locally calculate tick if (m_LocalAuthoritativeNetworkState.ExplicitSet) { @@ -1699,9 +1713,20 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra #if COM_UNITY_MODULES_PHYSICS var position = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetPosition() : InLocalSpace ? transformToUse.localPosition : transformToUse.position; var rotation = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetRotation() : InLocalSpace ? transformToUse.localRotation : transformToUse.rotation; + + var positionThreshold = Vector3.one * PositionThreshold; + var rotationThreshold = Vector3.one * RotAngleThreshold; + + if (m_UseRigidbodyForMotion) + { + positionThreshold = m_NetworkRigidbodyInternal.GetAdjustedPositionThreshold(); + rotationThreshold = m_NetworkRigidbodyInternal.GetAdjustedRotationThreshold(); + } #else var position = InLocalSpace ? transformToUse.localPosition : transformToUse.position; var rotation = InLocalSpace ? transformToUse.localRotation : transformToUse.rotation; + var positionThreshold = Vector3.one * PositionThreshold; + var rotationThreshold = Vector3.one * RotAngleThreshold; #endif var rotAngles = rotation.eulerAngles; var scale = transformToUse.localScale; @@ -1828,21 +1853,21 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra // Begin delta checks against last sent state update if (!UseHalfFloatPrecision) { - if (SyncPositionX && (Mathf.Abs(networkState.PositionX - position.x) >= PositionThreshold || networkState.IsTeleportingNextFrame || isAxisSync)) + if (SyncPositionX && (Mathf.Abs(networkState.PositionX - position.x) >= positionThreshold.x || networkState.IsTeleportingNextFrame || isAxisSync)) { networkState.PositionX = position.x; networkState.HasPositionX = true; isPositionDirty = true; } - if (SyncPositionY && (Mathf.Abs(networkState.PositionY - position.y) >= PositionThreshold || networkState.IsTeleportingNextFrame || isAxisSync)) + if (SyncPositionY && (Mathf.Abs(networkState.PositionY - position.y) >= positionThreshold.y || networkState.IsTeleportingNextFrame || isAxisSync)) { networkState.PositionY = position.y; networkState.HasPositionY = true; isPositionDirty = true; } - if (SyncPositionZ && (Mathf.Abs(networkState.PositionZ - position.z) >= PositionThreshold || networkState.IsTeleportingNextFrame || isAxisSync)) + if (SyncPositionZ && (Mathf.Abs(networkState.PositionZ - position.z) >= positionThreshold.z || networkState.IsTeleportingNextFrame || isAxisSync)) { networkState.PositionZ = position.z; networkState.HasPositionZ = true; @@ -1863,7 +1888,7 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra { for (int i = 0; i < 3; i++) { - if (Math.Abs(position[i] - m_HalfPositionState.PreviousPosition[i]) >= PositionThreshold) + if (Math.Abs(position[i] - m_HalfPositionState.PreviousPosition[i]) >= positionThreshold[i]) { isPositionDirty = i == 0 ? SyncPositionX : i == 1 ? SyncPositionY : SyncPositionZ; if (!isPositionDirty) @@ -1958,21 +1983,21 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra if (!UseQuaternionSynchronization) { - if (SyncRotAngleX && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleX, rotAngles.x)) >= RotAngleThreshold || networkState.IsTeleportingNextFrame || isAxisSync)) + if (SyncRotAngleX && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleX, rotAngles.x)) >= rotationThreshold.x || networkState.IsTeleportingNextFrame || isAxisSync)) { networkState.RotAngleX = rotAngles.x; networkState.HasRotAngleX = true; isRotationDirty = true; } - if (SyncRotAngleY && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleY, rotAngles.y)) >= RotAngleThreshold || networkState.IsTeleportingNextFrame || isAxisSync)) + if (SyncRotAngleY && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleY, rotAngles.y)) >= rotationThreshold.y || networkState.IsTeleportingNextFrame || isAxisSync)) { networkState.RotAngleY = rotAngles.y; networkState.HasRotAngleY = true; isRotationDirty = true; } - if (SyncRotAngleZ && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleZ, rotAngles.z)) >= RotAngleThreshold || networkState.IsTeleportingNextFrame || isAxisSync)) + if (SyncRotAngleZ && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleZ, rotAngles.z)) >= rotationThreshold.z || networkState.IsTeleportingNextFrame || isAxisSync)) { networkState.RotAngleZ = rotAngles.z; networkState.HasRotAngleZ = true; @@ -1989,7 +2014,7 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra var previousRotation = networkState.Rotation.eulerAngles; for (int i = 0; i < 3; i++) { - if (Mathf.Abs(Mathf.DeltaAngle(previousRotation[i], rotAngles[i])) >= RotAngleThreshold) + if (Mathf.Abs(Mathf.DeltaAngle(previousRotation[i], rotAngles[i])) >= rotationThreshold[i]) { isRotationDirty = true; break; @@ -2984,7 +3009,13 @@ private void InternalInitialization(bool isOwnershipChange = false) return; } m_CachedNetworkObject = NetworkObject; + if (m_CachedNetworkManager && m_CachedNetworkManager.DistributedAuthorityMode) + { + AuthorityMode = AuthorityModes.Owner; + } CanCommitToTransform = IsServerAuthoritative() ? IsServer : IsOwner; + + var currentPosition = GetSpaceRelativePosition(); var currentRotation = GetSpaceRelativeRotation(); @@ -3011,22 +3042,24 @@ private void InternalInitialization(bool isOwnershipChange = false) #else var forUpdate = true; #endif + m_LocalAuthoritativeNetworkState.SynchronizeBaseHalfFloat = false; if (CanCommitToTransform) { - // Make sure authority doesn't get added to updates (no need to do this on the authority side) m_CachedNetworkManager.NetworkTransformRegistration(this, forUpdate, false); if (UseHalfFloatPrecision) { m_HalfPositionState = new NetworkDeltaPosition(currentPosition, m_CachedNetworkManager.ServerTime.Tick, math.bool3(SyncPositionX, SyncPositionY, SyncPositionZ)); + m_LocalAuthoritativeNetworkState.SynchronizeBaseHalfFloat = isOwnershipChange; + SetState(teleportDisabled: false); } + m_CurrentPosition = currentPosition; m_TargetPosition = currentPosition; RegisterForTickUpdate(this); - m_LocalAuthoritativeNetworkState.SynchronizeBaseHalfFloat = false; if (UseHalfFloatPrecision && isOwnershipChange && !IsServerAuthoritative() && Interpolate) { m_HalfFloatTargetTickOwnership = m_CachedNetworkManager.ServerTime.Tick; @@ -3038,16 +3071,13 @@ private void InternalInitialization(bool isOwnershipChange = false) m_CachedNetworkManager.NetworkTransformRegistration(this, forUpdate, true); // Remove this instance from the tick update DeregisterForTickUpdate(this); - ResetInterpolatedStateToCurrentAuthoritativeState(); - m_LocalAuthoritativeNetworkState.SynchronizeBaseHalfFloat = false; m_CurrentPosition = currentPosition; m_TargetPosition = currentPosition; m_CurrentScale = transform.localScale; m_TargetScale = transform.localScale; m_CurrentRotation = currentRotation; m_TargetRotation = currentRotation.eulerAngles; - } OnInitialize(ref m_LocalAuthoritativeNetworkState); } @@ -3296,7 +3326,7 @@ private void UpdateInterpolation() { var serverTime = m_CachedNetworkManager.ServerTime; var cachedServerTime = serverTime.Time; - var offset = (float)serverTime.TickOffset; + //var offset = (float)serverTime.TickOffset; #if COM_UNITY_MODULES_PHYSICS var cachedDeltaTime = m_UseRigidbodyForMotion ? m_CachedNetworkManager.RealTimeProvider.FixedDeltaTime : m_CachedNetworkManager.RealTimeProvider.DeltaTime; #else @@ -3314,7 +3344,7 @@ private void UpdateInterpolation() //offset = m_NetworkTransformTickRegistration.Offset; //} - var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo, offset).Time; + var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo).Time; // Now only update the interpolators for the portions of the transform being synchronized if (SynchronizePosition) @@ -3388,28 +3418,32 @@ public virtual void OnFixedUpdate() #endif /// - /// Override this method and return false to switch to owner authoritative mode + /// Determines whether the is or based on the property. + /// You can override this method to control this logic. /// - /// ( or ) where when false it runs as owner-client authoritative + /// or protected virtual bool OnIsServerAuthoritative() { - if (m_CachedNetworkManager) - { - return !m_CachedNetworkManager.DistributedAuthorityMode; - } - return true; + return AuthorityMode == AuthorityModes.Server; } /// /// Method to determine if this instance is owner or server authoritative. /// /// - /// Used by to determines if this is server or owner authoritative. + /// When using a , this will always be viewed as a authoritative motion model. /// /// or public bool IsServerAuthoritative() { - return OnIsServerAuthoritative(); + if (m_CachedNetworkManager && m_CachedNetworkManager.DistributedAuthorityMode) + { + return false; + } + else + { + return OnIsServerAuthoritative(); + } } #endregion @@ -3451,9 +3485,10 @@ internal void TransformStateUpdate(ulong senderId) private NetworkTransformMessage m_OutboundMessage = new NetworkTransformMessage(); - internal void SerializeMessage(FastBufferWriter writer, int targetVersion) + internal int SerializeMessage(FastBufferWriter writer, int targetVersion) { var networkObject = NetworkObject; + var position = writer.Position; BytePacker.WriteValueBitPacked(writer, NetworkObjectId); BytePacker.WriteValueBitPacked(writer, (int)NetworkBehaviourId); writer.WriteNetworkSerializable(m_LocalAuthoritativeNetworkState); @@ -3470,6 +3505,7 @@ internal void SerializeMessage(FastBufferWriter writer, int targetVersion) BytePacker.WriteValuePacked(writer, targetId); } } + return writer.Position - position; } /// @@ -3482,7 +3518,7 @@ private void UpdateTransformState() return; } - bool isServerAuthoritative = OnIsServerAuthoritative(); + bool isServerAuthoritative = IsServerAuthoritative(); if (isServerAuthoritative && !IsServer) { Debug.LogError($"Server authoritative {nameof(NetworkTransform)} can only be updated by the server!"); @@ -3526,6 +3562,7 @@ private void UpdateTransformState() // Clients (owner authoritative) send messages to the server-host NetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, NetworkManager.ServerClientId); } + m_LocalAuthoritativeNetworkState.LastSerializedSize = m_OutboundMessage.BytesWritten; } #endregion diff --git a/Runtime/Connection/NetworkClient.cs b/Runtime/Connection/NetworkClient.cs index 8cee4e0..ff6ed61 100644 --- a/Runtime/Connection/NetworkClient.cs +++ b/Runtime/Connection/NetworkClient.cs @@ -1,15 +1,8 @@ -using System.Collections.Generic; using UnityEngine; namespace Unity.Netcode { - public enum NetworkTopologyTypes - { - ClientServer, - DistributedAuthority - } - /// /// A NetworkClient /// @@ -61,9 +54,9 @@ public class NetworkClient public NetworkObject PlayerObject; /// - /// The list of NetworkObject's owned by this client instance + /// The NetworkObject's owned by this client instance /// - public List OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new List(); + public NetworkObject[] OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new NetworkObject[] { }; internal NetworkSpawnManager SpawnManager { get; private set; } diff --git a/Runtime/Connection/NetworkConnectionManager.cs b/Runtime/Connection/NetworkConnectionManager.cs index cb19efe..722fbb2 100644 --- a/Runtime/Connection/NetworkConnectionManager.cs +++ b/Runtime/Connection/NetworkConnectionManager.cs @@ -1229,6 +1229,8 @@ internal void OnClientDisconnectFromServer(ulong clientId) var message = new ClientDisconnectedMessage { ClientId = clientId }; MessageManager?.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds); + // Used for testing/validation purposes only +#if ENABLE_DAHOST_AUTOPROMOTE_SESSION_OWNER if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress && NetworkManager.IsListening) { var newSessionOwner = NetworkManager.LocalClientId; @@ -1259,6 +1261,7 @@ internal void OnClientDisconnectFromServer(ulong clientId) MessageManager?.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds); NetworkManager.SetSessionOwner(newSessionOwner); } +#endif } // If the client ID transport map exists diff --git a/Runtime/Core/NetworkManager.cs b/Runtime/Core/NetworkManager.cs index 340eced..b956cfa 100644 --- a/Runtime/Core/NetworkManager.cs +++ b/Runtime/Core/NetworkManager.cs @@ -36,17 +36,13 @@ public class NetworkManager : MonoBehaviour, INetworkUpdateSystem #pragma warning restore IDE1006 // restore naming rule violation check + internal static bool IsDistributedAuthority; + /// /// Distributed Authority Mode /// Returns true if the current session is running in distributed authority mode. /// - public bool DistributedAuthorityMode - { - get - { - return NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority; - } - } + public bool DistributedAuthorityMode { get; private set; } /// /// Distributed Authority Mode @@ -131,6 +127,18 @@ public bool DAHost public ulong CurrentSessionOwner { get; internal set; } + /// + /// Delegate declaration for + /// + /// the new session owner client identifier + public delegate void OnSessionOwnerPromotedDelegateHandler(ulong sessionOwnerPromoted); + + /// + /// Network Topology: Distributed Authority + /// When a new session owner is promoted, this event is triggered on all connected clients + /// + public event OnSessionOwnerPromotedDelegateHandler OnSessionOwnerPromoted; + internal void SetSessionOwner(ulong sessionOwner) { var previousSessionOwner = CurrentSessionOwner; @@ -151,10 +159,12 @@ internal void SetSessionOwner(ulong sessionOwner) } } } + + OnSessionOwnerPromoted?.Invoke(sessionOwner); } // TODO: Make this internal after testing - public void PromoteSessionOwner(ulong clientId) + internal void PromoteSessionOwner(ulong clientId) { if (!DistributedAuthorityMode) { @@ -217,12 +227,27 @@ internal void NetworkTransformRegistration(NetworkTransform networkTransform, bo #endif } + private void UpdateTopology() + { + var transportTopology = IsListening ? NetworkConfig.NetworkTransport.CurrentTopology() : NetworkConfig.NetworkTopology; + if (transportTopology != NetworkConfig.NetworkTopology) + { + NetworkLog.LogErrorServer($"[Topology Mismatch] Transport detected an issue with the topology ({transportTopology} | {NetworkConfig.NetworkTopology}) usage or setting! Disconnecting from session."); + Shutdown(); + } + else + { + IsDistributedAuthority = DistributedAuthorityMode = transportTopology == NetworkTopologyTypes.DistributedAuthority; + } + } + public void NetworkUpdate(NetworkUpdateStage updateStage) { switch (updateStage) { case NetworkUpdateStage.EarlyUpdate: { + UpdateTopology(); ConnectionManager.ProcessPendingApprovals(); ConnectionManager.PollAndHandleNetworkEvents(); @@ -1012,6 +1037,8 @@ internal void Initialize(bool server) #endif NetworkTransformUpdate.Clear(); + UpdateTopology(); + //DANGOEXP TODO: Remove this before finalizing the experimental release NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode; @@ -1191,6 +1218,17 @@ public bool StartServer() { SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); + // Notify the server that all in-scnee placed NetworkObjects are spawned at this time. + foreach (var networkObject in SpawnManager.SpawnedObjectsList) + { + networkObject.InternalInSceneNetworkObjectsSpawned(); + } + + // Notify the server that everything should be synchronized/spawned at this time. + foreach (var networkObject in SpawnManager.SpawnedObjectsList) + { + networkObject.InternalNetworkSessionSynchronized(); + } OnServerStarted?.Invoke(); ConnectionManager.LocalClient.IsApproved = true; return true; @@ -1337,6 +1375,17 @@ private void HostServerInitialize() } SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); + // Notify the host that all in-scnee placed NetworkObjects are spawned at this time. + foreach (var networkObject in SpawnManager.SpawnedObjectsList) + { + networkObject.InternalInSceneNetworkObjectsSpawned(); + } + + // Notify the host that everything should be synchronized/spawned at this time. + foreach (var networkObject in SpawnManager.SpawnedObjectsList) + { + networkObject.InternalNetworkSessionSynchronized(); + } OnServerStarted?.Invoke(); OnClientStarted?.Invoke(); diff --git a/Runtime/Core/NetworkObject.cs b/Runtime/Core/NetworkObject.cs index 3e7ae26..b927722 100644 --- a/Runtime/Core/NetworkObject.cs +++ b/Runtime/Core/NetworkObject.cs @@ -430,7 +430,7 @@ public void DeferDespawn(int tickOffset, bool destroy = true) /// Determines whether a NetworkObject can be distributed to other clients during /// a session. /// -#if !MULTIPLAYER_SDK_INSTALLED +#if !MULTIPLAYER_SERVICES_SDK_INSTALLED [HideInInspector] #endif [SerializeField] diff --git a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs index 89eee0c..82eef24 100644 --- a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs +++ b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs @@ -243,6 +243,13 @@ public void Handle(ref NetworkContext context) // Spawn any in-scene placed NetworkObjects networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); + // With scene management enabled and since the session owner doesn't send a Synchronize scene event synchronize itself, + // we need to notify the session owner that all in-scnee placed NetworkObjects are spawned at this time. + foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList) + { + networkObject.InternalInSceneNetworkObjectsSpawned(); + } + // Spawn the local player of the session owner if (networkManager.AutoSpawnPlayerPrefabClientSide) { @@ -251,6 +258,17 @@ public void Handle(ref NetworkContext context) // Synchronize the service with the initial session owner's loaded scenes and spawned objects networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId); + + // With scene management enabled and since the session owner doesn't send a Synchronize scene event synchronize itself, + // we need to notify the session owner that everything should be synchronized/spawned at this time. + foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList) + { + networkObject.InternalNetworkSessionSynchronized(); + } + + // When scene management is enabled and since the session owner is synchronizing the service (i.e. acting like host), + // we need to locallyh invoke the OnClientConnected callback at this point in time. + networkManager.ConnectionManager.InvokeOnClientConnectedCallback(OwnerClientId); } } } diff --git a/Runtime/Messaging/Messages/NetworkTransformMessage.cs b/Runtime/Messaging/Messages/NetworkTransformMessage.cs index 3fbd869..56f25f2 100644 --- a/Runtime/Messaging/Messages/NetworkTransformMessage.cs +++ b/Runtime/Messaging/Messages/NetworkTransformMessage.cs @@ -17,6 +17,8 @@ internal struct NetworkTransformMessage : INetworkMessage internal NetworkTransform.NetworkTransformState State; private FastBufferReader m_CurrentReader; + internal int BytesWritten; + private unsafe void CopyPayload(ref FastBufferWriter writer) { writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position); @@ -30,7 +32,7 @@ public void Serialize(FastBufferWriter writer, int targetVersion) } else { - NetworkTransform.SerializeMessage(writer, targetVersion); + BytesWritten = NetworkTransform.SerializeMessage(writer, targetVersion); } } @@ -75,6 +77,7 @@ public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer; reader.ReadNetworkSerializableInPlace(ref NetworkTransform.InboundState); + NetworkTransform.InboundState.LastSerializedSize = reader.Position - currentPosition; } else { diff --git a/Runtime/Messaging/NetworkMessageManager.cs b/Runtime/Messaging/NetworkMessageManager.cs index b455c9b..d42251e 100644 --- a/Runtime/Messaging/NetworkMessageManager.cs +++ b/Runtime/Messaging/NetworkMessageManager.cs @@ -34,6 +34,9 @@ public InvalidMessageStructureException(string issue) : base(issue) internal class NetworkMessageManager : IDisposable { public bool StopProcessing = false; + private static Type s_ConnectionApprovedType = typeof(ConnectionApprovedMessage); + private static Type s_ConnectionRequestType = typeof(ConnectionRequestMessage); + private static Type s_DisconnectReasonType = typeof(DisconnectReasonMessage); private struct ReceiveQueueItem { @@ -524,6 +527,7 @@ internal void CleanupDisconnectedClients() return new T().Version; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal int GetMessageVersion(Type type, ulong clientId, bool forReceive = false) { if (!m_PerClientMessageVersions.TryGetValue(clientId, out var versionMap)) @@ -551,16 +555,20 @@ internal int GetMessageVersion(Type type, ulong clientId, bool forReceive = fals return messageVersion; } + + public static void ReceiveMessage(FastBufferReader reader, ref NetworkContext context, NetworkMessageManager manager) where T : INetworkMessage, new() { + var messageType = typeof(T); var message = new T(); var messageVersion = 0; + // Special cases because these are the messages that carry the version info - thus the version info isn't // populated yet when we get these. The first part of these messages always has to be the version data // and can't change. - if (typeof(T) != typeof(ConnectionRequestMessage) && typeof(T) != typeof(ConnectionApprovedMessage) && typeof(T) != typeof(DisconnectReasonMessage) && context.SenderId != manager.m_LocalClientId) + if (messageType != s_ConnectionRequestType && messageType != s_ConnectionApprovedType && messageType != s_DisconnectReasonType && context.SenderId != manager.m_LocalClientId) { - messageVersion = manager.GetMessageVersion(typeof(T), context.SenderId, true); + messageVersion = manager.GetMessageVersion(messageType, context.SenderId, true); if (messageVersion < 0) { return; @@ -612,7 +620,7 @@ internal int SendMessage(ref TMessageType messa var messageVersion = 0; // Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this. // The first part of this message always has to be the version data and can't change. - if (typeof(TMessageType) != typeof(ConnectionRequestMessage)) + if (typeof(TMessageType) != s_ConnectionRequestType) { messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]); if (messageVersion < 0) @@ -666,7 +674,7 @@ internal unsafe int SendPreSerializedMessage(in FastBufferWriter t // Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this. // The first part of this message always has to be the version data and can't change. - if (typeof(TMessageType) != typeof(ConnectionRequestMessage)) + if (typeof(TMessageType) != s_ConnectionRequestType) { var messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]); if (messageVersion < 0) @@ -746,7 +754,7 @@ internal unsafe int SendPreSerializedMessage(in FastBufferWriter t // Special case because this is the message that carries the version info - thus the version info isn't // populated yet when we get this. The first part of this message always has to be the version data // and can't change. - if (typeof(TMessageType) != typeof(ConnectionRequestMessage)) + if (typeof(TMessageType) != s_ConnectionRequestType) { messageVersion = GetMessageVersion(typeof(TMessageType), clientId); if (messageVersion < 0) diff --git a/Runtime/Messaging/RpcTargets/EveryoneRpcTarget.cs b/Runtime/Messaging/RpcTargets/EveryoneRpcTarget.cs index b0ae738..7b2089f 100644 --- a/Runtime/Messaging/RpcTargets/EveryoneRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/EveryoneRpcTarget.cs @@ -4,23 +4,37 @@ internal class EveryoneRpcTarget : BaseRpcTarget { private NotServerRpcTarget m_NotServerRpcTarget; private ServerRpcTarget m_ServerRpcTarget; + private NotAuthorityRpcTarget m_NotAuthorityRpcTarget; + private AuthorityRpcTarget m_AuthorityRpcTarget; public override void Dispose() { m_NotServerRpcTarget.Dispose(); m_ServerRpcTarget.Dispose(); + m_NotAuthorityRpcTarget.Dispose(); + m_AuthorityRpcTarget.Dispose(); } internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams) { - m_NotServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams); - m_ServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams); + if (NetworkManager.IsDistributedAuthority) + { + m_NotAuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams); + m_AuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams); + } + else + { + m_NotServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams); + m_ServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams); + } } internal EveryoneRpcTarget(NetworkManager manager) : base(manager) { m_NotServerRpcTarget = new NotServerRpcTarget(manager); m_ServerRpcTarget = new ServerRpcTarget(manager); + m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager); + m_AuthorityRpcTarget = new AuthorityRpcTarget(manager); } } } diff --git a/Runtime/NetworkVariable/NetworkVariableSerialization.cs b/Runtime/NetworkVariable/NetworkVariableSerialization.cs deleted file mode 100644 index df7c3b9..0000000 --- a/Runtime/NetworkVariable/NetworkVariableSerialization.cs +++ /dev/null @@ -1,2065 +0,0 @@ -using System; -using System.Collections.Generic; -using Unity.Collections; -using Unity.Collections.LowLevel.Unsafe; -using Unity.Mathematics; -using UnityEditor; -using UnityEngine; - -namespace Unity.Netcode -{ - /// - /// Interface used by NetworkVariables to serialize them - /// - /// - internal interface INetworkVariableSerializer - { - // 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); - } - - /// - /// Packing serializer for shorts - /// - internal class ShortSerializer : INetworkVariableSerializer - { - public void Write(FastBufferWriter writer, ref short value) - { - BytePacker.WriteValueBitPacked(writer, value); - } - public void Read(FastBufferReader reader, ref short value) - { - ByteUnpacker.ReadValueBitPacked(reader, out value); - } - - public void WriteDelta(FastBufferWriter writer, ref short value, ref short previousValue) - { - Write(writer, ref value); - } - public void ReadDelta(FastBufferReader reader, ref short value) - { - Read(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out short value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in short value, ref short duplicatedValue) - { - duplicatedValue = value; - } - } - - /// - /// Packing serializer for shorts - /// - internal class UshortSerializer : INetworkVariableSerializer - { - public void Write(FastBufferWriter writer, ref ushort value) - { - BytePacker.WriteValueBitPacked(writer, value); - } - public void Read(FastBufferReader reader, ref ushort value) - { - ByteUnpacker.ReadValueBitPacked(reader, out value); - } - - public void WriteDelta(FastBufferWriter writer, ref ushort value, ref ushort previousValue) - { - Write(writer, ref value); - } - public void ReadDelta(FastBufferReader reader, ref ushort value) - { - Read(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out ushort value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in ushort value, ref ushort duplicatedValue) - { - duplicatedValue = value; - } - } - - /// - /// Packing serializer for ints - /// - internal class IntSerializer : INetworkVariableSerializer - { - public void Write(FastBufferWriter writer, ref int value) - { - BytePacker.WriteValueBitPacked(writer, value); - } - public void Read(FastBufferReader reader, ref int value) - { - ByteUnpacker.ReadValueBitPacked(reader, out value); - } - - public void WriteDelta(FastBufferWriter writer, ref int value, ref int previousValue) - { - Write(writer, ref value); - } - public void ReadDelta(FastBufferReader reader, ref int value) - { - Read(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out int value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in int value, ref int duplicatedValue) - { - duplicatedValue = value; - } - } - - /// - /// Packing serializer for ints - /// - internal class UintSerializer : INetworkVariableSerializer - { - public void Write(FastBufferWriter writer, ref uint value) - { - BytePacker.WriteValueBitPacked(writer, value); - } - public void Read(FastBufferReader reader, ref uint value) - { - ByteUnpacker.ReadValueBitPacked(reader, out value); - } - - public void WriteDelta(FastBufferWriter writer, ref uint value, ref uint previousValue) - { - Write(writer, ref value); - } - public void ReadDelta(FastBufferReader reader, ref uint value) - { - Read(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out uint value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in uint value, ref uint duplicatedValue) - { - duplicatedValue = value; - } - } - - /// - /// Packing serializer for longs - /// - internal class LongSerializer : INetworkVariableSerializer - { - public void Write(FastBufferWriter writer, ref long value) - { - BytePacker.WriteValueBitPacked(writer, value); - } - public void Read(FastBufferReader reader, ref long value) - { - ByteUnpacker.ReadValueBitPacked(reader, out value); - } - - public void WriteDelta(FastBufferWriter writer, ref long value, ref long previousValue) - { - Write(writer, ref value); - } - public void ReadDelta(FastBufferReader reader, ref long value) - { - Read(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out long value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in long value, ref long duplicatedValue) - { - duplicatedValue = value; - } - } - - /// - /// Packing serializer for longs - /// - internal class UlongSerializer : INetworkVariableSerializer - { - public void Write(FastBufferWriter writer, ref ulong value) - { - BytePacker.WriteValueBitPacked(writer, value); - } - public void Read(FastBufferReader reader, ref ulong value) - { - ByteUnpacker.ReadValueBitPacked(reader, out value); - } - - public void WriteDelta(FastBufferWriter writer, ref ulong value, ref ulong previousValue) - { - Write(writer, ref value); - } - public void ReadDelta(FastBufferReader reader, ref ulong value) - { - Read(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out ulong value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in ulong value, ref ulong duplicatedValue) - { - duplicatedValue = value; - } - } - - /// - /// Basic serializer for unmanaged types. - /// This covers primitives, built-in unity types, and IForceSerializeByMemcpy - /// Since all of those ultimately end up calling WriteUnmanagedSafe, this simplifies things - /// by calling that directly - thus preventing us from having to have a specific T that meets - /// the specific constraints that the various generic WriteValue calls require. - /// - /// - internal class UnmanagedTypeSerializer : INetworkVariableSerializer where T : unmanaged - { - public void Write(FastBufferWriter writer, ref T value) - { - writer.WriteUnmanagedSafe(value); - } - public void Read(FastBufferReader reader, ref T value) - { - reader.ReadUnmanagedSafe(out value); - } - - public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) - { - Write(writer, ref value); - } - public void ReadDelta(FastBufferReader reader, ref T value) - { - Read(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in T value, ref T duplicatedValue) - { - duplicatedValue = value; - } - } - - internal class ListSerializer : INetworkVariableSerializer> - { - public void Write(FastBufferWriter writer, ref List value) - { - bool isNull = value == null; - writer.WriteValueSafe(isNull); - if (!isNull) - { - BytePacker.WriteValuePacked(writer, value.Count); - foreach (var item in value) - { - var reffable = item; - NetworkVariableSerialization.Write(writer, ref reffable); - } - } - } - public void Read(FastBufferReader reader, ref List value) - { - reader.ReadValueSafe(out bool isNull); - if (isNull) - { - value = null; - } - else - { - if (value == null) - { - value = new List(); - } - - ByteUnpacker.ReadValuePacked(reader, out int len); - if (len < value.Count) - { - value.RemoveRange(len, value.Count - len); - } - for (var i = 0; i < len; ++i) - { - // Read in place where possible - if (i < value.Count) - { - T item = value[i]; - NetworkVariableSerialization.Read(reader, ref item); - value[i] = item; - } - else - { - T item = default; - NetworkVariableSerialization.Read(reader, ref item); - value.Add(item); - } - } - } - } - - public void WriteDelta(FastBufferWriter writer, ref List value, ref List previousValue) - { - CollectionSerializationUtility.WriteListDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref List value) - { - CollectionSerializationUtility.ReadListDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out List value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in List value, ref List duplicatedValue) - { - if (duplicatedValue == null) - { - duplicatedValue = new List(); - } - - duplicatedValue.Clear(); - foreach (var item in value) - { - duplicatedValue.Add(item); - } - } - } - - internal class HashSetSerializer : INetworkVariableSerializer> where T : IEquatable - { - public void Write(FastBufferWriter writer, ref HashSet value) - { - bool isNull = value == null; - writer.WriteValueSafe(isNull); - if (!isNull) - { - writer.WriteValueSafe(value.Count); - foreach (var item in value) - { - var reffable = item; - NetworkVariableSerialization.Write(writer, ref reffable); - } - } - } - public void Read(FastBufferReader reader, ref HashSet value) - { - reader.ReadValueSafe(out bool isNull); - if (isNull) - { - value = null; - } - else - { - if (value == null) - { - value = new HashSet(); - } - else - { - value.Clear(); - } - reader.ReadValueSafe(out int len); - for (var i = 0; i < len; ++i) - { - T item = default; - NetworkVariableSerialization.Read(reader, ref item); - value.Add(item); - } - } - } - - public void WriteDelta(FastBufferWriter writer, ref HashSet value, ref HashSet previousValue) - { - CollectionSerializationUtility.WriteHashSetDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref HashSet value) - { - CollectionSerializationUtility.ReadHashSetDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out HashSet value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in HashSet value, ref HashSet duplicatedValue) - { - if (duplicatedValue == null) - { - duplicatedValue = new HashSet(); - } - - duplicatedValue.Clear(); - foreach (var item in value) - { - duplicatedValue.Add(item); - } - } - } - - - internal class DictionarySerializer : INetworkVariableSerializer> - where TKey : IEquatable - { - public void Write(FastBufferWriter writer, ref Dictionary value) - { - bool isNull = value == null; - writer.WriteValueSafe(isNull); - if (!isNull) - { - writer.WriteValueSafe(value.Count); - foreach (var item in value) - { - (var key, var val) = (item.Key, item.Value); - NetworkVariableSerialization.Write(writer, ref key); - NetworkVariableSerialization.Write(writer, ref val); - } - } - } - public void Read(FastBufferReader reader, ref Dictionary value) - { - reader.ReadValueSafe(out bool isNull); - if (isNull) - { - value = null; - } - else - { - if (value == null) - { - value = new Dictionary(); - } - else - { - value.Clear(); - } - reader.ReadValueSafe(out int len); - for (var i = 0; i < len; ++i) - { - (TKey key, TVal val) = (default, default); - NetworkVariableSerialization.Read(reader, ref key); - NetworkVariableSerialization.Read(reader, ref val); - value.Add(key, val); - } - } - } - - public void WriteDelta(FastBufferWriter writer, ref Dictionary value, ref Dictionary previousValue) - { - CollectionSerializationUtility.WriteDictionaryDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref Dictionary value) - { - CollectionSerializationUtility.ReadDictionaryDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out Dictionary value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in Dictionary value, ref Dictionary duplicatedValue) - { - if (duplicatedValue == null) - { - duplicatedValue = new Dictionary(); - } - - duplicatedValue.Clear(); - foreach (var item in value) - { - duplicatedValue.Add(item.Key, item.Value); - } - } - } - - internal class UnmanagedArraySerializer : INetworkVariableSerializer> where T : unmanaged - { - public void Write(FastBufferWriter writer, ref NativeArray value) - { - writer.WriteUnmanagedSafe(value); - } - public void Read(FastBufferReader reader, ref NativeArray value) - { - value.Dispose(); - reader.ReadUnmanagedSafe(out value, Allocator.Persistent); - } - - public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) - { - CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref NativeArray value) - { - CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator) - { - reader.ReadUnmanagedSafe(out value, allocator); - } - - public void Duplicate(in NativeArray value, ref NativeArray duplicatedValue) - { - if (!duplicatedValue.IsCreated || duplicatedValue.Length != value.Length) - { - if (duplicatedValue.IsCreated) - { - duplicatedValue.Dispose(); - } - - duplicatedValue = new NativeArray(value.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); - } - - duplicatedValue.CopyFrom(value); - } - } - -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - internal class UnmanagedListSerializer : INetworkVariableSerializer> where T : unmanaged - { - public void Write(FastBufferWriter writer, ref NativeList value) - { - writer.WriteUnmanagedSafe(value); - } - public void Read(FastBufferReader reader, ref NativeList value) - { - reader.ReadUnmanagedSafeInPlace(ref value); - } - - public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) - { - CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref NativeList value) - { - CollectionSerializationUtility.ReadNativeListDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in NativeList value, ref NativeList duplicatedValue) - { - if (!duplicatedValue.IsCreated) - { - duplicatedValue = new NativeList(value.Length, Allocator.Persistent); - } - else if (value.Length != duplicatedValue.Length) - { - duplicatedValue.ResizeUninitialized(value.Length); - } - - duplicatedValue.CopyFrom(value); - } - } - - - internal class NativeHashSetSerializer : INetworkVariableSerializer> where T : unmanaged, IEquatable - { - public void Write(FastBufferWriter writer, ref NativeHashSet value) - { - writer.WriteValueSafe(value); - } - public void Read(FastBufferReader reader, ref NativeHashSet value) - { - reader.ReadValueSafeInPlace(ref value); - } - - public void WriteDelta(FastBufferWriter writer, ref NativeHashSet value, ref NativeHashSet previousValue) - { - CollectionSerializationUtility.WriteNativeHashSetDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref NativeHashSet value) - { - CollectionSerializationUtility.ReadNativeHashSetDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeHashSet value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in NativeHashSet value, ref NativeHashSet duplicatedValue) - { - if (!duplicatedValue.IsCreated) - { - duplicatedValue = new NativeHashSet(value.Capacity, Allocator.Persistent); - } - - duplicatedValue.Clear(); - foreach (var item in value) - { - duplicatedValue.Add(item); - } - } - } - - - internal class NativeHashMapSerializer : INetworkVariableSerializer> - where TKey : unmanaged, IEquatable - where TVal : unmanaged - { - public void Write(FastBufferWriter writer, ref NativeHashMap value) - { - writer.WriteValueSafe(value); - } - public void Read(FastBufferReader reader, ref NativeHashMap value) - { - reader.ReadValueSafeInPlace(ref value); - } - - public void WriteDelta(FastBufferWriter writer, ref NativeHashMap value, ref NativeHashMap previousValue) - { - CollectionSerializationUtility.WriteNativeHashMapDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref NativeHashMap value) - { - CollectionSerializationUtility.ReadNativeHashMapDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeHashMap value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in NativeHashMap value, ref NativeHashMap duplicatedValue) - { - if (!duplicatedValue.IsCreated) - { - duplicatedValue = new NativeHashMap(value.Capacity, Allocator.Persistent); - } - - duplicatedValue.Clear(); - foreach (var item in value) - { - duplicatedValue.Add(item.Key, item.Value); - } - } - } -#endif - - /// - /// Serializer for FixedStrings - /// - /// - internal class FixedStringSerializer : INetworkVariableSerializer where T : unmanaged, INativeList, IUTF8Bytes - { - public void Write(FastBufferWriter writer, ref T value) - { - writer.WriteValueSafe(value); - } - public void Read(FastBufferReader reader, ref T value) - { - reader.ReadValueSafeInPlace(ref value); - } - - // Because of how strings are generally used, it is likely that most strings will still write as full strings - // instead of deltas. This actually adds one byte to the data to encode that it was serialized in full. - // But the potential savings from a small change to a large string are valuable enough to be worth that extra - // byte. - public unsafe void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) - { - 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.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() * numChanges > FastBufferWriter.GetWriteSize() * value.Length) - { - writer.WriteByteSafe(1); - writer.WriteValueSafe(value); - return; - } - writer.WriteByte(0); - BytePacker.WriteValuePacked(writer, value.Length); - writer.WriteValueSafe(changes); - unsafe - { - byte* ptr = value.GetUnsafePtr(); - byte* prevPtr = previousValue.GetUnsafePtr(); - for (int i = 0; i < value.Length; ++i) - { - if (changes.IsSet(i)) - { - if (i < previousValue.Length) - { - NetworkVariableSerialization.WriteDelta(writer, ref ptr[i], ref prevPtr[i]); - } - else - { - NetworkVariableSerialization.Write(writer, ref ptr[i]); - } - } - } - } - } - public unsafe void ReadDelta(FastBufferReader reader, ref T value) - { - // Writing can use the NativeArray logic as it is, but reading is a little different. - // Using the NativeArray logic for reading would result in length changes allocating a new NativeArray, - // which is not what we want for FixedString. With FixedString, the actual size of the data does not change, - // only an in-memory "length" value - so if the length changes, the only thing we want to do is change - // that value, and otherwise read everything in-place. - 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); - - value.Length = length; - - byte* ptr = value.GetUnsafePtr(); - for (var i = 0; i < value.Length; ++i) - { - if (changes.IsSet(i)) - { - reader.ReadByte(out ptr[i]); - } - } - } - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in T value, ref T duplicatedValue) - { - duplicatedValue = value; - } - } - - /// - /// Serializer for FixedStrings - /// - /// - internal class FixedStringArraySerializer : INetworkVariableSerializer> where T : unmanaged, INativeList, IUTF8Bytes - { - public void Write(FastBufferWriter writer, ref NativeArray value) - { - writer.WriteValueSafe(value); - } - public void Read(FastBufferReader reader, ref NativeArray value) - { - value.Dispose(); - reader.ReadValueSafe(out value, Allocator.Persistent); - } - - - public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) - { - CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref NativeArray value) - { - CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator) - { - reader.ReadValueSafe(out value, allocator); - } - - public void Duplicate(in NativeArray value, ref NativeArray duplicatedValue) - { - if (!duplicatedValue.IsCreated || duplicatedValue.Length != value.Length) - { - if (duplicatedValue.IsCreated) - { - duplicatedValue.Dispose(); - } - - duplicatedValue = new NativeArray(value.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); - } - - duplicatedValue.CopyFrom(value); - } - } - -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - /// - /// Serializer for FixedStrings - /// - /// - internal class FixedStringListSerializer : INetworkVariableSerializer> where T : unmanaged, INativeList, IUTF8Bytes - { - public void Write(FastBufferWriter writer, ref NativeList value) - { - writer.WriteValueSafe(value); - } - public void Read(FastBufferReader reader, ref NativeList value) - { - reader.ReadValueSafeInPlace(ref value); - } - - public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) - { - CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref NativeList value) - { - CollectionSerializationUtility.ReadNativeListDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in NativeList value, ref NativeList duplicatedValue) - { - if (!duplicatedValue.IsCreated) - { - duplicatedValue = new NativeList(value.Length, Allocator.Persistent); - } - else if (value.Length != duplicatedValue.Length) - { - duplicatedValue.ResizeUninitialized(value.Length); - } - - duplicatedValue.CopyFrom(value); - } - } -#endif - - /// - /// Serializer for unmanaged INetworkSerializable types - /// - /// - internal class UnmanagedNetworkSerializableSerializer : INetworkVariableSerializer where T : unmanaged, INetworkSerializable - { - public void Write(FastBufferWriter writer, ref T value) - { - var bufferSerializer = new BufferSerializer(new BufferSerializerWriter(writer)); - value.NetworkSerialize(bufferSerializer); - } - public void Read(FastBufferReader reader, ref T value) - { - var bufferSerializer = new BufferSerializer(new BufferSerializerReader(reader)); - value.NetworkSerialize(bufferSerializer); - } - - public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) - { - if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) - { - UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue); - return; - } - Write(writer, ref value); - } - public void ReadDelta(FastBufferReader reader, ref T value) - { - if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) - { - UserNetworkVariableSerialization.ReadDelta(reader, ref value); - return; - } - Read(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in T value, ref T duplicatedValue) - { - duplicatedValue = value; - } - } - - /// - /// Serializer for unmanaged INetworkSerializable types - /// - /// - internal class UnmanagedNetworkSerializableArraySerializer : INetworkVariableSerializer> where T : unmanaged, INetworkSerializable - { - public void Write(FastBufferWriter writer, ref NativeArray value) - { - writer.WriteNetworkSerializable(value); - } - public void Read(FastBufferReader reader, ref NativeArray value) - { - value.Dispose(); - reader.ReadNetworkSerializable(out value, Allocator.Persistent); - } - - - public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) - { - CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref NativeArray value) - { - CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator) - { - reader.ReadNetworkSerializable(out value, allocator); - } - - public void Duplicate(in NativeArray value, ref NativeArray duplicatedValue) - { - if (!duplicatedValue.IsCreated || duplicatedValue.Length != value.Length) - { - if (duplicatedValue.IsCreated) - { - duplicatedValue.Dispose(); - } - - duplicatedValue = new NativeArray(value.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); - } - - duplicatedValue.CopyFrom(value); - } - } - -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - /// - /// Serializer for unmanaged INetworkSerializable types - /// - /// - internal class UnmanagedNetworkSerializableListSerializer : INetworkVariableSerializer> where T : unmanaged, INetworkSerializable - { - public void Write(FastBufferWriter writer, ref NativeList value) - { - writer.WriteNetworkSerializable(value); - } - public void Read(FastBufferReader reader, ref NativeList value) - { - reader.ReadNetworkSerializableInPlace(ref value); - } - - public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) - { - CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue); - } - public void ReadDelta(FastBufferReader reader, ref NativeList value) - { - CollectionSerializationUtility.ReadNativeListDelta(reader, ref value); - } - - void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in NativeList value, ref NativeList duplicatedValue) - { - if (!duplicatedValue.IsCreated) - { - duplicatedValue = new NativeList(value.Length, Allocator.Persistent); - } - else if (value.Length != duplicatedValue.Length) - { - duplicatedValue.ResizeUninitialized(value.Length); - } - - duplicatedValue.CopyFrom(value); - } - } -#endif - - /// - /// Serializer for managed INetworkSerializable types, which differs from the unmanaged implementation in that it - /// has to be null-aware - /// - internal class ManagedNetworkSerializableSerializer : INetworkVariableSerializer where T : class, INetworkSerializable, new() - { - public void Write(FastBufferWriter writer, ref T value) - { - var bufferSerializer = new BufferSerializer(new BufferSerializerWriter(writer)); - bool isNull = (value == null); - bufferSerializer.SerializeValue(ref isNull); - if (!isNull) - { - value.NetworkSerialize(bufferSerializer); - } - } - public void Read(FastBufferReader reader, ref T value) - { - var bufferSerializer = new BufferSerializer(new BufferSerializerReader(reader)); - bool isNull = false; - bufferSerializer.SerializeValue(ref isNull); - if (isNull) - { - value = null; - } - else - { - if (value == null) - { - value = new T(); - } - value.NetworkSerialize(bufferSerializer); - } - } - - public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) - { - if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) - { - UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue); - return; - } - Write(writer, ref value); - } - public void ReadDelta(FastBufferReader reader, ref T value) - { - if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) - { - UserNetworkVariableSerialization.ReadDelta(reader, ref value); - return; - } - Read(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in T value, ref T duplicatedValue) - { - using var writer = new FastBufferWriter(256, Allocator.Temp, int.MaxValue); - var refValue = value; - Write(writer, ref refValue); - - using var reader = new FastBufferReader(writer, Allocator.None); - Read(reader, ref duplicatedValue); - } - } - - /// - /// 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) - /// - /// - public class UserNetworkVariableSerialization - { - /// - /// The write value delegate handler definition - /// - /// The to write the value of type `T` - /// The value of type `T` to be written - public delegate void WriteValueDelegate(FastBufferWriter writer, in T value); - - /// - /// The write value delegate handler definition - /// - /// The to write the value of type `T` - /// The value of type `T` to be written - public delegate void WriteDeltaDelegate(FastBufferWriter writer, in T value, in T previousValue); - - /// - /// The read value delegate handler definition - /// - /// The to read the value of type `T` - /// The value of type `T` to be read - public delegate void ReadValueDelegate(FastBufferReader reader, out T value); - - /// - /// The read value delegate handler definition - /// - /// The to read the value of type `T` - /// The value of type `T` to be read - public delegate void ReadDeltaDelegate(FastBufferReader reader, ref T value); - - /// - /// The read value delegate handler definition - /// - /// The to read the value of type `T` - /// The value of type `T` to be read - public delegate void DuplicateValueDelegate(in T value, ref T duplicatedValue); - - /// - /// Callback to write a value - /// - public static WriteValueDelegate WriteValue; - - /// - /// Callback to read a value - /// - public static ReadValueDelegate ReadValue; - - /// - /// Callback to write a delta between two values, based on computing the difference between the previous and - /// current values. - /// - public static WriteDeltaDelegate WriteDelta; - - /// - /// Callback to read a delta, applying only select changes to the current value. - /// - public static ReadDeltaDelegate ReadDelta; - - /// - /// Callback to create a duplicate of a value, used to check for dirty status. - /// - public static DuplicateValueDelegate DuplicateValue; - } - - /// - /// 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. - /// - /// - internal class FallbackSerializer : INetworkVariableSerializer - { - 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)}. 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)}.{nameof(UserNetworkVariableSerialization.WriteValue)}, {nameof(UserNetworkVariableSerialization)}.{nameof(UserNetworkVariableSerialization.ReadValue)}, and {nameof(UserNetworkVariableSerialization)}.{nameof(UserNetworkVariableSerialization.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.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) - { - ThrowArgumentError(); - } - UserNetworkVariableSerialization.WriteValue(writer, value); - } - public void Read(FastBufferReader reader, ref T value) - { - if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) - { - ThrowArgumentError(); - } - UserNetworkVariableSerialization.ReadValue(reader, out value); - } - - public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) - { - if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) - { - ThrowArgumentError(); - } - - if (UserNetworkVariableSerialization.WriteDelta == null || UserNetworkVariableSerialization.ReadDelta == null) - { - UserNetworkVariableSerialization.WriteValue(writer, value); - return; - } - UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue); - } - - public void ReadDelta(FastBufferReader reader, ref T value) - { - if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) - { - ThrowArgumentError(); - } - - if (UserNetworkVariableSerialization.WriteDelta == null || UserNetworkVariableSerialization.ReadDelta == null) - { - UserNetworkVariableSerialization.ReadValue(reader, out value); - return; - } - UserNetworkVariableSerialization.ReadDelta(reader, ref value); - } - - void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) - { - throw new NotImplementedException(); - } - - public void Duplicate(in T value, ref T duplicatedValue) - { - if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) - { - ThrowArgumentError(); - } - UserNetworkVariableSerialization.DuplicateValue(value, ref duplicatedValue); - } - } - - /// - /// 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 . - /// 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.) - /// - public static class NetworkVariableSerializationTypes - { - [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)] -#if UNITY_EDITOR - [InitializeOnLoadMethod] -#endif - internal static void InitializeIntegerSerialization() - { - NetworkVariableSerialization.Serializer = new ShortSerializer(); - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals; - NetworkVariableSerialization.Serializer = new UshortSerializer(); - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals; - NetworkVariableSerialization.Serializer = new IntSerializer(); - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals; - NetworkVariableSerialization.Serializer = new UintSerializer(); - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals; - NetworkVariableSerialization.Serializer = new LongSerializer(); - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals; - NetworkVariableSerialization.Serializer = new UlongSerializer(); - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals; - - // DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server - NetworkVariableSerialization.Type = CollectionItemType.Short; - NetworkVariableSerialization.Type = CollectionItemType.UShort; - NetworkVariableSerialization.Type = CollectionItemType.Int; - NetworkVariableSerialization.Type = CollectionItemType.UInt; - NetworkVariableSerialization.Type = CollectionItemType.Long; - NetworkVariableSerialization.Type = CollectionItemType.ULong; - } - - /// - /// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer - /// - /// - public static void InitializeSerializer_UnmanagedByMemcpy() where T : unmanaged - { - NetworkVariableSerialization.Serializer = new UnmanagedTypeSerializer(); - // DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server - NetworkVariableSerialization.Type = CollectionItemType.Unmanaged; - } - - /// - /// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer - /// - /// - public static void InitializeSerializer_UnmanagedByMemcpyArray() where T : unmanaged - { - NetworkVariableSerialization>.Serializer = new UnmanagedArraySerializer(); - } - -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - /// - /// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer - /// - /// - public static void InitializeSerializer_UnmanagedByMemcpyList() where T : unmanaged - { - NetworkVariableSerialization>.Serializer = new UnmanagedListSerializer(); - } - - /// - /// Registeres a native hash set (this generic implementation works with all types) - /// - /// - public static void InitializeSerializer_NativeHashSet() where T : unmanaged, IEquatable - { - NetworkVariableSerialization>.Serializer = new NativeHashSetSerializer(); - } - - /// - /// Registeres a native hash set (this generic implementation works with all types) - /// - /// - public static void InitializeSerializer_NativeHashMap() - where TKey : unmanaged, IEquatable - where TVal : unmanaged - { - NetworkVariableSerialization>.Serializer = new NativeHashMapSerializer(); - } -#endif - - /// - /// Registeres a native hash set (this generic implementation works with all types) - /// - /// - public static void InitializeSerializer_List() - { - NetworkVariableSerialization>.Serializer = new ListSerializer(); - } - - /// - /// Registeres a native hash set (this generic implementation works with all types) - /// - /// - public static void InitializeSerializer_HashSet() where T : IEquatable - { - NetworkVariableSerialization>.Serializer = new HashSetSerializer(); - } - - /// - /// Registeres a native hash set (this generic implementation works with all types) - /// - /// - public static void InitializeSerializer_Dictionary() where TKey : IEquatable - { - NetworkVariableSerialization>.Serializer = new DictionarySerializer(); - } - - /// - /// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to - /// NetworkSerialize - /// - /// - public static void InitializeSerializer_UnmanagedINetworkSerializable() where T : unmanaged, INetworkSerializable - { - NetworkVariableSerialization.Serializer = new UnmanagedNetworkSerializableSerializer(); - } - - /// - /// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to - /// NetworkSerialize - /// - /// - public static void InitializeSerializer_UnmanagedINetworkSerializableArray() where T : unmanaged, INetworkSerializable - { - NetworkVariableSerialization>.Serializer = new UnmanagedNetworkSerializableArraySerializer(); - } - -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - /// - /// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to - /// NetworkSerialize - /// - /// - public static void InitializeSerializer_UnmanagedINetworkSerializableList() where T : unmanaged, INetworkSerializable - { - NetworkVariableSerialization>.Serializer = new UnmanagedNetworkSerializableListSerializer(); - } -#endif - - /// - /// Registers a managed type that implements INetworkSerializable and will be serialized through a call to - /// NetworkSerialize - /// - /// - public static void InitializeSerializer_ManagedINetworkSerializable() where T : class, INetworkSerializable, new() - { - NetworkVariableSerialization.Serializer = new ManagedNetworkSerializableSerializer(); - } - - /// - /// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString - /// serializers - /// - /// - public static void InitializeSerializer_FixedString() where T : unmanaged, INativeList, IUTF8Bytes - { - NetworkVariableSerialization.Serializer = new FixedStringSerializer(); - } - - /// - /// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString - /// serializers - /// - /// - public static void InitializeSerializer_FixedStringArray() where T : unmanaged, INativeList, IUTF8Bytes - { - NetworkVariableSerialization>.Serializer = new FixedStringArraySerializer(); - } - -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - /// - /// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString - /// serializers - /// - /// - public static void InitializeSerializer_FixedStringList() where T : unmanaged, INativeList, IUTF8Bytes - { - NetworkVariableSerialization>.Serializer = new FixedStringListSerializer(); - } -#endif - - /// - /// Registers a managed type that will be checked for equality using T.Equals() - /// - /// - public static void InitializeEqualityChecker_ManagedIEquatable() where T : class, IEquatable - { - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.EqualityEqualsObject; - } - - /// - /// Registers an unmanaged type that will be checked for equality using T.Equals() - /// - /// - public static void InitializeEqualityChecker_UnmanagedIEquatable() where T : unmanaged, IEquatable - { - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.EqualityEquals; - } - - /// - /// Registers an unmanaged type that will be checked for equality using T.Equals() - /// - /// - public static void InitializeEqualityChecker_UnmanagedIEquatableArray() where T : unmanaged, IEquatable - { - NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsArray; - } - /// - /// Registers an unmanaged type that will be checked for equality using T.Equals() - /// - /// - public static void InitializeEqualityChecker_List() - { - NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsList; - } - /// - /// Registers an unmanaged type that will be checked for equality using T.Equals() - /// - /// - public static void InitializeEqualityChecker_HashSet() where T : IEquatable - { - NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsHashSet; - } - /// - /// Registers an unmanaged type that will be checked for equality using T.Equals() - /// - /// - public static void InitializeEqualityChecker_Dictionary() - where TKey : IEquatable - { - NetworkVariableSerialization>.AreEqual = NetworkVariableDictionarySerialization.GenericEqualsDictionary; - } - -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - /// - /// Registers an unmanaged type that will be checked for equality using T.Equals() - /// - /// - public static void InitializeEqualityChecker_UnmanagedIEquatableList() where T : unmanaged, IEquatable - { - NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsNativeList; - } - /// - /// Registers an unmanaged type that will be checked for equality using T.Equals() - /// - /// - public static void InitializeEqualityChecker_NativeHashSet() where T : unmanaged, IEquatable - { - NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsNativeHashSet; - } - /// - /// Registers an unmanaged type that will be checked for equality using T.Equals() - /// - /// - public static void InitializeEqualityChecker_NativeHashMap() - where TKey : unmanaged, IEquatable - where TVal : unmanaged - { - NetworkVariableSerialization>.AreEqual = NetworkVariableMapSerialization.GenericEqualsNativeHashMap; - } -#endif - - /// - /// Registers an unmanaged type that will be checked for equality using memcmp and only considered - /// equal if they are bitwise equivalent in memory - /// - /// - public static void InitializeEqualityChecker_UnmanagedValueEquals() where T : unmanaged - { - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals; - } - - /// - /// Registers an unmanaged type that will be checked for equality using memcmp and only considered - /// equal if they are bitwise equivalent in memory - /// - /// - public static void InitializeEqualityChecker_UnmanagedValueEqualsArray() where T : unmanaged - { - NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.ValueEqualsArray; - } - -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - /// - /// Registers an unmanaged type that will be checked for equality using memcmp and only considered - /// equal if they are bitwise equivalent in memory - /// - /// - public static void InitializeEqualityChecker_UnmanagedValueEqualsList() where T : unmanaged - { - NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.ValueEqualsList; - } -#endif - - /// - /// Registers a managed type that will be checked for equality using the == operator - /// - /// - public static void InitializeEqualityChecker_ManagedClassEquals() where T : class - { - NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ClassEquals; - } - } - - /// - /// 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. - /// - /// The type the associated NetworkVariable is templated on - [Serializable] - public static class NetworkVariableSerialization - { - internal static INetworkVariableSerializer Serializer = new FallbackSerializer(); - - /// - /// The collection item type tells the CMB server how to read the bytes of each item in the collection - /// - /// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server - internal static CollectionItemType Type = CollectionItemType.Unknown; - - /// - /// A callback to check if two values are equal. - /// - public delegate bool EqualsDelegate(ref T a, ref T b); - - /// - /// Uses the most efficient mechanism for a given type to determine if two values are equal. - /// For types that implement , it will call the Equals() method. - /// For unmanaged types, it will do a bytewise memory comparison. - /// For other types, it will call the == operator. - ///
- ///
- /// Note: If you are using this in a custom generic class, please make sure your class is - /// decorated with so that codegen can - /// initialize the serialization mechanisms correctly. If your class is NOT - /// generic, it is better to check their equality yourself. - ///
- public static EqualsDelegate AreEqual { get; internal set; } - - /// - /// 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. - ///
- ///
- /// Note: If you are using this in a custom generic class, please make sure your class is - /// decorated with so that codegen can - /// initialize the serialization mechanisms correctly. If your class is NOT - /// generic, it is better to use FastBufferWriter directly. - ///
- ///
- /// If the codegen is unable to determine a serializer for a type, - /// . is called, which, by default, - /// will throw an exception, unless you have assigned a user serialization callback to it at runtime. - ///
- /// - /// - public static void Write(FastBufferWriter writer, ref T value) - { - Serializer.Write(writer, ref value); - } - - /// - /// 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. - ///
- ///
- /// Note: If you are using this in a custom generic class, please make sure your class is - /// decorated with so that codegen can - /// initialize the serialization mechanisms correctly. If your class is NOT - /// generic, it is better to use FastBufferReader directly. - ///
- ///
- /// If the codegen is unable to determine a serializer for a type, - /// . is called, which, by default, - /// will throw an exception, unless you have assigned a user deserialization callback to it at runtime. - ///
- /// - /// - public static void Read(FastBufferReader reader, ref T value) - { - Serializer.Read(reader, ref value); - } - - /// - /// 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. - ///
- ///
- /// Note: If you are using this in a custom generic class, please make sure your class is - /// decorated with so that codegen can - /// initialize the serialization mechanisms correctly. If your class is NOT - /// generic, it is better to use FastBufferWriter directly. - ///
- ///
- /// If the codegen is unable to determine a serializer for a type, - /// . is called, which, by default, - /// will throw an exception, unless you have assigned a user serialization callback to it at runtime. - ///
- /// - /// - public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) - { - Serializer.WriteDelta(writer, ref value, ref previousValue); - } - - /// - /// 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. - ///
- ///
- /// Note: If you are using this in a custom generic class, please make sure your class is - /// decorated with so that codegen can - /// initialize the serialization mechanisms correctly. If your class is NOT - /// generic, it is better to use FastBufferReader directly. - ///
- ///
- /// If the codegen is unable to determine a serializer for a type, - /// . is called, which, by default, - /// will throw an exception, unless you have assigned a user deserialization callback to it at runtime. - ///
- /// - /// - public static void ReadDelta(FastBufferReader reader, ref T value) - { - Serializer.ReadDelta(reader, ref value); - } - - /// - /// 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. - ///
- ///
- /// Note: If you are using this in a custom generic class, please make sure your class is - /// decorated with so that codegen can - /// initialize the serialization mechanisms correctly. If your class is NOT - /// generic, it is better to duplicate it directly. - ///
- ///
- /// If the codegen is unable to determine a serializer for a type, - /// . is called, which, by default, - /// will throw an exception, unless you have assigned a user duplication callback to it at runtime. - ///
- /// - /// - public static void Duplicate(in T value, ref T duplicatedValue) - { - Serializer.Duplicate(value, ref duplicatedValue); - } - - // Compares two values of the same unmanaged type by underlying memory - // Ignoring any overridden value checks - // Size is fixed - internal static unsafe bool ValueEquals(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(ref NativeList a, ref NativeList 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(ref NativeArray a, ref NativeArray 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(ref TValueType a, ref TValueType b) where TValueType : class, IEquatable - { - if (a == null) - { - return b == null; - } - - if (b == null) - { - return false; - } - - return a.Equals(b); - } - - internal static bool EqualityEquals(ref TValueType a, ref TValueType b) where TValueType : unmanaged, IEquatable - { - return a.Equals(b); - } - - internal static bool EqualityEqualsList(ref List a, ref List 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.AreEqual(ref aItem, ref bItem)) - { - return false; - } - } - - return true; - } - - internal static bool EqualityEqualsHashSet(ref HashSet a, ref HashSet b) where TValueType : IEquatable - { - 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; - } - -#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(ref NativeList a, ref NativeList b) where TValueType : unmanaged, IEquatable - { - 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(ref NativeHashSet a, ref NativeHashSet b) where TValueType : unmanaged, IEquatable - { - 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 - - // Compares two values of the same unmanaged type by underlying memory - // Ignoring any overridden value checks - // Size is fixed - internal static unsafe bool EqualityEqualsArray(ref NativeArray a, ref NativeArray b) where TValueType : unmanaged, IEquatable - { - 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(ref TValueType a, ref TValueType b) where TValueType : class - { - return a == b; - } - } - internal class NetworkVariableDictionarySerialization - where TKey : IEquatable - { - - internal static bool GenericEqualsDictionary(ref Dictionary a, ref Dictionary 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.AreEqual(ref bVal, ref val)) - { - return false; - } - } - - return true; - } - } - -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - internal class NetworkVariableMapSerialization - where TKey : unmanaged, IEquatable - where TVal : unmanaged - { - - internal static bool GenericEqualsNativeHashMap(ref NativeHashMap a, ref NativeHashMap 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.AreEqual(ref item.Value, ref val)) - { - return false; - } - } - - return true; - } - } -#endif - - // RuntimeAccessModifiersILPP will make this `public` - // This is just pass-through to NetworkVariableSerialization but is here becaues I could not get ILPP - // to generate code that would successfully call Type.Method(T), but it has no problem calling Type.Method(T) - internal class RpcFallbackSerialization - { - public static void Write(FastBufferWriter writer, ref T value) - { - NetworkVariableSerialization.Write(writer, ref value); - } - - public static void Read(FastBufferReader reader, ref T value) - { - NetworkVariableSerialization.Read(reader, ref value); - } - } -} diff --git a/Runtime/NetworkVariable/NetworkVariableSerialization.cs.meta b/Runtime/NetworkVariable/NetworkVariableSerialization.cs.meta deleted file mode 100644 index 7ab0efc..0000000 --- a/Runtime/NetworkVariable/NetworkVariableSerialization.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 2c6ef5fdf2e94ec3b4ce8086d52700b3 -timeCreated: 1650985453 \ No newline at end of file diff --git a/Runtime/NetworkVariable/Serialization.meta b/Runtime/NetworkVariable/Serialization.meta new file mode 100644 index 0000000..4937ff6 --- /dev/null +++ b/Runtime/NetworkVariable/Serialization.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d960ae6c5b8241aa9e2906b709095ea1 +timeCreated: 1718215841 \ No newline at end of file diff --git a/Runtime/NetworkVariable/CollectionSerializationUtility.cs b/Runtime/NetworkVariable/Serialization/CollectionSerializationUtility.cs similarity index 100% rename from Runtime/NetworkVariable/CollectionSerializationUtility.cs rename to Runtime/NetworkVariable/Serialization/CollectionSerializationUtility.cs diff --git a/Runtime/NetworkVariable/CollectionSerializationUtility.cs.meta b/Runtime/NetworkVariable/Serialization/CollectionSerializationUtility.cs.meta similarity index 100% rename from Runtime/NetworkVariable/CollectionSerializationUtility.cs.meta rename to Runtime/NetworkVariable/Serialization/CollectionSerializationUtility.cs.meta diff --git a/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs b/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs new file mode 100644 index 0000000..5e85574 --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs @@ -0,0 +1,99 @@ +using System; +using Unity.Collections; + +namespace Unity.Netcode +{ + /// + /// 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. + /// + /// + internal class FallbackSerializer : INetworkVariableSerializer + { + 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)}. 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)}.{nameof(UserNetworkVariableSerialization.WriteValue)}, {nameof(UserNetworkVariableSerialization)}.{nameof(UserNetworkVariableSerialization.ReadValue)}, and {nameof(UserNetworkVariableSerialization)}.{nameof(UserNetworkVariableSerialization.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.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) + { + ThrowArgumentError(); + } + UserNetworkVariableSerialization.WriteValue(writer, value); + } + public void Read(FastBufferReader reader, ref T value) + { + if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) + { + ThrowArgumentError(); + } + UserNetworkVariableSerialization.ReadValue(reader, out value); + } + + public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) + { + ThrowArgumentError(); + } + + if (UserNetworkVariableSerialization.WriteDelta == null || UserNetworkVariableSerialization.ReadDelta == null) + { + UserNetworkVariableSerialization.WriteValue(writer, value); + return; + } + UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref T value) + { + if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) + { + ThrowArgumentError(); + } + + if (UserNetworkVariableSerialization.WriteDelta == null || UserNetworkVariableSerialization.ReadDelta == null) + { + UserNetworkVariableSerialization.ReadValue(reader, out value); + return; + } + UserNetworkVariableSerialization.ReadDelta(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in T value, ref T duplicatedValue) + { + if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) + { + ThrowArgumentError(); + } + UserNetworkVariableSerialization.DuplicateValue(value, ref duplicatedValue); + } + } + + // RuntimeAccessModifiersILPP will make this `public` + // This is just pass-through to NetworkVariableSerialization but is here because I could not get ILPP + // to generate code that would successfully call Type.Method(T), but it has no problem calling Type.Method(T) + internal class RpcFallbackSerialization + { + public static void Write(FastBufferWriter writer, ref T value) + { + NetworkVariableSerialization.Write(writer, ref value); + } + + public static void Read(FastBufferReader reader, ref T value) + { + NetworkVariableSerialization.Read(reader, ref value); + } + } +} diff --git a/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs.meta b/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs.meta new file mode 100644 index 0000000..4472d15 --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 288dbe7d1ff74860ae3552c034485538 +timeCreated: 1718219109 \ No newline at end of file diff --git a/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs b/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs new file mode 100644 index 0000000..f462e52 --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs @@ -0,0 +1,26 @@ +using Unity.Collections; + +namespace Unity.Netcode +{ + /// + /// Interface used by NetworkVariables to serialize them + /// + /// + /// + internal interface INetworkVariableSerializer + { + // 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); + } +} diff --git a/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs.meta b/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs.meta new file mode 100644 index 0000000..58433bb --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f78e258ef55f4ee89bc3f24d67b8d242 +timeCreated: 1718218205 \ No newline at end of file diff --git a/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs b/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs new file mode 100644 index 0000000..c8aecb3 --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs @@ -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 + { + // Compares two values of the same unmanaged type by underlying memory + // Ignoring any overridden value checks + // Size is fixed + internal static unsafe bool ValueEquals(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(ref NativeList a, ref NativeList 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(ref NativeArray a, ref NativeArray 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(ref TValueType a, ref TValueType b) where TValueType : class, IEquatable + { + if (a == null) + { + return b == null; + } + + if (b == null) + { + return false; + } + + return a.Equals(b); + } + + internal static bool EqualityEquals(ref TValueType a, ref TValueType b) where TValueType : unmanaged, IEquatable + { + return a.Equals(b); + } + + internal static bool EqualityEqualsList(ref List a, ref List 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.AreEqual(ref aItem, ref bItem)) + { + return false; + } + } + + return true; + } + + internal static bool EqualityEqualsHashSet(ref HashSet a, ref HashSet b) where TValueType : IEquatable + { + 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(ref NativeArray a, ref NativeArray b) where TValueType : unmanaged, IEquatable + { + 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(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(ref NativeList a, ref NativeList b) where TValueType : unmanaged, IEquatable + { + 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(ref NativeHashSet a, ref NativeHashSet b) where TValueType : unmanaged, IEquatable + { + 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 + } +} + +/// +/// 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. +/// +/// The type the associated NetworkVariable dictionary collection key templated on +/// The type the associated NetworkVariable dictionary collection value templated on +internal class NetworkVariableDictionarySerialization + where TKey : IEquatable +{ + internal static bool GenericEqualsDictionary(ref Dictionary a, ref Dictionary 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.AreEqual(ref bVal, ref val)) + { + return false; + } + } + + return true; + } +} + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT +internal class NetworkVariableMapSerialization + where TKey : unmanaged, IEquatable + where TVal : unmanaged +{ + internal static bool GenericEqualsNativeHashMap(ref NativeHashMap a, ref NativeHashMap 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.AreEqual(ref item.Value, ref val)) + { + return false; + } + } + + return true; + } +} +#endif diff --git a/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs.meta b/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs.meta new file mode 100644 index 0000000..9a91970 --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 24b8352a975044509931bf684ccfdb82 +timeCreated: 1718219366 \ No newline at end of file diff --git a/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs b/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs new file mode 100644 index 0000000..ebaba37 --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs @@ -0,0 +1,161 @@ +using System; + +namespace Unity.Netcode +{ + /// + /// 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. + /// + /// The type the associated NetworkVariable is templated on + [Serializable] + public static class NetworkVariableSerialization + { + internal static INetworkVariableSerializer Serializer = new FallbackSerializer(); + + internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority; + + /// + /// The collection item type tells the CMB server how to read the bytes of each item in the collection + /// + /// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server + internal static CollectionItemType Type = CollectionItemType.Unknown; + + /// + /// A callback to check if two values are equal. + /// + public delegate bool EqualsDelegate(ref T a, ref T b); + + /// + /// Uses the most efficient mechanism for a given type to determine if two values are equal. + /// For types that implement , it will call the Equals() method. + /// For unmanaged types, it will do a bytewise memory comparison. + /// For other types, it will call the == operator. + ///
+ ///
+ /// Note: If you are using this in a custom generic class, please make sure your class is + /// decorated with so that codegen can + /// initialize the serialization mechanisms correctly. If your class is NOT + /// generic, it is better to check their equality yourself. + ///
+ public static EqualsDelegate AreEqual { get; internal set; } + /// + /// 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. + ///
+ ///
+ /// Note: If you are using this in a custom generic class, please make sure your class is + /// decorated with so that codegen can + /// initialize the serialization mechanisms correctly. If your class is NOT + /// generic, it is better to use FastBufferWriter directly. + ///
+ ///
+ /// If the codegen is unable to determine a serializer for a type, + /// . is called, which, by default, + /// will throw an exception, unless you have assigned a user serialization callback to it at runtime. + ///
+ /// + /// + public static void Write(FastBufferWriter writer, ref T value) + { + Serializer.Write(writer, ref value); + } + + /// + /// 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. + ///
+ ///
+ /// Note: If you are using this in a custom generic class, please make sure your class is + /// decorated with so that codegen can + /// initialize the serialization mechanisms correctly. If your class is NOT + /// generic, it is better to use FastBufferReader directly. + ///
+ ///
+ /// If the codegen is unable to determine a serializer for a type, + /// . is called, which, by default, + /// will throw an exception, unless you have assigned a user deserialization callback to it at runtime. + ///
+ /// + /// + public static void Read(FastBufferReader reader, ref T value) + { + Serializer.Read(reader, ref value); + } + + /// + /// 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. + ///
+ ///
+ /// Note: If you are using this in a custom generic class, please make sure your class is + /// decorated with so that codegen can + /// initialize the serialization mechanisms correctly. If your class is NOT + /// generic, it is better to use FastBufferWriter directly. + ///
+ ///
+ /// If the codegen is unable to determine a serializer for a type, + /// . is called, which, by default, + /// will throw an exception, unless you have assigned a user serialization callback to it at runtime. + ///
+ /// + /// + public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + Serializer.WriteDelta(writer, ref value, ref previousValue); + } + + /// + /// 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. + ///
+ ///
+ /// Note: If you are using this in a custom generic class, please make sure your class is + /// decorated with so that codegen can + /// initialize the serialization mechanisms correctly. If your class is NOT + /// generic, it is better to use FastBufferReader directly. + ///
+ ///
+ /// If the codegen is unable to determine a serializer for a type, + /// . is called, which, by default, + /// will throw an exception, unless you have assigned a user deserialization callback to it at runtime. + ///
+ /// + /// + public static void ReadDelta(FastBufferReader reader, ref T value) + { + Serializer.ReadDelta(reader, ref value); + } + + /// + /// 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. + ///
+ ///
+ /// Note: If you are using this in a custom generic class, please make sure your class is + /// decorated with so that codegen can + /// initialize the serialization mechanisms correctly. If your class is NOT + /// generic, it is better to duplicate it directly. + ///
+ ///
+ /// If the codegen is unable to determine a serializer for a type, + /// . is called, which, by default, + /// will throw an exception, unless you have assigned a user duplication callback to it at runtime. + ///
+ /// + /// + public static void Duplicate(in T value, ref T duplicatedValue) + { + Serializer.Duplicate(value, ref duplicatedValue); + } + } +} diff --git a/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs.meta b/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs.meta new file mode 100644 index 0000000..d7b821f --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7a943170e35746e8913dd494d79bb63d +timeCreated: 1718215899 \ No newline at end of file diff --git a/Runtime/NetworkVariable/ResizableBitVector.cs b/Runtime/NetworkVariable/Serialization/ResizableBitVector.cs similarity index 100% rename from Runtime/NetworkVariable/ResizableBitVector.cs rename to Runtime/NetworkVariable/Serialization/ResizableBitVector.cs diff --git a/Runtime/NetworkVariable/ResizableBitVector.cs.meta b/Runtime/NetworkVariable/Serialization/ResizableBitVector.cs.meta similarity index 100% rename from Runtime/NetworkVariable/ResizableBitVector.cs.meta rename to Runtime/NetworkVariable/Serialization/ResizableBitVector.cs.meta diff --git a/Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs b/Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs new file mode 100644 index 0000000..f3e679a --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs @@ -0,0 +1,325 @@ +using System; +using System.Collections.Generic; +using Unity.Collections; +using UnityEditor; +using UnityEngine; + +namespace Unity.Netcode +{ + /// + /// 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 . + /// 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.) + /// + public static class NetworkVariableSerializationTypedInitializers + { + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)] +#if UNITY_EDITOR + [InitializeOnLoadMethod] +#endif + internal static void InitializeIntegerSerialization() + { + NetworkVariableSerialization.Serializer = new ShortSerializer(); + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.ValueEquals; + NetworkVariableSerialization.Serializer = new UshortSerializer(); + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.ValueEquals; + NetworkVariableSerialization.Serializer = new IntSerializer(); + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.ValueEquals; + NetworkVariableSerialization.Serializer = new UintSerializer(); + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.ValueEquals; + NetworkVariableSerialization.Serializer = new LongSerializer(); + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.ValueEquals; + NetworkVariableSerialization.Serializer = new UlongSerializer(); + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.ValueEquals; + + // DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server + NetworkVariableSerialization.Type = CollectionItemType.Short; + NetworkVariableSerialization.Type = CollectionItemType.UShort; + NetworkVariableSerialization.Type = CollectionItemType.Int; + NetworkVariableSerialization.Type = CollectionItemType.UInt; + NetworkVariableSerialization.Type = CollectionItemType.Long; + NetworkVariableSerialization.Type = CollectionItemType.ULong; + } + + /// + /// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer + /// + /// + public static void InitializeSerializer_UnmanagedByMemcpy() where T : unmanaged + { + NetworkVariableSerialization.Serializer = new UnmanagedTypeSerializer(); + // DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server + NetworkVariableSerialization.Type = CollectionItemType.Unmanaged; + } + + /// + /// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer + /// + /// + public static void InitializeSerializer_UnmanagedByMemcpyArray() where T : unmanaged + { + NetworkVariableSerialization>.Serializer = new UnmanagedArraySerializer(); + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + /// + /// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer + /// + /// + public static void InitializeSerializer_UnmanagedByMemcpyList() where T : unmanaged + { + NetworkVariableSerialization>.Serializer = new UnmanagedListSerializer(); + } + + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_NativeHashSet() where T : unmanaged, IEquatable + { + NetworkVariableSerialization>.Serializer = new NativeHashSetSerializer(); + } + + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_NativeHashMap() + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + NetworkVariableSerialization>.Serializer = new NativeHashMapSerializer(); + } +#endif + + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_List() + { + NetworkVariableSerialization>.Serializer = new ListSerializer(); + } + + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_HashSet() where T : IEquatable + { + NetworkVariableSerialization>.Serializer = new HashSetSerializer(); + } + + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_Dictionary() where TKey : IEquatable + { + NetworkVariableSerialization>.Serializer = new DictionarySerializer(); + } + + /// + /// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to + /// NetworkSerialize + /// + /// + public static void InitializeSerializer_UnmanagedINetworkSerializable() where T : unmanaged, INetworkSerializable + { + NetworkVariableSerialization.Serializer = new UnmanagedNetworkSerializableSerializer(); + } + + /// + /// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to + /// NetworkSerialize + /// + /// + public static void InitializeSerializer_UnmanagedINetworkSerializableArray() where T : unmanaged, INetworkSerializable + { + NetworkVariableSerialization>.Serializer = new UnmanagedNetworkSerializableArraySerializer(); + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + /// + /// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to + /// NetworkSerialize + /// + /// + public static void InitializeSerializer_UnmanagedINetworkSerializableList() where T : unmanaged, INetworkSerializable + { + NetworkVariableSerialization>.Serializer = new UnmanagedNetworkSerializableListSerializer(); + } +#endif + + /// + /// Registers a managed type that implements INetworkSerializable and will be serialized through a call to + /// NetworkSerialize + /// + /// + public static void InitializeSerializer_ManagedINetworkSerializable() where T : class, INetworkSerializable, new() + { + NetworkVariableSerialization.Serializer = new ManagedNetworkSerializableSerializer(); + } + + /// + /// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString + /// serializers + /// + /// + public static void InitializeSerializer_FixedString() where T : unmanaged, INativeList, IUTF8Bytes + { + NetworkVariableSerialization.Serializer = new FixedStringSerializer(); + } + + /// + /// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString + /// serializers + /// + /// + public static void InitializeSerializer_FixedStringArray() where T : unmanaged, INativeList, IUTF8Bytes + { + NetworkVariableSerialization>.Serializer = new FixedStringArraySerializer(); + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + /// + /// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString + /// serializers + /// + /// + public static void InitializeSerializer_FixedStringList() where T : unmanaged, INativeList, IUTF8Bytes + { + NetworkVariableSerialization>.Serializer = new FixedStringListSerializer(); + } +#endif + + /// + /// Registers a managed type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_ManagedIEquatable() where T : class, IEquatable + { + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.EqualityEqualsObject; + } + + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_UnmanagedIEquatable() where T : unmanaged, IEquatable + { + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.EqualityEquals; + } + + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_UnmanagedIEquatableArray() where T : unmanaged, IEquatable + { + NetworkVariableSerialization>.AreEqual = NetworkVariableEquality.EqualityEqualsArray; + } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_List() + { + NetworkVariableSerialization>.AreEqual = NetworkVariableEquality.EqualityEqualsList; + } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_HashSet() where T : IEquatable + { + NetworkVariableSerialization>.AreEqual = NetworkVariableEquality.EqualityEqualsHashSet; + } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_Dictionary() + where TKey : IEquatable + { + NetworkVariableSerialization>.AreEqual = NetworkVariableDictionarySerialization.GenericEqualsDictionary; + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_UnmanagedIEquatableList() where T : unmanaged, IEquatable + { + NetworkVariableSerialization>.AreEqual = NetworkVariableEquality.EqualityEqualsNativeList; + } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_NativeHashSet() where T : unmanaged, IEquatable + { + NetworkVariableSerialization>.AreEqual = NetworkVariableEquality.EqualityEqualsNativeHashSet; + } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_NativeHashMap() + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + NetworkVariableSerialization>.AreEqual = NetworkVariableMapSerialization.GenericEqualsNativeHashMap; + } +#endif + + /// + /// Registers an unmanaged type that will be checked for equality using memcmp and only considered + /// equal if they are bitwise equivalent in memory + /// + /// + public static void InitializeEqualityChecker_UnmanagedValueEquals() where T : unmanaged + { + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.ValueEquals; + } + + /// + /// Registers an unmanaged type that will be checked for equality using memcmp and only considered + /// equal if they are bitwise equivalent in memory + /// + /// + public static void InitializeEqualityChecker_UnmanagedValueEqualsArray() where T : unmanaged + { + NetworkVariableSerialization>.AreEqual = NetworkVariableEquality.ValueEqualsArray; + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + /// + /// Registers an unmanaged type that will be checked for equality using memcmp and only considered + /// equal if they are bitwise equivalent in memory + /// + /// + public static void InitializeEqualityChecker_UnmanagedValueEqualsList() where T : unmanaged + { + NetworkVariableSerialization>.AreEqual = NetworkVariableEquality.ValueEqualsList; + } +#endif + + /// + /// Registers a managed type that will be checked for equality using the == operator + /// + /// + public static void InitializeEqualityChecker_ManagedClassEquals() where T : class + { + NetworkVariableSerialization.AreEqual = NetworkVariableEquality.ClassEquals; + } + } +} diff --git a/Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs.meta b/Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs.meta new file mode 100644 index 0000000..6d1ebba --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 65bdb3e11a9a412ab5e936a9c96a3da0 +timeCreated: 1718216842 \ No newline at end of file diff --git a/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs b/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs new file mode 100644 index 0000000..91d3a60 --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs @@ -0,0 +1,1120 @@ +using System; +using System.Collections.Generic; +using Unity.Collections; +using Unity.Mathematics; + +namespace Unity.Netcode +{ + /// + /// Packing serializer for shorts + /// + internal class ShortSerializer : INetworkVariableSerializer + { + public void Write(FastBufferWriter writer, ref short value) + { + BytePacker.WriteValueBitPacked(writer, value); + } + + public void Read(FastBufferReader reader, ref short value) + { + ByteUnpacker.ReadValueBitPacked(reader, out value); + } + + public void WriteDelta(FastBufferWriter writer, ref short value, ref short previousValue) + { + Write(writer, ref value); + } + + public void ReadDelta(FastBufferReader reader, ref short value) + { + Read(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out short value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in short value, ref short duplicatedValue) + { + duplicatedValue = value; + } + } + + /// + /// Packing serializer for shorts + /// + internal class UshortSerializer : INetworkVariableSerializer + { + public void Write(FastBufferWriter writer, ref ushort value) + { + BytePacker.WriteValueBitPacked(writer, value); + } + + public void Read(FastBufferReader reader, ref ushort value) + { + ByteUnpacker.ReadValueBitPacked(reader, out value); + } + + public void WriteDelta(FastBufferWriter writer, ref ushort value, ref ushort previousValue) + { + Write(writer, ref value); + } + + public void ReadDelta(FastBufferReader reader, ref ushort value) + { + Read(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out ushort value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in ushort value, ref ushort duplicatedValue) + { + duplicatedValue = value; + } + } + + /// + /// Packing serializer for ints + /// + internal class IntSerializer : INetworkVariableSerializer + { + public void Write(FastBufferWriter writer, ref int value) + { + BytePacker.WriteValueBitPacked(writer, value); + } + + public void Read(FastBufferReader reader, ref int value) + { + ByteUnpacker.ReadValueBitPacked(reader, out value); + } + + public void WriteDelta(FastBufferWriter writer, ref int value, ref int previousValue) + { + Write(writer, ref value); + } + + public void ReadDelta(FastBufferReader reader, ref int value) + { + Read(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out int value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in int value, ref int duplicatedValue) + { + duplicatedValue = value; + } + } + + /// + /// Packing serializer for ints + /// + internal class UintSerializer : INetworkVariableSerializer + { + public void Write(FastBufferWriter writer, ref uint value) + { + BytePacker.WriteValueBitPacked(writer, value); + } + + public void Read(FastBufferReader reader, ref uint value) + { + ByteUnpacker.ReadValueBitPacked(reader, out value); + } + + public void WriteDelta(FastBufferWriter writer, ref uint value, ref uint previousValue) + { + Write(writer, ref value); + } + + public void ReadDelta(FastBufferReader reader, ref uint value) + { + Read(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out uint value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in uint value, ref uint duplicatedValue) + { + duplicatedValue = value; + } + } + + /// + /// Packing serializer for longs + /// + internal class LongSerializer : INetworkVariableSerializer + { + public void Write(FastBufferWriter writer, ref long value) + { + BytePacker.WriteValueBitPacked(writer, value); + } + + public void Read(FastBufferReader reader, ref long value) + { + ByteUnpacker.ReadValueBitPacked(reader, out value); + } + + public void WriteDelta(FastBufferWriter writer, ref long value, ref long previousValue) + { + Write(writer, ref value); + } + + public void ReadDelta(FastBufferReader reader, ref long value) + { + Read(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out long value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in long value, ref long duplicatedValue) + { + duplicatedValue = value; + } + } + + /// + /// Packing serializer for longs + /// + internal class UlongSerializer : INetworkVariableSerializer + { + public void Write(FastBufferWriter writer, ref ulong value) + { + BytePacker.WriteValueBitPacked(writer, value); + } + + public void Read(FastBufferReader reader, ref ulong value) + { + ByteUnpacker.ReadValueBitPacked(reader, out value); + } + + public void WriteDelta(FastBufferWriter writer, ref ulong value, ref ulong previousValue) + { + Write(writer, ref value); + } + + public void ReadDelta(FastBufferReader reader, ref ulong value) + { + Read(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out ulong value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in ulong value, ref ulong duplicatedValue) + { + duplicatedValue = value; + } + } + + /// + /// Basic serializer for unmanaged types. + /// This covers primitives, built-in unity types, and IForceSerializeByMemcpy + /// Since all of those ultimately end up calling WriteUnmanagedSafe, this simplifies things + /// by calling that directly - thus preventing us from having to have a specific T that meets + /// the specific constraints that the various generic WriteValue calls require. + /// + /// + internal class UnmanagedTypeSerializer : INetworkVariableSerializer where T : unmanaged + { + public void Write(FastBufferWriter writer, ref T value) + { + writer.WriteUnmanagedSafe(value); + } + + public void Read(FastBufferReader reader, ref T value) + { + reader.ReadUnmanagedSafe(out value); + } + + public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + Write(writer, ref value); + } + + public void ReadDelta(FastBufferReader reader, ref T value) + { + Read(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in T value, ref T duplicatedValue) + { + duplicatedValue = value; + } + } + + internal class ListSerializer : INetworkVariableSerializer> + { + public void Write(FastBufferWriter writer, ref List value) + { + var isNull = value == null; + writer.WriteValueSafe(isNull); + if (!isNull) + { + BytePacker.WriteValuePacked(writer, value.Count); + foreach (var item in value) + { + var reffable = item; + NetworkVariableSerialization.Write(writer, ref reffable); + } + } + } + + public void Read(FastBufferReader reader, ref List value) + { + reader.ReadValueSafe(out bool isNull); + if (isNull) + { + value = null; + } + else + { + if (value == null) + { + value = new List(); + } + + ByteUnpacker.ReadValuePacked(reader, out int len); + if (len < value.Count) + { + value.RemoveRange(len, value.Count - len); + } + + for (var i = 0; i < len; ++i) + { + // Read in place where possible + if (i < value.Count) + { + var item = value[i]; + NetworkVariableSerialization.Read(reader, ref item); + value[i] = item; + } + else + { + T item = default; + NetworkVariableSerialization.Read(reader, ref item); + value.Add(item); + } + } + } + } + + public void WriteDelta(FastBufferWriter writer, ref List value, ref List previousValue) + { + CollectionSerializationUtility.WriteListDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref List value) + { + CollectionSerializationUtility.ReadListDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out List value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in List value, ref List duplicatedValue) + { + if (duplicatedValue == null) + { + duplicatedValue = new List(); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item); + } + } + } + + internal class HashSetSerializer : INetworkVariableSerializer> where T : IEquatable + { + public void Write(FastBufferWriter writer, ref HashSet value) + { + var isNull = value == null; + writer.WriteValueSafe(isNull); + if (!isNull) + { + writer.WriteValueSafe(value.Count); + foreach (var item in value) + { + var reffable = item; + NetworkVariableSerialization.Write(writer, ref reffable); + } + } + } + + + public void Read(FastBufferReader reader, ref HashSet value) + { + reader.ReadValueSafe(out bool isNull); + if (isNull) + { + value = null; + } + else + { + if (value == null) + { + value = new HashSet(); + } + else + { + value.Clear(); + } + + reader.ReadValueSafe(out int len); + for (var i = 0; i < len; ++i) + { + T item = default; + NetworkVariableSerialization.Read(reader, ref item); + value.Add(item); + } + } + } + + public void WriteDelta(FastBufferWriter writer, ref HashSet value, ref HashSet previousValue) + { + CollectionSerializationUtility.WriteHashSetDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref HashSet value) + { + CollectionSerializationUtility.ReadHashSetDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out HashSet value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in HashSet value, ref HashSet duplicatedValue) + { + if (duplicatedValue == null) + { + duplicatedValue = new HashSet(); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item); + } + } + } + + + internal class DictionarySerializer : INetworkVariableSerializer> + where TKey : IEquatable + { + public void Write(FastBufferWriter writer, ref Dictionary value) + { + var isNull = value == null; + writer.WriteValueSafe(isNull); + if (!isNull) + { + writer.WriteValueSafe(value.Count); + foreach (var item in value) + { + var (key, val) = (item.Key, item.Value); + NetworkVariableSerialization.Write(writer, ref key); + NetworkVariableSerialization.Write(writer, ref val); + } + } + } + + public void Read(FastBufferReader reader, ref Dictionary value) + { + reader.ReadValueSafe(out bool isNull); + if (isNull) + { + value = null; + } + else + { + if (value == null) + { + value = new Dictionary(); + } + else + { + value.Clear(); + } + + reader.ReadValueSafe(out int len); + for (var i = 0; i < len; ++i) + { + (TKey key, TVal val) = (default, default); + NetworkVariableSerialization.Read(reader, ref key); + NetworkVariableSerialization.Read(reader, ref val); + value.Add(key, val); + } + } + } + + public void WriteDelta(FastBufferWriter writer, ref Dictionary value, ref Dictionary previousValue) + { + CollectionSerializationUtility.WriteDictionaryDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref Dictionary value) + { + CollectionSerializationUtility.ReadDictionaryDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out Dictionary value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in Dictionary value, ref Dictionary duplicatedValue) + { + if (duplicatedValue == null) + { + duplicatedValue = new Dictionary(); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item.Key, item.Value); + } + } + } + + internal class UnmanagedArraySerializer : INetworkVariableSerializer> where T : unmanaged + { + public void Write(FastBufferWriter writer, ref NativeArray value) + { + writer.WriteUnmanagedSafe(value); + } + + public void Read(FastBufferReader reader, ref NativeArray value) + { + value.Dispose(); + reader.ReadUnmanagedSafe(out value, Allocator.Persistent); + } + + public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) + { + CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref NativeArray value) + { + CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator) + { + reader.ReadUnmanagedSafe(out value, allocator); + } + + public void Duplicate(in NativeArray value, ref NativeArray duplicatedValue) + { + if (!duplicatedValue.IsCreated || duplicatedValue.Length != value.Length) + { + if (duplicatedValue.IsCreated) + { + duplicatedValue.Dispose(); + } + + duplicatedValue = new NativeArray(value.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); + } + + duplicatedValue.CopyFrom(value); + } + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + internal class UnmanagedListSerializer : INetworkVariableSerializer> where T : unmanaged + { + public void Write(FastBufferWriter writer, ref NativeList value) + { + writer.WriteUnmanagedSafe(value); + } + + public void Read(FastBufferReader reader, ref NativeList value) + { + reader.ReadUnmanagedSafeInPlace(ref value); + } + + public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) + { + CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref NativeList value) + { + CollectionSerializationUtility.ReadNativeListDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in NativeList value, ref NativeList duplicatedValue) + { + if (!duplicatedValue.IsCreated) + { + duplicatedValue = new NativeList(value.Length, Allocator.Persistent); + } + else if (value.Length != duplicatedValue.Length) + { + duplicatedValue.ResizeUninitialized(value.Length); + } + + duplicatedValue.CopyFrom(value); + } + } + + + internal class NativeHashSetSerializer : INetworkVariableSerializer> where T : unmanaged, IEquatable + { + public void Write(FastBufferWriter writer, ref NativeHashSet value) + { + writer.WriteValueSafe(value); + } + + public void Read(FastBufferReader reader, ref NativeHashSet value) + { + reader.ReadValueSafeInPlace(ref value); + } + + public void WriteDelta(FastBufferWriter writer, ref NativeHashSet value, ref NativeHashSet previousValue) + { + CollectionSerializationUtility.WriteNativeHashSetDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref NativeHashSet value) + { + CollectionSerializationUtility.ReadNativeHashSetDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeHashSet value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in NativeHashSet value, ref NativeHashSet duplicatedValue) + { + if (!duplicatedValue.IsCreated) + { + duplicatedValue = new NativeHashSet(value.Capacity, Allocator.Persistent); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item); + } + } + } + + + internal class NativeHashMapSerializer : INetworkVariableSerializer> + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + public void Write(FastBufferWriter writer, ref NativeHashMap value) + { + writer.WriteValueSafe(value); + } + + public void Read(FastBufferReader reader, ref NativeHashMap value) + { + reader.ReadValueSafeInPlace(ref value); + } + + public void WriteDelta(FastBufferWriter writer, ref NativeHashMap value, ref NativeHashMap previousValue) + { + CollectionSerializationUtility.WriteNativeHashMapDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref NativeHashMap value) + { + CollectionSerializationUtility.ReadNativeHashMapDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeHashMap value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in NativeHashMap value, ref NativeHashMap duplicatedValue) + { + if (!duplicatedValue.IsCreated) + { + duplicatedValue = new NativeHashMap(value.Capacity, Allocator.Persistent); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item.Key, item.Value); + } + } + } +#endif + + /// + /// Serializer for FixedStrings + /// + /// + internal class FixedStringSerializer : INetworkVariableSerializer where T : unmanaged, INativeList, IUTF8Bytes + { + // The item type can only be bytes for fixedStrings, so the DA runtime doesn't need details on it + + public void Write(FastBufferWriter writer, ref T value) + { + writer.WriteValueSafe(value); + } + + public void Read(FastBufferReader reader, ref T value) + { + reader.ReadValueSafeInPlace(ref value); + } + + // Because of how strings are generally used, it is likely that most strings will still write as full strings + // instead of deltas. This actually adds one byte to the data to encode that it was serialized in full. + // But the potential savings from a small change to a large string are valuable enough to be worth that extra + // byte. + public unsafe void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + using var changes = new ResizableBitVector(Allocator.Temp); + var 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.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() * numChanges > FastBufferWriter.GetWriteSize() * value.Length) + { + // If there are too many changes, send the entire array. + writer.WriteByteSafe(1); // Flag that we're sending the entire array + writer.WriteValueSafe(value); + return; + } + + writer.WriteByte(0); // Flag that we're sending a delta + BytePacker.WriteValuePacked(writer, value.Length); + writer.WriteValueSafe(changes); + var ptr = value.GetUnsafePtr(); + var prevPtr = previousValue.GetUnsafePtr(); + for (var i = 0; i < value.Length; ++i) + { + if (changes.IsSet(i)) + { + if (i < previousValue.Length) + { + NetworkVariableSerialization.WriteDelta(writer, ref ptr[i], ref prevPtr[i]); + } + else + { + NetworkVariableSerialization.Write(writer, ref ptr[i]); + } + } + } + } + + public unsafe void ReadDelta(FastBufferReader reader, ref T value) + { + // Writing can use the NativeArray logic as it is, but reading is a little different. + // Using the NativeArray logic for reading would result in length changes allocating a new NativeArray, + // which is not what we want for FixedString. With FixedString, the actual size of the data does not change, + // only an in-memory "length" value - so if the length changes, the only thing we want to do is change + // that value, and otherwise read everything in-place. + reader.ReadByteSafe(out var 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); + + value.Length = length; + + var ptr = value.GetUnsafePtr(); + for (var i = 0; i < value.Length; ++i) + { + if (changes.IsSet(i)) + { + reader.ReadByte(out ptr[i]); + } + } + } + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in T value, ref T duplicatedValue) + { + duplicatedValue = value; + } + } + + /// + /// Serializer for FixedStrings + /// + /// + internal class FixedStringArraySerializer : INetworkVariableSerializer> where T : unmanaged, INativeList, IUTF8Bytes + { + public void Write(FastBufferWriter writer, ref NativeArray value) + { + writer.WriteValueSafe(value); + } + + public void Read(FastBufferReader reader, ref NativeArray value) + { + value.Dispose(); + reader.ReadValueSafe(out value, Allocator.Persistent); + } + + + public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) + { + CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref NativeArray value) + { + CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator) + { + reader.ReadValueSafe(out value, allocator); + } + + public void Duplicate(in NativeArray value, ref NativeArray duplicatedValue) + { + if (!duplicatedValue.IsCreated || duplicatedValue.Length != value.Length) + { + if (duplicatedValue.IsCreated) + { + duplicatedValue.Dispose(); + } + + duplicatedValue = new NativeArray(value.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); + } + + duplicatedValue.CopyFrom(value); + } + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + /// + /// Serializer for FixedStrings + /// + /// + internal class FixedStringListSerializer : INetworkVariableSerializer> where T : unmanaged, INativeList, IUTF8Bytes + { + public void Write(FastBufferWriter writer, ref NativeList value) + { + writer.WriteValueSafe(value); + } + + public void Read(FastBufferReader reader, ref NativeList value) + { + reader.ReadValueSafeInPlace(ref value); + } + + public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) + { + CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref NativeList value) + { + CollectionSerializationUtility.ReadNativeListDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in NativeList value, ref NativeList duplicatedValue) + { + if (!duplicatedValue.IsCreated) + { + duplicatedValue = new NativeList(value.Length, Allocator.Persistent); + } + else if (value.Length != duplicatedValue.Length) + { + duplicatedValue.ResizeUninitialized(value.Length); + } + + duplicatedValue.CopyFrom(value); + } + } +#endif + + /// + /// Serializer for unmanaged INetworkSerializable types + /// + /// + internal class UnmanagedNetworkSerializableSerializer : INetworkVariableSerializer where T : unmanaged, INetworkSerializable + { + public void Write(FastBufferWriter writer, ref T value) + { + var bufferSerializer = new BufferSerializer(new BufferSerializerWriter(writer)); + value.NetworkSerialize(bufferSerializer); + } + + public void Read(FastBufferReader reader, ref T value) + { + var bufferSerializer = new BufferSerializer(new BufferSerializerReader(reader)); + value.NetworkSerialize(bufferSerializer); + } + + public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) + { + UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue); + return; + } + + Write(writer, ref value); + } + + public void ReadDelta(FastBufferReader reader, ref T value) + { + if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) + { + UserNetworkVariableSerialization.ReadDelta(reader, ref value); + return; + } + + Read(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in T value, ref T duplicatedValue) + { + duplicatedValue = value; + } + } + + + /// + /// Serializer for unmanaged INetworkSerializable types + /// + /// + internal class UnmanagedNetworkSerializableArraySerializer : INetworkVariableSerializer> where T : unmanaged, INetworkSerializable + { + public void Write(FastBufferWriter writer, ref NativeArray value) + { + writer.WriteNetworkSerializable(value); + } + + public void Read(FastBufferReader reader, ref NativeArray value) + { + value.Dispose(); + reader.ReadNetworkSerializable(out value, Allocator.Persistent); + } + + + public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) + { + CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref NativeArray value) + { + CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator) + { + reader.ReadNetworkSerializable(out value, allocator); + } + + public void Duplicate(in NativeArray value, ref NativeArray duplicatedValue) + { + if (!duplicatedValue.IsCreated || duplicatedValue.Length != value.Length) + { + if (duplicatedValue.IsCreated) + { + duplicatedValue.Dispose(); + } + + duplicatedValue = new NativeArray(value.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); + } + + duplicatedValue.CopyFrom(value); + } + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + /// + /// Serializer for unmanaged INetworkSerializable types + /// + /// + internal class UnmanagedNetworkSerializableListSerializer : INetworkVariableSerializer> where T : unmanaged, INetworkSerializable + { + public void Write(FastBufferWriter writer, ref NativeList value) + { + writer.WriteNetworkSerializable(value); + } + + public void Read(FastBufferReader reader, ref NativeList value) + { + reader.ReadNetworkSerializableInPlace(ref value); + } + + public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) + { + CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref NativeList value) + { + CollectionSerializationUtility.ReadNativeListDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in NativeList value, ref NativeList duplicatedValue) + { + if (!duplicatedValue.IsCreated) + { + duplicatedValue = new NativeList(value.Length, Allocator.Persistent); + } + else if (value.Length != duplicatedValue.Length) + { + duplicatedValue.ResizeUninitialized(value.Length); + } + + duplicatedValue.CopyFrom(value); + } + } +#endif + + /// + /// Serializer for managed INetworkSerializable types, which differs from the unmanaged implementation in that it + /// has to be null-aware + /// + internal class ManagedNetworkSerializableSerializer : INetworkVariableSerializer where T : class, INetworkSerializable, new() + { + public void Write(FastBufferWriter writer, ref T value) + { + var bufferSerializer = new BufferSerializer(new BufferSerializerWriter(writer)); + var isNull = value == null; + bufferSerializer.SerializeValue(ref isNull); + if (!isNull) + { + value.NetworkSerialize(bufferSerializer); + } + } + + public void Read(FastBufferReader reader, ref T value) + { + var bufferSerializer = new BufferSerializer(new BufferSerializerReader(reader)); + var isNull = false; + bufferSerializer.SerializeValue(ref isNull); + if (isNull) + { + value = null; + } + else + { + if (value == null) + { + value = new T(); + } + + value.NetworkSerialize(bufferSerializer); + } + } + + public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) + { + UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue); + return; + } + + Write(writer, ref value); + } + + public void ReadDelta(FastBufferReader reader, ref T value) + { + if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) + { + UserNetworkVariableSerialization.ReadDelta(reader, ref value); + return; + } + + Read(reader, ref value); + } + + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) + { + throw new NotImplementedException(); + } + + + public void Duplicate(in T value, ref T duplicatedValue) + { + using var writer = new FastBufferWriter(256, Allocator.Temp, int.MaxValue); + var refValue = value; + Write(writer, ref refValue); + + using var reader = new FastBufferReader(writer, Allocator.None); + Read(reader, ref duplicatedValue); + } + } +} diff --git a/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs.meta b/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs.meta new file mode 100644 index 0000000..e430403 --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bbfa170e9dd448bbbe381ce38d5c139d +timeCreated: 1718216671 \ No newline at end of file diff --git a/Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs b/Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs new file mode 100644 index 0000000..c39ca0f --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs @@ -0,0 +1,73 @@ +namespace Unity.Netcode +{ + /// + /// 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) + /// + /// + public class UserNetworkVariableSerialization + { + /// + /// The write value delegate handler definition + /// + /// The to write the value of type `T` + /// The value of type `T` to be written + public delegate void WriteValueDelegate(FastBufferWriter writer, in T value); + + /// + /// The write value delegate handler definition + /// + /// The to write the value of type `T` + /// The value of type `T` to be written + public delegate void WriteDeltaDelegate(FastBufferWriter writer, in T value, in T previousValue); + + /// + /// The read value delegate handler definition + /// + /// The to read the value of type `T` + /// The value of type `T` to be read + public delegate void ReadValueDelegate(FastBufferReader reader, out T value); + + /// + /// The read value delegate handler definition + /// + /// The to read the value of type `T` + /// The value of type `T` to be read + public delegate void ReadDeltaDelegate(FastBufferReader reader, ref T value); + + /// + /// The read value delegate handler definition + /// + /// The to read the value of type `T` + /// The value of type `T` to be read + public delegate void DuplicateValueDelegate(in T value, ref T duplicatedValue); + + /// + /// Callback to write a value + /// + public static WriteValueDelegate WriteValue; + + /// + /// Callback to read a value + /// + public static ReadValueDelegate ReadValue; + + /// + /// Callback to write a delta between two values, based on computing the difference between the previous and + /// current values. + /// + public static WriteDeltaDelegate WriteDelta; + + /// + /// Callback to read a delta, applying only select changes to the current value. + /// + public static ReadDeltaDelegate ReadDelta; + + /// + /// Callback to create a duplicate of a value, used to check for dirty status. + /// + public static DuplicateValueDelegate DuplicateValue; + } +} diff --git a/Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs.meta b/Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs.meta new file mode 100644 index 0000000..a21252a --- /dev/null +++ b/Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b295a6756640488b9824d2ec6e26ddae +timeCreated: 1718218272 \ No newline at end of file diff --git a/Runtime/Serialization/FastBufferReader.cs b/Runtime/Serialization/FastBufferReader.cs index c2cfc13..3612855 100644 --- a/Runtime/Serialization/FastBufferReader.cs +++ b/Runtime/Serialization/FastBufferReader.cs @@ -523,8 +523,8 @@ public void ReadNetworkSerializableInPlace(ref T value) where T : INetworkSer /// Whether or not to use one byte per character. This will only allow ASCII public unsafe void ReadValue(out string s, bool oneByteChars = false) { - ReadValue(out uint length); - s = "".PadRight((int)length); + ReadLength(out int length); + s = "".PadRight(length); int target = s.Length; fixed (char* native = s) { @@ -562,18 +562,18 @@ public unsafe void ReadValueSafe(out string s, bool oneByteChars = false) } #endif - if (!TryBeginReadInternal(sizeof(uint))) + if (!TryBeginReadInternal(SizeOfLengthField())) { throw new OverflowException("Reading past the end of the buffer"); } - ReadValue(out uint length); + ReadLength(out int length); - if (!TryBeginReadInternal((int)length * (oneByteChars ? 1 : sizeof(char)))) + if (!TryBeginReadInternal(length * (oneByteChars ? 1 : sizeof(char)))) { throw new OverflowException("Reading past the end of the buffer"); } - s = "".PadRight((int)length); + s = "".PadRight(length); int target = s.Length; fixed (char* native = s) { @@ -592,6 +592,33 @@ public unsafe void ReadValueSafe(out string s, bool oneByteChars = false) } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int SizeOfLengthField() => sizeof(uint); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReadLengthSafe(out uint length) => ReadUnmanagedSafe(out length); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReadLength(out uint length) => ReadUnmanaged(out length); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReadLengthSafe(out int length) + { + ReadLengthSafe(out uint temp); + if (temp > int.MaxValue) + { + throw new InvalidCastException("length value outside of int32 range"); + } + length = (int)temp; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReadLength(out int length) + { + ReadLength(out uint temp); + length = (int)temp; + } + /// /// Read a partial value. The value is zero-initialized and then the specified number of bytes is read into it. /// @@ -777,7 +804,7 @@ internal unsafe void ReadUnmanagedSafe(out T value) where T : unmanaged [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void ReadUnmanaged(out T[] value) where T : unmanaged { - ReadUnmanaged(out int sizeInTs); + ReadLength(out int sizeInTs); int sizeInBytes = sizeInTs * sizeof(T); value = new T[sizeInTs]; fixed (T* ptr = value) @@ -789,7 +816,7 @@ internal unsafe void ReadUnmanaged(out T[] value) where T : unmanaged [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void ReadUnmanagedSafe(out T[] value) where T : unmanaged { - ReadUnmanagedSafe(out int sizeInTs); + ReadLengthSafe(out int sizeInTs); int sizeInBytes = sizeInTs * sizeof(T); value = new T[sizeInTs]; fixed (T* ptr = value) @@ -801,7 +828,7 @@ internal unsafe void ReadUnmanagedSafe(out T[] value) where T : unmanaged [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void ReadUnmanaged(out NativeArray value, Allocator allocator) where T : unmanaged { - ReadUnmanaged(out int sizeInTs); + ReadLength(out int sizeInTs); int sizeInBytes = sizeInTs * sizeof(T); value = new NativeArray(sizeInTs, allocator); byte* bytes = (byte*)value.GetUnsafePtr(); @@ -810,7 +837,7 @@ internal unsafe void ReadUnmanaged(out NativeArray value, Allocator alloca [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void ReadUnmanagedSafe(out NativeArray value, Allocator allocator) where T : unmanaged { - ReadUnmanagedSafe(out int sizeInTs); + ReadLengthSafe(out int sizeInTs); int sizeInBytes = sizeInTs * sizeof(T); value = new NativeArray(sizeInTs, allocator); byte* bytes = (byte*)value.GetUnsafePtr(); @@ -820,7 +847,7 @@ internal unsafe void ReadUnmanagedSafe(out NativeArray value, Allocator al [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void ReadUnmanagedInPlace(ref NativeList value) where T : unmanaged { - ReadUnmanaged(out int sizeInTs); + ReadLength(out int sizeInTs); int sizeInBytes = sizeInTs * sizeof(T); value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory); byte* bytes = (byte*)value.GetUnsafePtr(); @@ -829,7 +856,7 @@ internal unsafe void ReadUnmanagedInPlace(ref NativeList value) where T : [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void ReadUnmanagedSafeInPlace(ref NativeList value) where T : unmanaged { - ReadUnmanagedSafe(out int sizeInTs); + ReadLengthSafe(out int sizeInTs); int sizeInBytes = sizeInTs * sizeof(T); value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory); byte* bytes = (byte*)value.GetUnsafePtr(); @@ -1078,7 +1105,7 @@ public void ReadValueSafeInPlace(ref NativeList value, FastBufferWriter.Fo [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ReadValueSafeInPlace(ref NativeHashSet value) where T : unmanaged, IEquatable { - ReadUnmanagedSafe(out int length); + ReadLengthSafe(out int length); value.Clear(); for (var i = 0; i < length; ++i) { @@ -1093,7 +1120,7 @@ internal void ReadValueSafeInPlace(ref NativeHashMap val where TKey : unmanaged, IEquatable where TVal : unmanaged { - ReadUnmanagedSafe(out int length); + ReadLengthSafe(out int length); value.Clear(); for (var i = 0; i < length; ++i) { @@ -1553,7 +1580,7 @@ internal void ReadValueSafeInPlace(ref NativeHashMap val /// This method is a little difficult to use, since you have to know the size of the string before /// reading it, but is useful when the string is a known, fixed size. Note that the size of the /// string is also encoded, so the size to call TryBeginRead on is actually the fixed size (in bytes) - /// plus sizeof(int) + /// plus sizeof(uint) /// /// the value to read /// An unused parameter used for enabling overload resolution based on generic constraints @@ -1562,7 +1589,7 @@ internal void ReadValueSafeInPlace(ref NativeHashMap val public unsafe void ReadValue(out T value, FastBufferWriter.ForFixedStrings unused = default) where T : unmanaged, INativeList, IUTF8Bytes { - ReadUnmanaged(out int length); + ReadLength(out int length); value = new T { Length = length @@ -1584,7 +1611,7 @@ public unsafe void ReadValue(out T value, FastBufferWriter.ForFixedStrings un public unsafe void ReadValueSafe(out T value, FastBufferWriter.ForFixedStrings unused = default) where T : unmanaged, INativeList, IUTF8Bytes { - ReadUnmanagedSafe(out int length); + ReadLengthSafe(out int length); value = new T { Length = length @@ -1606,7 +1633,7 @@ public unsafe void ReadValueSafe(out T value, FastBufferWriter.ForFixedString public unsafe void ReadValueSafeInPlace(ref T value, FastBufferWriter.ForFixedStrings unused = default) where T : unmanaged, INativeList, IUTF8Bytes { - ReadUnmanagedSafe(out int length); + ReadLengthSafe(out int length); value.Length = length; ReadBytesSafe(value.GetUnsafePtr(), length); } @@ -1625,7 +1652,7 @@ public unsafe void ReadValueSafeInPlace(ref T value, FastBufferWriter.ForFixe public unsafe void ReadValueSafe(out NativeArray value, Allocator allocator) where T : unmanaged, INativeList, IUTF8Bytes { - ReadUnmanagedSafe(out int length); + ReadLengthSafe(out int length); value = new NativeArray(length, allocator); var ptr = (T*)value.GetUnsafePtr(); for (var i = 0; i < length; ++i) @@ -1647,7 +1674,7 @@ public unsafe void ReadValueSafe(out NativeArray value, Allocator allocato public unsafe void ReadValueSafeTemp(out NativeArray value) where T : unmanaged, INativeList, IUTF8Bytes { - ReadUnmanagedSafe(out int length); + ReadLengthSafe(out int length); value = new NativeArray(length, Allocator.Temp); var ptr = (T*)value.GetUnsafePtr(); for (var i = 0; i < length; ++i) @@ -1669,7 +1696,7 @@ public unsafe void ReadValueSafeTemp(out NativeArray value) public void ReadValueSafe(out T[] value, FastBufferWriter.ForFixedStrings unused = default) where T : unmanaged, INativeList, IUTF8Bytes { - ReadUnmanagedSafe(out int length); + ReadLengthSafe(out int length); value = new T[length]; for (var i = 0; i < length; ++i) { @@ -1691,7 +1718,7 @@ public void ReadValueSafe(out T[] value, FastBufferWriter.ForFixedStrings unu public void ReadValueSafeInPlace(ref NativeList value) where T : unmanaged, INativeList, IUTF8Bytes { - ReadUnmanagedSafe(out int length); + ReadLengthSafe(out int length); value.Resize(length, NativeArrayOptions.UninitializedMemory); for (var i = 0; i < length; ++i) { diff --git a/Runtime/Serialization/FastBufferWriter.cs b/Runtime/Serialization/FastBufferWriter.cs index a686540..b2a43a0 100644 --- a/Runtime/Serialization/FastBufferWriter.cs +++ b/Runtime/Serialization/FastBufferWriter.cs @@ -421,7 +421,7 @@ internal unsafe ArraySegment ToTempByteArray() [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetWriteSize(string s, bool oneByteChars = false) { - return sizeof(int) + s.Length * (oneByteChars ? sizeof(byte) : sizeof(char)); + return SizeOfLengthField() + s.Length * (oneByteChars ? sizeof(byte) : sizeof(char)); } /// @@ -445,7 +445,7 @@ public void WriteNetworkSerializable(in T value) where T : INetworkSerializab public void WriteNetworkSerializable(T[] array, int count = -1, int offset = 0) where T : INetworkSerializable { int sizeInTs = count != -1 ? count : array.Length - offset; - WriteValueSafe(sizeInTs); + WriteLengthSafe(sizeInTs); foreach (var item in array) { WriteNetworkSerializable(item); @@ -462,7 +462,7 @@ public void WriteNetworkSerializable(T[] array, int count = -1, int offset = public void WriteNetworkSerializable(NativeArray array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable { int sizeInTs = count != -1 ? count : array.Length - offset; - WriteValueSafe(sizeInTs); + WriteLengthSafe(sizeInTs); foreach (var item in array) { WriteNetworkSerializable(item); @@ -480,7 +480,7 @@ public void WriteNetworkSerializable(NativeArray array, int count = -1, in public void WriteNetworkSerializable(NativeList array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable { int sizeInTs = count != -1 ? count : array.Length - offset; - WriteValueSafe(sizeInTs); + WriteLengthSafe(sizeInTs); foreach (var item in array) { WriteNetworkSerializable(item); @@ -495,7 +495,7 @@ public void WriteNetworkSerializable(NativeList array, int count = -1, int /// Whether or not to use one byte per character. This will only allow ASCII public unsafe void WriteValue(string s, bool oneByteChars = false) { - WriteValue((uint)s.Length); + WriteLength((uint)s.Length); int target = s.Length; if (oneByteChars) { @@ -538,7 +538,7 @@ public unsafe void WriteValueSafe(string s, bool oneByteChars = false) throw new OverflowException("Writing past the end of the buffer"); } - WriteValue((uint)s.Length); + WriteLength((uint)s.Length); int target = s.Length; if (oneByteChars) { @@ -569,7 +569,7 @@ public static unsafe int GetWriteSize(T[] array, int count = -1, int offset = { int sizeInTs = count != -1 ? count : array.Length - offset; int sizeInBytes = sizeInTs * sizeof(T); - return sizeof(int) + sizeInBytes; + return SizeOfLengthField() + sizeInBytes; } /// @@ -585,7 +585,7 @@ public static unsafe int GetWriteSize(NativeArray array, int count = -1, i { int sizeInTs = count != -1 ? count : array.Length - offset; int sizeInBytes = sizeInTs * sizeof(T); - return sizeof(int) + sizeInBytes; + return SizeOfLengthField() + sizeInBytes; } #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT @@ -602,7 +602,7 @@ public static unsafe int GetWriteSize(NativeList array, int count = -1, in { int sizeInTs = count != -1 ? count : array.Length - offset; int sizeInBytes = sizeInTs * sizeof(T); - return sizeof(int) + sizeInBytes; + return SizeOfLengthField() + sizeInBytes; } #endif @@ -876,7 +876,7 @@ public static unsafe int GetWriteSize(in T value, ForStructs unused = default public static int GetWriteSize(in T value) where T : unmanaged, INativeList, IUTF8Bytes { - return value.Length + sizeof(int); + return SizeOfLengthField() + value.Length; } /// @@ -888,10 +888,10 @@ public static int GetWriteSize(in T value) public static int GetWriteSize(in NativeArray value) where T : unmanaged, INativeList, IUTF8Bytes { - var size = sizeof(int); + var size = SizeOfLengthField(); foreach (var item in value) { - size += sizeof(int) + item.Length; + size += SizeOfLengthField() + item.Length; } return size; @@ -907,10 +907,10 @@ public static int GetWriteSize(in NativeArray value) public static int GetWriteSize(in NativeList value) where T : unmanaged, INativeList, IUTF8Bytes { - var size = sizeof(int); + var size = SizeOfLengthField(); foreach (var item in value) { - size += sizeof(int) + item.Length; + size += SizeOfLengthField() + item.Length; } return size; @@ -946,10 +946,32 @@ internal unsafe void WriteUnmanagedSafe(in T value) where T : unmanaged } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int SizeOfLengthField() => sizeof(uint); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteLengthSafe(uint length) => WriteUnmanagedSafe(length); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteLength(uint length) => WriteUnmanaged(length); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteLengthSafe(int length) + { + if (length < 0) + { + throw new InvalidCastException("Cannot write negative length"); + } + WriteLengthSafe((uint)length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void WriteLength(int length) => WriteLength((uint)length); + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void WriteUnmanaged(T[] value) where T : unmanaged { - WriteUnmanaged(value.Length); + WriteLength(value.Length); fixed (T* ptr = value) { byte* bytes = (byte*)ptr; @@ -959,7 +981,7 @@ internal unsafe void WriteUnmanaged(T[] value) where T : unmanaged [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void WriteUnmanagedSafe(T[] value) where T : unmanaged { - WriteUnmanagedSafe(value.Length); + WriteLengthSafe(value.Length); fixed (T* ptr = value) { byte* bytes = (byte*)ptr; @@ -970,7 +992,7 @@ internal unsafe void WriteUnmanagedSafe(T[] value) where T : unmanaged [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void WriteUnmanaged(NativeArray value) where T : unmanaged { - WriteUnmanaged(value.Length); + WriteLength(value.Length); var ptr = (T*)value.GetUnsafePtr(); { byte* bytes = (byte*)ptr; @@ -980,7 +1002,7 @@ internal unsafe void WriteUnmanaged(NativeArray value) where T : unmanaged [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void WriteUnmanagedSafe(NativeArray value) where T : unmanaged { - WriteUnmanagedSafe(value.Length); + WriteLengthSafe(value.Length); var ptr = (T*)value.GetUnsafePtr(); { byte* bytes = (byte*)ptr; @@ -992,7 +1014,7 @@ internal unsafe void WriteUnmanagedSafe(NativeArray value) where T : unman [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void WriteUnmanaged(NativeList value) where T : unmanaged { - WriteUnmanaged(value.Length); + WriteLength(value.Length); #if UTP_TRANSPORT_2_0_ABOVE var ptr = value.GetUnsafePtr(); #else @@ -1006,7 +1028,7 @@ internal unsafe void WriteUnmanaged(NativeList value) where T : unmanaged [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void WriteUnmanagedSafe(NativeList value) where T : unmanaged { - WriteUnmanagedSafe(value.Length); + WriteLengthSafe(value.Length); #if UTP_TRANSPORT_2_0_ABOVE var ptr = value.GetUnsafePtr(); #else @@ -1210,9 +1232,9 @@ public void WriteValue(NativeList value, ForGeneric unused = default) wher internal void WriteValueSafe(NativeHashSet value) where T : unmanaged, IEquatable { #if UTP_TRANSPORT_2_0_ABOVE - WriteUnmanagedSafe(value.Count); + WriteLengthSafe(value.Count); #else - WriteUnmanagedSafe(value.Count()); + WriteLengthSafe(value.Count()); #endif foreach (var item in value) { @@ -1227,9 +1249,9 @@ internal void WriteValueSafe(NativeHashMap value) where TVal : unmanaged { #if UTP_TRANSPORT_2_0_ABOVE - WriteUnmanagedSafe(value.Count); + WriteLengthSafe(value.Count); #else - WriteUnmanagedSafe(value.Count()); + WriteLengthSafe(value.Count()); #endif foreach (var item in value) { @@ -1765,7 +1787,8 @@ public void WriteValueSafe(NativeList value, ForGeneric unused = default) public unsafe void WriteValue(in T value, ForFixedStrings unused = default) where T : unmanaged, INativeList, IUTF8Bytes { - WriteUnmanaged(value.Length); + // BytePacker.WriteValuePacked(this, value.Length); + WriteLength(value.Length); // This avoids a copy on the string, which could be costly for FixedString4096Bytes // Otherwise, GetUnsafePtr() is an impure function call and will result in a copy // for `in` parameters. @@ -1787,7 +1810,7 @@ public unsafe void WriteValue(in T value, ForFixedStrings unused = default) public void WriteValue(T[] value, ForFixedStrings unused = default) where T : unmanaged, INativeList, IUTF8Bytes { - WriteUnmanaged(value.Length); + WriteLength(value.Length); foreach (var str in value) { WriteValue(str); @@ -1806,7 +1829,7 @@ public void WriteValue(T[] value, ForFixedStrings unused = default) public void WriteValue(in NativeArray value, ForFixedStrings unused = default) where T : unmanaged, INativeList, IUTF8Bytes { - WriteUnmanaged(value.Length); + WriteLength(value.Length); foreach (var str in value) { WriteValue(str); @@ -1826,7 +1849,7 @@ public void WriteValue(in NativeArray value, ForFixedStrings unused = defa public void WriteValue(in NativeList value, ForFixedStrings unused = default) where T : unmanaged, INativeList, IUTF8Bytes { - WriteUnmanaged(value.Length); + WriteLength(value.Length); foreach (var str in value) { WriteValue(str); @@ -1848,7 +1871,7 @@ public void WriteValue(in NativeList value, ForFixedStrings unused = defau public void WriteValueSafe(in T value, ForFixedStrings unused = default) where T : unmanaged, INativeList, IUTF8Bytes { - if (!TryBeginWriteInternal(sizeof(int) + value.Length)) + if (!TryBeginWriteInternal(SizeOfLengthField() + value.Length)) { throw new OverflowException("Writing past the end of the buffer"); } @@ -1871,7 +1894,7 @@ public void WriteValueSafe(T[] value, ForFixedStrings unused = default) { throw new OverflowException("Writing past the end of the buffer"); } - WriteUnmanaged(value.Length); + WriteLength(value.Length); foreach (var str in value) { WriteValue(str); @@ -1894,7 +1917,7 @@ public void WriteValueSafe(in NativeArray value) { throw new OverflowException("Writing past the end of the buffer"); } - WriteUnmanaged(value.Length); + WriteLength(value.Length); foreach (var str in value) { WriteValue(str); @@ -1918,7 +1941,7 @@ public void WriteValueSafe(in NativeList value) { throw new OverflowException("Writing past the end of the buffer"); } - WriteUnmanaged(value.Length); + WriteLength(value.Length); foreach (var str in value) { WriteValue(str); diff --git a/Runtime/Spawning/NetworkSpawnManager.cs b/Runtime/Spawning/NetworkSpawnManager.cs index e021505..0de0da4 100644 --- a/Runtime/Spawning/NetworkSpawnManager.cs +++ b/Runtime/Spawning/NetworkSpawnManager.cs @@ -275,17 +275,17 @@ internal void UpdateOwnershipTable(NetworkObject networkObject, ulong newOwner, } /// - /// Returns a list of all NetworkObjects that belong to a client. + /// Returns an array of all NetworkObjects that belong to a client. /// - /// the client's id - /// returns the list of s owned by the client - public List GetClientOwnedObjects(ulong clientId) + /// the client's id + /// returns an array of the s owned by the client + public NetworkObject[] GetClientOwnedObjects(ulong clientId) { if (!OwnershipToObjectsTable.ContainsKey(clientId)) { OwnershipToObjectsTable.Add(clientId, new Dictionary()); } - return OwnershipToObjectsTable[clientId].Values.ToList(); + return OwnershipToObjectsTable[clientId].Values.ToArray(); } /// diff --git a/Runtime/Transports/NetworkTransport.cs b/Runtime/Transports/NetworkTransport.cs index 9de70af..b624120 100644 --- a/Runtime/Transports/NetworkTransport.cs +++ b/Runtime/Transports/NetworkTransport.cs @@ -106,6 +106,22 @@ protected void InvokeOnTransportEvent(NetworkEvent eventType, ulong clientId, Ar /// /// /// optionally pass in NetworkManager public abstract void Initialize(NetworkManager networkManager = null); + + protected virtual NetworkTopologyTypes OnCurrentTopology() + { + return NetworkTopologyTypes.ClientServer; + } + + internal NetworkTopologyTypes CurrentTopology() + { + return OnCurrentTopology(); + } + } + + public enum NetworkTopologyTypes + { + ClientServer, + DistributedAuthority } #if UNITY_INCLUDE_TESTS diff --git a/Runtime/Transports/UTP/UnityTransport.cs b/Runtime/Transports/UTP/UnityTransport.cs index 6922699..f3d036b 100644 --- a/Runtime/Transports/UTP/UnityTransport.cs +++ b/Runtime/Transports/UTP/UnityTransport.cs @@ -1477,6 +1477,11 @@ private void ConfigureSimulatorForUtp1() } #endif + protected override NetworkTopologyTypes OnCurrentTopology() + { + return NetworkManager != null ? NetworkManager.NetworkConfig.NetworkTopology : NetworkTopologyTypes.ClientServer; + } + private string m_ServerPrivateKey; private string m_ServerCertificate; diff --git a/Runtime/com.unity.netcode.runtime.asmdef b/Runtime/com.unity.netcode.runtime.asmdef index 1577ff0..b76ae6f 100644 --- a/Runtime/com.unity.netcode.runtime.asmdef +++ b/Runtime/com.unity.netcode.runtime.asmdef @@ -15,7 +15,13 @@ "Unity.Burst", "Unity.Mathematics" ], + "includePlatforms": [], + "excludePlatforms": [], "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], "versionDefines": [ { "name": "com.unity.multiplayer.tools", @@ -61,6 +67,12 @@ "name": "com.unity.modules.physics2d", "expression": "", "define": "COM_UNITY_MODULES_PHYSICS2D" + }, + { + "name": "com.unity.services.multiplayer", + "expression": "0.2.0", + "define": "MULTIPLAYER_SERVICES_SDK_INSTALLED" } - ] -} + ], + "noEngineReferences": false +} \ No newline at end of file diff --git a/TestHelpers/Runtime/MockTransport.cs b/TestHelpers/Runtime/MockTransport.cs index 1bfc130..4ff644e 100644 --- a/TestHelpers/Runtime/MockTransport.cs +++ b/TestHelpers/Runtime/MockTransport.cs @@ -81,6 +81,11 @@ public override void Shutdown() { } + protected override NetworkTopologyTypes OnCurrentTopology() + { + return NetworkManager != null ? NetworkManager.NetworkConfig.NetworkTopology : NetworkTopologyTypes.ClientServer; + } + public override void Initialize(NetworkManager networkManager = null) { NetworkManager = networkManager; diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs index f1f6e53..faf4402 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs @@ -358,7 +358,7 @@ private bool AllClientsHaveCorrectObjectCount() foreach (var clientNetworkManager in m_ClientNetworkManagers) { - if (clientNetworkManager.LocalClient.OwnedObjects.Count < k_NumberOfSpawnedObjects) + if (clientNetworkManager.LocalClient.OwnedObjects.Length < k_NumberOfSpawnedObjects) { return false; } @@ -372,7 +372,7 @@ private bool ServerHasCorrectClientOwnedObjectCount() // Only check when we are the host if (m_ServerNetworkManager.IsHost) { - if (m_ServerNetworkManager.LocalClient.OwnedObjects.Count < k_NumberOfSpawnedObjects) + if (m_ServerNetworkManager.LocalClient.OwnedObjects.Length < k_NumberOfSpawnedObjects) { return false; } @@ -380,7 +380,7 @@ private bool ServerHasCorrectClientOwnedObjectCount() foreach (var connectedClient in m_ServerNetworkManager.ConnectedClients) { - if (connectedClient.Value.OwnedObjects.Count < k_NumberOfSpawnedObjects) + if (connectedClient.Value.OwnedObjects.Length < k_NumberOfSpawnedObjects) { return false; } diff --git a/package.json b/package.json index 1c92939..74a942e 100644 --- a/package.json +++ b/package.json @@ -2,23 +2,23 @@ "name": "com.unity.netcode.gameobjects", "displayName": "Netcode for GameObjects", "description": "Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.", - "version": "2.0.0-exp.5", + "version": "2.0.0-pre.1", "unity": "6000.0", "dependencies": { "com.unity.nuget.mono-cecil": "1.11.4", "com.unity.transport": "2.2.1" }, "_upm": { - "changelog": "### Fixed\n\n- Fixed issue where SessionOwner message was being treated as a new entry for the new message indexing when it should have been ordinally sorted with the legacy message indices. (#2942)" + "changelog": "### Added\n\n- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)\n- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)\n- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)\n\n### Fixed\n\n- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)\n- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)\n- 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)\n\n### Changed\n\n- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)\n- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)\n- 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)" }, "upmCi": { - "footprint": "a38ece4dabc6c27e6618262e980d5de89bbda2e8" + "footprint": "18101c69b1634ca6a71617efbaf53473b389e8ec" }, "documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.0/manual/index.html", "repository": { "url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git", "type": "git", - "revision": "79e8fc8634b961f05fbc3f79e82d57c8f131c715" + "revision": "ba4102f8ded1ed3f18c5b0604bd39a846437e9b6" }, "samples": [ {