From 8990cb4253616af41dcf9f70b581f91c0ff52b2d Mon Sep 17 00:00:00 2001 From: "M. Fatih MAR" Date: Wed, 18 Aug 2021 00:31:45 +0100 Subject: [PATCH 01/25] refactor!: convert NetworkTransform.NetworkState to `struct` --- .../Prototyping/NetworkTransform.cs | 18 +---- .../NetworkVariable/NetworkVariable.cs | 8 ++ .../NetworkTransformStateTests.cs | 80 +++++++++---------- 3 files changed, 52 insertions(+), 54 deletions(-) diff --git a/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs b/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs index 2d6b6f153a..0132d24e16 100644 --- a/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs +++ b/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.Prototyping [AddComponentMenu("Netcode/" + nameof(NetworkTransform))] public class NetworkTransform : NetworkBehaviour { - internal class NetworkState : INetworkSerializable + internal struct NetworkState : INetworkSerializable { internal const int InLocalSpaceBit = 0; internal const int PositionXBit = 1; @@ -161,13 +161,8 @@ public void NetworkSerialize(NetworkSerializer serializer) // updates `NetworkState` properties if they need to and returns a `bool` indicating whether or not there was any changes made // returned boolean would be useful to change encapsulating `NetworkVariable`'s dirty state, e.g. ReplNetworkState.SetDirty(isDirty); - internal bool UpdateNetworkState(NetworkState networkState) + internal bool UpdateNetworkState(ref NetworkState networkState) { - if (networkState == null) - { - return false; - } - var position = InLocalSpace ? m_Transform.localPosition : m_Transform.position; var rotAngles = InLocalSpace ? m_Transform.localEulerAngles : m_Transform.eulerAngles; var scale = InLocalSpace ? m_Transform.localScale : m_Transform.lossyScale; @@ -376,11 +371,6 @@ private void Awake() ReplNetworkState.OnValueChanged += OnNetworkStateChanged; } - public override void OnNetworkSpawn() - { - PrevNetworkState = null; - } - private void OnDestroy() { ReplNetworkState.OnValueChanged -= OnNetworkStateChanged; @@ -395,12 +385,12 @@ private void FixedUpdate() if (IsServer) { - ReplNetworkState.SetDirty(UpdateNetworkState(ReplNetworkState.Value)); + ReplNetworkState.SetDirty(UpdateNetworkState(ref ReplNetworkState.ValueRef)); } // try to update previously consumed NetworkState // if we have any changes, that means made some updates locally // we apply the latest ReplNetworkState again to revert our changes - else if (UpdateNetworkState(PrevNetworkState)) + else if (UpdateNetworkState(ref PrevNetworkState)) { ApplyNetworkState(ReplNetworkState.Value); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index b1f303292e..57f082da62 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -66,6 +66,14 @@ public NetworkVariable(T value) [SerializeField] private T m_InternalValue; + /// + /// The temporary accessor to enable struct element access until [MTT-1020] complete + /// + public ref T ValueRef + { + get => ref m_InternalValue; + } + /// /// The value of the NetworkVariable container /// diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs index ecb8db4cda..1cae896568 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs @@ -66,7 +66,7 @@ public void TestSyncAxes( networkTransform.transform.eulerAngles = new Vector3(30, 45, 90); networkTransform.transform.localScale = new Vector3(1.1f, 0.5f, 2.5f); - bool isDirty = networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value); + bool isDirty = networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef); networkTransform.ReplNetworkState.SetDirty(isDirty); Assert.IsTrue(isDirty); } @@ -75,7 +75,7 @@ public void TestSyncAxes( { networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - bool isDirty = networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value); + bool isDirty = networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef); Assert.IsFalse(isDirty); } @@ -92,7 +92,7 @@ public void TestSyncAxes( position.x++; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // SyncPositionY { @@ -101,7 +101,7 @@ public void TestSyncAxes( position.y++; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // SyncPositionZ { @@ -110,7 +110,7 @@ public void TestSyncAxes( position.z++; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // SyncRotAngleX @@ -120,7 +120,7 @@ public void TestSyncAxes( rotAngles.x++; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // SyncRotAngleY { @@ -129,7 +129,7 @@ public void TestSyncAxes( rotAngles.y++; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // SyncRotAngleZ { @@ -138,7 +138,7 @@ public void TestSyncAxes( rotAngles.z++; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // SyncScaleX @@ -148,7 +148,7 @@ public void TestSyncAxes( scale.x++; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // SyncScaleY { @@ -157,7 +157,7 @@ public void TestSyncAxes( scale.y++; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // SyncScaleZ { @@ -166,7 +166,7 @@ public void TestSyncAxes( scale.z++; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } } @@ -227,7 +227,7 @@ public void TestThresholds( networkTransform.transform.eulerAngles = new Vector3(30, 45, 90); networkTransform.transform.localScale = new Vector3(1.1f, 0.5f, 2.5f); - bool isDirty = networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value); + bool isDirty = networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef); networkTransform.ReplNetworkState.SetDirty(isDirty); Assert.IsTrue(isDirty); } @@ -236,7 +236,7 @@ public void TestThresholds( { networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - bool isDirty = networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value); + bool isDirty = networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef); Assert.IsFalse(isDirty); } @@ -253,42 +253,42 @@ public void TestThresholds( { position.x += positionThreshold / 2; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); position.x += positionThreshold * 2; networkTransform.transform.position = position; - Assert.IsTrue(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // PositionY { position.y += positionThreshold / 2; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); position.y += positionThreshold * 2; networkTransform.transform.position = position; - Assert.IsTrue(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // PositionZ { position.z += positionThreshold / 2; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); position.z += positionThreshold * 2; networkTransform.transform.position = position; - Assert.IsTrue(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } } @@ -301,42 +301,42 @@ public void TestThresholds( { rotAngles.x += rotAngleThreshold / 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); rotAngles.x += rotAngleThreshold * 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsTrue(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // RotAngleY { rotAngles.y += rotAngleThreshold / 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); rotAngles.y += rotAngleThreshold * 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsTrue(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // RotAngleZ { rotAngles.z += rotAngleThreshold / 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); rotAngles.z += rotAngleThreshold * 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsTrue(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } } @@ -349,42 +349,42 @@ public void TestThresholds( { scale.x += scaleThreshold / 2; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); scale.x += scaleThreshold * 2; networkTransform.transform.localScale = scale; - Assert.IsTrue(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // ScaleY { scale.y += scaleThreshold / 2; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); scale.y += scaleThreshold * 2; networkTransform.transform.localScale = scale; - Assert.IsTrue(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } // ScaleZ { scale.z += scaleThreshold / 2; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); scale.z += scaleThreshold * 2; networkTransform.transform.localScale = scale; - Assert.IsTrue(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(networkTransform.ReplNetworkState.Value)); + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); } } } From a304dcc1f9e2b0c626be9eff7c1bce6e2a75be9b Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Fri, 13 Aug 2021 15:22:46 -0700 Subject: [PATCH 02/25] feat!: remove client network permissions [MTT-1019] --- .../Editor/NetworkBehaviourEditor.cs | 9 +- .../Runtime/Core/NetworkBehaviour.cs | 93 +-------------- .../MessageQueue/MessageQueueProcessor.cs | 5 +- .../Collections/NetworkDictionary.cs | 64 +--------- .../Collections/NetworkList.cs | 64 +--------- .../NetworkVariable/Collections/NetworkSet.cs | 76 +----------- .../NetworkVariable/INetworkVariable.cs | 7 -- .../NetworkVariable/NetworkVariable.cs | 61 +--------- .../NetworkVariablePermission.cs | 25 ++-- .../NetworkVariableSettings.cs | 10 +- .../NetworkVariableTestComponent.cs | 12 +- .../Runtime/Helpers/NetworkVariableHelper.cs | 2 +- .../NetworkTransformTests.cs.meta | 3 - .../Tests/Runtime/NetworkVariableTests.cs | 110 ++++++++---------- .../Profiling/NetworkVariableNameTests.cs | 5 +- testproject/Assets/Scripts/SyncTransform.cs | 6 - .../Tests/Manual/Scripts/BandwidthTest.cs | 2 - 17 files changed, 94 insertions(+), 460 deletions(-) delete mode 100644 com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs.meta diff --git a/com.unity.netcode.gameobjects/Editor/NetworkBehaviourEditor.cs b/com.unity.netcode.gameobjects/Editor/NetworkBehaviourEditor.cs index c525d121d6..f017384196 100644 --- a/com.unity.netcode.gameobjects/Editor/NetworkBehaviourEditor.cs +++ b/com.unity.netcode.gameobjects/Editor/NetworkBehaviourEditor.cs @@ -66,12 +66,7 @@ private void RenderNetworkVariable(int index) var genericType = type.GetGenericArguments()[0]; EditorGUILayout.BeginHorizontal(); - if (genericType == typeof(string)) - { - var networkVariable = (NetworkVariable)m_NetworkVariableFields[m_NetworkVariableNames[index]].GetValue(target); - networkVariable.Value = EditorGUILayout.TextField(m_NetworkVariableNames[index], networkVariable.Value); - } - else if (genericType.IsValueType) + if (genericType.IsValueType) { var method = typeof(NetworkBehaviourEditor).GetMethod("RenderNetworkVariableValueType", BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic); var genericMethod = method.MakeGenericMethod(genericType); @@ -86,7 +81,7 @@ private void RenderNetworkVariable(int index) EditorGUILayout.EndHorizontal(); } - private void RenderNetworkVariableValueType(int index) where T : struct + private void RenderNetworkVariableValueType(int index) where T : unmanaged { var networkVariable = (NetworkVariable)m_NetworkVariableFields[m_NetworkVariableNames[index]].GetValue(target); var type = typeof(T); diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index b12cb90cb6..540c880182 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -543,8 +543,7 @@ private void NetworkVariableUpdate(ulong clientId, int behaviourIndex) // if I'm dirty AND a client, write (server always has all permissions) // if I'm dirty AND the server AND the client can read me, send. - bool shouldWrite = isDirty && - (!IsServer || NetworkVariableFields[k].CanClientRead(clientId)); + bool shouldWrite = isDirty && IsServer && NetworkVariableFields[k].CanClientRead(clientId); if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { @@ -653,7 +652,7 @@ internal static void HandleNetworkVariableDeltas(List networkV } } - if (networkManager.IsServer && !networkVariableList[i].CanClientWrite(clientId)) + if (networkManager.IsServer)// ?? && !networkVariableList[i].CanClientWrite(clientId)) { if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { @@ -722,94 +721,6 @@ internal static void HandleNetworkVariableDeltas(List networkV } } - internal static void HandleNetworkVariableUpdate(List networkVariableList, Stream stream, ulong clientId, NetworkBehaviour logInstance, NetworkManager networkManager) - { - using (var reader = PooledNetworkReader.Get(stream)) - { - for (int i = 0; i < networkVariableList.Count; i++) - { - ushort varSize = 0; - - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) - { - varSize = reader.ReadUInt16Packed(); - - if (varSize == 0) - { - continue; - } - } - else - { - if (!reader.ReadBool()) - { - continue; - } - } - - if (networkManager.IsServer && !networkVariableList[i].CanClientWrite(clientId)) - { - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) - { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) - { - NetworkLog.LogWarning($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); - } - - stream.Position += varSize; - continue; - } - - //This client wrote somewhere they are not allowed. This is critical - //We can't just skip this field. Because we don't actually know how to dummy read - //That is, we don't know how many bytes to skip. Because the interface doesn't have a - //Read that gives us the value. Only a Read that applies the value straight away - //A dummy read COULD be added to the interface for this situation, but it's just being too nice. - //This is after all a developer fault. A critical error should be fine. - // - TwoTen - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) - { - NetworkLog.LogError($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. No more variables can be read. This is critical. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); - } - - return; - } - - long readStartPos = stream.Position; - - networkVariableList[i].ReadField(stream); - - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) - { - if (stream is NetworkBuffer networkBuffer) - { - networkBuffer.SkipPadBits(); - } - - if (stream.Position > (readStartPos + varSize)) - { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) - { - NetworkLog.LogWarning($"Var update read too far. {stream.Position - (readStartPos + varSize)} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); - } - - stream.Position = readStartPos + varSize; - } - else if (stream.Position < (readStartPos + varSize)) - { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) - { - NetworkLog.LogWarning($"Var update read too little. {(readStartPos + varSize) - stream.Position} bytes. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); - } - - stream.Position = readStartPos + varSize; - } - } - } - } - } - - internal static void WriteNetworkVariableData(List networkVariableList, Stream stream, ulong clientId, NetworkManager networkManager) { if (networkVariableList.Count == 0) diff --git a/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs b/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs index bbe86e60c6..e4e1f2e63a 100644 --- a/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs +++ b/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs @@ -107,7 +107,10 @@ public void ProcessMessage(in MessageFrameItem item) InternalMessageHandler.HandleSnapshot(item.NetworkId, item.NetworkBuffer); break; case MessageQueueContainer.MessageType.NetworkVariableDelta: - m_NetworkManager.MessageHandler.HandleNetworkVariableDelta(item.NetworkId, item.NetworkBuffer); + if (m_NetworkManager.IsClient) + { + m_NetworkManager.MessageHandler.HandleNetworkVariableDelta(item.NetworkId, item.NetworkBuffer); + } break; case MessageQueueContainer.MessageType.SwitchScene: if (m_NetworkManager.IsClient) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index c09985ddaf..3a03c73cc6 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode /// /// The type for the dictionary keys /// The type for the dictionary values - public class NetworkDictionary : IDictionary, INetworkVariable + public class NetworkDictionary : IDictionary, INetworkVariable where TKey : unmanaged where TValue : unmanaged { /// /// Gets the last time the variable was synced @@ -325,51 +325,15 @@ public void WriteField(Stream stream) } } - /// - public bool CanClientWrite(ulong clientId) - { - switch (Settings.WritePermission) - { - case NetworkVariablePermission.Everyone: - return true; - case NetworkVariablePermission.ServerOnly: - return false; - case NetworkVariablePermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; - case NetworkVariablePermission.Custom: - { - if (Settings.WritePermissionCallback == null) - { - return false; - } - - return Settings.WritePermissionCallback(clientId); - } - } - - return true; - } - /// public bool CanClientRead(ulong clientId) { switch (Settings.ReadPermission) { - case NetworkVariablePermission.Everyone: + case NetworkVariableReadPermission.Everyone: return true; - case NetworkVariablePermission.ServerOnly: - return false; - case NetworkVariablePermission.OwnerOnly: + case NetworkVariableReadPermission.OwnerOnly: return m_NetworkBehaviour.OwnerClientId == clientId; - case NetworkVariablePermission.Custom: - { - if (Settings.ReadPermissionCallback == null) - { - return false; - } - - return Settings.ReadPermissionCallback(clientId); - } } return true; @@ -378,27 +342,7 @@ public bool CanClientRead(ulong clientId) /// public bool IsDirty() { - if (m_DirtyEvents.Count == 0) - { - return false; - } - - if (Settings.SendTickrate == 0) - { - return true; - } - - if (Settings.SendTickrate < 0) - { - return false; - } - - if (m_NetworkBehaviour.NetworkManager.LocalTime.FixedTime - LastSyncedTime.FixedTime >= (1.0 / Settings.SendTickrate)) - { - return true; - } - - return false; + return m_DirtyEvents.Count > 0; } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index ad9feda01d..2f3e04f17e 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode /// Event based NetworkVariable container for syncing Lists /// /// The type for the list - public class NetworkList : IList, INetworkVariable + public class NetworkList : IList, INetworkVariable where T : unmanaged { private readonly IList m_List = new List(); private readonly List> m_DirtyEvents = new List>(); @@ -86,27 +86,7 @@ public void ResetDirty() /// public bool IsDirty() { - if (m_DirtyEvents.Count == 0) - { - return false; - } - - if (Settings.SendTickrate == 0) - { - return true; - } - - if (Settings.SendTickrate < 0) - { - return false; - } - - if (m_NetworkBehaviour.NetworkManager.LocalTime.FixedTime - LastSyncedTime.FixedTime >= (1.0 / Settings.SendTickrate)) - { - return true; - } - - return false; + return m_DirtyEvents.Count > 0; } /// @@ -115,51 +95,15 @@ public NetworkChannel GetChannel() return Settings.SendNetworkChannel; } - /// - public bool CanClientWrite(ulong clientId) - { - switch (Settings.WritePermission) - { - case NetworkVariablePermission.Everyone: - return true; - case NetworkVariablePermission.ServerOnly: - return false; - case NetworkVariablePermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; - case NetworkVariablePermission.Custom: - { - if (Settings.WritePermissionCallback == null) - { - return false; - } - - return Settings.WritePermissionCallback(clientId); - } - } - - return true; - } - /// public bool CanClientRead(ulong clientId) { switch (Settings.ReadPermission) { - case NetworkVariablePermission.Everyone: + case NetworkVariableReadPermission.Everyone: return true; - case NetworkVariablePermission.ServerOnly: - return false; - case NetworkVariablePermission.OwnerOnly: + case NetworkVariableReadPermission.OwnerOnly: return m_NetworkBehaviour.OwnerClientId == clientId; - case NetworkVariablePermission.Custom: - { - if (Settings.ReadPermissionCallback == null) - { - return false; - } - - return Settings.ReadPermissionCallback(clientId); - } } return true; diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index 9e0e58953f..2131aab74e 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode /// Event based NetworkVariable container for syncing Sets /// /// The type for the set - public class NetworkSet : ISet, INetworkVariable + public class NetworkSet : ISet, INetworkVariable where T: unmanaged { private readonly ISet m_Set = new HashSet(); private readonly List> m_DirtyEvents = new List>(); @@ -87,27 +87,7 @@ public void ResetDirty() /// public bool IsDirty() { - if (m_DirtyEvents.Count == 0) - { - return false; - } - - if (Settings.SendTickrate == 0) - { - return true; - } - - if (Settings.SendTickrate < 0) - { - return false; - } - - if ((m_NetworkBehaviour.NetworkManager.LocalTime.FixedTime - LastSyncedTime.FixedTime) >= (1.0 / Settings.SendTickrate)) - { - return true; - } - - return false; + return m_DirtyEvents.Count > 0; } /// @@ -116,51 +96,15 @@ public NetworkChannel GetChannel() return Settings.SendNetworkChannel; } - /// - public bool CanClientWrite(ulong clientId) - { - switch (Settings.WritePermission) - { - case NetworkVariablePermission.Everyone: - return true; - case NetworkVariablePermission.ServerOnly: - return false; - case NetworkVariablePermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; - case NetworkVariablePermission.Custom: - { - if (Settings.WritePermissionCallback == null) - { - return false; - } - - return Settings.WritePermissionCallback(clientId); - } - } - - return true; - } - /// public bool CanClientRead(ulong clientId) { switch (Settings.ReadPermission) { - case NetworkVariablePermission.Everyone: + case NetworkVariableReadPermission.Everyone: return true; - case NetworkVariablePermission.ServerOnly: - return false; - case NetworkVariablePermission.OwnerOnly: + case NetworkVariableReadPermission.OwnerOnly: return m_NetworkBehaviour.OwnerClientId == clientId; - case NetworkVariablePermission.Custom: - { - if (Settings.ReadPermissionCallback == null) - { - return false; - } - - return Settings.ReadPermissionCallback(clientId); - } } return true; @@ -455,7 +399,7 @@ public void UnionWith(IEnumerable other) } } - public void Add(T item) + public bool Add(T item) { EnsureInitialized(); @@ -475,20 +419,12 @@ public void Add(T item) { OnSetChanged(setEvent); } - } - /// - bool ISet.Add(T item) - { - Add(item); return true; } /// - void ICollection.Add(T item) - { - Add(item); - } + void ICollection.Add(T item) => Add(item); /// public void Clear() diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs index 338aab906b..060d43ff06 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs @@ -30,13 +30,6 @@ public interface INetworkVariable /// Whether or not the container is dirty bool IsDirty(); - /// - /// Gets Whether or not a specific client can write to the varaible - /// - /// The clientId of the remote client - /// Whether or not the client can write to the variable - bool CanClientWrite(ulong clientId); - /// /// Gets Whether or not a specific client can read to the varaible /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index 57f082da62..14529e7c56 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode /// A variable that can be synchronized over the network. /// [Serializable] - public class NetworkVariable : INetworkVariable + public class NetworkVariable : INetworkVariable where T : unmanaged { /// /// The settings for this var @@ -127,21 +127,10 @@ public bool CanClientRead(ulong clientId) { switch (Settings.ReadPermission) { - case NetworkVariablePermission.Everyone: + case NetworkVariableReadPermission.Everyone: return true; - case NetworkVariablePermission.ServerOnly: - return false; - case NetworkVariablePermission.OwnerOnly: + case NetworkVariableReadPermission.OwnerOnly: return m_NetworkBehaviour.OwnerClientId == clientId; - case NetworkVariablePermission.Custom: - { - if (Settings.ReadPermissionCallback == null) - { - return false; - } - - return Settings.ReadPermissionCallback(clientId); - } } return true; } @@ -155,31 +144,6 @@ public void WriteDelta(Stream stream) WriteField(stream); } - /// - public bool CanClientWrite(ulong clientId) - { - switch (Settings.WritePermission) - { - case NetworkVariablePermission.Everyone: - return true; - case NetworkVariablePermission.ServerOnly: - return false; - case NetworkVariablePermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; - case NetworkVariablePermission.Custom: - { - if (Settings.WritePermissionCallback == null) - { - return false; - } - - return Settings.WritePermissionCallback(clientId); - } - } - - return true; - } - /// /// Reads value from the reader and applies it /// @@ -229,25 +193,6 @@ public NetworkChannel GetChannel() } } - /// - /// A NetworkVariable that holds strings and support serialization - /// - [Serializable] - public class NetworkVariableString : NetworkVariable - { - /// - public NetworkVariableString() : base(string.Empty) { } - - /// - public NetworkVariableString(NetworkVariableSettings settings) : base(settings, string.Empty) { } - - /// - public NetworkVariableString(string value) : base(value) { } - - /// - public NetworkVariableString(NetworkVariableSettings settings, string value) : base(settings, value) { } - } - /// /// A NetworkVariable that holds bools and support serialization /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariablePermission.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariablePermission.cs index 3773bb9ba9..2a070de841 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariablePermission.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariablePermission.cs @@ -3,26 +3,29 @@ namespace Unity.Netcode /// /// Permission type /// - public enum NetworkVariablePermission +// public enum NetworkVariableWritePermission +// { +// /// +// /// Server-only operation +// /// +// ServerOnly, +// +// /// +// /// Owner-ownly +// /// +// OwnerOnly, +// } + + public enum NetworkVariableReadPermission { /// /// Everyone /// Everyone, - /// - /// Server-only operation - /// - ServerOnly, - /// /// Owner-ownly /// OwnerOnly, - - /// - /// Custom delegate - /// - Custom } } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs index 84ed8ac663..02c69bb2f9 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs @@ -11,23 +11,15 @@ namespace Unity.Netcode /// public class NetworkVariableSettings { - /// - /// Defines the write permissions for this var - /// - public NetworkVariablePermission WritePermission = NetworkVariablePermission.ServerOnly; /// /// Defines the read permissions for this var /// - public NetworkVariablePermission ReadPermission = NetworkVariablePermission.Everyone; + public NetworkVariableReadPermission ReadPermission = NetworkVariableReadPermission.Everyone; /// /// The delegate used to evaluate write permission when the "Custom" mode is used /// public NetworkVariablePermissionsDelegate WritePermissionCallback = null; /// - /// The delegate used to evaluate read permission when the "Custom" mode is used - /// - public NetworkVariablePermissionsDelegate ReadPermissionCallback = null; - /// /// The maximum times per second this var will be synced. /// A value of 0 will cause the variable to sync as soon as possible after being changed. /// A value of less than 0 will cause the variable to sync only at once at spawn and not update again. diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs index 639534455b..bf01820c4c 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs @@ -22,7 +22,6 @@ internal class NetworkVariableTestComponent : NetworkBehaviour private NetworkVariableSByte m_NetworkVariableSByte; private NetworkVariableQuaternion m_NetworkVariableQuaternion; private NetworkVariableShort m_NetworkVariableShort; - private NetworkVariableString m_NetworkVariableString; private NetworkVariableVector4 m_NetworkVariableVector4; private NetworkVariableVector3 m_NetworkVariableVector3; private NetworkVariableVector2 m_NetworkVariableVector2; @@ -43,7 +42,6 @@ internal class NetworkVariableTestComponent : NetworkBehaviour public NetworkVariableHelper Sbyte_Var; public NetworkVariableHelper Quaternion_Var; public NetworkVariableHelper Short_Var; - public NetworkVariableHelper String_Var; public NetworkVariableHelper Vector4_Var; public NetworkVariableHelper Vector3_Var; public NetworkVariableHelper Vector2_Var; @@ -75,7 +73,6 @@ private void InitializeTest() m_NetworkVariableSByte = new NetworkVariableSByte(); m_NetworkVariableQuaternion = new NetworkVariableQuaternion(); m_NetworkVariableShort = new NetworkVariableShort(); - m_NetworkVariableString = new NetworkVariableString(); m_NetworkVariableVector4 = new NetworkVariableVector4(); m_NetworkVariableVector3 = new NetworkVariableVector3(); m_NetworkVariableVector2 = new NetworkVariableVector2(); @@ -97,7 +94,6 @@ private void InitializeTest() m_NetworkVariableSByte = new NetworkVariableSByte(0); m_NetworkVariableQuaternion = new NetworkVariableQuaternion(Quaternion.identity); m_NetworkVariableShort = new NetworkVariableShort(256); - m_NetworkVariableString = new NetworkVariableString("My String Value"); m_NetworkVariableVector4 = new NetworkVariableVector4(new Vector4(1, 1, 1, 1)); m_NetworkVariableVector3 = new NetworkVariableVector3(new Vector3(1, 1, 1)); m_NetworkVariableVector2 = new NetworkVariableVector2(new Vector2(1, 1)); @@ -109,8 +105,7 @@ private void InitializeTest() // NetworkVariable NetworkVariableSettings Constructor Test Coverage var settings = new NetworkVariableSettings(); - settings.ReadPermission = NetworkVariablePermission.ServerOnly; - settings.WritePermission = NetworkVariablePermission.ServerOnly; + settings.ReadPermission = NetworkVariableReadPermission.Everyone; m_NetworkVariableBool = new NetworkVariableBool(settings); m_NetworkVariableByte = new NetworkVariableByte(settings); m_NetworkVariableColor = new NetworkVariableColor(settings); @@ -122,7 +117,6 @@ private void InitializeTest() m_NetworkVariableSByte = new NetworkVariableSByte(settings); m_NetworkVariableQuaternion = new NetworkVariableQuaternion(settings); m_NetworkVariableShort = new NetworkVariableShort(settings); - m_NetworkVariableString = new NetworkVariableString(settings); m_NetworkVariableVector4 = new NetworkVariableVector4(settings); m_NetworkVariableVector3 = new NetworkVariableVector3(settings); m_NetworkVariableVector2 = new NetworkVariableVector2(settings); @@ -132,7 +126,6 @@ private void InitializeTest() m_NetworkVariableUShort = new NetworkVariableUShort(settings); - // NetworkVariable Value Type and NetworkVariableSettings Constructor Test Coverage m_NetworkVariableBool = new NetworkVariableBool(settings, true); m_NetworkVariableByte = new NetworkVariableByte(settings, 0); @@ -145,7 +138,6 @@ private void InitializeTest() m_NetworkVariableSByte = new NetworkVariableSByte(settings, 0); m_NetworkVariableQuaternion = new NetworkVariableQuaternion(settings, Quaternion.identity); m_NetworkVariableShort = new NetworkVariableShort(settings, 1); - m_NetworkVariableString = new NetworkVariableString(settings, "My String Value"); m_NetworkVariableVector4 = new NetworkVariableVector4(settings, new Vector4(1, 1, 1, 1)); m_NetworkVariableVector3 = new NetworkVariableVector3(settings, new Vector3(1, 1, 1)); m_NetworkVariableVector2 = new NetworkVariableVector2(settings, new Vector2(1, 1)); @@ -169,7 +161,6 @@ private void InitializeTest() Sbyte_Var = new NetworkVariableHelper(m_NetworkVariableSByte); Quaternion_Var = new NetworkVariableHelper(m_NetworkVariableQuaternion); Short_Var = new NetworkVariableHelper(m_NetworkVariableShort); - String_Var = new NetworkVariableHelper(m_NetworkVariableString); Vector4_Var = new NetworkVariableHelper(m_NetworkVariableVector4); Vector3_Var = new NetworkVariableHelper(m_NetworkVariableVector3); Vector2_Var = new NetworkVariableHelper(m_NetworkVariableVector2); @@ -238,7 +229,6 @@ private void Update() m_NetworkVariableSByte.Value = -127; m_NetworkVariableQuaternion.Value = new Quaternion(100, 100, 100, 100); m_NetworkVariableShort.Value = short.MaxValue; - m_NetworkVariableString.Value = "My Changed String Value"; m_NetworkVariableVector4.Value = new Vector4(1000, 1000, 1000, 1000); m_NetworkVariableVector3.Value = new Vector3(1000, 1000, 1000); m_NetworkVariableVector2.Value = new Vector2(1000, 1000); diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs index b6d56486b3..f725b7369c 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs @@ -13,7 +13,7 @@ namespace Unity.Netcode.RuntimeTests /// From both we can then at least determine if the value indeed changed /// /// - internal class NetworkVariableHelper : BaseNetworkVariableHelper + internal class NetworkVariableHelper : BaseNetworkVariableHelper where T : unmanaged { private NetworkVariable m_NetworkVariable; public delegate void OnMyValueChangedDelegateHandler(T previous, T next); diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs.meta b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs.meta deleted file mode 100644 index 9103284456..0000000000 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: cf4ff0d6357bb4474a404b9ce52b22ad -timeCreated: 1620872927 \ No newline at end of file diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs index 660eb65c9a..1fc4ee5e90 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs @@ -23,26 +23,18 @@ public class TestClass : INetworkSerializable public uint SomeInt; public bool SomeBool; - public void NetworkSerialize(NetworkSerializer serializer) - { - serializer.Serialize(ref SomeInt); - serializer.Serialize(ref SomeBool); - } - } - - public class NetworkVariableTest : NetworkBehaviour + public void NetworkSerialize(NetworkSerializer serializer) { - public readonly NetworkList TheList = new NetworkList( - new NetworkVariableSettings { WritePermission = NetworkVariablePermission.ServerOnly } - ); - - public readonly NetworkSet TheSet = new NetworkSet( - new NetworkVariableSettings { WritePermission = NetworkVariablePermission.ServerOnly } - ); - - public readonly NetworkDictionary TheDictionary = new NetworkDictionary( - new NetworkVariableSettings { WritePermission = NetworkVariablePermission.ServerOnly } - ); + serializer.Serialize(ref SomeInt); + serializer.Serialize(ref SomeBool); + } +} +public class NetworkVariableTest : NetworkBehaviour +{ + public readonly NetworkVariable TheScalar = new NetworkVariable(); + public readonly NetworkList TheList = new NetworkList(); + public readonly NetworkSet TheSet = new NetworkSet(); + public readonly NetworkDictionary TheDictionary = new NetworkDictionary(); private void ListChanged(NetworkListEvent e) { @@ -63,8 +55,7 @@ public void Awake() TheDictionary.OnDictionaryChanged += DictionaryChanged; } - public readonly NetworkVariable TheStruct = new NetworkVariable(); - public readonly NetworkVariable TheClass = new NetworkVariable(new TestClass()); + public readonly NetworkVariable TheStruct = new NetworkVariable(); public bool ListDelegateTriggered; public bool SetDelegateTriggered; @@ -173,11 +164,31 @@ public IEnumerator AllNetworkVariableTypes() Assert.IsTrue(testsAreComplete); - // This would normally go in Teardown, but since every other test but this one - // uses MultiInstanceHelper, and it does its own NetworkManager setup / teardown, - // for now we put this within this one test until we migrate it to MIH - NetworkManagerHelper.ShutdownNetworkManager(); - } + // This would normally go in Teardown, but since every other test but this one + // uses MultiInstanceHelper, and it does its own NetworkManager setup / teardown, + // for now we put this within this one test until we migrate it to MIH + NetworkManagerHelper.ShutdownNetworkManager(); + } + + [UnityTest] + public IEnumerator PermissionTest() + { + + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerComp.TheScalar.Value = k_TestVal1; + m_ClientComp.TheScalar.Value = k_TestVal2; + }, + () => + { + // the client should not have overwritten the server, and the server's + // write will stomp the client's value + return m_ServerComp.TheScalar.Value == k_TestVal1 && + m_ClientComp.TheScalar.Value == k_TestVal1; + } + ); + } [UnityTest] public IEnumerator NetworkListAdd() @@ -386,39 +397,20 @@ public IEnumerator NetworkDictionaryClear() // first put some stuff in; re-use the add test yield return NetworkDictionaryAdd(); - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheDictionary.Clear(); - }, - () => - { - return m_ServerComp.TheDictionary.Count == 0 && - m_ClientComp.TheDictionary.Count == 0 && - m_ServerComp.DictionaryDelegateTriggered && - m_ClientComp.DictionaryDelegateTriggered; - } - ); - } - - [UnityTest] - public IEnumerator TestNetworkVariableClass() - { - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheClass.Value.SomeBool = false; - m_ServerComp.TheClass.Value.SomeInt = k_TestUInt; - m_ServerComp.TheClass.SetDirty(true); - }, - () => - { - return - m_ClientComp.TheClass.Value.SomeBool == false && - m_ClientComp.TheClass.Value.SomeInt == k_TestUInt; - } - ); - } + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerComp.TheDictionary.Clear(); + }, + () => + { + return m_ServerComp.TheDictionary.Count == 0 && + m_ClientComp.TheDictionary.Count == 0 && + m_ServerComp.DictionaryDelegateTriggered && + m_ClientComp.DictionaryDelegateTriggered; + } + ); + } [UnityTest] public IEnumerator TestNetworkVariableStruct() diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Profiling/NetworkVariableNameTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Profiling/NetworkVariableNameTests.cs index 82b9e559b1..5adbc4ffbf 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Profiling/NetworkVariableNameTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Profiling/NetworkVariableNameTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using NUnit.Framework; namespace Unity.Netcode.RuntimeTests @@ -27,7 +27,6 @@ public void TearDown() public void VerifyNetworkVariableNameInitialization() { // Properties have the following name format: "k__BackingField" - StringAssert.Contains(nameof(NetworkVariableNameComponent.NetworkVarString), m_NetworkVariableNameComponent.NetworkVarString.Name); StringAssert.Contains(nameof(NetworkVariableNameComponent.NetworkVarSet), m_NetworkVariableNameComponent.NetworkVarSet.Name); // Fields have regular naming @@ -37,8 +36,6 @@ public void VerifyNetworkVariableNameInitialization() private class NetworkVariableNameComponent : NetworkBehaviour { - public NetworkVariableString NetworkVarString { get; } = new NetworkVariableString(); - public NetworkSet NetworkVarSet { get; } = new NetworkSet(); public NetworkList NetworkVarList = new NetworkList(); diff --git a/testproject/Assets/Scripts/SyncTransform.cs b/testproject/Assets/Scripts/SyncTransform.cs index 9d774757f7..4b47b3b18b 100644 --- a/testproject/Assets/Scripts/SyncTransform.cs +++ b/testproject/Assets/Scripts/SyncTransform.cs @@ -68,12 +68,6 @@ private void SyncRotChanged(Quaternion before, Quaternion after) } } - private void Start() - { - m_VarPos.Settings.WritePermission = NetworkVariablePermission.Everyone; - m_VarRot.Settings.WritePermission = NetworkVariablePermission.Everyone; - } - private void FixedUpdate() { float now = Time.time; diff --git a/testproject/Assets/Tests/Manual/Scripts/BandwidthTest.cs b/testproject/Assets/Tests/Manual/Scripts/BandwidthTest.cs index 17244686f4..ddc25509b7 100644 --- a/testproject/Assets/Tests/Manual/Scripts/BandwidthTest.cs +++ b/testproject/Assets/Tests/Manual/Scripts/BandwidthTest.cs @@ -21,9 +21,7 @@ private void Start() private void Awake() { m_Ids = new NetworkList(); - m_Ids.Settings.WritePermission = NetworkVariablePermission.ServerOnly; m_Ids.OnListChanged += ListChanged; - Debug.Log("Awake"); } From 28eff19a1bf0ec5bbe5b75491a38c801c45cb1af Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Thu, 19 Aug 2021 18:06:49 -0700 Subject: [PATCH 03/25] feat: client auth experiment --- .../Runtime/Core/NetworkBehaviour.cs | 9 +- .../Runtime/Core/NetworkBehaviourUpdater.cs | 7 +- .../MessageQueue/MessageQueueProcessor.cs | 3 - .../NetworkVariable/ClientNetworkVariable.cs | 57 ++ .../ClientNetworkVariable.cs.meta | 11 + .../Collections/NetworkDictionary.cs | 10 + .../Collections/NetworkList.cs | 10 + .../NetworkVariable/Collections/NetworkSet.cs | 9 + .../NetworkVariable/INetworkVariable.cs | 9 + .../NetworkVariable/NetworkVariable.cs | 19 +- .../Tests/Runtime/NetworkVarBufferCopyTest.cs | 9 +- .../Tests/Runtime/NetworkVariableTests.cs | 667 +++++++++--------- 12 files changed, 485 insertions(+), 335 deletions(-) create mode 100644 com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs create mode 100644 com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs.meta diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index 540c880182..a2f6deb59c 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -514,6 +514,7 @@ private void NetworkVariableUpdate(ulong clientId, int behaviourIndex) { using (var writer = PooledNetworkWriter.Get(buffer)) { + // could skip this if no variables dirty writer.WriteUInt64Packed(NetworkObjectId); writer.WriteUInt16Packed(NetworkObject.GetNetworkBehaviourOrderIndex(this)); @@ -522,6 +523,7 @@ private void NetworkVariableUpdate(ulong clientId, int behaviourIndex) var writtenAny = false; for (int k = 0; k < NetworkVariableFields.Count; k++) { + // could skip up here if not client, etc if (!m_ChannelMappedNetworkVariableIndexes[j].Contains(k)) { // This var does not belong to the currently iterating channel group. @@ -543,7 +545,7 @@ private void NetworkVariableUpdate(ulong clientId, int behaviourIndex) // if I'm dirty AND a client, write (server always has all permissions) // if I'm dirty AND the server AND the client can read me, send. - bool shouldWrite = isDirty && IsServer && NetworkVariableFields[k].CanClientRead(clientId); + bool shouldWrite = NetworkVariableFields[k].ShouldWrite(clientId, IsServer); if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { @@ -618,7 +620,7 @@ private bool CouldHaveDirtyNetworkVariables() // TODO: There should be a better way by reading one dirty variable vs. 'n' for (int i = 0; i < NetworkVariableFields.Count; i++) { - if (NetworkVariableFields[i].IsDirty()) + if (NetworkVariableFields[i].IsDirty()) // needs to bifurcate! { return true; } @@ -652,7 +654,7 @@ internal static void HandleNetworkVariableDeltas(List networkV } } - if (networkManager.IsServer)// ?? && !networkVariableList[i].CanClientWrite(clientId)) + if (networkManager.IsServer && !networkVariableList[i].CanClientWrite(clientId)) { if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { @@ -682,7 +684,6 @@ internal static void HandleNetworkVariableDeltas(List networkV return; } - long readStartPos = stream.Position; networkVariableList[i].ReadDelta(stream, networkManager.IsServer); diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviourUpdater.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviourUpdater.cs index d38209ad0f..522c310208 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviourUpdater.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviourUpdater.cs @@ -50,9 +50,12 @@ internal void NetworkBehaviourUpdate(NetworkManager networkManager) // when client updates the server, it tells it about all its objects foreach (var sobj in networkManager.SpawnManager.SpawnedObjectsList) { - for (int k = 0; k < sobj.ChildNetworkBehaviours.Count; k++) + if (sobj.IsOwner) { - sobj.ChildNetworkBehaviours[k].VariableUpdate(networkManager.ServerClientId); + for (int k = 0; k < sobj.ChildNetworkBehaviours.Count; k++) + { + sobj.ChildNetworkBehaviours[k].VariableUpdate(networkManager.ServerClientId); + } } } diff --git a/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs b/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs index e4e1f2e63a..5bfa0639af 100644 --- a/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs +++ b/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs @@ -107,10 +107,7 @@ public void ProcessMessage(in MessageFrameItem item) InternalMessageHandler.HandleSnapshot(item.NetworkId, item.NetworkBuffer); break; case MessageQueueContainer.MessageType.NetworkVariableDelta: - if (m_NetworkManager.IsClient) - { m_NetworkManager.MessageHandler.HandleNetworkVariableDelta(item.NetworkId, item.NetworkBuffer); - } break; case MessageQueueContainer.MessageType.SwitchScene: if (m_NetworkManager.IsClient) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs new file mode 100644 index 0000000000..c06f84da59 --- /dev/null +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using UnityEngine; +using System.IO; +using System; + +namespace Unity.Netcode +{ + /// + /// A variable that can be synchronized over the network. + /// + [Serializable] + public class ClientNetworkVariable : NetworkVariable where T : unmanaged + { + /// + /// The value of the ClientNetworkVariable container + /// + public new T Value + { + get => m_InternalValue; + set + { + if (EqualityComparer.Default.Equals(m_InternalValue, value)) + { + return; + } + + m_IsDirty = true; + T previousValue = m_InternalValue; + m_InternalValue = value; + OnValueChanged?.Invoke(previousValue, m_InternalValue); + } + } + + /// + public bool CanClientRead(ulong clientId) + { + switch (Settings.ReadPermission) + { + case NetworkVariableReadPermission.Everyone: + return true; + case NetworkVariableReadPermission.OwnerOnly: + return m_NetworkBehaviour.OwnerClientId == clientId; + } + return true; + } + + public override bool CanClientWrite(ulong clientId) + { + return m_NetworkBehaviour.OwnerClientId == clientId; + } + + public override bool ShouldWrite(ulong clientId, bool isServer) + { + return m_IsDirty && !isServer && CanClientRead(clientId) && m_NetworkBehaviour.IsOwner; + } + } +} diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs.meta b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs.meta new file mode 100644 index 0000000000..85deda8734 --- /dev/null +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2eede058d58f4493ba93dc19a82131fd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 3a03c73cc6..957f539a76 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -339,12 +339,22 @@ public bool CanClientRead(ulong clientId) return true; } + public bool CanClientWrite(ulong clientId) + { + return false; + } + + /// public bool IsDirty() { return m_DirtyEvents.Count > 0; } + public bool ShouldWrite(ulong clientId, bool isServer) + { + return IsDirty() && isServer && CanClientRead(clientId); + } /// public TValue this[TKey key] diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index 2f3e04f17e..ff76e8f6ac 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -89,6 +89,11 @@ public bool IsDirty() return m_DirtyEvents.Count > 0; } + public bool ShouldWrite(ulong clientId, bool isServer) + { + return IsDirty() && isServer && CanClientRead(clientId); + } + /// public NetworkChannel GetChannel() { @@ -109,6 +114,11 @@ public bool CanClientRead(ulong clientId) return true; } + public bool CanClientWrite(ulong clientId) + { + return false; + } + /// public void WriteDelta(Stream stream) { diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index 2131aab74e..669274ddc4 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -90,6 +90,11 @@ public bool IsDirty() return m_DirtyEvents.Count > 0; } + public bool ShouldWrite(ulong clientId, bool isServer) + { + return IsDirty() && isServer && CanClientRead(clientId); + } + /// public NetworkChannel GetChannel() { @@ -109,6 +114,10 @@ public bool CanClientRead(ulong clientId) return true; } + public bool CanClientWrite(ulong clientId) + { + return false; + } /// public void WriteDelta(Stream stream) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs index 060d43ff06..8d3355a66b 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs @@ -30,6 +30,8 @@ public interface INetworkVariable /// Whether or not the container is dirty bool IsDirty(); + bool ShouldWrite(ulong clientId, bool isServer); + /// /// Gets Whether or not a specific client can read to the varaible /// @@ -37,6 +39,13 @@ public interface INetworkVariable /// Whether or not the client can read to the variable bool CanClientRead(ulong clientId); + /// + /// Gets Whether or not a specific client can read to the varaible + /// + /// The clientId of the remote client + /// Whether or not the client can read to the variable + bool CanClientWrite(ulong clientId); + /// /// Writes the dirty changes, that is, the changes since the variable was last dirty, to the writer /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index 14529e7c56..e43ddf886c 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode /// A variable that can be synchronized over the network. /// [Serializable] - public class NetworkVariable : INetworkVariable where T : unmanaged + public class NetworkVariable : INetworkVariable where T : unmanaged /** SEAL ?? **/ { /// /// The settings for this var @@ -27,7 +27,8 @@ public class NetworkVariable : INetworkVariable where T : unmanaged /// public OnValueChangedDelegate OnValueChanged; - private NetworkBehaviour m_NetworkBehaviour; + // demolish me + private protected NetworkBehaviour m_NetworkBehaviour; /// /// Creates a NetworkVariable with the default value and settings @@ -64,7 +65,7 @@ public NetworkVariable(T value) } [SerializeField] - private T m_InternalValue; + private protected T m_InternalValue; /// /// The temporary accessor to enable struct element access until [MTT-1020] complete @@ -94,7 +95,7 @@ public T Value } } - private bool m_IsDirty = false; + private protected bool m_IsDirty = false; /// /// Gets or sets the name of the network variable's instance @@ -116,6 +117,11 @@ public bool IsDirty() return m_IsDirty; } + public virtual bool ShouldWrite(ulong clientId, bool isServer) + { + return m_IsDirty && isServer && CanClientRead(clientId); + } + /// public void ResetDirty() { @@ -135,6 +141,11 @@ public bool CanClientRead(ulong clientId) return true; } + public virtual bool CanClientWrite(ulong clientId) + { + return false; + } + /// /// Writes the variable to the writer /// diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs index 42ddc12774..badb761732 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs @@ -33,9 +33,9 @@ public bool IsDirty() return Dirty; } - public bool CanClientWrite(ulong clientId) + public bool ShouldWrite(ulong clientId, bool isServer) { - return true; + return Dirty && isServer && CanClientRead(clientId); } public bool CanClientRead(ulong clientId) @@ -43,6 +43,11 @@ public bool CanClientRead(ulong clientId) return true; } + public bool CanClientWrite(ulong clientId) + { + return false; + } + public void WriteDelta(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs index 1fc4ee5e90..42f30990a7 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs @@ -17,24 +17,14 @@ public void NetworkSerialize(NetworkSerializer serializer) serializer.Serialize(ref SomeBool); } } - - public class TestClass : INetworkSerializable + public class NetworkVariableTest : NetworkBehaviour { - public uint SomeInt; - public bool SomeBool; + public readonly ClientNetworkVariable ClientVar = new ClientNetworkVariable(); - public void NetworkSerialize(NetworkSerializer serializer) - { - serializer.Serialize(ref SomeInt); - serializer.Serialize(ref SomeBool); - } -} -public class NetworkVariableTest : NetworkBehaviour -{ - public readonly NetworkVariable TheScalar = new NetworkVariable(); - public readonly NetworkList TheList = new NetworkList(); - public readonly NetworkSet TheSet = new NetworkSet(); - public readonly NetworkDictionary TheDictionary = new NetworkDictionary(); + public readonly NetworkVariable TheScalar = new NetworkVariable(); + public readonly NetworkList TheList = new NetworkList(); + public readonly NetworkSet TheSet = new NetworkSet(); + public readonly NetworkDictionary TheDictionary = new NetworkDictionary(); private void ListChanged(NetworkListEvent e) { @@ -62,107 +52,119 @@ public void Awake() public bool DictionaryDelegateTriggered; } - namespace Unity.Netcode.RuntimeTests + public class NetworkVariableTests : BaseMultiInstanceTest { - public class NetworkVariableTests : BaseMultiInstanceTest - { - protected override int NbClients => 1; + protected override int NbClients => 2; - private const uint k_TestUInt = 0xdeadbeef; + private const uint k_TestUInt = 0xdeadbeef; - private const int k_TestVal1 = 111; - private const int k_TestVal2 = 222; - private const int k_TestVal3 = 333; + private const int k_TestVal1 = 111; + private const int k_TestVal2 = 222; + private const int k_TestVal3 = 333; - private const int k_TestKey1 = 0x0f0f; - private const int k_TestKey2 = 0xf0f0; + private const int k_TestKey1 = 0x0f0f; + private const int k_TestKey2 = 0xf0f0; - private NetworkVariableTest m_ServerComp; - private NetworkVariableTest m_ClientComp; + private NetworkVariableTest m_ServerVersionPlayer1Comp; + private NetworkVariableTest m_ServerVersionPlayer2Comp; + private NetworkVariableTest m_ClientComp; + private NetworkVariableTest m_ClientComp2; - private readonly bool m_TestWithHost = false; + private readonly bool m_TestWithHost = false; - [UnitySetUp] - public override IEnumerator Setup() - { - yield return StartSomeClientsAndServerWithPlayers(useHost: m_TestWithHost, nbClients: NbClients, - updatePlayerPrefab: playerPrefab => - { - var networkTransform = playerPrefab.AddComponent(); - }); + [UnitySetUp] + public override IEnumerator Setup() + { + yield return StartSomeClientsAndServerWithPlayers(useHost: m_TestWithHost, nbClients: NbClients, + updatePlayerPrefab: playerPrefab => + { + var networkTransform = playerPrefab.AddComponent(); + }); - // This is the *SERVER VERSION* of the *CLIENT PLAYER* - var serverClientPlayerResult = new MultiInstanceHelpers.CoroutineResultWrapper(); + // These are the *SERVER VERSIONS* of the *CLIENT PLAYER 1 & 2* + var result1 = new MultiInstanceHelpers.CoroutineResultWrapper(); + var result2 = new MultiInstanceHelpers.CoroutineResultWrapper(); - yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( - x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, - m_ServerNetworkManager, serverClientPlayerResult)); + yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( + x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, + m_ServerNetworkManager, result1)); + m_ServerVersionPlayer1Comp = result1.Result.GetComponent(); - // This is the *CLIENT VERSION* of the *CLIENT PLAYER* - var clientClientPlayerResult = new MultiInstanceHelpers.CoroutineResultWrapper(); - yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( - x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, - m_ClientNetworkManagers[0], clientClientPlayerResult)); + yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( + x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[1].LocalClientId, + m_ServerNetworkManager, result2)); + m_ServerVersionPlayer2Comp = result2.Result.GetComponent(); - var serverSideClientPlayer = serverClientPlayerResult.Result; - var clientSideClientPlayer = clientClientPlayerResult.Result; + // This is the *CLIENT VERSION* of the *CLIENT PLAYER 1* + var clientClientPlayerResult = new MultiInstanceHelpers.CoroutineResultWrapper(); + yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( + x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, + m_ClientNetworkManagers[0], clientClientPlayerResult)); - m_ServerComp = serverSideClientPlayer.GetComponent(); - m_ClientComp = clientSideClientPlayer.GetComponent(); + var clientSideClientPlayer = clientClientPlayerResult.Result; + m_ClientComp = clientSideClientPlayer.GetComponent(); - m_ServerComp.TheList.Clear(); - m_ServerComp.TheSet.Clear(); - m_ServerComp.TheDictionary.Clear(); + var clientClientPlayerResult2 = new MultiInstanceHelpers.CoroutineResultWrapper(); + yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( + x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[1].LocalClientId, + m_ClientNetworkManagers[1], clientClientPlayerResult2)); - if (m_ServerComp.TheList.Count > 0 || m_ServerComp.TheSet.Count > 0 || m_ServerComp.TheDictionary.Count > 0) - { - throw new Exception("at least one server network container not empty at start"); - } - if (m_ClientComp.TheList.Count > 0 || m_ClientComp.TheSet.Count > 0 || m_ClientComp.TheDictionary.Count > 0) - { - throw new Exception("at least one client network container not empty at start"); - } - } + var clientSideClientPlayer2 = clientClientPlayerResult2.Result; + m_ClientComp2 = clientSideClientPlayer2.GetComponent(); + + m_ServerVersionPlayer1Comp.TheList.Clear(); + m_ServerVersionPlayer1Comp.TheSet.Clear(); + m_ServerVersionPlayer1Comp.TheDictionary.Clear(); - /// - /// Runs generalized tests on all predefined NetworkVariable types - /// - [UnityTest] - public IEnumerator AllNetworkVariableTypes() + if (m_ServerVersionPlayer1Comp.TheList.Count > 0 || m_ServerVersionPlayer1Comp.TheSet.Count > 0 || m_ServerVersionPlayer1Comp.TheDictionary.Count > 0) { - // Create, instantiate, and host - // This would normally go in Setup, but since every other test but this one - // uses MultiInstanceHelper, and it does its own NetworkManager setup / teardown, - // for now we put this within this one test until we migrate it to MIH - Assert.IsTrue(NetworkManagerHelper.StartNetworkManager(out _)); + throw new Exception("at least one server network container not empty at start"); + } + if (m_ClientComp.TheList.Count > 0 || m_ClientComp.TheSet.Count > 0 || m_ClientComp.TheDictionary.Count > 0) + { + throw new Exception("at least one client network container not empty at start"); + } + } - Guid gameObjectId = NetworkManagerHelper.AddGameNetworkObject("NetworkVariableTestComponent"); + /// + /// Runs generalized tests on all predefined NetworkVariable types + /// + [UnityTest] + public IEnumerator AllNetworkVariableTypes() + { + // Create, instantiate, and host + // This would normally go in Setup, but since every other test but this one + // uses MultiInstanceHelper, and it does its own NetworkManager setup / teardown, + // for now we put this within this one test until we migrate it to MIH + Assert.IsTrue(NetworkManagerHelper.StartNetworkManager(out _)); - var networkVariableTestComponent = NetworkManagerHelper.AddComponentToObject(gameObjectId); + Guid gameObjectId = NetworkManagerHelper.AddGameNetworkObject("NetworkVariableTestComponent"); - NetworkManagerHelper.SpawnNetworkObject(gameObjectId); + var networkVariableTestComponent = NetworkManagerHelper.AddComponentToObject(gameObjectId); - // Start Testing - networkVariableTestComponent.EnableTesting = true; + NetworkManagerHelper.SpawnNetworkObject(gameObjectId); - var testsAreComplete = networkVariableTestComponent.IsTestComplete(); + // Start Testing + networkVariableTestComponent.EnableTesting = true; - // Wait for the NetworkVariable tests to complete - while (!testsAreComplete) - { - yield return new WaitForSeconds(0.003f); - testsAreComplete = networkVariableTestComponent.IsTestComplete(); - } + var testsAreComplete = networkVariableTestComponent.IsTestComplete(); - // Stop Testing - networkVariableTestComponent.EnableTesting = false; + // Wait for the NetworkVariable tests to complete + while (!testsAreComplete) + { + yield return new WaitForSeconds(0.003f); + testsAreComplete = networkVariableTestComponent.IsTestComplete(); + } - Assert.IsTrue(networkVariableTestComponent.DidAllValuesChange()); + // Stop Testing + networkVariableTestComponent.EnableTesting = false; - // Disable this once we are done. - networkVariableTestComponent.gameObject.SetActive(false); + Assert.IsTrue(networkVariableTestComponent.DidAllValuesChange()); - Assert.IsTrue(testsAreComplete); + // Disable this once we are done. + networkVariableTestComponent.gameObject.SetActive(false); + + Assert.IsTrue(testsAreComplete); // This would normally go in Teardown, but since every other test but this one // uses MultiInstanceHelper, and it does its own NetworkManager setup / teardown, @@ -171,272 +173,297 @@ public IEnumerator AllNetworkVariableTypes() } [UnityTest] - public IEnumerator PermissionTest() + public IEnumerator ServerPermissionTest() { - yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerComp.TheScalar.Value = k_TestVal1; + m_ServerVersionPlayer1Comp.TheScalar.Value = k_TestVal1; + m_ServerVersionPlayer2Comp.TheScalar.Value = k_TestVal2; m_ClientComp.TheScalar.Value = k_TestVal2; + m_ClientComp2.TheScalar.Value = k_TestVal3; }, () => { // the client should not have overwritten the server, and the server's // write will stomp the client's value - return m_ServerComp.TheScalar.Value == k_TestVal1 && - m_ClientComp.TheScalar.Value == k_TestVal1; + return m_ServerVersionPlayer1Comp.TheScalar.Value == k_TestVal1 && + m_ServerVersionPlayer2Comp.TheScalar.Value == k_TestVal2 && + m_ClientComp.TheScalar.Value == k_TestVal1 && + m_ClientComp2.TheScalar.Value == k_TestVal2; } ); } - [UnityTest] - public IEnumerator NetworkListAdd() - { - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheList.Add(k_TestVal1); - m_ServerComp.TheList.Add(k_TestVal2); - }, - () => - { - return m_ServerComp.TheList.Count == 2 && - m_ClientComp.TheList.Count == 2 && - m_ServerComp.ListDelegateTriggered && - m_ClientComp.ListDelegateTriggered && - m_ServerComp.TheList[0] == k_TestVal1 && - m_ClientComp.TheList[0] == k_TestVal1 && - m_ServerComp.TheList[1] == k_TestVal2 && - m_ClientComp.TheList[1] == k_TestVal2; - } - ); - } + [UnityTest] + public IEnumerator ClientPermissionTest() + { + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerVersionPlayer1Comp.ClientVar.Value = k_TestVal1; + m_ServerVersionPlayer2Comp.ClientVar.Value = k_TestVal1; + m_ClientComp.ClientVar.Value = k_TestVal2; + m_ClientComp2.ClientVar.Value = k_TestVal3; + }, + () => + { + // the client's values should win on the objects it owns + return + m_ServerVersionPlayer1Comp.ClientVar.Value == k_TestVal2 && + m_ServerVersionPlayer2Comp.ClientVar.Value == k_TestVal3 && + m_ClientComp.ClientVar.Value == k_TestVal2 && + m_ClientComp2.ClientVar.Value == k_TestVal3; + } + ); + } - [UnityTest] - public IEnumerator NetworkListRemove() - { - // first put some stuff in; re-use the add test - yield return NetworkListAdd(); - - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => m_ServerComp.TheList.RemoveAt(0), - () => - { - return m_ServerComp.TheList.Count == 1 && - m_ClientComp.TheList.Count == 1 && - m_ServerComp.ListDelegateTriggered && - m_ClientComp.ListDelegateTriggered && - m_ServerComp.TheList[0] == k_TestVal2 && - m_ClientComp.TheList[0] == k_TestVal2; - } - ); - } + [UnityTest] + public IEnumerator NetworkListAdd() + { + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerVersionPlayer1Comp.TheList.Add(k_TestVal1); + m_ServerVersionPlayer1Comp.TheList.Add(k_TestVal2); + }, + () => + { + return m_ServerVersionPlayer1Comp.TheList.Count == 2 && + m_ClientComp.TheList.Count == 2 && + m_ServerVersionPlayer1Comp.ListDelegateTriggered && + m_ClientComp.ListDelegateTriggered && + m_ServerVersionPlayer1Comp.TheList[0] == k_TestVal1 && + m_ClientComp.TheList[0] == k_TestVal1 && + m_ServerVersionPlayer1Comp.TheList[1] == k_TestVal2 && + m_ClientComp.TheList[1] == k_TestVal2; + } + ); + } - [UnityTest] - public IEnumerator NetworkListClear() - { - // first put some stuff in; re-use the add test - yield return NetworkListAdd(); - - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => m_ServerComp.TheList.Clear(), - () => - { - return - m_ServerComp.ListDelegateTriggered && - m_ClientComp.ListDelegateTriggered && - m_ServerComp.TheList.Count == 0 && - m_ClientComp.TheList.Count == 0; - } - ); - } + [UnityTest] + public IEnumerator NetworkListRemove() + { + // first put some stuff in; re-use the add test + yield return NetworkListAdd(); - [UnityTest] - public IEnumerator NetworkSetAdd() - { - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheSet.Add(k_TestVal1); - m_ServerComp.TheSet.Add(k_TestVal2); - }, - () => - { - return m_ServerComp.TheSet.Count == 2 && - m_ClientComp.TheSet.Count == 2 && - m_ServerComp.SetDelegateTriggered && - m_ClientComp.SetDelegateTriggered && - m_ServerComp.TheSet.Contains(k_TestVal1) && - m_ClientComp.TheSet.Contains(k_TestVal1) && - m_ServerComp.TheSet.Contains(k_TestVal2) && - m_ClientComp.TheSet.Contains(k_TestVal2); - } - ); - } + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => m_ServerVersionPlayer1Comp.TheList.RemoveAt(0), + () => + { + return m_ServerVersionPlayer1Comp.TheList.Count == 1 && + m_ClientComp.TheList.Count == 1 && + m_ServerVersionPlayer1Comp.ListDelegateTriggered && + m_ClientComp.ListDelegateTriggered && + m_ServerVersionPlayer1Comp.TheList[0] == k_TestVal2 && + m_ClientComp.TheList[0] == k_TestVal2; + } + ); + } - [UnityTest] - public IEnumerator NetworkSetRemove() - { - // first put some stuff in; re-use the add test - yield return NetworkSetAdd(); - - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheSet.Remove(k_TestVal1); - }, - () => - { - return m_ServerComp.TheSet.Count == 1 && - m_ClientComp.TheSet.Count == 1 && - m_ServerComp.SetDelegateTriggered && - m_ClientComp.SetDelegateTriggered && - m_ServerComp.TheSet.Contains(k_TestVal2) && - m_ClientComp.TheSet.Contains(k_TestVal2); - } - ); - } + [UnityTest] + public IEnumerator NetworkListClear() + { + // first put some stuff in; re-use the add test + yield return NetworkListAdd(); - [UnityTest] - public IEnumerator NetworkSetClear() - { - // first put some stuff in; re-use the add test - yield return NetworkSetAdd(); - - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheSet.Clear(); - }, - () => - { - return m_ServerComp.TheSet.Count == 0 && - m_ClientComp.TheSet.Count == 0 && - m_ServerComp.SetDelegateTriggered && - m_ClientComp.SetDelegateTriggered; - } - ); - } + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => m_ServerVersionPlayer1Comp.TheList.Clear(), + () => + { + return + m_ServerVersionPlayer1Comp.ListDelegateTriggered && + m_ClientComp.ListDelegateTriggered && + m_ServerVersionPlayer1Comp.TheList.Count == 0 && + m_ClientComp.TheList.Count == 0; + } + ); + } - [UnityTest] - public IEnumerator NetworkDictionaryAdd() - { - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheDictionary.Add(k_TestKey1, k_TestVal1); - m_ServerComp.TheDictionary.Add(k_TestKey2, k_TestVal2); - }, - () => - { - return m_ServerComp.TheDictionary.Count == 2 && - m_ClientComp.TheDictionary.Count == 2 && - m_ServerComp.DictionaryDelegateTriggered && - m_ClientComp.DictionaryDelegateTriggered && - m_ServerComp.TheDictionary[k_TestKey1] == k_TestVal1 && - m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal1 && - m_ServerComp.TheDictionary[k_TestKey2] == k_TestVal2 && - m_ClientComp.TheDictionary[k_TestKey2] == k_TestVal2; - } - ); - } + [UnityTest] + public IEnumerator NetworkSetAdd() + { + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerVersionPlayer1Comp.TheSet.Add(k_TestVal1); + m_ServerVersionPlayer1Comp.TheSet.Add(k_TestVal2); + }, + () => + { + return m_ServerVersionPlayer1Comp.TheSet.Count == 2 && + m_ClientComp.TheSet.Count == 2 && + m_ServerVersionPlayer1Comp.SetDelegateTriggered && + m_ClientComp.SetDelegateTriggered && + m_ServerVersionPlayer1Comp.TheSet.Contains(k_TestVal1) && + m_ClientComp.TheSet.Contains(k_TestVal1) && + m_ServerVersionPlayer1Comp.TheSet.Contains(k_TestVal2) && + m_ClientComp.TheSet.Contains(k_TestVal2); + } + ); + } - /* Note, not adding coverage for RemovePair, because we plan to remove - * this in the next PR - */ - [UnityTest] - public IEnumerator NetworkDictionaryRemoveByKey() - { - // first put some stuff in; re-use the add test - yield return NetworkDictionaryAdd(); - - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheDictionary.Remove(k_TestKey2); - }, - () => - { - return m_ServerComp.TheDictionary.Count == 1 && - m_ClientComp.TheDictionary.Count == 1 && - m_ServerComp.DictionaryDelegateTriggered && - m_ClientComp.DictionaryDelegateTriggered && - m_ServerComp.TheDictionary[k_TestKey1] == k_TestVal1 && - m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal1; - } - ); - } + [UnityTest] + public IEnumerator NetworkSetRemove() + { + // first put some stuff in; re-use the add test + yield return NetworkSetAdd(); - [UnityTest] - public IEnumerator NetworkDictionaryChangeValue() - { - // first put some stuff in; re-use the add test - yield return NetworkDictionaryAdd(); - - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheDictionary[k_TestKey1] = k_TestVal3; - }, - () => - { - return m_ServerComp.TheDictionary.Count == 2 && - m_ClientComp.TheDictionary.Count == 2 && - m_ServerComp.DictionaryDelegateTriggered && - m_ClientComp.DictionaryDelegateTriggered && - m_ServerComp.TheDictionary[k_TestKey1] == k_TestVal3 && - m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal3; - } - ); - } + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerVersionPlayer1Comp.TheSet.Remove(k_TestVal1); + }, + () => + { + return m_ServerVersionPlayer1Comp.TheSet.Count == 1 && + m_ClientComp.TheSet.Count == 1 && + m_ServerVersionPlayer1Comp.SetDelegateTriggered && + m_ClientComp.SetDelegateTriggered && + m_ServerVersionPlayer1Comp.TheSet.Contains(k_TestVal2) && + m_ClientComp.TheSet.Contains(k_TestVal2); + } + ); + } - [UnityTest] - public IEnumerator NetworkDictionaryClear() - { - // first put some stuff in; re-use the add test - yield return NetworkDictionaryAdd(); + [UnityTest] + public IEnumerator NetworkSetClear() + { + // first put some stuff in; re-use the add test + yield return NetworkSetAdd(); yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerComp.TheDictionary.Clear(); + m_ServerVersionPlayer1Comp.TheSet.Clear(); }, () => { - return m_ServerComp.TheDictionary.Count == 0 && + return m_ServerVersionPlayer1Comp.TheSet.Count == 0 && + m_ClientComp.TheSet.Count == 0 && + m_ServerVersionPlayer1Comp.SetDelegateTriggered && + m_ClientComp.SetDelegateTriggered; + } + ); + } + + [UnityTest] + public IEnumerator NetworkDictionaryAdd() + { + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerVersionPlayer1Comp.TheDictionary.Add(k_TestKey1, k_TestVal1); + m_ServerVersionPlayer1Comp.TheDictionary.Add(k_TestKey2, k_TestVal2); + }, + () => + { + return m_ServerVersionPlayer1Comp.TheDictionary.Count == 2 && + m_ClientComp.TheDictionary.Count == 2 && + m_ServerVersionPlayer1Comp.DictionaryDelegateTriggered && + m_ClientComp.DictionaryDelegateTriggered && + m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal1 && + m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal1 && + m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey2] == k_TestVal2 && + m_ClientComp.TheDictionary[k_TestKey2] == k_TestVal2; + } + ); + } + + /* Note, not adding coverage for RemovePair, because we plan to remove + * this in the next PR + */ + [UnityTest] + public IEnumerator NetworkDictionaryRemoveByKey() + { + // first put some stuff in; re-use the add test + yield return NetworkDictionaryAdd(); + + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerVersionPlayer1Comp.TheDictionary.Remove(k_TestKey2); + }, + () => + { + return m_ServerVersionPlayer1Comp.TheDictionary.Count == 1 && + m_ClientComp.TheDictionary.Count == 1 && + m_ServerVersionPlayer1Comp.DictionaryDelegateTriggered && + m_ClientComp.DictionaryDelegateTriggered && + m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal1 && + m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal1; + } + ); + } + + [UnityTest] + public IEnumerator NetworkDictionaryChangeValue() + { + // first put some stuff in; re-use the add test + yield return NetworkDictionaryAdd(); + + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey1] = k_TestVal3; + }, + () => + { + return m_ServerVersionPlayer1Comp.TheDictionary.Count == 2 && + m_ClientComp.TheDictionary.Count == 2 && + m_ServerVersionPlayer1Comp.DictionaryDelegateTriggered && + m_ClientComp.DictionaryDelegateTriggered && + m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal3 && + m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal3; + } + ); + } + + [UnityTest] + public IEnumerator NetworkDictionaryClear() + { + // first put some stuff in; re-use the add test + yield return NetworkDictionaryAdd(); + + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerVersionPlayer1Comp.TheDictionary.Clear(); + }, + () => + { + return m_ServerVersionPlayer1Comp.TheDictionary.Count == 0 && m_ClientComp.TheDictionary.Count == 0 && - m_ServerComp.DictionaryDelegateTriggered && + m_ServerVersionPlayer1Comp.DictionaryDelegateTriggered && m_ClientComp.DictionaryDelegateTriggered; } ); } - [UnityTest] - public IEnumerator TestNetworkVariableStruct() - { - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerComp.TheStruct.Value = - new TestStruct() { SomeInt = k_TestUInt, SomeBool = false }; - m_ServerComp.TheStruct.SetDirty(true); - }, - () => - { - return - m_ClientComp.TheStruct.Value.SomeBool == false && - m_ClientComp.TheStruct.Value.SomeInt == k_TestUInt; - } - ); - } + [UnityTest] + public IEnumerator TestNetworkVariableStruct() + { + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + m_ServerVersionPlayer1Comp.TheStruct.Value = + new TestStruct() { SomeInt = k_TestUInt, SomeBool = false }; + m_ServerVersionPlayer1Comp.TheStruct.SetDirty(true); + }, + () => + { + return + m_ClientComp.TheStruct.Value.SomeBool == false && + m_ClientComp.TheStruct.Value.SomeInt == k_TestUInt; + } + ); + } - [UnityTearDown] - public override IEnumerator Teardown() - { - yield return base.Teardown(); - UnityEngine.Object.Destroy(m_PlayerPrefab); - } + [UnityTearDown] + public override IEnumerator Teardown() + { + yield return base.Teardown(); + UnityEngine.Object.Destroy(m_PlayerPrefab); } } } From b5c8041b090c5ff208889b8c698e3241d8db47f0 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Fri, 20 Aug 2021 07:27:39 -0700 Subject: [PATCH 04/25] removed unneeded function --- .../NetworkVariable/ClientNetworkVariable.cs | 38 ++----------------- 1 file changed, 4 insertions(+), 34 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs index c06f84da59..7dc5389637 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -6,44 +6,14 @@ namespace Unity.Netcode { /// - /// A variable that can be synchronized over the network. + /// A Client NetworkVariable is special in that + /// - only the owner of the variable can write to it + /// - not even the server can write to it + /// - it is not snapshotted /// [Serializable] public class ClientNetworkVariable : NetworkVariable where T : unmanaged { - /// - /// The value of the ClientNetworkVariable container - /// - public new T Value - { - get => m_InternalValue; - set - { - if (EqualityComparer.Default.Equals(m_InternalValue, value)) - { - return; - } - - m_IsDirty = true; - T previousValue = m_InternalValue; - m_InternalValue = value; - OnValueChanged?.Invoke(previousValue, m_InternalValue); - } - } - - /// - public bool CanClientRead(ulong clientId) - { - switch (Settings.ReadPermission) - { - case NetworkVariableReadPermission.Everyone: - return true; - case NetworkVariableReadPermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; - } - return true; - } - public override bool CanClientWrite(ulong clientId) { return m_NetworkBehaviour.OwnerClientId == clientId; From 63cbc7ac6d62bd2ccf0b5274ee4b7c9d56495140 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Fri, 20 Aug 2021 08:57:15 -0700 Subject: [PATCH 05/25] NetworkList is now a derived class --- .../Runtime/Core/NetworkBehaviour.cs | 4 - .../MessageQueue/MessageQueueProcessor.cs | 2 +- .../Collections/NetworkList.cs | 74 ++++--------------- .../NetworkVariable/NetworkVariable.cs | 14 ++-- 4 files changed, 21 insertions(+), 73 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index a2f6deb59c..fa93351205 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -539,10 +539,6 @@ private void NetworkVariableUpdate(ulong clientId, int behaviourIndex) continue; } - bool isDirty = - NetworkVariableFields[k] - .IsDirty(); // cache this here. You never know what operations users will do in the dirty methods - // if I'm dirty AND a client, write (server always has all permissions) // if I'm dirty AND the server AND the client can read me, send. bool shouldWrite = NetworkVariableFields[k].ShouldWrite(clientId, IsServer); diff --git a/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs b/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs index 5bfa0639af..bbe86e60c6 100644 --- a/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs +++ b/com.unity.netcode.gameobjects/Runtime/Messaging/MessageQueue/MessageQueueProcessor.cs @@ -107,7 +107,7 @@ public void ProcessMessage(in MessageFrameItem item) InternalMessageHandler.HandleSnapshot(item.NetworkId, item.NetworkBuffer); break; case MessageQueueContainer.MessageType.NetworkVariableDelta: - m_NetworkManager.MessageHandler.HandleNetworkVariableDelta(item.NetworkId, item.NetworkBuffer); + m_NetworkManager.MessageHandler.HandleNetworkVariableDelta(item.NetworkId, item.NetworkBuffer); break; case MessageQueueContainer.MessageType.SwitchScene: if (m_NetworkManager.IsClient) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index ff76e8f6ac..b40a956063 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.IO; +using UnityEngine; namespace Unity.Netcode { @@ -9,22 +10,16 @@ namespace Unity.Netcode /// Event based NetworkVariable container for syncing Lists /// /// The type for the list - public class NetworkList : IList, INetworkVariable where T : unmanaged + public class NetworkList : NetworkVariable, IList where T : unmanaged { private readonly IList m_List = new List(); private readonly List> m_DirtyEvents = new List>(); - private NetworkBehaviour m_NetworkBehaviour; /// /// Gets the last time the variable was synced /// public NetworkTime LastSyncedTime { get; internal set; } - /// - /// The settings for this container - /// - public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); - /// /// Delegate type for list changed event /// @@ -45,19 +40,15 @@ public NetworkList() { } /// Creates a NetworkList with the default value and custom settings /// /// The settings to use for the NetworkList - public NetworkList(NetworkVariableSettings settings) - { - Settings = settings; - } + public NetworkList(NetworkVariableSettings settings) : base(settings) { } /// /// Creates a NetworkList with a custom value and custom settings /// /// The settings to use for the NetworkList /// The initial value to use for the NetworkList - public NetworkList(NetworkVariableSettings settings, IList value) + public NetworkList(NetworkVariableSettings settings, IList value) : base(settings) { - Settings = settings; m_List = value; } @@ -70,57 +61,23 @@ public NetworkList(IList value) m_List = value; } - /// - /// Gets or sets the name of the network variable's instance - /// (MemberInfo) where it was declared. - /// - public string Name { get; internal set; } - /// - public void ResetDirty() + public override void ResetDirty() { + base.ResetDirty(); m_DirtyEvents.Clear(); LastSyncedTime = m_NetworkBehaviour.NetworkManager.LocalTime; } /// - public bool IsDirty() - { - return m_DirtyEvents.Count > 0; - } - - public bool ShouldWrite(ulong clientId, bool isServer) - { - return IsDirty() && isServer && CanClientRead(clientId); - } - - /// - public NetworkChannel GetChannel() + public override bool IsDirty() { - return Settings.SendNetworkChannel; + // we call the base class to allow the SetDirty() mechanism to work + return base.IsDirty() || m_DirtyEvents.Count > 0; } /// - public bool CanClientRead(ulong clientId) - { - switch (Settings.ReadPermission) - { - case NetworkVariableReadPermission.Everyone: - return true; - case NetworkVariableReadPermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; - } - - return true; - } - - public bool CanClientWrite(ulong clientId) - { - return false; - } - - /// - public void WriteDelta(Stream stream) + public override void WriteDelta(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { @@ -168,7 +125,7 @@ public void WriteDelta(Stream stream) } /// - public void WriteField(Stream stream) + public override void WriteField(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { @@ -181,7 +138,7 @@ public void WriteField(Stream stream) } /// - public void ReadField(Stream stream) + public override void ReadField(Stream stream) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -195,7 +152,7 @@ public void ReadField(Stream stream) } /// - public void ReadDelta(Stream stream, bool keepDirtyDelta) + public override void ReadDelta(Stream stream, bool keepDirtyDelta) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -367,11 +324,6 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta) } } - /// - public void SetNetworkBehaviour(NetworkBehaviour behaviour) - { - m_NetworkBehaviour = behaviour; - } /// public IEnumerator GetEnumerator() diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index e43ddf886c..38b26d2c70 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -112,18 +112,18 @@ public void SetDirty(bool isDirty) } /// - public bool IsDirty() + public virtual bool IsDirty() { return m_IsDirty; } public virtual bool ShouldWrite(ulong clientId, bool isServer) { - return m_IsDirty && isServer && CanClientRead(clientId); + return IsDirty() && isServer && CanClientRead(clientId); } /// - public void ResetDirty() + public virtual void ResetDirty() { m_IsDirty = false; } @@ -150,7 +150,7 @@ public virtual bool CanClientWrite(ulong clientId) /// Writes the variable to the writer /// /// The stream to write the value to - public void WriteDelta(Stream stream) + public virtual void WriteDelta(Stream stream) { WriteField(stream); } @@ -160,7 +160,7 @@ public void WriteDelta(Stream stream) /// /// The stream to read the value from /// Whether or not the container should keep the dirty delta, or mark the delta as consumed - public void ReadDelta(Stream stream, bool keepDirtyDelta) + public virtual void ReadDelta(Stream stream, bool keepDirtyDelta) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -183,13 +183,13 @@ public void SetNetworkBehaviour(NetworkBehaviour behaviour) } /// - public void ReadField(Stream stream) + public virtual void ReadField(Stream stream) { ReadDelta(stream, false); } /// - public void WriteField(Stream stream) + public virtual void WriteField(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { From efd612a5eb980f26c115a1bcedb0ddae1e431a04 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Fri, 20 Aug 2021 10:17:43 -0700 Subject: [PATCH 06/25] dict & set --- .../Collections/NetworkDictionary.cs | 77 +++---------------- .../NetworkVariable/Collections/NetworkSet.cs | 72 +++-------------- 2 files changed, 23 insertions(+), 126 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 957f539a76..0c821b88e8 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -10,20 +10,14 @@ namespace Unity.Netcode /// /// The type for the dictionary keys /// The type for the dictionary values - public class NetworkDictionary : IDictionary, INetworkVariable where TKey : unmanaged where TValue : unmanaged + public class NetworkDictionary : NetworkVariable, IDictionary where TKey : unmanaged where TValue : unmanaged { /// /// Gets the last time the variable was synced /// public NetworkTime LastSyncedTime { get; internal set; } - /// - /// The settings for this container - /// - public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); - private readonly IDictionary m_Dictionary = new Dictionary(); - private NetworkBehaviour m_NetworkBehaviour; private readonly List> m_DirtyEvents = new List>(); /// @@ -37,7 +31,6 @@ public class NetworkDictionary : IDictionary, INetwo /// public event OnDictionaryChangedDelegate OnDictionaryChanged; - /// /// Creates a NetworkDictionary with the default value and settings /// @@ -47,19 +40,15 @@ public NetworkDictionary() { } /// Creates a NetworkDictionary with the default value and custom settings /// /// The settings to use for the NetworkDictionary - public NetworkDictionary(NetworkVariableSettings settings) - { - Settings = settings; - } + public NetworkDictionary(NetworkVariableSettings settings) : base(settings) { } /// /// Creates a NetworkDictionary with a custom value and custom settings /// /// The settings to use for the NetworkDictionary /// The initial value to use for the NetworkDictionary - public NetworkDictionary(NetworkVariableSettings settings, IDictionary value) + public NetworkDictionary(NetworkVariableSettings settings, IDictionary value) : base(settings) { - Settings = settings; m_Dictionary = value; } @@ -72,27 +61,16 @@ public NetworkDictionary(IDictionary value) m_Dictionary = value; } - /// - /// Gets or sets the name of the network variable's instance - /// (MemberInfo) where it was declared. - /// - public string Name { get; internal set; } - /// - public void ResetDirty() + public override void ResetDirty() { + base.ResetDirty(); m_DirtyEvents.Clear(); LastSyncedTime = m_NetworkBehaviour.NetworkManager.LocalTime; } /// - public NetworkChannel GetChannel() - { - return Settings.SendNetworkChannel; - } - - /// - public void ReadDelta(Stream stream, bool keepDirtyDelta) + public override void ReadDelta(Stream stream, bool keepDirtyDelta) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -240,7 +218,7 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta) } /// - public void ReadField(Stream stream) + public override void ReadField(Stream stream) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -255,12 +233,6 @@ public void ReadField(Stream stream) } } - /// - public void SetNetworkBehaviour(NetworkBehaviour behaviour) - { - m_NetworkBehaviour = behaviour; - } - /// public bool TryGetValue(TKey key, out TValue value) { @@ -268,7 +240,7 @@ public bool TryGetValue(TKey key, out TValue value) } /// - public void WriteDelta(Stream stream) + public override void WriteDelta(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { @@ -312,7 +284,7 @@ public void WriteDelta(Stream stream) } /// - public void WriteField(Stream stream) + public override void WriteField(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { @@ -326,34 +298,9 @@ public void WriteField(Stream stream) } /// - public bool CanClientRead(ulong clientId) - { - switch (Settings.ReadPermission) - { - case NetworkVariableReadPermission.Everyone: - return true; - case NetworkVariableReadPermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; - } - - return true; - } - - public bool CanClientWrite(ulong clientId) - { - return false; - } - - - /// - public bool IsDirty() - { - return m_DirtyEvents.Count > 0; - } - - public bool ShouldWrite(ulong clientId, bool isServer) + public override bool IsDirty() { - return IsDirty() && isServer && CanClientRead(clientId); + return base.IsDirty() || m_DirtyEvents.Count > 0; } /// @@ -390,7 +337,7 @@ public TValue this[TKey key] public int Count => m_Dictionary.Count; /// - public bool IsReadOnly => m_Dictionary.IsReadOnly; + public bool IsReadOnly => m_Dictionary.IsReadOnly; // hrm /// public void Add(TKey key, TValue value) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index 669274ddc4..6424aa407c 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -10,22 +10,16 @@ namespace Unity.Netcode /// Event based NetworkVariable container for syncing Sets /// /// The type for the set - public class NetworkSet : ISet, INetworkVariable where T: unmanaged + public class NetworkSet : NetworkVariable, ISet where T: unmanaged { private readonly ISet m_Set = new HashSet(); private readonly List> m_DirtyEvents = new List>(); - private NetworkBehaviour m_NetworkBehaviour; /// /// Gets the last time the variable was synced /// public NetworkTime LastSyncedTime { get; internal set; } - /// - /// The settings for this container - /// - public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); - /// /// Delegate type for set changed event /// @@ -46,19 +40,15 @@ public NetworkSet() { } /// Creates a NetworkSet with the default value and custom settings /// /// The settings to use for the NetworkList - public NetworkSet(NetworkVariableSettings settings) - { - Settings = settings; - } + public NetworkSet(NetworkVariableSettings settings) : base(settings) { } /// /// Creates a NetworkSet with a custom value and custom settings /// /// The settings to use for the NetworkSet /// The initial value to use for the NetworkSet - public NetworkSet(NetworkVariableSettings settings, ISet value) + public NetworkSet(NetworkVariableSettings settings, ISet value) : base(settings) { - Settings = settings; m_Set = value; } @@ -71,56 +61,22 @@ public NetworkSet(ISet value) m_Set = value; } - /// - /// Gets or sets the name of the network variable's instance - /// (MemberInfo) where it was declared. - /// - public string Name { get; internal set; } - /// - public void ResetDirty() + public override void ResetDirty() { + base.ResetDirty(); m_DirtyEvents.Clear(); LastSyncedTime = m_NetworkBehaviour.NetworkManager.LocalTime; } /// - public bool IsDirty() - { - return m_DirtyEvents.Count > 0; - } - - public bool ShouldWrite(ulong clientId, bool isServer) - { - return IsDirty() && isServer && CanClientRead(clientId); - } - - /// - public NetworkChannel GetChannel() + public override bool IsDirty() { - return Settings.SendNetworkChannel; + return base.IsDirty() || m_DirtyEvents.Count > 0; } /// - public bool CanClientRead(ulong clientId) - { - switch (Settings.ReadPermission) - { - case NetworkVariableReadPermission.Everyone: - return true; - case NetworkVariableReadPermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; - } - - return true; - } - public bool CanClientWrite(ulong clientId) - { - return false; - } - - /// - public void WriteDelta(Stream stream) + public override void WriteDelta(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { @@ -152,7 +108,7 @@ public void WriteDelta(Stream stream) } /// - public void WriteField(Stream stream) + public override void WriteField(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { @@ -166,7 +122,7 @@ public void WriteField(Stream stream) } /// - public void ReadField(Stream stream) + public override void ReadField(Stream stream) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -181,7 +137,7 @@ public void ReadField(Stream stream) } /// - public void ReadDelta(Stream stream, bool keepDirtyDelta) + public override void ReadDelta(Stream stream, bool keepDirtyDelta) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -266,12 +222,6 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta) } } - /// - public void SetNetworkBehaviour(NetworkBehaviour behaviour) - { - m_NetworkBehaviour = behaviour; - } - /// public IEnumerator GetEnumerator() { From 51159b1356fa52feaaf238cacb46a7957a602fa7 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Fri, 20 Aug 2021 10:46:28 -0700 Subject: [PATCH 07/25] de-interface checkpoint --- .../Runtime/Core/NetworkBehaviour.cs | 2 +- .../Collections/NetworkDictionary.cs | 2 +- .../Collections/NetworkList.cs | 2 +- .../NetworkVariable/Collections/NetworkSet.cs | 2 +- .../NetworkVariable/INetworkVariable.cs | 81 ++++++++++++++--- .../NetworkVariable/NetworkVariable.cs | 86 ++----------------- .../Runtime/Reflection/TypeExtensions.cs | 1 + .../Tests/Runtime/NetworkVarBufferCopyTest.cs | 49 ++--------- 8 files changed, 87 insertions(+), 138 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index fa93351205..3efda021a2 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -415,7 +415,7 @@ internal void InitializeVariables() { Type fieldType = sortedFields[i].FieldType; - if (fieldType.HasInterface(typeof(INetworkVariable))) + if (fieldType.IsSubclassOf(typeof(INetworkVariable))) { var instance = (INetworkVariable)sortedFields[i].GetValue(this); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 0c821b88e8..5417bff388 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode /// /// The type for the dictionary keys /// The type for the dictionary values - public class NetworkDictionary : NetworkVariable, IDictionary where TKey : unmanaged where TValue : unmanaged + public class NetworkDictionary : INetworkVariable, IDictionary where TKey : unmanaged where TValue : unmanaged { /// /// Gets the last time the variable was synced diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index b40a956063..29a2e8cfa4 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode /// Event based NetworkVariable container for syncing Lists /// /// The type for the list - public class NetworkList : NetworkVariable, IList where T : unmanaged + public class NetworkList : INetworkVariable, IList where T : unmanaged { private readonly IList m_List = new List(); private readonly List> m_DirtyEvents = new List>(); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index 6424aa407c..805961d36c 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode /// Event based NetworkVariable container for syncing Sets /// /// The type for the set - public class NetworkSet : NetworkVariable, ISet where T: unmanaged + public class NetworkSet : INetworkVariable, ISet where T: unmanaged { private readonly ISet m_Set = new HashSet(); private readonly List> m_DirtyEvents = new List>(); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs index 8d3355a66b..ba894beb02 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs @@ -5,58 +5,109 @@ namespace Unity.Netcode /// /// Interface for network value containers /// - public interface INetworkVariable + public abstract class INetworkVariable { + protected INetworkVariable() { } + + protected INetworkVariable(NetworkVariableSettings settings) + { + Settings = settings; + } + + // demolish me + // or better setter? + private protected NetworkBehaviour m_NetworkBehaviour; + + private protected bool m_IsDirty = false; + /// /// Gets or sets the name of the network variable's instance /// (MemberInfo) where it was declared. /// - string Name { get; } + public string Name { get; internal set; } + + /// + /// The settings for this var + /// + public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); /// /// Returns the name of the channel to be used for syncing /// /// The name of the channel to be used for syncing - NetworkChannel GetChannel(); + public NetworkChannel GetChannel() + { + return Settings.SendNetworkChannel; + } + + /// + /// Sets whether or not the variable needs to be delta synced + /// + public void SetDirty(bool isDirty) + { + m_IsDirty = isDirty; + } /// /// Resets the dirty state and marks the variable as synced / clean /// - void ResetDirty(); + public virtual void ResetDirty() + { + m_IsDirty = false; + } /// /// Gets Whether or not the container is dirty /// /// Whether or not the container is dirty - bool IsDirty(); + public virtual bool IsDirty() + { + return m_IsDirty; + } - bool ShouldWrite(ulong clientId, bool isServer); + public virtual bool ShouldWrite(ulong clientId, bool isServer) + { + return IsDirty() && isServer && CanClientRead(clientId); + } /// /// Gets Whether or not a specific client can read to the varaible /// /// The clientId of the remote client /// Whether or not the client can read to the variable - bool CanClientRead(ulong clientId); + public bool CanClientRead(ulong clientId) + { + switch (Settings.ReadPermission) + { + case NetworkVariableReadPermission.Everyone: + return true; + case NetworkVariableReadPermission.OwnerOnly: + return m_NetworkBehaviour.OwnerClientId == clientId; + } + return true; + } /// /// Gets Whether or not a specific client can read to the varaible /// /// The clientId of the remote client /// Whether or not the client can read to the variable - bool CanClientWrite(ulong clientId); + public virtual bool CanClientWrite(ulong clientId) + { + return false; + } /// /// Writes the dirty changes, that is, the changes since the variable was last dirty, to the writer /// /// The stream to write the dirty changes to - void WriteDelta(Stream stream); + public abstract void WriteDelta(Stream stream); /// /// Writes the complete state of the variable to the writer /// /// The stream to write the state to - void WriteField(Stream stream); + public abstract void WriteField(Stream stream); /// /// Reads the complete state from the reader and applies it @@ -64,7 +115,7 @@ public interface INetworkVariable /// The stream to read the state from /// The local network tick at which this var was written, on the machine it was written /// The remote network tick at which this var was sent by the host - void ReadField(Stream stream); + public abstract void ReadField(Stream stream); /// /// Reads delta from the reader and applies them to the internal value @@ -73,12 +124,16 @@ public interface INetworkVariable /// Whether or not the delta should be kept as dirty or consumed /// The local network tick at which this var was written, on the machine it was written /// The remote network tick at which this var was sent by the host - void ReadDelta(Stream stream, bool keepDirtyDelta); + public abstract void ReadDelta(Stream stream, bool keepDirtyDelta); /// /// Sets NetworkBehaviour the container belongs to. /// /// The behaviour the container behaves to - void SetNetworkBehaviour(NetworkBehaviour behaviour); + public void SetNetworkBehaviour(NetworkBehaviour behaviour) + { + m_NetworkBehaviour = behaviour; + } + } } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index 38b26d2c70..d0784619d2 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -11,11 +11,6 @@ namespace Unity.Netcode [Serializable] public class NetworkVariable : INetworkVariable where T : unmanaged /** SEAL ?? **/ { - /// - /// The settings for this var - /// - public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); - /// /// Delegate type for value changed event /// @@ -27,9 +22,6 @@ public class NetworkVariable : INetworkVariable where T : unmanaged /** SEAL /// public OnValueChangedDelegate OnValueChanged; - // demolish me - private protected NetworkBehaviour m_NetworkBehaviour; - /// /// Creates a NetworkVariable with the default value and settings /// @@ -39,19 +31,15 @@ public NetworkVariable() { } /// Creates a NetworkVariable with the default value and custom settings /// /// The settings to use for the NetworkVariable - public NetworkVariable(NetworkVariableSettings settings) - { - Settings = settings; - } + public NetworkVariable(NetworkVariableSettings settings) : base(settings) { } /// /// Creates a NetworkVariable with a custom value and custom settings /// /// The settings to use for the NetworkVariable /// The initial value to use for the NetworkVariable - public NetworkVariable(NetworkVariableSettings settings, T value) + public NetworkVariable(NetworkVariableSettings settings, T value) : base(settings) { - Settings = settings; m_InternalValue = value; } @@ -95,62 +83,12 @@ public T Value } } - private protected bool m_IsDirty = false; - - /// - /// Gets or sets the name of the network variable's instance - /// (MemberInfo) where it was declared. - /// - public string Name { get; internal set; } - - /// - /// Sets whether or not the variable needs to be delta synced - /// - public void SetDirty(bool isDirty) - { - m_IsDirty = isDirty; - } - - /// - public virtual bool IsDirty() - { - return m_IsDirty; - } - - public virtual bool ShouldWrite(ulong clientId, bool isServer) - { - return IsDirty() && isServer && CanClientRead(clientId); - } - - /// - public virtual void ResetDirty() - { - m_IsDirty = false; - } - - /// - public bool CanClientRead(ulong clientId) - { - switch (Settings.ReadPermission) - { - case NetworkVariableReadPermission.Everyone: - return true; - case NetworkVariableReadPermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; - } - return true; - } - - public virtual bool CanClientWrite(ulong clientId) - { - return false; - } /// /// Writes the variable to the writer /// /// The stream to write the value to - public virtual void WriteDelta(Stream stream) + public override void WriteDelta(Stream stream) { WriteField(stream); } @@ -160,7 +98,7 @@ public virtual void WriteDelta(Stream stream) /// /// The stream to read the value from /// Whether or not the container should keep the dirty delta, or mark the delta as consumed - public virtual void ReadDelta(Stream stream, bool keepDirtyDelta) + public override void ReadDelta(Stream stream, bool keepDirtyDelta) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -177,31 +115,19 @@ public virtual void ReadDelta(Stream stream, bool keepDirtyDelta) } /// - public void SetNetworkBehaviour(NetworkBehaviour behaviour) - { - m_NetworkBehaviour = behaviour; - } - - /// - public virtual void ReadField(Stream stream) + public override void ReadField(Stream stream) { ReadDelta(stream, false); } /// - public virtual void WriteField(Stream stream) + public override void WriteField(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { writer.WriteObjectPacked(m_InternalValue); //BOX } } - - /// - public NetworkChannel GetChannel() - { - return Settings.SendNetworkChannel; - } } /// diff --git a/com.unity.netcode.gameobjects/Runtime/Reflection/TypeExtensions.cs b/com.unity.netcode.gameobjects/Runtime/Reflection/TypeExtensions.cs index 216e489e0a..5d325c1e9d 100644 --- a/com.unity.netcode.gameobjects/Runtime/Reflection/TypeExtensions.cs +++ b/com.unity.netcode.gameobjects/Runtime/Reflection/TypeExtensions.cs @@ -4,6 +4,7 @@ namespace Unity.Netcode { internal static class TypeExtensions { + //?? internal static bool HasInterface(this Type type, Type interfaceType) { var ifaces = type.GetInterfaces(); diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs index badb761732..6a375fb12d 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs @@ -14,41 +14,13 @@ public class DummyNetVar : INetworkVariable public bool FieldWritten; public bool DeltaRead; public bool FieldRead; - public bool Dirty = true; - public string Name { get; internal set; } +//hrm public override NetworkChannel GetChannel() +//hrm { +//hrm return NetworkChannel.NetworkVariable; +//hrm } - public NetworkChannel GetChannel() - { - return NetworkChannel.NetworkVariable; - } - - public void ResetDirty() - { - Dirty = false; - } - - public bool IsDirty() - { - return Dirty; - } - - public bool ShouldWrite(ulong clientId, bool isServer) - { - return Dirty && isServer && CanClientRead(clientId); - } - - public bool CanClientRead(ulong clientId) - { - return true; - } - - public bool CanClientWrite(ulong clientId) - { - return false; - } - - public void WriteDelta(Stream stream) + public override void WriteDelta(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { @@ -59,7 +31,7 @@ public void WriteDelta(Stream stream) DeltaWritten = true; } - public void WriteField(Stream stream) + public override void WriteField(Stream stream) { using (var writer = PooledNetworkWriter.Get(stream)) { @@ -70,7 +42,7 @@ public void WriteField(Stream stream) FieldWritten = true; } - public void ReadField(Stream stream) + public override void ReadField(Stream stream) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -81,7 +53,7 @@ public void ReadField(Stream stream) FieldRead = true; } - public void ReadDelta(Stream stream, bool keepDirtyDelta) + public override void ReadDelta(Stream stream, bool keepDirtyDelta) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -91,11 +63,6 @@ public void ReadDelta(Stream stream, bool keepDirtyDelta) DeltaRead = true; } - - public void SetNetworkBehaviour(NetworkBehaviour behaviour) - { - // nop - } } public class DummyNetBehaviour : NetworkBehaviour From b85b7b3fb85f3205e18595908c84ffcc328fea64 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Fri, 20 Aug 2021 14:40:02 -0700 Subject: [PATCH 08/25] lint fixes --- .../Runtime/NetworkVariable/ClientNetworkVariable.cs | 3 --- .../Runtime/NetworkVariable/Collections/NetworkList.cs | 1 - .../Runtime/NetworkVariable/NetworkVariable.cs | 2 +- 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs index 7dc5389637..318614dff7 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using UnityEngine; -using System.IO; using System; namespace Unity.Netcode diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index 29a2e8cfa4..324f5f40d8 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -2,7 +2,6 @@ using System.Collections; using System.Collections.Generic; using System.IO; -using UnityEngine; namespace Unity.Netcode { diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index d0784619d2..df2315f7d8 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode /// A variable that can be synchronized over the network. /// [Serializable] - public class NetworkVariable : INetworkVariable where T : unmanaged /** SEAL ?? **/ + public class NetworkVariable : INetworkVariable where T : unmanaged { /// /// Delegate type for value changed event From c6da3c7233a9e7f3e312e5334136c0a40eaa5d4b Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Mon, 23 Aug 2021 08:58:43 -0700 Subject: [PATCH 09/25] removed valueRef --- .../Prototyping/NetworkTransform.cs | 9 +- .../Runtime/Core/NetworkBehaviour.cs | 3 +- .../NetworkVariable/ClientNetworkVariable.cs | 22 +++ .../NetworkVariable/NetworkVariable.cs | 34 ++-- .../NetworkTransformStateTests.cs | 163 +++++++++++++----- .../Tests/Runtime/NetworkVariableTests.cs | 146 ++++++++-------- 6 files changed, 241 insertions(+), 136 deletions(-) diff --git a/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs b/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs index 0132d24e16..67d94bdc13 100644 --- a/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs +++ b/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs @@ -385,7 +385,14 @@ private void FixedUpdate() if (IsServer) { - ReplNetworkState.SetDirty(UpdateNetworkState(ref ReplNetworkState.ValueRef)); + // save off current value + var tmp = ReplNetworkState.Value; + + // mutate the tmp value, set dirty if we mutated it + ReplNetworkState.SetDirty(UpdateNetworkState(ref tmp)); + + // commit the value + ReplNetworkState.Value = tmp; } // try to update previously consumed NetworkState // if we have any changes, that means made some updates locally diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index 3efda021a2..486374b916 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -652,6 +652,8 @@ internal static void HandleNetworkVariableDeltas(List networkV if (networkManager.IsServer && !networkVariableList[i].CanClientWrite(clientId)) { + // we are choosing not to fire an exception here, because otherwise a malicious client could use + // this to crash the server if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) @@ -671,7 +673,6 @@ internal static void HandleNetworkVariableDeltas(List networkV //A dummy read COULD be added to the interface for this situation, but it's just being too nice. //This is after all a developer fault. A critical error should be fine. // - TwoTen - if (NetworkLog.CurrentLogLevel <= LogLevel.Error) { NetworkLog.LogError($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. No more variables can be read. This is critical. => {(logInstance != null ? ($"{nameof(NetworkObjectId)}: {logInstance.NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {logInstance.NetworkObject.GetNetworkBehaviourOrderIndex(logInstance)} - VariableIndex: {i}") : string.Empty)}"); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs index 318614dff7..5be59ad21d 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using UnityEngine; namespace Unity.Netcode { @@ -7,6 +9,8 @@ namespace Unity.Netcode /// - only the owner of the variable can write to it /// - not even the server can write to it /// - it is not snapshotted + /// + /// This class may be removed in the future /// [Serializable] public class ClientNetworkVariable : NetworkVariable where T : unmanaged @@ -20,5 +24,23 @@ public override bool ShouldWrite(ulong clientId, bool isServer) { return m_IsDirty && !isServer && CanClientRead(clientId) && m_NetworkBehaviour.IsOwner; } + + /// + /// The value of the NetworkVariable container + /// + public override T Value + { + get => m_InternalValue; + set + { + // this could be improved. The Networking Manager is not always initialized here. + // Good place to decouple network manager from the network variable + if (m_NetworkBehaviour.NetworkManager.IsServer) + { + throw new InvalidOperationException("Server not allowed to write to ClientNetworkVariables"); + } + Set(value); + } + } } } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index df2315f7d8..fd43bda442 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -55,34 +55,36 @@ public NetworkVariable(T value) [SerializeField] private protected T m_InternalValue; - /// - /// The temporary accessor to enable struct element access until [MTT-1020] complete - /// - public ref T ValueRef - { - get => ref m_InternalValue; - } - /// /// The value of the NetworkVariable container /// - public T Value + public virtual T Value { get => m_InternalValue; set { - if (EqualityComparer.Default.Equals(m_InternalValue, value)) + // this could be improved. The Networking Manager is not always initialized here + // Good place to decouple network manager from the network variable + if (m_NetworkBehaviour && m_NetworkBehaviour.NetworkManager.IsClient) { - return; + throw new InvalidOperationException("Client can't write to NetworkVariables"); } - - m_IsDirty = true; - T previousValue = m_InternalValue; - m_InternalValue = value; - OnValueChanged?.Invoke(previousValue, m_InternalValue); + Set(value); } } + private protected void Set(T value) + { + if (EqualityComparer.Default.Equals(m_InternalValue, value)) + { + return; + } + + m_IsDirty = true; + T previousValue = m_InternalValue; + m_InternalValue = value; + OnValueChanged?.Invoke(previousValue, m_InternalValue); + } /// /// Writes the variable to the writer diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs index 1cae896568..2fcf40d8f8 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs @@ -1,5 +1,6 @@ using NUnit.Framework; using Unity.Netcode.Prototyping; +using UnityEditor.AssetImporters; using UnityEngine; namespace Unity.Netcode.RuntimeTests @@ -66,7 +67,9 @@ public void TestSyncAxes( networkTransform.transform.eulerAngles = new Vector3(30, 45, 90); networkTransform.transform.localScale = new Vector3(1.1f, 0.5f, 2.5f); - bool isDirty = networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef); + var tmp = networkTransform.ReplNetworkState.Value; + bool isDirty = networkTransform.UpdateNetworkState(ref tmp); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ReplNetworkState.SetDirty(isDirty); Assert.IsTrue(isDirty); } @@ -75,7 +78,9 @@ public void TestSyncAxes( { networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - bool isDirty = networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef); + var tmp = networkTransform.ReplNetworkState.Value; + bool isDirty = networkTransform.UpdateNetworkState(ref tmp); + networkTransform.ReplNetworkState.Value = tmp; Assert.IsFalse(isDirty); } @@ -92,7 +97,9 @@ public void TestSyncAxes( position.x++; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // SyncPositionY { @@ -101,7 +108,9 @@ public void TestSyncAxes( position.y++; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // SyncPositionZ { @@ -110,7 +119,9 @@ public void TestSyncAxes( position.z++; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // SyncRotAngleX @@ -120,7 +131,9 @@ public void TestSyncAxes( rotAngles.x++; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // SyncRotAngleY { @@ -129,7 +142,9 @@ public void TestSyncAxes( rotAngles.y++; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // SyncRotAngleZ { @@ -138,7 +153,9 @@ public void TestSyncAxes( rotAngles.z++; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // SyncScaleX @@ -148,7 +165,9 @@ public void TestSyncAxes( scale.x++; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // SyncScaleY { @@ -157,7 +176,9 @@ public void TestSyncAxes( scale.y++; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // SyncScaleZ { @@ -166,7 +187,9 @@ public void TestSyncAxes( scale.z++; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } } @@ -227,7 +250,9 @@ public void TestThresholds( networkTransform.transform.eulerAngles = new Vector3(30, 45, 90); networkTransform.transform.localScale = new Vector3(1.1f, 0.5f, 2.5f); - bool isDirty = networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef); + var tmp = networkTransform.ReplNetworkState.Value; + bool isDirty = networkTransform.UpdateNetworkState(ref tmp); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ReplNetworkState.SetDirty(isDirty); Assert.IsTrue(isDirty); } @@ -236,7 +261,10 @@ public void TestThresholds( { networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - bool isDirty = networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef); + var tmp = networkTransform.ReplNetworkState.Value; + bool isDirty = networkTransform.UpdateNetworkState(ref tmp); + networkTransform.ReplNetworkState.Value = tmp; + networkTransform.ReplNetworkState.SetDirty(isDirty); Assert.IsFalse(isDirty); } @@ -253,42 +281,61 @@ public void TestThresholds( { position.x += positionThreshold / 2; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; position.x += positionThreshold * 2; networkTransform.transform.position = position; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // PositionY { position.y += positionThreshold / 2; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; position.y += positionThreshold * 2; networkTransform.transform.position = position; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // PositionZ { position.z += positionThreshold / 2; networkTransform.transform.position = position; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; position.z += positionThreshold * 2; networkTransform.transform.position = position; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } } @@ -301,42 +348,60 @@ public void TestThresholds( { rotAngles.x += rotAngleThreshold / 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; rotAngles.x += rotAngleThreshold * 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // RotAngleY { rotAngles.y += rotAngleThreshold / 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; rotAngles.y += rotAngleThreshold * 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // RotAngleZ { rotAngles.z += rotAngleThreshold / 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; rotAngles.z += rotAngleThreshold * 2; networkTransform.transform.eulerAngles = rotAngles; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } } @@ -349,42 +414,60 @@ public void TestThresholds( { scale.x += scaleThreshold / 2; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; scale.x += scaleThreshold * 2; networkTransform.transform.localScale = scale; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // ScaleY { scale.y += scaleThreshold / 2; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; scale.y += scaleThreshold * 2; networkTransform.transform.localScale = scale; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } // ScaleZ { scale.z += scaleThreshold / 2; networkTransform.transform.localScale = scale; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + var tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; scale.z += scaleThreshold * 2; networkTransform.transform.localScale = scale; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransform.ReplNetworkState.ValueRef)); + tmp = networkTransform.ReplNetworkState.Value; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); + networkTransform.ReplNetworkState.Value = tmp; } } } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs index 42f30990a7..8a46f64867 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs @@ -61,12 +61,13 @@ public class NetworkVariableTests : BaseMultiInstanceTest private const int k_TestVal1 = 111; private const int k_TestVal2 = 222; private const int k_TestVal3 = 333; + private const int k_TestVal4 = 444; private const int k_TestKey1 = 0x0f0f; private const int k_TestKey2 = 0xf0f0; - private NetworkVariableTest m_ServerVersionPlayer1Comp; - private NetworkVariableTest m_ServerVersionPlayer2Comp; + private NetworkVariableTest m_ServersPlayer1Comp; + private NetworkVariableTest m_ServersPlayer2Comp; private NetworkVariableTest m_ClientComp; private NetworkVariableTest m_ClientComp2; @@ -88,12 +89,12 @@ public override IEnumerator Setup() yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, m_ServerNetworkManager, result1)); - m_ServerVersionPlayer1Comp = result1.Result.GetComponent(); + m_ServersPlayer1Comp = result1.Result.GetComponent(); yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[1].LocalClientId, m_ServerNetworkManager, result2)); - m_ServerVersionPlayer2Comp = result2.Result.GetComponent(); + m_ServersPlayer2Comp = result2.Result.GetComponent(); // This is the *CLIENT VERSION* of the *CLIENT PLAYER 1* var clientClientPlayerResult = new MultiInstanceHelpers.CoroutineResultWrapper(); @@ -112,11 +113,11 @@ public override IEnumerator Setup() var clientSideClientPlayer2 = clientClientPlayerResult2.Result; m_ClientComp2 = clientSideClientPlayer2.GetComponent(); - m_ServerVersionPlayer1Comp.TheList.Clear(); - m_ServerVersionPlayer1Comp.TheSet.Clear(); - m_ServerVersionPlayer1Comp.TheDictionary.Clear(); + m_ServersPlayer1Comp.TheList.Clear(); + m_ServersPlayer1Comp.TheSet.Clear(); + m_ServersPlayer1Comp.TheDictionary.Clear(); - if (m_ServerVersionPlayer1Comp.TheList.Count > 0 || m_ServerVersionPlayer1Comp.TheSet.Count > 0 || m_ServerVersionPlayer1Comp.TheDictionary.Count > 0) + if (m_ServersPlayer1Comp.TheList.Count > 0 || m_ServersPlayer1Comp.TheSet.Count > 0 || m_ServersPlayer1Comp.TheDictionary.Count > 0) { throw new Exception("at least one server network container not empty at start"); } @@ -172,37 +173,26 @@ public IEnumerator AllNetworkVariableTypes() NetworkManagerHelper.ShutdownNetworkManager(); } - [UnityTest] - public IEnumerator ServerPermissionTest() + [Test] + public void ClientWritePermissionTest() { - yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => - { - m_ServerVersionPlayer1Comp.TheScalar.Value = k_TestVal1; - m_ServerVersionPlayer2Comp.TheScalar.Value = k_TestVal2; - m_ClientComp.TheScalar.Value = k_TestVal2; - m_ClientComp2.TheScalar.Value = k_TestVal3; - }, - () => - { - // the client should not have overwritten the server, and the server's - // write will stomp the client's value - return m_ServerVersionPlayer1Comp.TheScalar.Value == k_TestVal1 && - m_ServerVersionPlayer2Comp.TheScalar.Value == k_TestVal2 && - m_ClientComp.TheScalar.Value == k_TestVal1 && - m_ClientComp2.TheScalar.Value == k_TestVal2; - } - ); + // server must not be allowed to write to a client auth variable + Assert.Throws(() => m_ClientComp.TheScalar.Value = k_TestVal1); + } + + [Test] + public void ServerWritePermissionTest() + { + // server must not be allowed to write to a client auth variable + Assert.Throws(() => m_ServersPlayer1Comp.ClientVar.Value = k_TestVal1); } [UnityTest] - public IEnumerator ClientPermissionTest() + public IEnumerator ClientNetvarTest() { yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.ClientVar.Value = k_TestVal1; - m_ServerVersionPlayer2Comp.ClientVar.Value = k_TestVal1; m_ClientComp.ClientVar.Value = k_TestVal2; m_ClientComp2.ClientVar.Value = k_TestVal3; }, @@ -210,8 +200,8 @@ public IEnumerator ClientPermissionTest() { // the client's values should win on the objects it owns return - m_ServerVersionPlayer1Comp.ClientVar.Value == k_TestVal2 && - m_ServerVersionPlayer2Comp.ClientVar.Value == k_TestVal3 && + m_ServersPlayer1Comp.ClientVar.Value == k_TestVal2 && + m_ServersPlayer2Comp.ClientVar.Value == k_TestVal3 && m_ClientComp.ClientVar.Value == k_TestVal2 && m_ClientComp2.ClientVar.Value == k_TestVal3; } @@ -224,18 +214,18 @@ public IEnumerator NetworkListAdd() yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.TheList.Add(k_TestVal1); - m_ServerVersionPlayer1Comp.TheList.Add(k_TestVal2); + m_ServersPlayer1Comp.TheList.Add(k_TestVal1); + m_ServersPlayer1Comp.TheList.Add(k_TestVal2); }, () => { - return m_ServerVersionPlayer1Comp.TheList.Count == 2 && + return m_ServersPlayer1Comp.TheList.Count == 2 && m_ClientComp.TheList.Count == 2 && - m_ServerVersionPlayer1Comp.ListDelegateTriggered && + m_ServersPlayer1Comp.ListDelegateTriggered && m_ClientComp.ListDelegateTriggered && - m_ServerVersionPlayer1Comp.TheList[0] == k_TestVal1 && + m_ServersPlayer1Comp.TheList[0] == k_TestVal1 && m_ClientComp.TheList[0] == k_TestVal1 && - m_ServerVersionPlayer1Comp.TheList[1] == k_TestVal2 && + m_ServersPlayer1Comp.TheList[1] == k_TestVal2 && m_ClientComp.TheList[1] == k_TestVal2; } ); @@ -248,14 +238,14 @@ public IEnumerator NetworkListRemove() yield return NetworkListAdd(); yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => m_ServerVersionPlayer1Comp.TheList.RemoveAt(0), + () => m_ServersPlayer1Comp.TheList.RemoveAt(0), () => { - return m_ServerVersionPlayer1Comp.TheList.Count == 1 && + return m_ServersPlayer1Comp.TheList.Count == 1 && m_ClientComp.TheList.Count == 1 && - m_ServerVersionPlayer1Comp.ListDelegateTriggered && + m_ServersPlayer1Comp.ListDelegateTriggered && m_ClientComp.ListDelegateTriggered && - m_ServerVersionPlayer1Comp.TheList[0] == k_TestVal2 && + m_ServersPlayer1Comp.TheList[0] == k_TestVal2 && m_ClientComp.TheList[0] == k_TestVal2; } ); @@ -268,13 +258,13 @@ public IEnumerator NetworkListClear() yield return NetworkListAdd(); yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => m_ServerVersionPlayer1Comp.TheList.Clear(), + () => m_ServersPlayer1Comp.TheList.Clear(), () => { return - m_ServerVersionPlayer1Comp.ListDelegateTriggered && + m_ServersPlayer1Comp.ListDelegateTriggered && m_ClientComp.ListDelegateTriggered && - m_ServerVersionPlayer1Comp.TheList.Count == 0 && + m_ServersPlayer1Comp.TheList.Count == 0 && m_ClientComp.TheList.Count == 0; } ); @@ -286,18 +276,18 @@ public IEnumerator NetworkSetAdd() yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.TheSet.Add(k_TestVal1); - m_ServerVersionPlayer1Comp.TheSet.Add(k_TestVal2); + m_ServersPlayer1Comp.TheSet.Add(k_TestVal1); + m_ServersPlayer1Comp.TheSet.Add(k_TestVal2); }, () => { - return m_ServerVersionPlayer1Comp.TheSet.Count == 2 && + return m_ServersPlayer1Comp.TheSet.Count == 2 && m_ClientComp.TheSet.Count == 2 && - m_ServerVersionPlayer1Comp.SetDelegateTriggered && + m_ServersPlayer1Comp.SetDelegateTriggered && m_ClientComp.SetDelegateTriggered && - m_ServerVersionPlayer1Comp.TheSet.Contains(k_TestVal1) && + m_ServersPlayer1Comp.TheSet.Contains(k_TestVal1) && m_ClientComp.TheSet.Contains(k_TestVal1) && - m_ServerVersionPlayer1Comp.TheSet.Contains(k_TestVal2) && + m_ServersPlayer1Comp.TheSet.Contains(k_TestVal2) && m_ClientComp.TheSet.Contains(k_TestVal2); } ); @@ -312,15 +302,15 @@ public IEnumerator NetworkSetRemove() yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.TheSet.Remove(k_TestVal1); + m_ServersPlayer1Comp.TheSet.Remove(k_TestVal1); }, () => { - return m_ServerVersionPlayer1Comp.TheSet.Count == 1 && + return m_ServersPlayer1Comp.TheSet.Count == 1 && m_ClientComp.TheSet.Count == 1 && - m_ServerVersionPlayer1Comp.SetDelegateTriggered && + m_ServersPlayer1Comp.SetDelegateTriggered && m_ClientComp.SetDelegateTriggered && - m_ServerVersionPlayer1Comp.TheSet.Contains(k_TestVal2) && + m_ServersPlayer1Comp.TheSet.Contains(k_TestVal2) && m_ClientComp.TheSet.Contains(k_TestVal2); } ); @@ -335,13 +325,13 @@ public IEnumerator NetworkSetClear() yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.TheSet.Clear(); + m_ServersPlayer1Comp.TheSet.Clear(); }, () => { - return m_ServerVersionPlayer1Comp.TheSet.Count == 0 && + return m_ServersPlayer1Comp.TheSet.Count == 0 && m_ClientComp.TheSet.Count == 0 && - m_ServerVersionPlayer1Comp.SetDelegateTriggered && + m_ServersPlayer1Comp.SetDelegateTriggered && m_ClientComp.SetDelegateTriggered; } ); @@ -353,18 +343,18 @@ public IEnumerator NetworkDictionaryAdd() yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.TheDictionary.Add(k_TestKey1, k_TestVal1); - m_ServerVersionPlayer1Comp.TheDictionary.Add(k_TestKey2, k_TestVal2); + m_ServersPlayer1Comp.TheDictionary.Add(k_TestKey1, k_TestVal1); + m_ServersPlayer1Comp.TheDictionary.Add(k_TestKey2, k_TestVal2); }, () => { - return m_ServerVersionPlayer1Comp.TheDictionary.Count == 2 && + return m_ServersPlayer1Comp.TheDictionary.Count == 2 && m_ClientComp.TheDictionary.Count == 2 && - m_ServerVersionPlayer1Comp.DictionaryDelegateTriggered && + m_ServersPlayer1Comp.DictionaryDelegateTriggered && m_ClientComp.DictionaryDelegateTriggered && - m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal1 && + m_ServersPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal1 && m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal1 && - m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey2] == k_TestVal2 && + m_ServersPlayer1Comp.TheDictionary[k_TestKey2] == k_TestVal2 && m_ClientComp.TheDictionary[k_TestKey2] == k_TestVal2; } ); @@ -382,15 +372,15 @@ public IEnumerator NetworkDictionaryRemoveByKey() yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.TheDictionary.Remove(k_TestKey2); + m_ServersPlayer1Comp.TheDictionary.Remove(k_TestKey2); }, () => { - return m_ServerVersionPlayer1Comp.TheDictionary.Count == 1 && + return m_ServersPlayer1Comp.TheDictionary.Count == 1 && m_ClientComp.TheDictionary.Count == 1 && - m_ServerVersionPlayer1Comp.DictionaryDelegateTriggered && + m_ServersPlayer1Comp.DictionaryDelegateTriggered && m_ClientComp.DictionaryDelegateTriggered && - m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal1 && + m_ServersPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal1 && m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal1; } ); @@ -405,15 +395,15 @@ public IEnumerator NetworkDictionaryChangeValue() yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey1] = k_TestVal3; + m_ServersPlayer1Comp.TheDictionary[k_TestKey1] = k_TestVal3; }, () => { - return m_ServerVersionPlayer1Comp.TheDictionary.Count == 2 && + return m_ServersPlayer1Comp.TheDictionary.Count == 2 && m_ClientComp.TheDictionary.Count == 2 && - m_ServerVersionPlayer1Comp.DictionaryDelegateTriggered && + m_ServersPlayer1Comp.DictionaryDelegateTriggered && m_ClientComp.DictionaryDelegateTriggered && - m_ServerVersionPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal3 && + m_ServersPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal3 && m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal3; } ); @@ -428,13 +418,13 @@ public IEnumerator NetworkDictionaryClear() yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.TheDictionary.Clear(); + m_ServersPlayer1Comp.TheDictionary.Clear(); }, () => { - return m_ServerVersionPlayer1Comp.TheDictionary.Count == 0 && + return m_ServersPlayer1Comp.TheDictionary.Count == 0 && m_ClientComp.TheDictionary.Count == 0 && - m_ServerVersionPlayer1Comp.DictionaryDelegateTriggered && + m_ServersPlayer1Comp.DictionaryDelegateTriggered && m_ClientComp.DictionaryDelegateTriggered; } ); @@ -446,9 +436,9 @@ public IEnumerator TestNetworkVariableStruct() yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServerVersionPlayer1Comp.TheStruct.Value = + m_ServersPlayer1Comp.TheStruct.Value = new TestStruct() { SomeInt = k_TestUInt, SomeBool = false }; - m_ServerVersionPlayer1Comp.TheStruct.SetDirty(true); + m_ServersPlayer1Comp.TheStruct.SetDirty(true); }, () => { From acc1db206c6e056ca96f6380d0620e1d4f222a78 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Mon, 23 Aug 2021 17:23:50 -0700 Subject: [PATCH 10/25] cleanup --- .../NetworkVariable/NetworkVariablePermission.cs | 13 ------------- .../Runtime/Reflection/TypeExtensions.cs | 1 - 2 files changed, 14 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariablePermission.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariablePermission.cs index 2a070de841..df2456f7e2 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariablePermission.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariablePermission.cs @@ -3,19 +3,6 @@ namespace Unity.Netcode /// /// Permission type /// -// public enum NetworkVariableWritePermission -// { -// /// -// /// Server-only operation -// /// -// ServerOnly, -// -// /// -// /// Owner-ownly -// /// -// OwnerOnly, -// } - public enum NetworkVariableReadPermission { /// diff --git a/com.unity.netcode.gameobjects/Runtime/Reflection/TypeExtensions.cs b/com.unity.netcode.gameobjects/Runtime/Reflection/TypeExtensions.cs index 5d325c1e9d..216e489e0a 100644 --- a/com.unity.netcode.gameobjects/Runtime/Reflection/TypeExtensions.cs +++ b/com.unity.netcode.gameobjects/Runtime/Reflection/TypeExtensions.cs @@ -4,7 +4,6 @@ namespace Unity.Netcode { internal static class TypeExtensions { - //?? internal static bool HasInterface(this Type type, Type interfaceType) { var ifaces = type.GetInterfaces(); From 0d7555b51fa5d935f9694297499ffd3bd8a1b712 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Mon, 23 Aug 2021 18:31:00 -0700 Subject: [PATCH 11/25] added host tests --- .../Runtime/Core/NetworkBehaviour.cs | 2 +- .../NetworkVariable/ClientNetworkVariable.cs | 5 +- .../NetworkVariable/NetworkVariable.cs | 5 +- .../Tests/Runtime/NetworkVariableTests.cs | 71 +++++++++++++------ 4 files changed, 57 insertions(+), 26 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index 486374b916..e674c54aa6 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -523,7 +523,7 @@ private void NetworkVariableUpdate(ulong clientId, int behaviourIndex) var writtenAny = false; for (int k = 0; k < NetworkVariableFields.Count; k++) { - // could skip up here if not client, etc + // could skip up here if not client, etc if (!m_ChannelMappedNetworkVariableIndexes[j].Contains(k)) { // This var does not belong to the currently iterating channel group. diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs index 5be59ad21d..1939bfeaaf 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -33,8 +33,11 @@ public override T Value get => m_InternalValue; set { - // this could be improved. The Networking Manager is not always initialized here. + // this could be improved. The Networking Manager is not always initialized here // Good place to decouple network manager from the network variable + + // Also, note this is not really very water-tight, if you are running as a host + // we cannot tell if a ClientNetworkVariable write is happening inside server-ish code if (m_NetworkBehaviour.NetworkManager.IsServer) { throw new InvalidOperationException("Server not allowed to write to ClientNetworkVariables"); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index fd43bda442..ea3bf4ac90 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -65,7 +65,10 @@ public virtual T Value { // this could be improved. The Networking Manager is not always initialized here // Good place to decouple network manager from the network variable - if (m_NetworkBehaviour && m_NetworkBehaviour.NetworkManager.IsClient) + + // Also, note this is not really very water-tight, if you are running as a host + // we cannot tell if a NetworkVariable write is happening inside client-ish code + if (m_NetworkBehaviour && (m_NetworkBehaviour.NetworkManager.IsClient && !m_NetworkBehaviour.NetworkManager.IsHost)) { throw new InvalidOperationException("Client can't write to NetworkVariables"); } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs index 8a46f64867..3c8c07650c 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs @@ -71,7 +71,7 @@ public class NetworkVariableTests : BaseMultiInstanceTest private NetworkVariableTest m_ClientComp; private NetworkVariableTest m_ClientComp2; - private readonly bool m_TestWithHost = false; + private bool m_TestWithHost = false; [UnitySetUp] public override IEnumerator Setup() @@ -131,8 +131,10 @@ public override IEnumerator Setup() /// Runs generalized tests on all predefined NetworkVariable types /// [UnityTest] - public IEnumerator AllNetworkVariableTypes() + public IEnumerator AllNetworkVariableTypes([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + // Create, instantiate, and host // This would normally go in Setup, but since every other test but this one // uses MultiInstanceHelper, and it does its own NetworkManager setup / teardown, @@ -174,22 +176,28 @@ public IEnumerator AllNetworkVariableTypes() } [Test] - public void ClientWritePermissionTest() + public void ClientWritePermissionTest([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + // server must not be allowed to write to a client auth variable Assert.Throws(() => m_ClientComp.TheScalar.Value = k_TestVal1); } [Test] - public void ServerWritePermissionTest() + public void ServerWritePermissionTest([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + // server must not be allowed to write to a client auth variable Assert.Throws(() => m_ServersPlayer1Comp.ClientVar.Value = k_TestVal1); } [UnityTest] - public IEnumerator ClientNetvarTest() + public IEnumerator ClientNetvarTest([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { @@ -209,8 +217,9 @@ public IEnumerator ClientNetvarTest() } [UnityTest] - public IEnumerator NetworkListAdd() + public IEnumerator NetworkListAdd([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { @@ -232,10 +241,11 @@ public IEnumerator NetworkListAdd() } [UnityTest] - public IEnumerator NetworkListRemove() + public IEnumerator NetworkListRemove([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; // first put some stuff in; re-use the add test - yield return NetworkListAdd(); + yield return NetworkListAdd(useHost); yield return MultiInstanceHelpers.RunAndWaitForCondition( () => m_ServersPlayer1Comp.TheList.RemoveAt(0), @@ -252,10 +262,12 @@ public IEnumerator NetworkListRemove() } [UnityTest] - public IEnumerator NetworkListClear() + public IEnumerator NetworkListClear([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + // first put some stuff in; re-use the add test - yield return NetworkListAdd(); + yield return NetworkListAdd(useHost); yield return MultiInstanceHelpers.RunAndWaitForCondition( () => m_ServersPlayer1Comp.TheList.Clear(), @@ -271,8 +283,10 @@ public IEnumerator NetworkListClear() } [UnityTest] - public IEnumerator NetworkSetAdd() + public IEnumerator NetworkSetAdd([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { @@ -294,10 +308,12 @@ public IEnumerator NetworkSetAdd() } [UnityTest] - public IEnumerator NetworkSetRemove() + public IEnumerator NetworkSetRemove([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + // first put some stuff in; re-use the add test - yield return NetworkSetAdd(); + yield return NetworkSetAdd(useHost); yield return MultiInstanceHelpers.RunAndWaitForCondition( () => @@ -317,10 +333,10 @@ public IEnumerator NetworkSetRemove() } [UnityTest] - public IEnumerator NetworkSetClear() + public IEnumerator NetworkSetClear([Values(true, false)] bool useHost) { // first put some stuff in; re-use the add test - yield return NetworkSetAdd(); + yield return NetworkSetAdd(useHost); yield return MultiInstanceHelpers.RunAndWaitForCondition( () => @@ -338,8 +354,10 @@ public IEnumerator NetworkSetClear() } [UnityTest] - public IEnumerator NetworkDictionaryAdd() + public IEnumerator NetworkDictionaryAdd([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { @@ -364,10 +382,12 @@ public IEnumerator NetworkDictionaryAdd() * this in the next PR */ [UnityTest] - public IEnumerator NetworkDictionaryRemoveByKey() + public IEnumerator NetworkDictionaryRemoveByKey([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + // first put some stuff in; re-use the add test - yield return NetworkDictionaryAdd(); + yield return NetworkDictionaryAdd(useHost); yield return MultiInstanceHelpers.RunAndWaitForCondition( () => @@ -387,10 +407,12 @@ public IEnumerator NetworkDictionaryRemoveByKey() } [UnityTest] - public IEnumerator NetworkDictionaryChangeValue() + public IEnumerator NetworkDictionaryChangeValue([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + // first put some stuff in; re-use the add test - yield return NetworkDictionaryAdd(); + yield return NetworkDictionaryAdd(useHost); yield return MultiInstanceHelpers.RunAndWaitForCondition( () => @@ -410,10 +432,12 @@ public IEnumerator NetworkDictionaryChangeValue() } [UnityTest] - public IEnumerator NetworkDictionaryClear() + public IEnumerator NetworkDictionaryClear([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; + // first put some stuff in; re-use the add test - yield return NetworkDictionaryAdd(); + yield return NetworkDictionaryAdd(useHost); yield return MultiInstanceHelpers.RunAndWaitForCondition( () => @@ -431,8 +455,9 @@ public IEnumerator NetworkDictionaryClear() } [UnityTest] - public IEnumerator TestNetworkVariableStruct() + public IEnumerator TestNetworkVariableStruct([Values(true, false)] bool useHost) { + m_TestWithHost = useHost; yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { From ae454773d65a1308aab749d91fe64e391b639561 Mon Sep 17 00:00:00 2001 From: "M. Fatih MAR" Date: Tue, 24 Aug 2021 14:59:53 +0100 Subject: [PATCH 12/25] promoto tmp netstate to be a legit member --- .../Prototyping/NetworkTransform.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs b/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs index 67d94bdc13..f19bd8e9cb 100644 --- a/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs +++ b/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs @@ -156,6 +156,7 @@ public void NetworkSerialize(NetworkSerializer serializer) public float FixedSendsPerSecond = 30f; private Transform m_Transform; // cache the transform component to reduce unnecessary bounce between managed and native + internal NetworkState LocalNetworkState; internal readonly NetworkVariable ReplNetworkState = new NetworkVariable(new NetworkState()); internal NetworkState PrevNetworkState; @@ -385,14 +386,13 @@ private void FixedUpdate() if (IsServer) { - // save off current value - var tmp = ReplNetworkState.Value; - - // mutate the tmp value, set dirty if we mutated it - ReplNetworkState.SetDirty(UpdateNetworkState(ref tmp)); - - // commit the value - ReplNetworkState.Value = tmp; + // try to update local NetworkState + if (UpdateNetworkState(ref LocalNetworkState)) + { + // if updated (dirty), change NetVar, mark it dirty + ReplNetworkState.Value = LocalNetworkState; + ReplNetworkState.SetDirty(true); + } } // try to update previously consumed NetworkState // if we have any changes, that means made some updates locally From 77262383f61c82b782b6cb518cdd3cd9fc5165f4 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Tue, 24 Aug 2021 08:49:59 -0700 Subject: [PATCH 13/25] hrm channel --- .../Runtime/NetworkVariable/INetworkVariable.cs | 2 +- .../Tests/Runtime/NetworkVarBufferCopyTest.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs index ba894beb02..72d00ee60b 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs @@ -35,7 +35,7 @@ protected INetworkVariable(NetworkVariableSettings settings) /// Returns the name of the channel to be used for syncing /// /// The name of the channel to be used for syncing - public NetworkChannel GetChannel() + public virtual NetworkChannel GetChannel() { return Settings.SendNetworkChannel; } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs index 6a375fb12d..19d16a7ef5 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs @@ -15,10 +15,10 @@ public class DummyNetVar : INetworkVariable public bool DeltaRead; public bool FieldRead; -//hrm public override NetworkChannel GetChannel() -//hrm { -//hrm return NetworkChannel.NetworkVariable; -//hrm } + public override NetworkChannel GetChannel() + { + return NetworkChannel.NetworkVariable; + } public override void WriteDelta(Stream stream) { From e205ded3f7573d94857809fb315d65a65383b65c Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Tue, 24 Aug 2021 09:52:00 -0700 Subject: [PATCH 14/25] fix NetworkVarBufferCopyTest --- .../Runtime/NetworkVariable/INetworkVariable.cs | 2 +- .../Tests/Runtime/NetworkVarBufferCopyTest.cs | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs index 72d00ee60b..6481f1830a 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs @@ -43,7 +43,7 @@ public virtual NetworkChannel GetChannel() /// /// Sets whether or not the variable needs to be delta synced /// - public void SetDirty(bool isDirty) + public virtual void SetDirty(bool isDirty) { m_IsDirty = isDirty; } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs index 19d16a7ef5..9fab16facb 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs @@ -1,6 +1,7 @@ using System.Collections; using System.IO; using NUnit.Framework; +using UnityEngine; using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests @@ -14,7 +15,17 @@ public class DummyNetVar : INetworkVariable public bool FieldWritten; public bool DeltaRead; public bool FieldRead; + public bool Dirty = true; + public override void ResetDirty() + { + Dirty = false; + } + + public override bool IsDirty() + { + return Dirty; + } public override NetworkChannel GetChannel() { return NetworkChannel.NetworkVariable; From fb50bdd82be4799bcf3e4d050a781bc56ec3b633 Mon Sep 17 00:00:00 2001 From: "M. Fatih MAR" Date: Tue, 24 Aug 2021 20:30:23 +0100 Subject: [PATCH 15/25] fix networktransformstatetests --- .../NetworkTransformStateTests.cs | 201 ++++-------------- 1 file changed, 36 insertions(+), 165 deletions(-) diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs index 2fcf40d8f8..f36ea0408e 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs @@ -1,6 +1,5 @@ using NUnit.Framework; using Unity.Netcode.Prototyping; -using UnityEditor.AssetImporters; using UnityEngine; namespace Unity.Netcode.RuntimeTests @@ -37,7 +36,7 @@ public void TestSyncAxes( networkTransform.SyncScaleZ = syncScaZ; networkTransform.InLocalSpace = inLocalSpace; - networkTransform.ReplNetworkState.Value = new NetworkTransform.NetworkState + var networkTransformState = new NetworkTransform.NetworkState { PositionX = initialPosition.x, PositionY = initialPosition.y, @@ -62,29 +61,17 @@ public void TestSyncAxes( // Step 1: change properties, expect state to be dirty { - networkTransform.InLocalSpace = !inLocalSpace; networkTransform.transform.position = new Vector3(3, 4, 5); networkTransform.transform.eulerAngles = new Vector3(30, 45, 90); networkTransform.transform.localScale = new Vector3(1.1f, 0.5f, 2.5f); - var tmp = networkTransform.ReplNetworkState.Value; - bool isDirty = networkTransform.UpdateNetworkState(ref tmp); - networkTransform.ReplNetworkState.Value = tmp; - networkTransform.ReplNetworkState.SetDirty(isDirty); - Assert.IsTrue(isDirty); - } - - // Step 2: apply current state locally, expect state to be not dirty/different - { - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - - var tmp = networkTransform.ReplNetworkState.Value; - bool isDirty = networkTransform.UpdateNetworkState(ref tmp); - networkTransform.ReplNetworkState.Value = tmp; - Assert.IsFalse(isDirty); + if (syncPosX || syncPosY || syncPosZ || syncRotX || syncRotY || syncRotZ || syncScaX || syncScaY || syncScaZ) + { + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); + } } - // Step 3: disable a particular sync flag, expect state to be not dirty + // Step 2: disable a particular sync flag, expect state to be not dirty { var position = networkTransform.transform.position; var rotAngles = networkTransform.transform.eulerAngles; @@ -97,9 +84,7 @@ public void TestSyncAxes( position.x++; networkTransform.transform.position = position; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); } // SyncPositionY { @@ -108,9 +93,7 @@ public void TestSyncAxes( position.y++; networkTransform.transform.position = position; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); } // SyncPositionZ { @@ -119,9 +102,7 @@ public void TestSyncAxes( position.z++; networkTransform.transform.position = position; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); } // SyncRotAngleX @@ -131,9 +112,7 @@ public void TestSyncAxes( rotAngles.x++; networkTransform.transform.eulerAngles = rotAngles; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); } // SyncRotAngleY { @@ -142,9 +121,7 @@ public void TestSyncAxes( rotAngles.y++; networkTransform.transform.eulerAngles = rotAngles; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); } // SyncRotAngleZ { @@ -153,9 +130,7 @@ public void TestSyncAxes( rotAngles.z++; networkTransform.transform.eulerAngles = rotAngles; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); } // SyncScaleX @@ -165,9 +140,7 @@ public void TestSyncAxes( scale.x++; networkTransform.transform.localScale = scale; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); } // SyncScaleY { @@ -176,9 +149,7 @@ public void TestSyncAxes( scale.y++; networkTransform.transform.localScale = scale; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); } // SyncScaleZ { @@ -187,9 +158,7 @@ public void TestSyncAxes( scale.z++; networkTransform.transform.localScale = scale; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); } } @@ -229,7 +198,7 @@ public void TestThresholds( networkTransform.RotAngleThreshold = rotAngleThreshold; networkTransform.ScaleThreshold = scaleThreshold; - networkTransform.ReplNetworkState.Value = new NetworkTransform.NetworkState + var networkTransformState = new NetworkTransform.NetworkState { PositionX = initialPosition.x, PositionY = initialPosition.y, @@ -245,30 +214,14 @@ public void TestThresholds( // Step 1: change properties, expect state to be dirty { - networkTransform.InLocalSpace = !inLocalSpace; networkTransform.transform.position = new Vector3(3, 4, 5); networkTransform.transform.eulerAngles = new Vector3(30, 45, 90); networkTransform.transform.localScale = new Vector3(1.1f, 0.5f, 2.5f); - var tmp = networkTransform.ReplNetworkState.Value; - bool isDirty = networkTransform.UpdateNetworkState(ref tmp); - networkTransform.ReplNetworkState.Value = tmp; - networkTransform.ReplNetworkState.SetDirty(isDirty); - Assert.IsTrue(isDirty); + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } - // Step 2: apply current state locally, expect state to be not dirty/different - { - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - - var tmp = networkTransform.ReplNetworkState.Value; - bool isDirty = networkTransform.UpdateNetworkState(ref tmp); - networkTransform.ReplNetworkState.Value = tmp; - networkTransform.ReplNetworkState.SetDirty(isDirty); - Assert.IsFalse(isDirty); - } - - // Step 3: make changes below and above thresholds + // Step 2: make changes below and above thresholds // changes below the threshold should not make `NetworkState` dirty // changes above the threshold should make `NetworkState` dirty { @@ -281,61 +234,33 @@ public void TestThresholds( { position.x += positionThreshold / 2; networkTransform.transform.position = position; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); position.x += positionThreshold * 2; networkTransform.transform.position = position; - - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; - - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } // PositionY { position.y += positionThreshold / 2; networkTransform.transform.position = position; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); position.y += positionThreshold * 2; networkTransform.transform.position = position; - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; - - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } // PositionZ { position.z += positionThreshold / 2; networkTransform.transform.position = position; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); position.z += positionThreshold * 2; networkTransform.transform.position = position; - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; - - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } } @@ -348,60 +273,33 @@ public void TestThresholds( { rotAngles.x += rotAngleThreshold / 2; networkTransform.transform.eulerAngles = rotAngles; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); rotAngles.x += rotAngleThreshold * 2; networkTransform.transform.eulerAngles = rotAngles; - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; - - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } // RotAngleY { rotAngles.y += rotAngleThreshold / 2; networkTransform.transform.eulerAngles = rotAngles; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); rotAngles.y += rotAngleThreshold * 2; networkTransform.transform.eulerAngles = rotAngles; - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; - - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } // RotAngleZ { rotAngles.z += rotAngleThreshold / 2; networkTransform.transform.eulerAngles = rotAngles; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); rotAngles.z += rotAngleThreshold * 2; networkTransform.transform.eulerAngles = rotAngles; - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; - - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } } @@ -414,60 +312,33 @@ public void TestThresholds( { scale.x += scaleThreshold / 2; networkTransform.transform.localScale = scale; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); scale.x += scaleThreshold * 2; networkTransform.transform.localScale = scale; - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; - - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } // ScaleY { scale.y += scaleThreshold / 2; networkTransform.transform.localScale = scale; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); scale.y += scaleThreshold * 2; networkTransform.transform.localScale = scale; - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; - - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } // ScaleZ { scale.z += scaleThreshold / 2; networkTransform.transform.localScale = scale; - var tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsFalse(networkTransform.UpdateNetworkState(ref networkTransformState)); scale.z += scaleThreshold * 2; networkTransform.transform.localScale = scale; - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsTrue(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; - - networkTransform.ApplyNetworkState(networkTransform.ReplNetworkState.Value); - tmp = networkTransform.ReplNetworkState.Value; - Assert.IsFalse(networkTransform.UpdateNetworkState(ref tmp)); - networkTransform.ReplNetworkState.Value = tmp; + Assert.IsTrue(networkTransform.UpdateNetworkState(ref networkTransformState)); } } } From 2b9a477d464e1a7b6e4ce28aeb7884bde8783c96 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Tue, 24 Aug 2021 13:28:39 -0700 Subject: [PATCH 16/25] more container cleanup --- .../Collections/NetworkDictionary.cs | 58 ++++--------------- .../Collections/NetworkList.cs | 49 +++------------- .../NetworkVariable/Collections/NetworkSet.cs | 38 ++++-------- .../NetworkTransformStateTests.cs | 1 - .../Tests/Runtime/NetworkVarBufferCopyTest.cs | 1 - 5 files changed, 30 insertions(+), 117 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 5417bff388..9b2dc42a4d 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -12,11 +12,6 @@ namespace Unity.Netcode /// The type for the dictionary values public class NetworkDictionary : INetworkVariable, IDictionary where TKey : unmanaged where TValue : unmanaged { - /// - /// Gets the last time the variable was synced - /// - public NetworkTime LastSyncedTime { get; internal set; } - private readonly IDictionary m_Dictionary = new Dictionary(); private readonly List> m_DirtyEvents = new List>(); @@ -66,7 +61,6 @@ public override void ResetDirty() { base.ResetDirty(); m_DirtyEvents.Clear(); - LastSyncedTime = m_NetworkBehaviour.NetworkManager.LocalTime; } /// @@ -311,10 +305,7 @@ public TValue this[TKey key] { EnsureInitialized(); - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Dictionary[key] = value; - } + m_Dictionary[key] = value; var dictionaryEvent = new NetworkDictionaryEvent() { @@ -343,11 +334,7 @@ public TValue this[TKey key] public void Add(TKey key, TValue value) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Dictionary.Add(key, value); - } + m_Dictionary.Add(key, value); var dictionaryEvent = new NetworkDictionaryEvent() { @@ -363,11 +350,7 @@ public void Add(TKey key, TValue value) public void Add(KeyValuePair item) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Dictionary.Add(item); - } + m_Dictionary.Add(item); var dictionaryEvent = new NetworkDictionaryEvent() { @@ -383,11 +366,7 @@ public void Add(KeyValuePair item) public void Clear() { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Dictionary.Clear(); - } + m_Dictionary.Clear(); var dictionaryEvent = new NetworkDictionaryEvent() { @@ -425,11 +404,7 @@ public IEnumerator> GetEnumerator() public bool Remove(TKey key) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Dictionary.Remove(key); - } + m_Dictionary.Remove(key); TValue value; m_Dictionary.TryGetValue(key, out value); @@ -451,11 +426,7 @@ public bool Remove(TKey key) public bool Remove(KeyValuePair item) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Dictionary.Remove(item); - } + m_Dictionary.Remove(item); var dictionaryEvent = new NetworkDictionaryEvent() { @@ -476,19 +447,12 @@ IEnumerator IEnumerable.GetEnumerator() private void HandleAddDictionaryEvent(NetworkDictionaryEvent dictionaryEvent) { - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - if (m_NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) - { - m_DirtyEvents.Add(dictionaryEvent); - } + if (m_NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) + { + m_DirtyEvents.Add(dictionaryEvent); + } - OnDictionaryChanged?.Invoke(dictionaryEvent); - } - else - { - m_DirtyEvents.Add(dictionaryEvent); - } + OnDictionaryChanged?.Invoke(dictionaryEvent); } public int LastModifiedTick diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index 324f5f40d8..67ab5f7577 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -339,11 +339,7 @@ IEnumerator IEnumerable.GetEnumerator() public void Add(T item) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_List.Add(item); - } + m_List.Add(item); var listEvent = new NetworkListEvent() { @@ -359,11 +355,7 @@ public void Add(T item) public void Clear() { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_List.Clear(); - } + m_List.Clear(); var listEvent = new NetworkListEvent() { @@ -389,11 +381,7 @@ public void CopyTo(T[] array, int arrayIndex) public bool Remove(T item) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_List.Remove(item); - } + m_List.Remove(item); var listEvent = new NetworkListEvent() { @@ -421,11 +409,7 @@ public int IndexOf(T item) public void Insert(int index, T item) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_List.Insert(index, item); - } + m_List.Insert(index, item); var listEvent = new NetworkListEvent() { @@ -441,11 +425,7 @@ public void Insert(int index, T item) public void RemoveAt(int index) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_List.RemoveAt(index); - } + m_List.RemoveAt(index); var listEvent = new NetworkListEvent() { @@ -464,11 +444,7 @@ public T this[int index] set { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_List[index] = value; - } + m_List[index] = value; var listEvent = new NetworkListEvent() { @@ -483,19 +459,12 @@ public T this[int index] private void HandleAddListEvent(NetworkListEvent listEvent) { - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - if (m_NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) - { - m_DirtyEvents.Add(listEvent); - } - - OnListChanged?.Invoke(listEvent); - } - else + if (m_NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) { m_DirtyEvents.Add(listEvent); } + + OnListChanged?.Invoke(listEvent); } public int LastModifiedTick diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index 805961d36c..a877ecda5a 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -309,10 +309,7 @@ public void SymmetricExceptWith(IEnumerable other) } else { - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Set.Add(value); - } + m_Set.Add(value); var setEvent = new NetworkSetEvent() { @@ -321,7 +318,7 @@ public void SymmetricExceptWith(IEnumerable other) }; m_DirtyEvents.Add(setEvent); - if (m_NetworkBehaviour.NetworkManager.IsServer && OnSetChanged != null) + if (OnSetChanged != null) { OnSetChanged(setEvent); } @@ -338,10 +335,7 @@ public void UnionWith(IEnumerable other) { if (!m_Set.Contains(value)) { - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Set.Add(value); - } + m_Set.Add(value); var setEvent = new NetworkSetEvent() { @@ -350,7 +344,7 @@ public void UnionWith(IEnumerable other) }; m_DirtyEvents.Add(setEvent); - if (m_NetworkBehaviour.NetworkManager.IsServer && OnSetChanged != null) + if (OnSetChanged != null) { OnSetChanged(setEvent); } @@ -361,11 +355,7 @@ public void UnionWith(IEnumerable other) public bool Add(T item) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Set.Add(item); - } + m_Set.Add(item); var setEvent = new NetworkSetEvent() { @@ -374,7 +364,7 @@ public bool Add(T item) }; m_DirtyEvents.Add(setEvent); - if (m_NetworkBehaviour.NetworkManager.IsServer && OnSetChanged != null) + if (OnSetChanged != null) { OnSetChanged(setEvent); } @@ -389,11 +379,7 @@ public bool Add(T item) public void Clear() { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Set.Clear(); - } + m_Set.Clear(); var setEvent = new NetworkSetEvent() { @@ -401,7 +387,7 @@ public void Clear() }; m_DirtyEvents.Add(setEvent); - if (m_NetworkBehaviour.NetworkManager.IsServer && OnSetChanged != null) + if (OnSetChanged != null) { OnSetChanged(setEvent); } @@ -423,11 +409,7 @@ public void CopyTo(T[] array, int arrayIndex) public bool Remove(T item) { EnsureInitialized(); - - if (m_NetworkBehaviour.NetworkManager.IsServer) - { - m_Set.Remove(item); - } + m_Set.Remove(item); var setEvent = new NetworkSetEvent() { @@ -436,7 +418,7 @@ public bool Remove(T item) }; m_DirtyEvents.Add(setEvent); - if (m_NetworkBehaviour.NetworkManager.IsServer && OnSetChanged != null) + if (OnSetChanged != null) { OnSetChanged(setEvent); } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs index 2fcf40d8f8..8ef0c938f6 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs @@ -1,6 +1,5 @@ using NUnit.Framework; using Unity.Netcode.Prototyping; -using UnityEditor.AssetImporters; using UnityEngine; namespace Unity.Netcode.RuntimeTests diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs index 9fab16facb..5b450390e6 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs @@ -1,7 +1,6 @@ using System.Collections; using System.IO; using NUnit.Framework; -using UnityEngine; using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests From 2e0b565791d4658461e3f967c940d168705bb387 Mon Sep 17 00:00:00 2001 From: "M. Fatih MAR" Date: Tue, 24 Aug 2021 21:29:26 +0100 Subject: [PATCH 17/25] put meta file back --- .../Runtime/NetworkTransform/NetworkTransformTests.cs.meta | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs.meta diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs.meta b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs.meta new file mode 100644 index 0000000000..d5b272620d --- /dev/null +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cf4ff0d6357bb4474a404b9ce52b22ad +timeCreated: 1620872927 \ No newline at end of file From aad72e02984c146d198f07d97e9fad65692803d5 Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Tue, 24 Aug 2021 14:49:20 -0700 Subject: [PATCH 18/25] channel cleanup --- .../Prototyping/NetworkTransform.cs | 10 --------- .../Runtime/Core/NetworkBehaviour.cs | 2 +- .../NetworkVariable/INetworkVariable.cs | 14 +++++-------- .../NetworkVariableSettings.cs | 21 ------------------- .../Tests/Runtime/NetworkVarBufferCopyTest.cs | 4 ---- 5 files changed, 6 insertions(+), 45 deletions(-) diff --git a/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs b/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs index f19bd8e9cb..dfeefad15f 100644 --- a/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs +++ b/com.unity.netcode.gameobjects/Prototyping/NetworkTransform.cs @@ -128,12 +128,6 @@ public void NetworkSerialize(NetworkSerializer serializer) } } - /// - /// The network channel to use send updates - /// - [Tooltip("The network channel to use send updates")] - public NetworkChannel Channel = NetworkChannel.NetworkVariable; - /// /// Sets whether this transform should sync in local space or in world space. /// This is important to set since reparenting this transform could have issues, @@ -365,10 +359,6 @@ private void OnNetworkStateChanged(NetworkState oldState, NetworkState newState) private void Awake() { m_Transform = transform; - - ReplNetworkState.Settings.SendNetworkChannel = Channel; - ReplNetworkState.Settings.SendTickrate = FixedSendsPerSecond; - ReplNetworkState.OnValueChanged += OnNetworkStateChanged; } diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index e674c54aa6..645ca597a5 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -442,7 +442,7 @@ internal void InitializeVariables() for (int i = 0; i < NetworkVariableFields.Count; i++) { - NetworkChannel networkChannel = NetworkVariableFields[i].GetChannel(); + NetworkChannel networkChannel = INetworkVariable.NetworkVariableChannel; if (!firstLevelIndex.ContainsKey(networkChannel)) { diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs index 6481f1830a..90a477c361 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs @@ -7,6 +7,11 @@ namespace Unity.Netcode /// public abstract class INetworkVariable { + /// + /// The name of the channel to be used for syncing + /// + public const NetworkChannel NetworkVariableChannel = NetworkChannel.NetworkVariable; + protected INetworkVariable() { } protected INetworkVariable(NetworkVariableSettings settings) @@ -31,15 +36,6 @@ protected INetworkVariable(NetworkVariableSettings settings) /// public readonly NetworkVariableSettings Settings = new NetworkVariableSettings(); - /// - /// Returns the name of the channel to be used for syncing - /// - /// The name of the channel to be used for syncing - public virtual NetworkChannel GetChannel() - { - return Settings.SendNetworkChannel; - } - /// /// Sets whether or not the variable needs to be delta synced /// diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs index 02c69bb2f9..8bedabe0e3 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableSettings.cs @@ -15,26 +15,5 @@ public class NetworkVariableSettings /// Defines the read permissions for this var /// public NetworkVariableReadPermission ReadPermission = NetworkVariableReadPermission.Everyone; - /// - /// The delegate used to evaluate write permission when the "Custom" mode is used - /// - public NetworkVariablePermissionsDelegate WritePermissionCallback = null; - /// - /// The maximum times per second this var will be synced. - /// A value of 0 will cause the variable to sync as soon as possible after being changed. - /// A value of less than 0 will cause the variable to sync only at once at spawn and not update again. - /// - public double SendTickrate = 0; - - /// - /// The name of the channel to use for this variable. - /// Variables with different channels will be split into different packets - /// - public NetworkChannel SendNetworkChannel = NetworkChannel.NetworkVariable; - - /// - /// Constructs a new NetworkVariableSettings instance - /// - public NetworkVariableSettings() { } } } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs index 5b450390e6..464bf3373f 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs @@ -25,10 +25,6 @@ public override bool IsDirty() { return Dirty; } - public override NetworkChannel GetChannel() - { - return NetworkChannel.NetworkVariable; - } public override void WriteDelta(Stream stream) { From 5674c62b93b2efe4b81104ed66c10e73515cdbfb Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Tue, 24 Aug 2021 16:17:11 -0700 Subject: [PATCH 19/25] fixed client perm, more tests, cleanup --- .../NetworkVariable/ClientNetworkVariable.cs | 6 +- .../Tests/Runtime/NetworkVariableTests.cs | 272 ++++++++++-------- 2 files changed, 163 insertions(+), 115 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs index 1939bfeaaf..6012e6a39e 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -15,6 +15,10 @@ namespace Unity.Netcode [Serializable] public class ClientNetworkVariable : NetworkVariable where T : unmanaged { + public ClientNetworkVariable() { } + + public ClientNetworkVariable(NetworkVariableSettings settings) : base(settings) { } + public override bool CanClientWrite(ulong clientId) { return m_NetworkBehaviour.OwnerClientId == clientId; @@ -22,7 +26,7 @@ public override bool CanClientWrite(ulong clientId) public override bool ShouldWrite(ulong clientId, bool isServer) { - return m_IsDirty && !isServer && CanClientRead(clientId) && m_NetworkBehaviour.IsOwner; + return m_IsDirty && !isServer && m_NetworkBehaviour.IsOwner; } /// diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs index 3c8c07650c..48f6c7ca5c 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs @@ -21,6 +21,9 @@ public class NetworkVariableTest : NetworkBehaviour { public readonly ClientNetworkVariable ClientVar = new ClientNetworkVariable(); + public readonly ClientNetworkVariable ClientVarPrivate = + new ClientNetworkVariable(new NetworkVariableSettings { ReadPermission = NetworkVariableReadPermission.OwnerOnly }); + public readonly NetworkVariable TheScalar = new NetworkVariable(); public readonly NetworkList TheList = new NetworkList(); public readonly NetworkSet TheSet = new NetworkSet(); @@ -56,22 +59,31 @@ public class NetworkVariableTests : BaseMultiInstanceTest { protected override int NbClients => 2; - private const uint k_TestUInt = 0xdeadbeef; + private const uint k_TestUInt = 0x12345678; private const int k_TestVal1 = 111; private const int k_TestVal2 = 222; private const int k_TestVal3 = 333; - private const int k_TestVal4 = 444; private const int k_TestKey1 = 0x0f0f; private const int k_TestKey2 = 0xf0f0; - private NetworkVariableTest m_ServersPlayer1Comp; - private NetworkVariableTest m_ServersPlayer2Comp; - private NetworkVariableTest m_ClientComp; - private NetworkVariableTest m_ClientComp2; + // Player1 component on the server + private NetworkVariableTest m_Player1OnServer; + + // Player2 component on the server + private NetworkVariableTest m_Player2OnServer; + + // Player1 component on client1 + private NetworkVariableTest m_Player1OnClient1; + + // Player2 component on client1 + private NetworkVariableTest m_Player1OnClient2; - private bool m_TestWithHost = false; + // client2's version of client1's player object + private NetworkVariableTest m_Player1FromClient2; + + private bool m_TestWithHost; [UnitySetUp] public override IEnumerator Setup() @@ -83,45 +95,50 @@ public override IEnumerator Setup() }); // These are the *SERVER VERSIONS* of the *CLIENT PLAYER 1 & 2* - var result1 = new MultiInstanceHelpers.CoroutineResultWrapper(); - var result2 = new MultiInstanceHelpers.CoroutineResultWrapper(); + var result = new MultiInstanceHelpers.CoroutineResultWrapper(); yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, - m_ServerNetworkManager, result1)); - m_ServersPlayer1Comp = result1.Result.GetComponent(); + m_ServerNetworkManager, result)); + m_Player1OnServer = result.Result.GetComponent(); yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[1].LocalClientId, - m_ServerNetworkManager, result2)); - m_ServersPlayer2Comp = result2.Result.GetComponent(); + m_ServerNetworkManager, result)); + m_Player2OnServer = result.Result.GetComponent(); - // This is the *CLIENT VERSION* of the *CLIENT PLAYER 1* - var clientClientPlayerResult = new MultiInstanceHelpers.CoroutineResultWrapper(); + // This is client1's view of itself yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, - m_ClientNetworkManagers[0], clientClientPlayerResult)); + m_ClientNetworkManagers[0], result)); - var clientSideClientPlayer = clientClientPlayerResult.Result; - m_ClientComp = clientSideClientPlayer.GetComponent(); + m_Player1OnClient1 = result.Result.GetComponent(); - var clientClientPlayerResult2 = new MultiInstanceHelpers.CoroutineResultWrapper(); + // This is client2's view of itself + result = new MultiInstanceHelpers.CoroutineResultWrapper(); yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[1].LocalClientId, - m_ClientNetworkManagers[1], clientClientPlayerResult2)); + m_ClientNetworkManagers[1], result)); - var clientSideClientPlayer2 = clientClientPlayerResult2.Result; - m_ClientComp2 = clientSideClientPlayer2.GetComponent(); + m_Player1OnClient2 = result.Result.GetComponent(); - m_ServersPlayer1Comp.TheList.Clear(); - m_ServersPlayer1Comp.TheSet.Clear(); - m_ServersPlayer1Comp.TheDictionary.Clear(); + // This is client2's view of client 1's object + yield return MultiInstanceHelpers.Run(MultiInstanceHelpers.GetNetworkObjectByRepresentation( + x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, + m_ClientNetworkManagers[1], result)); - if (m_ServersPlayer1Comp.TheList.Count > 0 || m_ServersPlayer1Comp.TheSet.Count > 0 || m_ServersPlayer1Comp.TheDictionary.Count > 0) +// var client2client1 = result.Result; + m_Player1FromClient2 = result.Result.GetComponent(); + + m_Player1OnServer.TheList.Clear(); + m_Player1OnServer.TheSet.Clear(); + m_Player1OnServer.TheDictionary.Clear(); + + if (m_Player1OnServer.TheList.Count > 0 || m_Player1OnServer.TheSet.Count > 0 || m_Player1OnServer.TheDictionary.Count > 0) { throw new Exception("at least one server network container not empty at start"); } - if (m_ClientComp.TheList.Count > 0 || m_ClientComp.TheSet.Count > 0 || m_ClientComp.TheDictionary.Count > 0) + if (m_Player1OnClient1.TheList.Count > 0 || m_Player1OnClient1.TheSet.Count > 0 || m_Player1OnClient1.TheDictionary.Count > 0) { throw new Exception("at least one client network container not empty at start"); } @@ -180,8 +197,8 @@ public void ClientWritePermissionTest([Values(true, false)] bool useHost) { m_TestWithHost = useHost; - // server must not be allowed to write to a client auth variable - Assert.Throws(() => m_ClientComp.TheScalar.Value = k_TestVal1); + // client must not be allowed to write to a server auth variable + Assert.Throws(() => m_Player1OnClient1.TheScalar.Value = k_TestVal1); } [Test] @@ -190,28 +207,55 @@ public void ServerWritePermissionTest([Values(true, false)] bool useHost) m_TestWithHost = useHost; // server must not be allowed to write to a client auth variable - Assert.Throws(() => m_ServersPlayer1Comp.ClientVar.Value = k_TestVal1); + Assert.Throws(() => m_Player1OnServer.ClientVar.Value = k_TestVal1); } [UnityTest] - public IEnumerator ClientNetvarTest([Values(true, false)] bool useHost) + public IEnumerator ClientTest([Values(true, false)] bool useHost) { m_TestWithHost = useHost; yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ClientComp.ClientVar.Value = k_TestVal2; - m_ClientComp2.ClientVar.Value = k_TestVal3; + m_Player1OnClient1.ClientVar.Value = k_TestVal2; + m_Player1OnClient2.ClientVar.Value = k_TestVal3; }, () => { // the client's values should win on the objects it owns return - m_ServersPlayer1Comp.ClientVar.Value == k_TestVal2 && - m_ServersPlayer2Comp.ClientVar.Value == k_TestVal3 && - m_ClientComp.ClientVar.Value == k_TestVal2 && - m_ClientComp2.ClientVar.Value == k_TestVal3; + m_Player1OnServer.ClientVar.Value == k_TestVal2 && + m_Player2OnServer.ClientVar.Value == k_TestVal3 && + m_Player1OnClient1.ClientVar.Value == k_TestVal2 && + m_Player1OnClient2.ClientVar.Value == k_TestVal3; + } + ); + } + + [UnityTest] + public IEnumerator PrivateClientTest([Values(true, false)] bool useHost) + { + m_TestWithHost = useHost; + + yield return MultiInstanceHelpers.RunAndWaitForCondition( + () => + { + // we are writing to the private and public variables on player 1's object... + m_Player1OnClient1.ClientVarPrivate.Value = k_TestVal1; + m_Player1OnClient1.ClientVar.Value = k_TestVal2; + }, + () => + { + // ...and we should see the writes to the private var only on the server & the owner, + // but the public variable everywhere + return + m_Player1FromClient2.ClientVarPrivate.Value != k_TestVal1 && + m_Player1OnClient1.ClientVarPrivate.Value == k_TestVal1 && + m_Player1FromClient2.ClientVar.Value != k_TestVal2 && + m_Player1OnClient1.ClientVar.Value == k_TestVal2 && + m_Player1OnServer.ClientVarPrivate.Value == k_TestVal1 && + m_Player1OnServer.ClientVar.Value == k_TestVal2; } ); } @@ -223,19 +267,19 @@ public IEnumerator NetworkListAdd([Values(true, false)] bool useHost) yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServersPlayer1Comp.TheList.Add(k_TestVal1); - m_ServersPlayer1Comp.TheList.Add(k_TestVal2); + m_Player1OnServer.TheList.Add(k_TestVal1); + m_Player1OnServer.TheList.Add(k_TestVal2); }, () => { - return m_ServersPlayer1Comp.TheList.Count == 2 && - m_ClientComp.TheList.Count == 2 && - m_ServersPlayer1Comp.ListDelegateTriggered && - m_ClientComp.ListDelegateTriggered && - m_ServersPlayer1Comp.TheList[0] == k_TestVal1 && - m_ClientComp.TheList[0] == k_TestVal1 && - m_ServersPlayer1Comp.TheList[1] == k_TestVal2 && - m_ClientComp.TheList[1] == k_TestVal2; + return m_Player1OnServer.TheList.Count == 2 && + m_Player1OnClient1.TheList.Count == 2 && + m_Player1OnServer.ListDelegateTriggered && + m_Player1OnClient1.ListDelegateTriggered && + m_Player1OnServer.TheList[0] == k_TestVal1 && + m_Player1OnClient1.TheList[0] == k_TestVal1 && + m_Player1OnServer.TheList[1] == k_TestVal2 && + m_Player1OnClient1.TheList[1] == k_TestVal2; } ); } @@ -248,15 +292,15 @@ public IEnumerator NetworkListRemove([Values(true, false)] bool useHost) yield return NetworkListAdd(useHost); yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => m_ServersPlayer1Comp.TheList.RemoveAt(0), + () => m_Player1OnServer.TheList.RemoveAt(0), () => { - return m_ServersPlayer1Comp.TheList.Count == 1 && - m_ClientComp.TheList.Count == 1 && - m_ServersPlayer1Comp.ListDelegateTriggered && - m_ClientComp.ListDelegateTriggered && - m_ServersPlayer1Comp.TheList[0] == k_TestVal2 && - m_ClientComp.TheList[0] == k_TestVal2; + return m_Player1OnServer.TheList.Count == 1 && + m_Player1OnClient1.TheList.Count == 1 && + m_Player1OnServer.ListDelegateTriggered && + m_Player1OnClient1.ListDelegateTriggered && + m_Player1OnServer.TheList[0] == k_TestVal2 && + m_Player1OnClient1.TheList[0] == k_TestVal2; } ); } @@ -270,14 +314,14 @@ public IEnumerator NetworkListClear([Values(true, false)] bool useHost) yield return NetworkListAdd(useHost); yield return MultiInstanceHelpers.RunAndWaitForCondition( - () => m_ServersPlayer1Comp.TheList.Clear(), + () => m_Player1OnServer.TheList.Clear(), () => { return - m_ServersPlayer1Comp.ListDelegateTriggered && - m_ClientComp.ListDelegateTriggered && - m_ServersPlayer1Comp.TheList.Count == 0 && - m_ClientComp.TheList.Count == 0; + m_Player1OnServer.ListDelegateTriggered && + m_Player1OnClient1.ListDelegateTriggered && + m_Player1OnServer.TheList.Count == 0 && + m_Player1OnClient1.TheList.Count == 0; } ); } @@ -290,19 +334,19 @@ public IEnumerator NetworkSetAdd([Values(true, false)] bool useHost) yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServersPlayer1Comp.TheSet.Add(k_TestVal1); - m_ServersPlayer1Comp.TheSet.Add(k_TestVal2); + m_Player1OnServer.TheSet.Add(k_TestVal1); + m_Player1OnServer.TheSet.Add(k_TestVal2); }, () => { - return m_ServersPlayer1Comp.TheSet.Count == 2 && - m_ClientComp.TheSet.Count == 2 && - m_ServersPlayer1Comp.SetDelegateTriggered && - m_ClientComp.SetDelegateTriggered && - m_ServersPlayer1Comp.TheSet.Contains(k_TestVal1) && - m_ClientComp.TheSet.Contains(k_TestVal1) && - m_ServersPlayer1Comp.TheSet.Contains(k_TestVal2) && - m_ClientComp.TheSet.Contains(k_TestVal2); + return m_Player1OnServer.TheSet.Count == 2 && + m_Player1OnClient1.TheSet.Count == 2 && + m_Player1OnServer.SetDelegateTriggered && + m_Player1OnClient1.SetDelegateTriggered && + m_Player1OnServer.TheSet.Contains(k_TestVal1) && + m_Player1OnClient1.TheSet.Contains(k_TestVal1) && + m_Player1OnServer.TheSet.Contains(k_TestVal2) && + m_Player1OnClient1.TheSet.Contains(k_TestVal2); } ); } @@ -318,16 +362,16 @@ public IEnumerator NetworkSetRemove([Values(true, false)] bool useHost) yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServersPlayer1Comp.TheSet.Remove(k_TestVal1); + m_Player1OnServer.TheSet.Remove(k_TestVal1); }, () => { - return m_ServersPlayer1Comp.TheSet.Count == 1 && - m_ClientComp.TheSet.Count == 1 && - m_ServersPlayer1Comp.SetDelegateTriggered && - m_ClientComp.SetDelegateTriggered && - m_ServersPlayer1Comp.TheSet.Contains(k_TestVal2) && - m_ClientComp.TheSet.Contains(k_TestVal2); + return m_Player1OnServer.TheSet.Count == 1 && + m_Player1OnClient1.TheSet.Count == 1 && + m_Player1OnServer.SetDelegateTriggered && + m_Player1OnClient1.SetDelegateTriggered && + m_Player1OnServer.TheSet.Contains(k_TestVal2) && + m_Player1OnClient1.TheSet.Contains(k_TestVal2); } ); } @@ -341,14 +385,14 @@ public IEnumerator NetworkSetClear([Values(true, false)] bool useHost) yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServersPlayer1Comp.TheSet.Clear(); + m_Player1OnServer.TheSet.Clear(); }, () => { - return m_ServersPlayer1Comp.TheSet.Count == 0 && - m_ClientComp.TheSet.Count == 0 && - m_ServersPlayer1Comp.SetDelegateTriggered && - m_ClientComp.SetDelegateTriggered; + return m_Player1OnServer.TheSet.Count == 0 && + m_Player1OnClient1.TheSet.Count == 0 && + m_Player1OnServer.SetDelegateTriggered && + m_Player1OnClient1.SetDelegateTriggered; } ); } @@ -361,19 +405,19 @@ public IEnumerator NetworkDictionaryAdd([Values(true, false)] bool useHost) yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServersPlayer1Comp.TheDictionary.Add(k_TestKey1, k_TestVal1); - m_ServersPlayer1Comp.TheDictionary.Add(k_TestKey2, k_TestVal2); + m_Player1OnServer.TheDictionary.Add(k_TestKey1, k_TestVal1); + m_Player1OnServer.TheDictionary.Add(k_TestKey2, k_TestVal2); }, () => { - return m_ServersPlayer1Comp.TheDictionary.Count == 2 && - m_ClientComp.TheDictionary.Count == 2 && - m_ServersPlayer1Comp.DictionaryDelegateTriggered && - m_ClientComp.DictionaryDelegateTriggered && - m_ServersPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal1 && - m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal1 && - m_ServersPlayer1Comp.TheDictionary[k_TestKey2] == k_TestVal2 && - m_ClientComp.TheDictionary[k_TestKey2] == k_TestVal2; + return m_Player1OnServer.TheDictionary.Count == 2 && + m_Player1OnClient1.TheDictionary.Count == 2 && + m_Player1OnServer.DictionaryDelegateTriggered && + m_Player1OnClient1.DictionaryDelegateTriggered && + m_Player1OnServer.TheDictionary[k_TestKey1] == k_TestVal1 && + m_Player1OnClient1.TheDictionary[k_TestKey1] == k_TestVal1 && + m_Player1OnServer.TheDictionary[k_TestKey2] == k_TestVal2 && + m_Player1OnClient1.TheDictionary[k_TestKey2] == k_TestVal2; } ); } @@ -392,16 +436,16 @@ public IEnumerator NetworkDictionaryRemoveByKey([Values(true, false)] bool useHo yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServersPlayer1Comp.TheDictionary.Remove(k_TestKey2); + m_Player1OnServer.TheDictionary.Remove(k_TestKey2); }, () => { - return m_ServersPlayer1Comp.TheDictionary.Count == 1 && - m_ClientComp.TheDictionary.Count == 1 && - m_ServersPlayer1Comp.DictionaryDelegateTriggered && - m_ClientComp.DictionaryDelegateTriggered && - m_ServersPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal1 && - m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal1; + return m_Player1OnServer.TheDictionary.Count == 1 && + m_Player1OnClient1.TheDictionary.Count == 1 && + m_Player1OnServer.DictionaryDelegateTriggered && + m_Player1OnClient1.DictionaryDelegateTriggered && + m_Player1OnServer.TheDictionary[k_TestKey1] == k_TestVal1 && + m_Player1OnClient1.TheDictionary[k_TestKey1] == k_TestVal1; } ); } @@ -417,16 +461,16 @@ public IEnumerator NetworkDictionaryChangeValue([Values(true, false)] bool useHo yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServersPlayer1Comp.TheDictionary[k_TestKey1] = k_TestVal3; + m_Player1OnServer.TheDictionary[k_TestKey1] = k_TestVal3; }, () => { - return m_ServersPlayer1Comp.TheDictionary.Count == 2 && - m_ClientComp.TheDictionary.Count == 2 && - m_ServersPlayer1Comp.DictionaryDelegateTriggered && - m_ClientComp.DictionaryDelegateTriggered && - m_ServersPlayer1Comp.TheDictionary[k_TestKey1] == k_TestVal3 && - m_ClientComp.TheDictionary[k_TestKey1] == k_TestVal3; + return m_Player1OnServer.TheDictionary.Count == 2 && + m_Player1OnClient1.TheDictionary.Count == 2 && + m_Player1OnServer.DictionaryDelegateTriggered && + m_Player1OnClient1.DictionaryDelegateTriggered && + m_Player1OnServer.TheDictionary[k_TestKey1] == k_TestVal3 && + m_Player1OnClient1.TheDictionary[k_TestKey1] == k_TestVal3; } ); } @@ -442,14 +486,14 @@ public IEnumerator NetworkDictionaryClear([Values(true, false)] bool useHost) yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServersPlayer1Comp.TheDictionary.Clear(); + m_Player1OnServer.TheDictionary.Clear(); }, () => { - return m_ServersPlayer1Comp.TheDictionary.Count == 0 && - m_ClientComp.TheDictionary.Count == 0 && - m_ServersPlayer1Comp.DictionaryDelegateTriggered && - m_ClientComp.DictionaryDelegateTriggered; + return m_Player1OnServer.TheDictionary.Count == 0 && + m_Player1OnClient1.TheDictionary.Count == 0 && + m_Player1OnServer.DictionaryDelegateTriggered && + m_Player1OnClient1.DictionaryDelegateTriggered; } ); } @@ -461,15 +505,15 @@ public IEnumerator TestNetworkVariableStruct([Values(true, false)] bool useHost) yield return MultiInstanceHelpers.RunAndWaitForCondition( () => { - m_ServersPlayer1Comp.TheStruct.Value = + m_Player1OnServer.TheStruct.Value = new TestStruct() { SomeInt = k_TestUInt, SomeBool = false }; - m_ServersPlayer1Comp.TheStruct.SetDirty(true); + m_Player1OnServer.TheStruct.SetDirty(true); }, () => { return - m_ClientComp.TheStruct.Value.SomeBool == false && - m_ClientComp.TheStruct.Value.SomeInt == k_TestUInt; + m_Player1OnClient1.TheStruct.Value.SomeBool == false && + m_Player1OnClient1.TheStruct.Value.SomeInt == k_TestUInt; } ); } From 5fd4b51e199b775a3d53a6b58edae92196249b3b Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Tue, 24 Aug 2021 16:36:03 -0700 Subject: [PATCH 20/25] INetworkVariable -> NetworkVariableBase --- .../Editor/NetworkBehaviourEditor.cs | 2 +- .../Runtime/Core/NetworkBehaviour.cs | 18 +++++++++--------- .../Runtime/Core/SnapshotSystem.cs | 6 +++--- .../Collections/NetworkDictionary.cs | 2 +- .../NetworkVariable/Collections/NetworkList.cs | 2 +- .../NetworkVariable/Collections/NetworkSet.cs | 2 +- .../NetworkVariable/INetworkVariable.cs.meta | 11 ----------- .../Runtime/NetworkVariable/NetworkVariable.cs | 2 +- ...tworkVariable.cs => NetworkVariableBase.cs} | 6 +++--- .../Runtime/Helpers/NetworkVariableHelper.cs | 12 ++++++------ .../Tests/Runtime/NetworkVarBufferCopyTest.cs | 2 +- 11 files changed, 27 insertions(+), 38 deletions(-) delete mode 100644 com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs.meta rename com.unity.netcode.gameobjects/Runtime/NetworkVariable/{INetworkVariable.cs => NetworkVariableBase.cs} (96%) diff --git a/com.unity.netcode.gameobjects/Editor/NetworkBehaviourEditor.cs b/com.unity.netcode.gameobjects/Editor/NetworkBehaviourEditor.cs index f017384196..d3350d395e 100644 --- a/com.unity.netcode.gameobjects/Editor/NetworkBehaviourEditor.cs +++ b/com.unity.netcode.gameobjects/Editor/NetworkBehaviourEditor.cs @@ -58,7 +58,7 @@ private void RenderNetworkVariable(int index) if (value == null) { var fieldType = m_NetworkVariableFields[m_NetworkVariableNames[index]].FieldType; - var networkVariable = (INetworkVariable)Activator.CreateInstance(fieldType, true); + var networkVariable = (NetworkVariableBase)Activator.CreateInstance(fieldType, true); m_NetworkVariableFields[m_NetworkVariableNames[index]].SetValue(target, networkVariable); } diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index 645ca597a5..3dc3b3bf2c 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -366,7 +366,7 @@ public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObje private readonly List> m_ChannelMappedNetworkVariableIndexes = new List>(); private readonly List m_ChannelsForNetworkVariableGroups = new List(); - internal readonly List NetworkVariableFields = new List(); + internal readonly List NetworkVariableFields = new List(); private static Dictionary s_FieldTypes = new Dictionary(); @@ -415,19 +415,19 @@ internal void InitializeVariables() { Type fieldType = sortedFields[i].FieldType; - if (fieldType.IsSubclassOf(typeof(INetworkVariable))) + if (fieldType.IsSubclassOf(typeof(NetworkVariableBase))) { - var instance = (INetworkVariable)sortedFields[i].GetValue(this); + var instance = (NetworkVariableBase)sortedFields[i].GetValue(this); if (instance == null) { - instance = (INetworkVariable)Activator.CreateInstance(fieldType, true); + instance = (NetworkVariableBase)Activator.CreateInstance(fieldType, true); sortedFields[i].SetValue(this, instance); } instance.SetNetworkBehaviour(this); - var instanceNameProperty = fieldType.GetProperty(nameof(INetworkVariable.Name)); + var instanceNameProperty = fieldType.GetProperty(nameof(NetworkVariableBase.Name)); var sanitizedVariableName = sortedFields[i].Name.Replace("<", string.Empty).Replace(">k__BackingField", string.Empty); instanceNameProperty?.SetValue(instance, sanitizedVariableName); @@ -442,7 +442,7 @@ internal void InitializeVariables() for (int i = 0; i < NetworkVariableFields.Count; i++) { - NetworkChannel networkChannel = INetworkVariable.NetworkVariableChannel; + NetworkChannel networkChannel = NetworkVariableBase.NetworkVariableChannel; if (!firstLevelIndex.ContainsKey(networkChannel)) { @@ -625,7 +625,7 @@ private bool CouldHaveDirtyNetworkVariables() return false; } - internal static void HandleNetworkVariableDeltas(List networkVariableList, Stream stream, ulong clientId, NetworkBehaviour logInstance, NetworkManager networkManager) + internal static void HandleNetworkVariableDeltas(List networkVariableList, Stream stream, ulong clientId, NetworkBehaviour logInstance, NetworkManager networkManager) { using (var reader = PooledNetworkReader.Get(stream)) { @@ -719,7 +719,7 @@ internal static void HandleNetworkVariableDeltas(List networkV } } - internal static void WriteNetworkVariableData(List networkVariableList, Stream stream, ulong clientId, NetworkManager networkManager) + internal static void WriteNetworkVariableData(List networkVariableList, Stream stream, ulong clientId, NetworkManager networkManager) { if (networkVariableList.Count == 0) { @@ -767,7 +767,7 @@ internal static void WriteNetworkVariableData(List networkVari } } - internal static void SetNetworkVariableData(List networkVariableList, Stream stream, NetworkManager networkManager) + internal static void SetNetworkVariableData(List networkVariableList, Stream stream, NetworkManager networkManager) { if (networkVariableList.Count == 0) { diff --git a/com.unity.netcode.gameobjects/Runtime/Core/SnapshotSystem.cs b/com.unity.netcode.gameobjects/Runtime/Core/SnapshotSystem.cs index 78cbb9f6b0..3c435752d2 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/SnapshotSystem.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/SnapshotSystem.cs @@ -558,7 +558,7 @@ internal void ProcessSingleAck(ushort ackSequence, ulong clientId, ClientData cl /// This will look into all spawned objects /// /// The key to search for - private INetworkVariable FindNetworkVar(VariableKey key) + private NetworkVariableBase FindNetworkVar(VariableKey key) { var spawnedObjects = NetworkManager.SpawnManager.SpawnedObjects; @@ -895,7 +895,7 @@ internal void Despawn(SnapshotDespawnCommand command) /// Might not happen for all variable on every frame. Might even happen more than once. /// /// The NetworkVariable to write, or rather, its INetworkVariable - internal void Store(ulong networkObjectId, int behaviourIndex, int variableIndex, INetworkVariable networkVariable) + internal void Store(ulong networkObjectId, int behaviourIndex, int variableIndex, NetworkVariableBase networkVariable) { VariableKey k; k.NetworkObjectId = networkObjectId; @@ -914,7 +914,7 @@ internal void Store(ulong networkObjectId, int behaviourIndex, int variableIndex WriteVariableToSnapshot(m_Snapshot, networkVariable, pos); } - private void WriteVariableToSnapshot(Snapshot snapshot, INetworkVariable networkVariable, int index) + private void WriteVariableToSnapshot(Snapshot snapshot, NetworkVariableBase networkVariable, int index) { // write var into buffer, possibly adjusting entry's position and Length using (var varBuffer = PooledNetworkBuffer.Get()) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 9b2dc42a4d..659509430a 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode /// /// The type for the dictionary keys /// The type for the dictionary values - public class NetworkDictionary : INetworkVariable, IDictionary where TKey : unmanaged where TValue : unmanaged + public class NetworkDictionary : NetworkVariableBase, IDictionary where TKey : unmanaged where TValue : unmanaged { private readonly IDictionary m_Dictionary = new Dictionary(); private readonly List> m_DirtyEvents = new List>(); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index 67ab5f7577..c7b2f4bc31 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode /// Event based NetworkVariable container for syncing Lists /// /// The type for the list - public class NetworkList : INetworkVariable, IList where T : unmanaged + public class NetworkList : NetworkVariableBase, IList where T : unmanaged { private readonly IList m_List = new List(); private readonly List> m_DirtyEvents = new List>(); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index a877ecda5a..d82c98642a 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode /// Event based NetworkVariable container for syncing Sets /// /// The type for the set - public class NetworkSet : INetworkVariable, ISet where T: unmanaged + public class NetworkSet : NetworkVariableBase, ISet where T: unmanaged { private readonly ISet m_Set = new HashSet(); private readonly List> m_DirtyEvents = new List>(); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs.meta b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs.meta deleted file mode 100644 index 8ff8391fb8..0000000000 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 87f1fd4778c2dab4b8bc02c738cade25 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index 68193549ad..9bad906f5d 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode /// A variable that can be synchronized over the network. /// [Serializable] - public class NetworkVariable : INetworkVariable where T : unmanaged + public class NetworkVariable : NetworkVariableBase where T : unmanaged { /// /// Delegate type for value changed event diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs similarity index 96% rename from com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs rename to com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs index 90a477c361..6397a5811b 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/INetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -5,16 +5,16 @@ namespace Unity.Netcode /// /// Interface for network value containers /// - public abstract class INetworkVariable + public abstract class NetworkVariableBase { /// /// The name of the channel to be used for syncing /// public const NetworkChannel NetworkVariableChannel = NetworkChannel.NetworkVariable; - protected INetworkVariable() { } + protected NetworkVariableBase() { } - protected INetworkVariable(NetworkVariableSettings settings) + protected NetworkVariableBase(NetworkVariableSettings settings) { Settings = settings; } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs index f725b7369c..37653c8627 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs @@ -62,7 +62,7 @@ private void OnVariableChanged(T previous, T next) OnValueChanged?.Invoke(previous, next); } - public NetworkVariableHelper(INetworkVariable networkVariable) : base(networkVariable) + public NetworkVariableHelper(NetworkVariableBase networkVariable) : base(networkVariable) { m_NetworkVariable = networkVariable as NetworkVariable; m_NetworkVariable.OnValueChanged = OnVariableChanged; @@ -77,8 +77,8 @@ public NetworkVariableHelper(INetworkVariable networkVariable) : base(networkVar /// internal class BaseNetworkVariableHelper { - private static Dictionary s_Instances; - private static Dictionary s_InstanceChangedCount; + private static Dictionary s_Instances; + private static Dictionary s_InstanceChangedCount; /// /// Returns the total number of registered INetworkVariables @@ -129,16 +129,16 @@ protected void ValueChanged() } } - public BaseNetworkVariableHelper(INetworkVariable networkVariable) + public BaseNetworkVariableHelper(NetworkVariableBase networkVariable) { if (s_Instances == null) { - s_Instances = new Dictionary(); + s_Instances = new Dictionary(); } if (s_InstanceChangedCount == null) { - s_InstanceChangedCount = new Dictionary(); + s_InstanceChangedCount = new Dictionary(); } // Register new instance and associated INetworkVariable diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs index 464bf3373f..879bcd5ec2 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVarBufferCopyTest.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests { public class NetworkVarBufferCopyTest : BaseMultiInstanceTest { - public class DummyNetVar : INetworkVariable + public class DummyNetVar : NetworkVariableBase { private const int k_DummyValue = 0x13579BDF; public bool DeltaWritten; From d42a64125eb7f70a0a1f8b75c1cc589aff04873c Mon Sep 17 00:00:00 2001 From: Matt Walsh Date: Tue, 24 Aug 2021 16:48:42 -0700 Subject: [PATCH 21/25] comment cleanup --- .../Runtime/Core/NetworkBehaviour.cs | 5 ++--- .../Runtime/NetworkVariable/Collections/NetworkDictionary.cs | 3 ++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index 3dc3b3bf2c..fa8188200f 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -514,7 +514,7 @@ private void NetworkVariableUpdate(ulong clientId, int behaviourIndex) { using (var writer = PooledNetworkWriter.Get(buffer)) { - // could skip this if no variables dirty + // TODO: could skip this if no variables dirty, though obsolete w/ Snapshot writer.WriteUInt64Packed(NetworkObjectId); writer.WriteUInt16Packed(NetworkObject.GetNetworkBehaviourOrderIndex(this)); @@ -523,7 +523,6 @@ private void NetworkVariableUpdate(ulong clientId, int behaviourIndex) var writtenAny = false; for (int k = 0; k < NetworkVariableFields.Count; k++) { - // could skip up here if not client, etc if (!m_ChannelMappedNetworkVariableIndexes[j].Contains(k)) { // This var does not belong to the currently iterating channel group. @@ -616,7 +615,7 @@ private bool CouldHaveDirtyNetworkVariables() // TODO: There should be a better way by reading one dirty variable vs. 'n' for (int i = 0; i < NetworkVariableFields.Count; i++) { - if (NetworkVariableFields[i].IsDirty()) // needs to bifurcate! + if (NetworkVariableFields[i].IsDirty()) { return true; } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index 659509430a..ef8fcc341f 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -328,7 +328,8 @@ public TValue this[TKey key] public int Count => m_Dictionary.Count; /// - public bool IsReadOnly => m_Dictionary.IsReadOnly; // hrm + // TODO: remove w/ native containers + public bool IsReadOnly => m_Dictionary.IsReadOnly; /// public void Add(TKey key, TValue value) From 7cc4fd548d8113daef6a32ecb12f0d71960752a7 Mon Sep 17 00:00:00 2001 From: "M. Fatih MAR" Date: Wed, 25 Aug 2021 14:00:17 +0100 Subject: [PATCH 22/25] fix compile error: put NetworkVariableBase.cs.meta in --- .../NetworkVariable/NetworkVariableBase.cs.meta | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs.meta diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs.meta b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs.meta new file mode 100644 index 0000000000..ef85502152 --- /dev/null +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f45dec3ed9b6942d889ef48036aba763 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 690bcd9e611c03a7a62b4f14f078e81c9ca4d511 Mon Sep 17 00:00:00 2001 From: "M. Fatih MAR" Date: Wed, 25 Aug 2021 14:25:35 +0100 Subject: [PATCH 23/25] minor polish/cleanup --- .../Runtime/Core/NetworkBehaviour.cs | 5 ++--- .../NetworkVariable/ClientNetworkVariable.cs | 7 +++---- .../Components/NetworkVariableTestComponent.cs | 2 +- .../Runtime/Helpers/NetworkVariableHelper.cs | 18 ++++++++---------- .../Tests/Runtime/NetworkVariableTests.cs | 15 +++++++++------ 5 files changed, 23 insertions(+), 24 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index fa8188200f..85c508bce7 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -442,7 +442,7 @@ internal void InitializeVariables() for (int i = 0; i < NetworkVariableFields.Count; i++) { - NetworkChannel networkChannel = NetworkVariableBase.NetworkVariableChannel; + var networkChannel = NetworkVariableBase.NetworkVariableChannel; if (!firstLevelIndex.ContainsKey(networkChannel)) { @@ -651,8 +651,7 @@ internal static void HandleNetworkVariableDeltas(List netwo if (networkManager.IsServer && !networkVariableList[i].CanClientWrite(clientId)) { - // we are choosing not to fire an exception here, because otherwise a malicious client could use - // this to crash the server + // we are choosing not to fire an exception here, because otherwise a malicious client could use this to crash the server if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs index 6012e6a39e..e8b767355e 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -1,16 +1,14 @@ using System; -using System.Collections.Generic; -using UnityEngine; namespace Unity.Netcode { /// - /// A Client NetworkVariable is special in that + /// A ClientNetworkVariable is special in that: /// - only the owner of the variable can write to it /// - not even the server can write to it /// - it is not snapshotted /// - /// This class may be removed in the future + /// (This class may be removed in the future when integrated into NetworkVariable natively) /// [Serializable] public class ClientNetworkVariable : NetworkVariable where T : unmanaged @@ -46,6 +44,7 @@ public override T Value { throw new InvalidOperationException("Server not allowed to write to ClientNetworkVariables"); } + Set(value); } } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs index bf01820c4c..446918684c 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Components/NetworkVariableTestComponent.cs @@ -176,7 +176,7 @@ private void InitializeTest() /// public bool DidAllValuesChange() { - if (BaseNetworkVariableHelper.VarChangedCount == BaseNetworkVariableHelper.InstanceCount) + if (NetworkVariableBaseHelper.VarChangedCount == NetworkVariableBaseHelper.InstanceCount) { return true; } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs index 37653c8627..2b3a16ab98 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Helpers/NetworkVariableHelper.cs @@ -13,13 +13,12 @@ namespace Unity.Netcode.RuntimeTests /// From both we can then at least determine if the value indeed changed /// /// - internal class NetworkVariableHelper : BaseNetworkVariableHelper where T : unmanaged + internal class NetworkVariableHelper : NetworkVariableBaseHelper where T : unmanaged { - private NetworkVariable m_NetworkVariable; + private readonly NetworkVariable m_NetworkVariable; public delegate void OnMyValueChangedDelegateHandler(T previous, T next); public event OnMyValueChangedDelegateHandler OnValueChanged; - /// /// IEquatable Equals Check /// @@ -49,10 +48,9 @@ private void CheckVariableChanged(ValueType previous, ValueType next) /// private void OnVariableChanged(T previous, T next) { - var testValueType = previous as ValueType; - if (testValueType != null) + if (previous is ValueType testValueType) { - CheckVariableChanged(previous as ValueType, next as ValueType); + CheckVariableChanged(previous, next); } else { @@ -75,9 +73,9 @@ public NetworkVariableHelper(NetworkVariableBase networkVariable) : base(network /// The number of times a specific NetworkVariable instance had its value changed (i.e. !Equal) /// Note: This could be expanded for future tests focuses around NetworkVariables /// - internal class BaseNetworkVariableHelper + internal class NetworkVariableBaseHelper { - private static Dictionary s_Instances; + private static Dictionary s_Instances; private static Dictionary s_InstanceChangedCount; /// @@ -129,11 +127,11 @@ protected void ValueChanged() } } - public BaseNetworkVariableHelper(NetworkVariableBase networkVariable) + public NetworkVariableBaseHelper(NetworkVariableBase networkVariable) { if (s_Instances == null) { - s_Instances = new Dictionary(); + s_Instances = new Dictionary(); } if (s_InstanceChangedCount == null) diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs index 48f6c7ca5c..60a5f0e3be 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariableTests.cs @@ -33,14 +33,17 @@ private void ListChanged(NetworkListEvent e) { ListDelegateTriggered = true; } + private void SetChanged(NetworkSetEvent e) { SetDelegateTriggered = true; } + private void DictionaryChanged(NetworkDictionaryEvent e) { DictionaryDelegateTriggered = true; } + public void Awake() { TheList.OnListChanged += ListChanged; @@ -48,7 +51,7 @@ public void Awake() TheDictionary.OnDictionaryChanged += DictionaryChanged; } - public readonly NetworkVariable TheStruct = new NetworkVariable(); + public readonly NetworkVariable TheStruct = new NetworkVariable(); public bool ListDelegateTriggered; public bool SetDelegateTriggered; @@ -127,7 +130,7 @@ public override IEnumerator Setup() x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, m_ClientNetworkManagers[1], result)); -// var client2client1 = result.Result; + // var client2client1 = result.Result; m_Player1FromClient2 = result.Result.GetComponent(); m_Player1OnServer.TheList.Clear(); @@ -198,7 +201,7 @@ public void ClientWritePermissionTest([Values(true, false)] bool useHost) m_TestWithHost = useHost; // client must not be allowed to write to a server auth variable - Assert.Throws(() => m_Player1OnClient1.TheScalar.Value = k_TestVal1); + Assert.Throws(() => m_Player1OnClient1.TheScalar.Value = k_TestVal1); } [Test] @@ -207,7 +210,7 @@ public void ServerWritePermissionTest([Values(true, false)] bool useHost) m_TestWithHost = useHost; // server must not be allowed to write to a client auth variable - Assert.Throws(() => m_Player1OnServer.ClientVar.Value = k_TestVal1); + Assert.Throws(() => m_Player1OnServer.ClientVar.Value = k_TestVal1); } [UnityTest] @@ -223,7 +226,7 @@ public IEnumerator ClientTest([Values(true, false)] bool useHost) }, () => { - // the client's values should win on the objects it owns + // the client's values should win on the objects it owns return m_Player1OnServer.ClientVar.Value == k_TestVal2 && m_Player2OnServer.ClientVar.Value == k_TestVal3 && @@ -522,7 +525,7 @@ public IEnumerator TestNetworkVariableStruct([Values(true, false)] bool useHost) public override IEnumerator Teardown() { yield return base.Teardown(); - UnityEngine.Object.Destroy(m_PlayerPrefab); + UnityEngine.Object.DestroyImmediate(m_PlayerPrefab); } } } From 78be4fe4627e8d2d89f9f905533e950956d6ee06 Mon Sep 17 00:00:00 2001 From: "M. Fatih MAR" Date: Wed, 25 Aug 2021 14:28:46 +0100 Subject: [PATCH 24/25] remove NetworkVariableBase.SetNetworkBehaviour() --- .../Runtime/Core/NetworkBehaviour.cs | 2 +- .../NetworkVariable/ClientNetworkVariable.cs | 6 +++--- .../Collections/NetworkDictionary.cs | 4 ++-- .../NetworkVariable/Collections/NetworkList.cs | 6 +++--- .../NetworkVariable/Collections/NetworkSet.cs | 4 ++-- .../Runtime/NetworkVariable/NetworkVariable.cs | 2 +- .../Runtime/NetworkVariable/NetworkVariableBase.cs | 14 ++------------ 7 files changed, 14 insertions(+), 24 deletions(-) diff --git a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs index 85c508bce7..d871509288 100644 --- a/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs +++ b/com.unity.netcode.gameobjects/Runtime/Core/NetworkBehaviour.cs @@ -425,7 +425,7 @@ internal void InitializeVariables() sortedFields[i].SetValue(this, instance); } - instance.SetNetworkBehaviour(this); + instance.NetworkBehaviour = this; var instanceNameProperty = fieldType.GetProperty(nameof(NetworkVariableBase.Name)); var sanitizedVariableName = sortedFields[i].Name.Replace("<", string.Empty).Replace(">k__BackingField", string.Empty); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs index e8b767355e..6d5c5e03f1 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/ClientNetworkVariable.cs @@ -19,12 +19,12 @@ public ClientNetworkVariable(NetworkVariableSettings settings) : base(settings) public override bool CanClientWrite(ulong clientId) { - return m_NetworkBehaviour.OwnerClientId == clientId; + return NetworkBehaviour.OwnerClientId == clientId; } public override bool ShouldWrite(ulong clientId, bool isServer) { - return m_IsDirty && !isServer && m_NetworkBehaviour.IsOwner; + return m_IsDirty && !isServer && NetworkBehaviour.IsOwner; } /// @@ -40,7 +40,7 @@ public override T Value // Also, note this is not really very water-tight, if you are running as a host // we cannot tell if a ClientNetworkVariable write is happening inside server-ish code - if (m_NetworkBehaviour.NetworkManager.IsServer) + if (NetworkBehaviour.NetworkManager.IsServer) { throw new InvalidOperationException("Server not allowed to write to ClientNetworkVariables"); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs index ef8fcc341f..5e533124f5 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkDictionary.cs @@ -448,7 +448,7 @@ IEnumerator IEnumerable.GetEnumerator() private void HandleAddDictionaryEvent(NetworkDictionaryEvent dictionaryEvent) { - if (m_NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) + if (NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) { m_DirtyEvents.Add(dictionaryEvent); } @@ -467,7 +467,7 @@ public int LastModifiedTick private void EnsureInitialized() { - if (m_NetworkBehaviour == null) + if (NetworkBehaviour == null) { throw new InvalidOperationException("Cannot access " + nameof(NetworkDictionary) + " before it's initialized"); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs index c7b2f4bc31..e19dc4eaa0 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -65,7 +65,7 @@ public override void ResetDirty() { base.ResetDirty(); m_DirtyEvents.Clear(); - LastSyncedTime = m_NetworkBehaviour.NetworkManager.LocalTime; + LastSyncedTime = NetworkBehaviour.NetworkManager.LocalTime; } /// @@ -459,7 +459,7 @@ public T this[int index] private void HandleAddListEvent(NetworkListEvent listEvent) { - if (m_NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) + if (NetworkBehaviour.NetworkManager.ConnectedClients.Count > 0) { m_DirtyEvents.Add(listEvent); } @@ -478,7 +478,7 @@ public int LastModifiedTick private void EnsureInitialized() { - if (m_NetworkBehaviour == null) + if (NetworkBehaviour == null) { throw new InvalidOperationException("Cannot access " + nameof(NetworkList) + " before it's initialized"); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs index d82c98642a..865e8f45fc 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Collections/NetworkSet.cs @@ -66,7 +66,7 @@ public override void ResetDirty() { base.ResetDirty(); m_DirtyEvents.Clear(); - LastSyncedTime = m_NetworkBehaviour.NetworkManager.LocalTime; + LastSyncedTime = NetworkBehaviour.NetworkManager.LocalTime; } /// @@ -443,7 +443,7 @@ public int LastModifiedTick private void EnsureInitialized() { - if (m_NetworkBehaviour == null) + if (NetworkBehaviour == null) { throw new InvalidOperationException("Cannot access " + nameof(NetworkSet) + " before it's initialized"); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs index 9bad906f5d..77399a636e 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariable.cs @@ -76,7 +76,7 @@ public virtual T Value // Also, note this is not really very water-tight, if you are running as a host // we cannot tell if a NetworkVariable write is happening inside client-ish code - if (m_NetworkBehaviour && (m_NetworkBehaviour.NetworkManager.IsClient && !m_NetworkBehaviour.NetworkManager.IsHost)) + if (NetworkBehaviour && (NetworkBehaviour.NetworkManager.IsClient && !NetworkBehaviour.NetworkManager.IsHost)) { throw new InvalidOperationException("Client can't write to NetworkVariables"); } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs index 6397a5811b..119dd88aa5 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -21,7 +21,7 @@ protected NetworkVariableBase(NetworkVariableSettings settings) // demolish me // or better setter? - private protected NetworkBehaviour m_NetworkBehaviour; + internal protected NetworkBehaviour NetworkBehaviour { get; internal set; } private protected bool m_IsDirty = false; @@ -78,7 +78,7 @@ public bool CanClientRead(ulong clientId) case NetworkVariableReadPermission.Everyone: return true; case NetworkVariableReadPermission.OwnerOnly: - return m_NetworkBehaviour.OwnerClientId == clientId; + return NetworkBehaviour.OwnerClientId == clientId; } return true; } @@ -121,15 +121,5 @@ public virtual bool CanClientWrite(ulong clientId) /// The local network tick at which this var was written, on the machine it was written /// The remote network tick at which this var was sent by the host public abstract void ReadDelta(Stream stream, bool keepDirtyDelta); - - /// - /// Sets NetworkBehaviour the container belongs to. - /// - /// The behaviour the container behaves to - public void SetNetworkBehaviour(NetworkBehaviour behaviour) - { - m_NetworkBehaviour = behaviour; - } - } } From fdbccbce2be683eb1a21b8cfeeb9766888f4a7dc Mon Sep 17 00:00:00 2001 From: "M. Fatih MAR" Date: Wed, 25 Aug 2021 14:55:22 +0100 Subject: [PATCH 25/25] fix tools project tests --- .../Runtime/Metrics/Utility/NetworkVariableComponent.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Metrics/Utility/NetworkVariableComponent.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Metrics/Utility/NetworkVariableComponent.cs index f4eb14db88..c61f4c0845 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Metrics/Utility/NetworkVariableComponent.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Metrics/Utility/NetworkVariableComponent.cs @@ -1,17 +1,17 @@ #if MULTIPLAYER_TOOLS -using System; +using UnityEngine; namespace Unity.Netcode.RuntimeTests.Metrics.Utlity { public class NetworkVariableComponent : NetworkBehaviour { - public NetworkVariableString MyNetworkVariable { get; } = new NetworkVariableString(); + public NetworkVariable MyNetworkVariable { get; } = new NetworkVariable(); - void Update() + private void Update() { if (IsServer) { - MyNetworkVariable.Value = Guid.NewGuid().ToString(); + MyNetworkVariable.Value = Random.Range(100, 999); } } }