com.unity.netcode.gameobjects@1.5.1
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com). ## [1.5.1] - 2023-06-07 ### Added - Added support for serializing `NativeArray<>` and `NativeList<>` in `FastBufferReader`/`FastBufferWriter`, `BufferSerializer`, `NetworkVariable`, and RPCs. (To use `NativeList<>`, add `UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT` to your Scripting Define Symbols in `Project Settings > Player`) (#2375) - The location of the automatically-created default network prefab list can now be configured (#2544) - Added: Message size limits (max single message and max fragmented message) can now be set using NetworkManager.MaximumTransmissionUnitSize and NetworkManager.MaximumFragmentedMessageSize for transports that don't work with the default values (#2530) - Added `NetworkObject.SpawnWithObservers` property (default is true) that when set to false will spawn a `NetworkObject` with no observers and will not be spawned on any client until `NetworkObject.NetworkShow` is invoked. (#2568) ### Fixed - Fixed: Fixed a null reference in codegen in some projects (#2581) - Fixed issue where the `OnClientDisconnected` client identifier was incorrect after a pending client connection was denied. (#2569) - Fixed warning "Runtime Network Prefabs was not empty at initialization time." being erroneously logged when no runtime network prefabs had been added (#2565) - Fixed issue where some temporary debug console logging was left in a merged PR. (#2562) - Fixed the "Generate Default Network Prefabs List" setting not loading correctly and always reverting to being checked. (#2545) - Fixed issue where users could not use NetworkSceneManager.VerifySceneBeforeLoading to exclude runtime generated scenes from client synchronization. (#2550) - Fixed missing value on `NetworkListEvent` for `EventType.RemoveAt` events. (#2542,#2543) - Fixed issue where parenting a NetworkTransform under a transform with a scale other than Vector3.one would result in incorrect values on non-authoritative instances. (#2538) - Fixed issue where a server would include scene migrated and then despawned NetworkObjects to a client that was being synchronized. (#2532) - Fixed the inspector throwing exceptions when attempting to render `NetworkVariable`s of enum types. (#2529) - Making a `NetworkVariable` with an `INetworkSerializable` type that doesn't meet the `new()` constraint will now create a compile-time error instead of an editor crash (#2528) - Fixed Multiplayer Tools package installation docs page link on the NetworkManager popup. (#2526) - Fixed an exception and error logging when two different objects are shown and hidden on the same frame (#2524) - Fixed a memory leak in `UnityTransport` that occurred if `StartClient` failed. (#2518) - Fixed issue where a client could throw an exception if abruptly disconnected from a network session with one or more spawned `NetworkObject`(s). (#2510) - Fixed issue where invalid endpoint addresses were not being detected and returning false from NGO UnityTransport. (#2496) - Fixed some errors that could occur if a connection is lost and the loss is detected when attempting to write to the socket. (#2495) ## Changed - Adding network prefabs before NetworkManager initialization is now supported. (#2565) - Connecting clients being synchronized now switch to the server's active scene before spawning and synchronizing NetworkObjects. (#2532) - Updated `UnityTransport` dependency on `com.unity.transport` to 1.3.4. (#2533) - Improved performance of NetworkBehaviour initialization by replacing reflection when initializing NetworkVariables with compile-time code generation, which should help reduce hitching during additive scene loads. (#2522)
This commit is contained in:
72
Tests/Runtime/ClientApprovalDenied.cs
Normal file
72
Tests/Runtime/ClientApprovalDenied.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using NUnit.Framework;
|
||||
using Unity.Netcode.TestHelpers.Runtime;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
|
||||
namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
public class ClientApprovalDenied : NetcodeIntegrationTest
|
||||
{
|
||||
protected override int NumberOfClients => 2;
|
||||
private bool m_ApproveConnection = true;
|
||||
private ulong m_PendingClientId = 0;
|
||||
private ulong m_DisconnectedClientId = 0;
|
||||
|
||||
private List<ulong> m_DisconnectedClientIdentifiers = new List<ulong>();
|
||||
|
||||
private void ConnectionApproval(NetworkManager.ConnectionApprovalRequest connectionApprovalRequest, NetworkManager.ConnectionApprovalResponse connectionApprovalResponse)
|
||||
{
|
||||
connectionApprovalResponse.Approved = m_ApproveConnection;
|
||||
connectionApprovalResponse.CreatePlayerObject = true;
|
||||
// When denied, store the client identifier to use for validating the client disconnected notification identifier matches
|
||||
if (!m_ApproveConnection)
|
||||
{
|
||||
m_PendingClientId = connectionApprovalRequest.ClientNetworkId;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnNewClientCreated(NetworkManager networkManager)
|
||||
{
|
||||
networkManager.NetworkConfig.ConnectionApproval = true;
|
||||
base.OnNewClientCreated(networkManager);
|
||||
}
|
||||
|
||||
protected override bool ShouldWaitForNewClientToConnect(NetworkManager networkManager)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates that when a pending client is denied approval the server-host
|
||||
/// OnClientDisconnected method will return the valid pending client identifier.
|
||||
/// </summary>
|
||||
[UnityTest]
|
||||
public IEnumerator ClientDeniedAndDisconnectionNotificationTest()
|
||||
{
|
||||
m_ServerNetworkManager.NetworkConfig.ConnectionApproval = true;
|
||||
m_ServerNetworkManager.ConnectionApprovalCallback = ConnectionApproval;
|
||||
m_ApproveConnection = false;
|
||||
m_ServerNetworkManager.OnClientDisconnectCallback += OnClientDisconnectCallback;
|
||||
yield return CreateAndStartNewClient();
|
||||
yield return WaitForConditionOrTimeOut(() => m_PendingClientId == m_DisconnectedClientId);
|
||||
AssertOnTimeout($"Timed out waiting for disconnect notification for pending Client-{m_PendingClientId}!");
|
||||
|
||||
// Validate that we don't get multiple disconnect notifications for clients being disconnected
|
||||
// Have a client disconnect remotely
|
||||
m_ClientNetworkManagers[0].Shutdown();
|
||||
|
||||
// Have the server disconnect a client
|
||||
m_ServerNetworkManager.DisconnectClient(m_ClientNetworkManagers[1].LocalClientId);
|
||||
m_ServerNetworkManager.OnClientDisconnectCallback -= OnClientDisconnectCallback;
|
||||
}
|
||||
|
||||
private void OnClientDisconnectCallback(ulong clientId)
|
||||
{
|
||||
Assert.False(m_DisconnectedClientIdentifiers.Contains(clientId), $"Received two disconnect notifications from Client-{clientId}!");
|
||||
m_DisconnectedClientIdentifiers.Add(clientId);
|
||||
m_DisconnectedClientId = clientId;
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Tests/Runtime/ClientApprovalDenied.cs.meta
Normal file
11
Tests/Runtime/ClientApprovalDenied.cs.meta
Normal file
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e46e2cb14a6d49c48bc8c33094467961
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -6,10 +6,19 @@ using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
public class EmbeddedManagedNetworkSerializableType : INetworkSerializable
|
||||
{
|
||||
public int Int;
|
||||
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
||||
{
|
||||
serializer.SerializeValue(ref Int);
|
||||
}
|
||||
}
|
||||
public class ManagedNetworkSerializableType : INetworkSerializable, IEquatable<ManagedNetworkSerializableType>
|
||||
{
|
||||
public string Str = "";
|
||||
public int[] Ints = Array.Empty<int>();
|
||||
public EmbeddedManagedNetworkSerializableType Embedded = new EmbeddedManagedNetworkSerializableType();
|
||||
public int InMemoryValue;
|
||||
|
||||
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
||||
@@ -28,6 +37,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
serializer.SerializeValue(ref val);
|
||||
Ints[i] = val;
|
||||
}
|
||||
|
||||
serializer.SerializeValue(ref Embedded);
|
||||
}
|
||||
|
||||
public bool Equals(ManagedNetworkSerializableType other)
|
||||
@@ -60,6 +71,11 @@ namespace Unity.Netcode.RuntimeTests
|
||||
}
|
||||
}
|
||||
|
||||
if (Embedded.Int != other.Embedded.Int)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -280,7 +296,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
m_NetworkVariableManaged = new NetworkVariable<ManagedNetworkSerializableType>(new ManagedNetworkSerializableType
|
||||
{
|
||||
Str = "1234567890",
|
||||
Ints = new[] { 1, 2, 3, 4, 5 }
|
||||
Ints = new[] { 1, 2, 3, 4, 5 },
|
||||
Embedded = new EmbeddedManagedNetworkSerializableType { Int = 6 }
|
||||
});
|
||||
|
||||
// Use this nifty class: NetworkVariableHelper
|
||||
@@ -386,7 +403,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
Assert.IsTrue(m_NetworkVariableManaged.Value.Equals(new ManagedNetworkSerializableType
|
||||
{
|
||||
Str = "ManagedNetworkSerializableType",
|
||||
Ints = new[] { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 }
|
||||
Ints = new[] { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 },
|
||||
Embedded = new EmbeddedManagedNetworkSerializableType { Int = 20000 }
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -433,7 +451,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
m_NetworkVariableManaged.Value = new ManagedNetworkSerializableType
|
||||
{
|
||||
Str = "ManagedNetworkSerializableType",
|
||||
Ints = new[] { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 }
|
||||
Ints = new[] { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 },
|
||||
Embedded = new EmbeddedManagedNetworkSerializableType { Int = 20000 }
|
||||
};
|
||||
|
||||
//Set the timeout (i.e. how long we will wait for all NetworkVariables to have registered their changes)
|
||||
|
||||
@@ -60,7 +60,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
if (m_ApprovalFailureType == ApprovalTimedOutTypes.ServerDoesNotRespond)
|
||||
{
|
||||
// We catch (don't process) the incoming approval message to simulate the server not sending the approved message in time
|
||||
m_ClientNetworkManagers[0].MessagingSystem.Hook(new MessageCatcher<ConnectionApprovedMessage>(m_ClientNetworkManagers[0]));
|
||||
m_ClientNetworkManagers[0].ConnectionManager.MessageManager.Hook(new MessageCatcher<ConnectionApprovedMessage>(m_ClientNetworkManagers[0]));
|
||||
m_ExpectedLogMessage = new Regex("Timed out waiting for the server to approve the connection request.");
|
||||
m_LogType = LogType.Log;
|
||||
}
|
||||
@@ -68,7 +68,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
// We catch (don't process) the incoming connection request message to simulate a transport connection but the client never
|
||||
// sends (or takes too long to send) the connection request.
|
||||
m_ServerNetworkManager.MessagingSystem.Hook(new MessageCatcher<ConnectionRequestMessage>(m_ServerNetworkManager));
|
||||
m_ServerNetworkManager.ConnectionManager.MessageManager.Hook(new MessageCatcher<ConnectionRequestMessage>(m_ServerNetworkManager));
|
||||
|
||||
// For this test, we know the timed out client will be Client-1
|
||||
m_ExpectedLogMessage = new Regex("Server detected a transport connection from Client-1, but timed out waiting for the connection request message.");
|
||||
@@ -86,16 +86,18 @@ namespace Unity.Netcode.RuntimeTests
|
||||
// Verify we haven't received the time out message yet
|
||||
NetcodeLogAssert.LogWasNotReceived(LogType.Log, m_ExpectedLogMessage);
|
||||
|
||||
// Wait for 3/4s of the time out period to pass (totaling 1.25x the wait period)
|
||||
yield return new WaitForSeconds(k_TestTimeoutPeriod * 0.75f);
|
||||
yield return new WaitForSeconds(k_TestTimeoutPeriod * 1.5f);
|
||||
|
||||
// We should have the test relative log message by this time.
|
||||
NetcodeLogAssert.LogWasReceived(m_LogType, m_ExpectedLogMessage);
|
||||
|
||||
Debug.Log("Checking connected client count");
|
||||
// It should only have the host client connected
|
||||
Assert.AreEqual(1, m_ServerNetworkManager.ConnectedClients.Count, $"Expected only one client when there were {m_ServerNetworkManager.ConnectedClients.Count} clients connected!");
|
||||
Assert.AreEqual(0, m_ServerNetworkManager.PendingClients.Count, $"Expected no pending clients when there were {m_ServerNetworkManager.PendingClients.Count} pending clients!");
|
||||
Assert.True(!m_ClientNetworkManagers[0].IsApproved, $"Expected the client to not have been approved, but it was!");
|
||||
|
||||
|
||||
Assert.AreEqual(0, m_ServerNetworkManager.ConnectionManager.PendingClients.Count, $"Expected no pending clients when there were {m_ServerNetworkManager.ConnectionManager.PendingClients.Count} pending clients!");
|
||||
Assert.True(!m_ClientNetworkManagers[0].LocalClient.IsApproved, $"Expected the client to not have been approved, but it was!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
return ret;
|
||||
}
|
||||
|
||||
public int DeferredMessageCountForType(IDeferredMessageManager.TriggerType trigger)
|
||||
public int DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType trigger)
|
||||
{
|
||||
var count = 0;
|
||||
if (m_Triggers.TryGetValue(trigger, out var dict))
|
||||
@@ -68,7 +68,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
return count;
|
||||
}
|
||||
|
||||
public int DeferredMessageCountForKey(IDeferredMessageManager.TriggerType trigger, ulong key)
|
||||
public int DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType trigger, ulong key)
|
||||
{
|
||||
if (m_PurgedKeys.Contains(key))
|
||||
{
|
||||
@@ -85,20 +85,20 @@ namespace Unity.Netcode.RuntimeTests
|
||||
return 0;
|
||||
}
|
||||
|
||||
public override void DeferMessage(IDeferredMessageManager.TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context)
|
||||
public override void DeferMessage(IDeferredNetworkMessageManager.TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context)
|
||||
{
|
||||
OnBeforeDefer?.Invoke(this, key);
|
||||
DeferMessageCalled = true;
|
||||
base.DeferMessage(trigger, key, reader, ref context);
|
||||
}
|
||||
|
||||
public override void ProcessTriggers(IDeferredMessageManager.TriggerType trigger, ulong key)
|
||||
public override void ProcessTriggers(IDeferredNetworkMessageManager.TriggerType trigger, ulong key)
|
||||
{
|
||||
ProcessTriggersCalled = true;
|
||||
base.ProcessTriggers(trigger, key);
|
||||
}
|
||||
|
||||
protected override void PurgeTrigger(IDeferredMessageManager.TriggerType triggerType, ulong key, TriggerInfo triggerInfo)
|
||||
protected override void PurgeTrigger(IDeferredNetworkMessageManager.TriggerType triggerType, ulong key, TriggerInfo triggerInfo)
|
||||
{
|
||||
OnBeforePurge?.Invoke(this, key);
|
||||
base.PurgeTrigger(triggerType, key, triggerInfo);
|
||||
@@ -207,13 +207,13 @@ namespace Unity.Netcode.RuntimeTests
|
||||
m_UseHost = false;
|
||||
|
||||
// Replace the IDeferredMessageManager component with our test one in the component factory
|
||||
ComponentFactory.Register<IDeferredMessageManager>(networkManager => new TestDeferredMessageManager(networkManager));
|
||||
ComponentFactory.Register<IDeferredNetworkMessageManager>(networkManager => new TestDeferredMessageManager(networkManager));
|
||||
}
|
||||
|
||||
protected override void OnInlineTearDown()
|
||||
{
|
||||
// Revert the IDeferredMessageManager component to its default (DeferredMessageManager)
|
||||
ComponentFactory.Deregister<IDeferredMessageManager>();
|
||||
ComponentFactory.Deregister<IDeferredNetworkMessageManager>();
|
||||
m_ClientSpawnCatchers.Clear();
|
||||
}
|
||||
|
||||
@@ -294,7 +294,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
var catcher = new MessageCatcher<CreateObjectMessage>(client);
|
||||
m_ClientSpawnCatchers.Add(catcher);
|
||||
client.MessagingSystem.Hook(catcher);
|
||||
client.ConnectionManager.MessageManager.Hook(catcher);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,7 +303,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
for (var i = 0; i < m_ClientNetworkManagers.Length; ++i)
|
||||
{
|
||||
// Unhook first so the spawn catcher stops catching spawns
|
||||
m_ClientNetworkManagers[i].MessagingSystem.Unhook(m_ClientSpawnCatchers[i]);
|
||||
m_ClientNetworkManagers[i].ConnectionManager.MessageManager.Unhook(m_ClientSpawnCatchers[i]);
|
||||
m_ClientSpawnCatchers[i].ReleaseMessages();
|
||||
}
|
||||
m_ClientSpawnCatchers.Clear();
|
||||
@@ -343,9 +343,9 @@ namespace Unity.Netcode.RuntimeTests
|
||||
private void AssertSpawnTriggerCountForObject(TestDeferredMessageManager manager, GameObject serverObject, int expectedCount = 1)
|
||||
{
|
||||
Assert.AreEqual(expectedCount, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(expectedCount, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(expectedCount, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnAddPrefab));
|
||||
Assert.AreEqual(expectedCount, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(expectedCount, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab));
|
||||
}
|
||||
|
||||
private void WaitForAllClientsToReceive<T>() where T : INetworkMessage
|
||||
@@ -505,9 +505,9 @@ namespace Unity.Netcode.RuntimeTests
|
||||
Assert.IsTrue(manager.DeferMessageCalled);
|
||||
Assert.IsFalse(manager.ProcessTriggersCalled);
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnAddPrefab));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnAddPrefab, serverObject.GetComponent<NetworkObject>().GlobalObjectIdHash));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, serverObject.GetComponent<NetworkObject>().GlobalObjectIdHash));
|
||||
|
||||
var component = GetComponentForClient<DeferredMessageTestRpcComponent>(client.LocalClientId);
|
||||
Assert.IsNull(component);
|
||||
@@ -672,9 +672,9 @@ namespace Unity.Netcode.RuntimeTests
|
||||
Assert.IsFalse(manager.ProcessTriggersCalled);
|
||||
|
||||
Assert.AreEqual(4, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(4, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(4, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnAddPrefab));
|
||||
Assert.AreEqual(4, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(4, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab));
|
||||
AddPrefabsToClient(client);
|
||||
}
|
||||
|
||||
@@ -731,9 +731,9 @@ namespace Unity.Netcode.RuntimeTests
|
||||
Assert.IsFalse(manager.ProcessTriggersCalled);
|
||||
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnAddPrefab));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnAddPrefab, serverObject.GetComponent<NetworkObject>().GlobalObjectIdHash));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, serverObject.GetComponent<NetworkObject>().GlobalObjectIdHash));
|
||||
AddPrefabsToClient(client);
|
||||
}
|
||||
|
||||
@@ -816,10 +816,10 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
Assert.AreEqual(5, manager.DeferredMessageCountTotal());
|
||||
|
||||
Assert.AreEqual(4, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(4, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnAddPrefab));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnAddPrefab, serverObject.GetComponent<NetworkObject>().GlobalObjectIdHash));
|
||||
Assert.AreEqual(4, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(4, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, serverObject.GetComponent<NetworkObject>().GlobalObjectIdHash));
|
||||
AddPrefabsToClient(client);
|
||||
}
|
||||
|
||||
@@ -890,7 +890,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
foreach (var unused in m_ClientNetworkManagers)
|
||||
{
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
}
|
||||
|
||||
int purgeCount = 0;
|
||||
@@ -903,8 +903,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
Debug.Log(client.RealTimeProvider.GetType().FullName);
|
||||
Assert.GreaterOrEqual(elapsed, timeout);
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, key));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, key));
|
||||
Assert.AreEqual(serverObject.GetComponent<NetworkObject>().NetworkObjectId, key);
|
||||
};
|
||||
var manager = (TestDeferredMessageManager)client.DeferredMessageManager;
|
||||
@@ -986,7 +986,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
foreach (var unused in m_ClientNetworkManagers)
|
||||
{
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
}
|
||||
|
||||
int purgeCount = 0;
|
||||
@@ -998,8 +998,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
var elapsed = client.RealTimeProvider.RealTimeSinceStartup - start;
|
||||
Assert.GreaterOrEqual(elapsed, timeout);
|
||||
Assert.AreEqual(3, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(3, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(3, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, key));
|
||||
Assert.AreEqual(3, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(3, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, key));
|
||||
Assert.AreEqual(serverObject.GetComponent<NetworkObject>().NetworkObjectId, key);
|
||||
};
|
||||
var manager = (TestDeferredMessageManager)client.DeferredMessageManager;
|
||||
@@ -1092,8 +1092,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
foreach (var unused in m_ClientNetworkManagers)
|
||||
{
|
||||
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredMessageManager.TriggerType.OnSpawn} with key {serverObject2.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject2.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
}
|
||||
|
||||
int purgeCount = 0;
|
||||
@@ -1106,8 +1106,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
var elapsed = client.RealTimeProvider.RealTimeSinceStartup - start;
|
||||
Assert.GreaterOrEqual(elapsed, timeout - 0.25f);
|
||||
Assert.AreEqual(remainingMessagesTotalThisClient, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(remainingMessagesTotalThisClient, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(3, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, key));
|
||||
Assert.AreEqual(remainingMessagesTotalThisClient, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(3, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, key));
|
||||
remainingMessagesTotalThisClient -= 3;
|
||||
};
|
||||
var manager = (TestDeferredMessageManager)client.DeferredMessageManager;
|
||||
@@ -1167,8 +1167,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
var manager = (TestDeferredMessageManager)client.DeferredMessageManager;
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
}
|
||||
|
||||
serverObject.GetComponent<NetworkObject>().ChangeOwnership(m_ServerNetworkManager.LocalClientId);
|
||||
@@ -1178,13 +1178,13 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
var manager = (TestDeferredMessageManager)client.DeferredMessageManager;
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
}
|
||||
|
||||
foreach (var unused in m_ClientNetworkManagers)
|
||||
{
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
}
|
||||
|
||||
int purgeCount = 0;
|
||||
@@ -1196,8 +1196,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
var elapsed = client.RealTimeProvider.RealTimeSinceStartup - start;
|
||||
Assert.GreaterOrEqual(elapsed, timeout - 0.05f);
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, key));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, key));
|
||||
Assert.AreEqual(serverObject.GetComponent<NetworkObject>().NetworkObjectId, key);
|
||||
};
|
||||
var manager = (TestDeferredMessageManager)client.DeferredMessageManager;
|
||||
@@ -1262,9 +1262,9 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
var manager = (TestDeferredMessageManager)client.DeferredMessageManager;
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject2.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject2.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
}
|
||||
|
||||
serverObject2.GetComponent<NetworkObject>().ChangeOwnership(m_ServerNetworkManager.LocalClientId);
|
||||
@@ -1274,14 +1274,14 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
var manager = (TestDeferredMessageManager)client.DeferredMessageManager;
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject2.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject2.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
}
|
||||
|
||||
foreach (var unused in m_ClientNetworkManagers)
|
||||
{
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent<NetworkObject>().NetworkObjectId}, but that trigger was not received within within {timeout} second(s).");
|
||||
}
|
||||
|
||||
int purgeCount = 0;
|
||||
@@ -1293,10 +1293,10 @@ namespace Unity.Netcode.RuntimeTests
|
||||
var elapsed = client.RealTimeProvider.RealTimeSinceStartup - start;
|
||||
Assert.GreaterOrEqual(elapsed, timeout - 0.05f);
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(2, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject2.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject2.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
|
||||
Assert.AreEqual(serverObject.GetComponent<NetworkObject>().NetworkObjectId, key);
|
||||
};
|
||||
@@ -1316,9 +1316,9 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
var manager = (TestDeferredMessageManager)client.DeferredMessageManager;
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountTotal());
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredMessageManager.TriggerType.OnSpawn, serverObject2.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn));
|
||||
Assert.AreEqual(0, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
Assert.AreEqual(1, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject2.GetComponent<NetworkObject>().NetworkObjectId));
|
||||
}
|
||||
foreach (var client in m_ClientNetworkManagers)
|
||||
{
|
||||
|
||||
@@ -2,111 +2,165 @@ using System.Collections;
|
||||
using System.Linq;
|
||||
using NUnit.Framework;
|
||||
using Unity.Netcode.TestHelpers.Runtime;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
public class DisconnectTests
|
||||
/// <summary>
|
||||
/// Validates the client disconnection process.
|
||||
/// This assures that:
|
||||
/// - When a client disconnects from the server that the server:
|
||||
/// -- Detects the client disconnected.
|
||||
/// -- Cleans up the transport to NGO client (and vice versa) mappings.
|
||||
/// - When a server disconnects a client that:
|
||||
/// -- The client detects this disconnection.
|
||||
/// -- The server cleans up the transport to NGO client (and vice versa) mappings.
|
||||
/// - When <see cref="OwnerPersistence.DestroyWithOwner"/> the server-side player object is destroyed
|
||||
/// - When <see cref="OwnerPersistence.DontDestroyWithOwner"/> the server-side player object ownership is transferred back to the server
|
||||
/// </summary>
|
||||
[TestFixture(OwnerPersistence.DestroyWithOwner)]
|
||||
[TestFixture(OwnerPersistence.DontDestroyWithOwner)]
|
||||
public class DisconnectTests : NetcodeIntegrationTest
|
||||
{
|
||||
|
||||
private bool m_ClientDisconnected;
|
||||
[UnityTest]
|
||||
public IEnumerator RemoteDisconnectPlayerObjectCleanup()
|
||||
public enum OwnerPersistence
|
||||
{
|
||||
// create server and client instances
|
||||
NetcodeIntegrationTestHelpers.Create(1, out NetworkManager server, out NetworkManager[] clients);
|
||||
|
||||
// create prefab
|
||||
var gameObject = new GameObject("PlayerObject");
|
||||
var networkObject = gameObject.AddComponent<NetworkObject>();
|
||||
networkObject.DontDestroyWithOwner = true;
|
||||
NetcodeIntegrationTestHelpers.MakeNetworkObjectTestPrefab(networkObject);
|
||||
|
||||
server.NetworkConfig.PlayerPrefab = gameObject;
|
||||
|
||||
for (int i = 0; i < clients.Length; i++)
|
||||
{
|
||||
clients[i].NetworkConfig.PlayerPrefab = gameObject;
|
||||
}
|
||||
|
||||
// start server and connect clients
|
||||
NetcodeIntegrationTestHelpers.Start(false, server, clients);
|
||||
|
||||
// wait for connection on client side
|
||||
yield return NetcodeIntegrationTestHelpers.WaitForClientsConnected(clients);
|
||||
|
||||
// wait for connection on server side
|
||||
yield return NetcodeIntegrationTestHelpers.WaitForClientConnectedToServer(server);
|
||||
|
||||
// disconnect the remote client
|
||||
m_ClientDisconnected = false;
|
||||
server.DisconnectClient(clients[0].LocalClientId);
|
||||
clients[0].OnClientDisconnectCallback += OnClientDisconnectCallback;
|
||||
var timeoutHelper = new TimeoutHelper();
|
||||
yield return NetcodeIntegrationTest.WaitForConditionOrTimeOut(() => m_ClientDisconnected, timeoutHelper);
|
||||
|
||||
// We need to do this to remove other associated client properties/values from NetcodeIntegrationTestHelpers
|
||||
NetcodeIntegrationTestHelpers.StopOneClient(clients[0]);
|
||||
|
||||
// ensure the object was destroyed
|
||||
Assert.False(server.SpawnManager.SpawnedObjects.Any(x => x.Value.IsPlayerObject && x.Value.OwnerClientId == clients[0].LocalClientId));
|
||||
|
||||
// cleanup
|
||||
NetcodeIntegrationTestHelpers.Destroy();
|
||||
DestroyWithOwner,
|
||||
DontDestroyWithOwner
|
||||
}
|
||||
|
||||
public enum ClientDisconnectType
|
||||
{
|
||||
ServerDisconnectsClient,
|
||||
ClientDisconnectsFromServer
|
||||
}
|
||||
|
||||
protected override int NumberOfClients => 1;
|
||||
|
||||
private OwnerPersistence m_OwnerPersistence;
|
||||
private bool m_ClientDisconnected;
|
||||
private ulong m_TransportClientId;
|
||||
private ulong m_ClientId;
|
||||
|
||||
|
||||
public DisconnectTests(OwnerPersistence ownerPersistence)
|
||||
{
|
||||
m_OwnerPersistence = ownerPersistence;
|
||||
}
|
||||
|
||||
protected override void OnCreatePlayerPrefab()
|
||||
{
|
||||
m_PlayerPrefab.GetComponent<NetworkObject>().DontDestroyWithOwner = m_OwnerPersistence == OwnerPersistence.DontDestroyWithOwner;
|
||||
base.OnCreatePlayerPrefab();
|
||||
}
|
||||
|
||||
protected override void OnServerAndClientsCreated()
|
||||
{
|
||||
// Adjusting client and server timeout periods to reduce test time
|
||||
// Get the tick frequency in milliseconds and triple it for the heartbeat timeout
|
||||
var heartBeatTimeout = (int)(300 * (1.0f / m_ServerNetworkManager.NetworkConfig.TickRate));
|
||||
var unityTransport = m_ServerNetworkManager.NetworkConfig.NetworkTransport as Transports.UTP.UnityTransport;
|
||||
if (unityTransport != null)
|
||||
{
|
||||
unityTransport.HeartbeatTimeoutMS = heartBeatTimeout;
|
||||
}
|
||||
|
||||
unityTransport = m_ClientNetworkManagers[0].NetworkConfig.NetworkTransport as Transports.UTP.UnityTransport;
|
||||
if (unityTransport != null)
|
||||
{
|
||||
unityTransport.HeartbeatTimeoutMS = heartBeatTimeout;
|
||||
}
|
||||
|
||||
base.OnServerAndClientsCreated();
|
||||
}
|
||||
|
||||
protected override IEnumerator OnSetup()
|
||||
{
|
||||
m_ClientDisconnected = false;
|
||||
m_ClientId = 0;
|
||||
m_TransportClientId = 0;
|
||||
return base.OnSetup();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used to detect the client disconnected on the server side
|
||||
/// </summary>
|
||||
private void OnClientDisconnectCallback(ulong obj)
|
||||
{
|
||||
m_ClientDisconnected = true;
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator ClientDisconnectPlayerObjectCleanup()
|
||||
/// <summary>
|
||||
/// Conditional check to assure the transport to client (and vice versa) mappings are cleaned up
|
||||
/// </summary>
|
||||
private bool TransportIdCleanedUp()
|
||||
{
|
||||
// create server and client instances
|
||||
NetcodeIntegrationTestHelpers.Create(1, out NetworkManager server, out NetworkManager[] clients);
|
||||
|
||||
// create prefab
|
||||
var gameObject = new GameObject("PlayerObject");
|
||||
var networkObject = gameObject.AddComponent<NetworkObject>();
|
||||
networkObject.DontDestroyWithOwner = true;
|
||||
NetcodeIntegrationTestHelpers.MakeNetworkObjectTestPrefab(networkObject);
|
||||
|
||||
server.NetworkConfig.PlayerPrefab = gameObject;
|
||||
|
||||
for (int i = 0; i < clients.Length; i++)
|
||||
if (m_ServerNetworkManager.ConnectionManager.TransportIdToClientId(m_TransportClientId) == m_ClientId)
|
||||
{
|
||||
clients[i].NetworkConfig.PlayerPrefab = gameObject;
|
||||
return false;
|
||||
}
|
||||
|
||||
// start server and connect clients
|
||||
NetcodeIntegrationTestHelpers.Start(false, server, clients);
|
||||
if (m_ServerNetworkManager.ConnectionManager.ClientIdToTransportId(m_ClientId) == m_TransportClientId)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// wait for connection on client side
|
||||
yield return NetcodeIntegrationTestHelpers.WaitForClientsConnected(clients);
|
||||
/// <summary>
|
||||
/// Conditional check to make sure the client player object no longer exists on the server side
|
||||
/// </summary>
|
||||
private bool DoesServerStillHaveSpawnedPlayerObject()
|
||||
{
|
||||
if (m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId].ContainsKey(m_ClientId))
|
||||
{
|
||||
var playerObject = m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId][m_ClientId];
|
||||
if (playerObject != null && playerObject.IsSpawned)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return !m_ServerNetworkManager.SpawnManager.SpawnedObjects.Any(x => x.Value.IsPlayerObject && x.Value.OwnerClientId == m_ClientId);
|
||||
}
|
||||
|
||||
// wait for connection on server side
|
||||
yield return NetcodeIntegrationTestHelpers.WaitForClientConnectedToServer(server);
|
||||
[UnityTest]
|
||||
public IEnumerator ClientPlayerDisconnected([Values] ClientDisconnectType clientDisconnectType)
|
||||
{
|
||||
m_ClientId = m_ClientNetworkManagers[0].LocalClientId;
|
||||
|
||||
// disconnect the remote client
|
||||
m_ClientDisconnected = false;
|
||||
var serverSideClientPlayer = m_ServerNetworkManager.ConnectionManager.ConnectedClients[m_ClientId].PlayerObject;
|
||||
|
||||
server.OnClientDisconnectCallback += OnClientDisconnectCallback;
|
||||
m_TransportClientId = m_ServerNetworkManager.ConnectionManager.ClientIdToTransportId(m_ClientId);
|
||||
|
||||
var serverSideClientPlayer = server.ConnectedClients[clients[0].LocalClientId].PlayerObject;
|
||||
if (clientDisconnectType == ClientDisconnectType.ServerDisconnectsClient)
|
||||
{
|
||||
m_ClientNetworkManagers[0].OnClientDisconnectCallback += OnClientDisconnectCallback;
|
||||
m_ServerNetworkManager.DisconnectClient(m_ClientId);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_ServerNetworkManager.OnClientDisconnectCallback += OnClientDisconnectCallback;
|
||||
|
||||
// Stopping the client is the same as the client disconnecting
|
||||
NetcodeIntegrationTestHelpers.StopOneClient(clients[0]);
|
||||
yield return StopOneClient(m_ClientNetworkManagers[0]);
|
||||
}
|
||||
|
||||
var timeoutHelper = new TimeoutHelper();
|
||||
yield return NetcodeIntegrationTest.WaitForConditionOrTimeOut(() => m_ClientDisconnected, timeoutHelper);
|
||||
yield return WaitForConditionOrTimeOut(() => m_ClientDisconnected);
|
||||
AssertOnTimeout("Timed out waiting for client to disconnect!");
|
||||
|
||||
// ensure the object was destroyed
|
||||
Assert.True(serverSideClientPlayer.IsOwnedByServer, $"The client's player object's ownership was not transferred back to the server!");
|
||||
if (m_OwnerPersistence == OwnerPersistence.DestroyWithOwner)
|
||||
{
|
||||
// When we are destroying with the owner, validate the player object is destroyed on the server side
|
||||
yield return WaitForConditionOrTimeOut(DoesServerStillHaveSpawnedPlayerObject);
|
||||
AssertOnTimeout("Timed out waiting for client's player object to be destroyed!");
|
||||
}
|
||||
else
|
||||
{
|
||||
// When we are not destroying with the owner, ensure the player object's ownership was transferred back to the server
|
||||
yield return WaitForConditionOrTimeOut(() => serverSideClientPlayer.IsOwnedByServer);
|
||||
AssertOnTimeout("The client's player object's ownership was not transferred back to the server!");
|
||||
}
|
||||
|
||||
// cleanup
|
||||
NetcodeIntegrationTestHelpers.Destroy();
|
||||
yield return WaitForConditionOrTimeOut(TransportIdCleanedUp);
|
||||
AssertOnTimeout("Timed out waiting for transport and client id mappings to be cleaned up!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
public IEnumerator WhenSendingConnectionApprovedToAlreadyConnectedClient_ConnectionApprovedMessageIsRejected()
|
||||
{
|
||||
var message = new ConnectionApprovedMessage();
|
||||
m_ServerNetworkManager.SendMessage(ref message, NetworkDelivery.Reliable, m_ClientNetworkManagers[0].LocalClientId);
|
||||
m_ServerNetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, m_ClientNetworkManagers[0].LocalClientId);
|
||||
|
||||
// Unnamed message is something to wait for. When this one is received,
|
||||
// we know the above one has also reached its destination.
|
||||
@@ -91,7 +91,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
m_ServerNetworkManager.CustomMessagingManager.SendUnnamedMessage(m_ClientNetworkManagers[0].LocalClientId, writer);
|
||||
}
|
||||
|
||||
m_ClientNetworkManagers[0].MessagingSystem.Hook(new Hooks<ConnectionApprovedMessage>());
|
||||
m_ClientNetworkManagers[0].ConnectionManager.MessageManager.Hook(new Hooks<ConnectionApprovedMessage>());
|
||||
|
||||
LogAssert.Expect(LogType.Error, new Regex($"A {nameof(ConnectionApprovedMessage)} was received from the server when the connection has already been established\\. This should not happen\\."));
|
||||
|
||||
@@ -102,7 +102,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
public IEnumerator WhenSendingConnectionRequestToAnyClient_ConnectionRequestMessageIsRejected()
|
||||
{
|
||||
var message = new ConnectionRequestMessage();
|
||||
m_ServerNetworkManager.SendMessage(ref message, NetworkDelivery.Reliable, m_ClientNetworkManagers[0].LocalClientId);
|
||||
m_ServerNetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, m_ClientNetworkManagers[0].LocalClientId);
|
||||
|
||||
// Unnamed message is something to wait for. When this one is received,
|
||||
// we know the above one has also reached its destination.
|
||||
@@ -113,7 +113,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
m_ServerNetworkManager.CustomMessagingManager.SendUnnamedMessage(m_ClientNetworkManagers[0].LocalClientId, writer);
|
||||
}
|
||||
|
||||
m_ClientNetworkManagers[0].MessagingSystem.Hook(new Hooks<ConnectionRequestMessage>());
|
||||
m_ClientNetworkManagers[0].ConnectionManager.MessageManager.Hook(new Hooks<ConnectionRequestMessage>());
|
||||
|
||||
LogAssert.Expect(LogType.Error, new Regex($"A {nameof(ConnectionRequestMessage)} was received from the server on the client side\\. This should not happen\\."));
|
||||
|
||||
@@ -124,7 +124,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
public IEnumerator WhenSendingConnectionRequestFromAlreadyConnectedClient_ConnectionRequestMessageIsRejected()
|
||||
{
|
||||
var message = new ConnectionRequestMessage();
|
||||
m_ClientNetworkManagers[0].SendMessage(ref message, NetworkDelivery.Reliable, m_ServerNetworkManager.LocalClientId);
|
||||
m_ClientNetworkManagers[0].ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, m_ServerNetworkManager.LocalClientId);
|
||||
|
||||
// Unnamed message is something to wait for. When this one is received,
|
||||
// we know the above one has also reached its destination.
|
||||
@@ -135,7 +135,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
m_ClientNetworkManagers[0].CustomMessagingManager.SendUnnamedMessage(m_ServerNetworkManager.LocalClientId, writer);
|
||||
}
|
||||
|
||||
m_ServerNetworkManager.MessagingSystem.Hook(new Hooks<ConnectionRequestMessage>());
|
||||
m_ServerNetworkManager.ConnectionManager.MessageManager.Hook(new Hooks<ConnectionRequestMessage>());
|
||||
|
||||
LogAssert.Expect(LogType.Error, new Regex($"A {nameof(ConnectionRequestMessage)} was received from a client when the connection has already been established\\. This should not happen\\."));
|
||||
|
||||
@@ -146,7 +146,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
public IEnumerator WhenSendingConnectionApprovedFromAnyClient_ConnectionApprovedMessageIsRejected()
|
||||
{
|
||||
var message = new ConnectionApprovedMessage();
|
||||
m_ClientNetworkManagers[0].SendMessage(ref message, NetworkDelivery.Reliable, m_ServerNetworkManager.LocalClientId);
|
||||
m_ClientNetworkManagers[0].ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, m_ServerNetworkManager.LocalClientId);
|
||||
|
||||
// Unnamed message is something to wait for. When this one is received,
|
||||
// we know the above one has also reached its destination.
|
||||
@@ -157,7 +157,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
m_ClientNetworkManagers[0].CustomMessagingManager.SendUnnamedMessage(m_ServerNetworkManager.LocalClientId, writer);
|
||||
}
|
||||
|
||||
m_ServerNetworkManager.MessagingSystem.Hook(new Hooks<ConnectionApprovedMessage>());
|
||||
m_ServerNetworkManager.ConnectionManager.MessageManager.Hook(new Hooks<ConnectionApprovedMessage>());
|
||||
|
||||
LogAssert.Expect(LogType.Error, new Regex($"A {nameof(ConnectionApprovedMessage)} was received from a client on the server side\\. This should not happen\\."));
|
||||
|
||||
|
||||
@@ -37,6 +37,8 @@ namespace Unity.Netcode.RuntimeTests.Metrics
|
||||
[UnityTest]
|
||||
public IEnumerator TrackServerLogSentMetric()
|
||||
{
|
||||
// Set the client NetworkManager to assure the log is sent
|
||||
NetworkLog.NetworkManagerOverride = Client;
|
||||
var waitForSentMetric = new WaitForEventMetricValues<ServerLogEvent>(ClientMetrics.Dispatcher, NetworkMetricTypes.ServerLogSent);
|
||||
|
||||
var message = Guid.NewGuid().ToString();
|
||||
@@ -82,6 +84,12 @@ namespace Unity.Netcode.RuntimeTests.Metrics
|
||||
var serializedLength = GetWriteSizeForLog(NetworkLog.LogType.Warning, message);
|
||||
Assert.AreEqual(serializedLength, receivedMetric.BytesCount);
|
||||
}
|
||||
|
||||
protected override IEnumerator OnTearDown()
|
||||
{
|
||||
NetworkLog.NetworkManagerOverride = null;
|
||||
return base.OnTearDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
|
||||
{
|
||||
// Header is dynamically sized due to packing, will be 2 bytes for all test messages.
|
||||
private const int k_MessageHeaderSize = 2;
|
||||
private static readonly long k_MessageOverhead = 8 + FastBufferWriter.GetWriteSize<BatchHeader>() + k_MessageHeaderSize;
|
||||
private static readonly long k_MessageOverhead = 8 + FastBufferWriter.GetWriteSize<NetworkBatchHeader>() + k_MessageHeaderSize;
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator TrackTotalNumberOfBytesSent()
|
||||
|
||||
@@ -312,7 +312,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
}
|
||||
|
||||
// Update the NetworkBehaviours to make sure all network variables are no longer marked as dirty
|
||||
m_ServerNetworkManager.BehaviourUpdater.NetworkBehaviourUpdate(m_ServerNetworkManager);
|
||||
m_ServerNetworkManager.BehaviourUpdater.NetworkBehaviourUpdate();
|
||||
|
||||
// Verify that all network variables are no longer dirty on server side only if we have clients (including host)
|
||||
foreach (var serverSpawnedObject in spawnedPrefabs)
|
||||
|
||||
@@ -27,10 +27,6 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
callbackInvoked = true;
|
||||
Assert.IsFalse(wasAlsoClient);
|
||||
if (m_ServerManager.IsServer)
|
||||
{
|
||||
Assert.Fail("OnServerStopped called when the server is still active");
|
||||
}
|
||||
};
|
||||
|
||||
// Start server to cause initialization process
|
||||
@@ -57,10 +53,6 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
callbackInvoked = true;
|
||||
Assert.IsFalse(wasAlsoServer);
|
||||
if (m_ClientManager.IsClient)
|
||||
{
|
||||
Assert.Fail("onClientStopped called when the client is still active");
|
||||
}
|
||||
};
|
||||
|
||||
m_ClientManager.OnClientStopped += onClientStopped;
|
||||
@@ -85,20 +77,12 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
callbacksInvoked++;
|
||||
Assert.IsTrue(wasAlsoServer);
|
||||
if (m_ServerManager.IsClient)
|
||||
{
|
||||
Assert.Fail("onClientStopped called when the client is still active");
|
||||
}
|
||||
};
|
||||
|
||||
Action<bool> onServerStopped = (bool wasAlsoClient) =>
|
||||
{
|
||||
callbacksInvoked++;
|
||||
Assert.IsTrue(wasAlsoClient);
|
||||
if (m_ServerManager.IsServer)
|
||||
{
|
||||
Assert.Fail("OnServerStopped called when the server is still active");
|
||||
}
|
||||
};
|
||||
|
||||
// Start server to cause initialization process
|
||||
@@ -179,19 +163,11 @@ namespace Unity.Netcode.RuntimeTests
|
||||
Action onClientStarted = () =>
|
||||
{
|
||||
callbacksInvoked++;
|
||||
if (!m_ServerManager.IsClient)
|
||||
{
|
||||
Assert.Fail("OnClientStarted called when the client is not active yet");
|
||||
}
|
||||
};
|
||||
|
||||
Action onServerStarted = () =>
|
||||
{
|
||||
callbacksInvoked++;
|
||||
if (!m_ServerManager.IsServer)
|
||||
{
|
||||
Assert.Fail("OnServerStarted called when the server is not active yet");
|
||||
}
|
||||
};
|
||||
|
||||
m_ServerManager.OnServerStarted += onServerStarted;
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
manager.NetworkConfig = new NetworkConfig() { NetworkTransport = transport };
|
||||
|
||||
LogAssert.Expect(LogType.Error, $"Client is shutting down due to network transport start failure of {transport.GetType().Name}!");
|
||||
LogAssert.Expect(LogType.Error, $"[Netcode] Client is shutting down due to network transport start failure of {transport.GetType().Name}!");
|
||||
|
||||
Assert.False(manager.StartClient());
|
||||
Assert.False(manager.IsListening);
|
||||
@@ -45,7 +45,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
manager.NetworkConfig = new NetworkConfig() { NetworkTransport = transport };
|
||||
|
||||
LogAssert.Expect(LogType.Error, $"Server is shutting down due to network transport start failure of {transport.GetType().Name}!");
|
||||
LogAssert.Expect(LogType.Error, $"[Netcode] Host is shutting down due to network transport start failure of {transport.GetType().Name}!");
|
||||
|
||||
Assert.False(manager.StartHost());
|
||||
Assert.False(manager.IsListening);
|
||||
@@ -67,7 +67,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
manager.NetworkConfig = new NetworkConfig() { NetworkTransport = transport };
|
||||
|
||||
LogAssert.Expect(LogType.Error, $"Server is shutting down due to network transport start failure of {transport.GetType().Name}!");
|
||||
LogAssert.Expect(LogType.Error, $"[Netcode] Server is shutting down due to network transport start failure of {transport.GetType().Name}!");
|
||||
|
||||
Assert.False(manager.StartServer());
|
||||
Assert.False(manager.IsListening);
|
||||
@@ -92,7 +92,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
Assert.True(manager.StartServer());
|
||||
Assert.True(manager.IsListening);
|
||||
|
||||
LogAssert.Expect(LogType.Error, $"Shutting down due to network transport failure of {transport.GetType().Name}!");
|
||||
LogAssert.Expect(LogType.Error, $"[Netcode] Server is shutting down due to network transport failure of {transport.GetType().Name}!");
|
||||
|
||||
// Need two updates to actually shut down. First one to see the transport failing, which
|
||||
// marks the NetworkManager as shutting down. Second one where actual shutdown occurs.
|
||||
|
||||
@@ -52,24 +52,63 @@ namespace Unity.Netcode.RuntimeTests
|
||||
Assert.IsTrue(go == null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tests that a client cannot destroy a spawned networkobject.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[UnityTest]
|
||||
public IEnumerator TestNetworkObjectClientDestroy()
|
||||
|
||||
public enum ClientDestroyObject
|
||||
{
|
||||
// This is the *SERVER VERSION* of the *CLIENT PLAYER*
|
||||
var serverClientPlayerResult = new NetcodeIntegrationTestHelpers.ResultWrapper<NetworkObject>();
|
||||
yield return NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentation(x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, m_ServerNetworkManager, serverClientPlayerResult);
|
||||
ShuttingDown,
|
||||
ActiveSession
|
||||
}
|
||||
/// <summary>
|
||||
/// Validates the expected behavior when the client-side destroys a <see cref="NetworkObject"/>
|
||||
/// </summary>
|
||||
[UnityTest]
|
||||
public IEnumerator TestNetworkObjectClientDestroy([Values] ClientDestroyObject clientDestroyObject)
|
||||
{
|
||||
var isShuttingDown = clientDestroyObject == ClientDestroyObject.ShuttingDown;
|
||||
var clientPlayer = m_ClientNetworkManagers[0].LocalClient.PlayerObject;
|
||||
var clientId = clientPlayer.OwnerClientId;
|
||||
|
||||
// This is the *CLIENT VERSION* of the *CLIENT PLAYER*
|
||||
var clientClientPlayerResult = new NetcodeIntegrationTestHelpers.ResultWrapper<NetworkObject>();
|
||||
yield return NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentation(x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId, m_ClientNetworkManagers[0], clientClientPlayerResult);
|
||||
//destroying a NetworkObject while shutting down is allowed
|
||||
if (isShuttingDown)
|
||||
{
|
||||
m_ClientNetworkManagers[0].Shutdown();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogAssert.ignoreFailingMessages = true;
|
||||
NetworkLog.NetworkManagerOverride = m_ClientNetworkManagers[0];
|
||||
}
|
||||
|
||||
// destroy the client player, this is not allowed
|
||||
LogAssert.Expect(LogType.Exception, "NotServerException: Destroy a spawned NetworkObject on a non-host client is not valid. Call Destroy or Despawn on the server/host instead.");
|
||||
Object.DestroyImmediate(clientClientPlayerResult.Result.gameObject);
|
||||
Object.DestroyImmediate(clientPlayer.gameObject);
|
||||
|
||||
// destroying a NetworkObject while a session is active is not allowed
|
||||
if (!isShuttingDown)
|
||||
{
|
||||
yield return WaitForConditionOrTimeOut(HaveLogsBeenReceived);
|
||||
AssertOnTimeout($"Not all expected logs were received when destroying a {nameof(NetworkObject)} on the client side during an active session!");
|
||||
}
|
||||
}
|
||||
|
||||
private bool HaveLogsBeenReceived()
|
||||
{
|
||||
if (!NetcodeLogAssert.HasLogBeenReceived(LogType.Error, "[Netcode] Destroy a spawned NetworkObject on a non-host client is not valid. Call Destroy or Despawn on the server/host instead."))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!NetcodeLogAssert.HasLogBeenReceived(LogType.Error, $"[Netcode-Server Sender={m_ClientNetworkManagers[0].LocalClientId}] Destroy a spawned NetworkObject on a non-host client is not valid. Call Destroy or Despawn on the server/host instead."))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override IEnumerator OnTearDown()
|
||||
{
|
||||
NetworkLog.NetworkManagerOverride = null;
|
||||
LogAssert.ignoreFailingMessages = false;
|
||||
return base.OnTearDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,86 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
protected override int NumberOfClients => 2;
|
||||
|
||||
public enum ObserverTestTypes
|
||||
{
|
||||
WithObservers,
|
||||
WithoutObservers
|
||||
}
|
||||
private GameObject m_ObserverPrefab;
|
||||
private NetworkObject m_ObserverTestNetworkObject;
|
||||
private ObserverTestTypes m_ObserverTestType;
|
||||
|
||||
private const string k_ObserverTestObjName = "ObsObj";
|
||||
private const string k_WithObserversError = "Not all clients spawned the";
|
||||
private const string k_WithoutObserversError = "A client spawned the";
|
||||
|
||||
protected override void OnServerAndClientsCreated()
|
||||
{
|
||||
m_ObserverPrefab = CreateNetworkObjectPrefab(k_ObserverTestObjName);
|
||||
base.OnServerAndClientsCreated();
|
||||
}
|
||||
|
||||
|
||||
private bool CheckClientsSideObserverTestObj()
|
||||
{
|
||||
foreach (var client in m_ClientNetworkManagers)
|
||||
{
|
||||
if (!s_GlobalNetworkObjects.ContainsKey(client.LocalClientId))
|
||||
{
|
||||
// When no observers there shouldn't be any client spawned NetworkObjects
|
||||
// (players are held in a different list)
|
||||
return !(m_ObserverTestType == ObserverTestTypes.WithObservers);
|
||||
}
|
||||
var clientObjects = s_GlobalNetworkObjects[client.LocalClientId];
|
||||
// Make sure they did spawn the object
|
||||
if (m_ObserverTestType == ObserverTestTypes.WithObservers)
|
||||
{
|
||||
if (!clientObjects.ContainsKey(m_ObserverTestNetworkObject.NetworkObjectId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!clientObjects[m_ObserverTestNetworkObject.NetworkObjectId].IsSpawned)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator ObserverSpawnTests([Values] ObserverTestTypes observerTestTypes)
|
||||
{
|
||||
m_ObserverTestType = observerTestTypes;
|
||||
var prefabNetworkObject = m_ObserverPrefab.GetComponent<NetworkObject>();
|
||||
prefabNetworkObject.SpawnWithObservers = observerTestTypes == ObserverTestTypes.WithObservers;
|
||||
var instance = SpawnObject(m_ObserverPrefab, m_ServerNetworkManager);
|
||||
m_ObserverTestNetworkObject = instance.GetComponent<NetworkObject>();
|
||||
var withoutObservers = m_ObserverTestType == ObserverTestTypes.WithoutObservers;
|
||||
if (withoutObservers)
|
||||
{
|
||||
// Just give a little time to make sure nothing spawned
|
||||
yield return s_DefaultWaitForTick;
|
||||
}
|
||||
yield return WaitForConditionOrTimeOut(CheckClientsSideObserverTestObj);
|
||||
AssertOnTimeout($"{(withoutObservers ? k_WithoutObserversError : k_WithObserversError)} {k_ObserverTestObjName} object!");
|
||||
// If we spawned without observers
|
||||
if (withoutObservers)
|
||||
{
|
||||
// Make each client an observer
|
||||
foreach (var client in m_ClientNetworkManagers)
|
||||
{
|
||||
m_ObserverTestNetworkObject.NetworkShow(client.LocalClientId);
|
||||
}
|
||||
|
||||
// Validate the clients spawned the NetworkObject
|
||||
m_ObserverTestType = ObserverTestTypes.WithObservers;
|
||||
yield return WaitForConditionOrTimeOut(CheckClientsSideObserverTestObj);
|
||||
AssertOnTimeout($"{k_WithObserversError} {k_ObserverTestObjName} object!");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Tests that instantiating a <see cref="NetworkObject"/> and destroying without spawning it
|
||||
/// does not run <see cref="NetworkBehaviour.OnNetworkSpawn"/> or <see cref="NetworkBehaviour.OnNetworkSpawn"/>.
|
||||
@@ -52,6 +132,11 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
protected override IEnumerator OnTearDown()
|
||||
{
|
||||
if (m_ObserverPrefab != null)
|
||||
{
|
||||
Object.Destroy(m_ObserverPrefab);
|
||||
}
|
||||
|
||||
if (m_TestNetworkObjectPrefab != null)
|
||||
{
|
||||
Object.Destroy(m_TestNetworkObjectPrefab);
|
||||
|
||||
@@ -286,6 +286,36 @@ namespace Unity.Netcode.RuntimeTests
|
||||
}
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator ConcurrentShowAndHideOnDifferentObjects()
|
||||
{
|
||||
m_ClientId0 = m_ClientNetworkManagers[0].LocalClientId;
|
||||
ShowHideObject.ClientTargetedNetworkObjects.Clear();
|
||||
ShowHideObject.ClientIdToTarget = m_ClientId0;
|
||||
|
||||
|
||||
// create 3 objects
|
||||
var spawnedObject1 = SpawnObject(m_PrefabToSpawn, m_ServerNetworkManager);
|
||||
var spawnedObject2 = SpawnObject(m_PrefabToSpawn, m_ServerNetworkManager);
|
||||
var spawnedObject3 = SpawnObject(m_PrefabToSpawn, m_ServerNetworkManager);
|
||||
m_NetSpawnedObject1 = spawnedObject1.GetComponent<NetworkObject>();
|
||||
m_NetSpawnedObject2 = spawnedObject2.GetComponent<NetworkObject>();
|
||||
m_NetSpawnedObject3 = spawnedObject3.GetComponent<NetworkObject>();
|
||||
|
||||
// get the NetworkObject on a client instance
|
||||
yield return WaitForConditionOrTimeOut(RefreshNetworkObjects);
|
||||
AssertOnTimeout($"Could not refresh all NetworkObjects!");
|
||||
|
||||
m_NetSpawnedObject1.NetworkHide(m_ClientId0);
|
||||
|
||||
yield return WaitForTicks(m_ServerNetworkManager, 5);
|
||||
|
||||
m_NetSpawnedObject1.NetworkShow(m_ClientId0);
|
||||
m_NetSpawnedObject2.NetworkHide(m_ClientId0);
|
||||
|
||||
yield return WaitForTicks(m_ServerNetworkManager, 5);
|
||||
}
|
||||
|
||||
[UnityTest]
|
||||
public IEnumerator NetworkShowHideQuickTest()
|
||||
{
|
||||
|
||||
@@ -37,10 +37,17 @@ namespace Unity.Netcode.RuntimeTests
|
||||
return ServerAuthority;
|
||||
}
|
||||
|
||||
public static NetworkTransformTestComponent AuthorityInstance;
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
base.OnNetworkSpawn();
|
||||
|
||||
if (CanCommitToTransform)
|
||||
{
|
||||
AuthorityInstance = this;
|
||||
}
|
||||
|
||||
ReadyToReceivePositionUpdate = true;
|
||||
}
|
||||
|
||||
@@ -59,31 +66,38 @@ namespace Unity.Netcode.RuntimeTests
|
||||
/// <summary>
|
||||
/// Helper component for NetworkTransform parenting tests
|
||||
/// </summary>
|
||||
public class ChildObjectComponent : NetworkBehaviour
|
||||
public class ChildObjectComponent : NetworkTransform
|
||||
{
|
||||
public static readonly List<ChildObjectComponent> Instances = new List<ChildObjectComponent>();
|
||||
public static ChildObjectComponent ServerInstance { get; internal set; }
|
||||
public static ChildObjectComponent AuthorityInstance { get; internal set; }
|
||||
public static readonly Dictionary<ulong, NetworkObject> ClientInstances = new Dictionary<ulong, NetworkObject>();
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
ServerInstance = null;
|
||||
AuthorityInstance = null;
|
||||
ClientInstances.Clear();
|
||||
Instances.Clear();
|
||||
}
|
||||
|
||||
public bool ServerAuthority;
|
||||
|
||||
protected override bool OnIsServerAuthoritative()
|
||||
{
|
||||
return ServerAuthority;
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
if (IsServer)
|
||||
base.OnNetworkSpawn();
|
||||
if (CanCommitToTransform)
|
||||
{
|
||||
ServerInstance = this;
|
||||
AuthorityInstance = this;
|
||||
}
|
||||
else
|
||||
{
|
||||
ClientInstances.Add(NetworkManager.LocalClientId, NetworkObject);
|
||||
Instances.Add(this);
|
||||
}
|
||||
Instances.Add(this);
|
||||
base.OnNetworkSpawn();
|
||||
ClientInstances.Add(NetworkManager.LocalClientId, NetworkObject);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,7 +115,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
private NetworkObject m_AuthoritativePlayer;
|
||||
private NetworkObject m_NonAuthoritativePlayer;
|
||||
private NetworkObject m_ChildObjectToBeParented;
|
||||
private NetworkObject m_ChildObject;
|
||||
private NetworkObject m_ParentObject;
|
||||
|
||||
private NetworkTransformTestComponent m_AuthoritativeTransform;
|
||||
private NetworkTransformTestComponent m_NonAuthoritativeTransform;
|
||||
@@ -133,6 +148,13 @@ namespace Unity.Netcode.RuntimeTests
|
||||
Quaternion
|
||||
}
|
||||
|
||||
public enum RotationCompression
|
||||
{
|
||||
None,
|
||||
QuaternionCompress
|
||||
}
|
||||
|
||||
|
||||
public enum TransformSpace
|
||||
{
|
||||
World,
|
||||
@@ -190,6 +212,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
protected override void OnInlineSetup()
|
||||
{
|
||||
NetworkTransformTestComponent.AuthorityInstance = null;
|
||||
m_Precision = Precision.Full;
|
||||
ChildObjectComponent.Reset();
|
||||
}
|
||||
@@ -209,17 +232,22 @@ namespace Unity.Netcode.RuntimeTests
|
||||
protected override void OnServerAndClientsCreated()
|
||||
{
|
||||
var childObject = CreateNetworkObjectPrefab("ChildObject");
|
||||
childObject.AddComponent<ChildObjectComponent>();
|
||||
var childNetworkTransform = childObject.AddComponent<NetworkTransform>();
|
||||
childNetworkTransform.InLocalSpace = true;
|
||||
m_ChildObjectToBeParented = childObject.GetComponent<NetworkObject>();
|
||||
var childNetworkTransform = childObject.AddComponent<ChildObjectComponent>();
|
||||
childNetworkTransform.ServerAuthority = m_Authority == Authority.ServerAuthority;
|
||||
m_ChildObject = childObject.GetComponent<NetworkObject>();
|
||||
|
||||
var parentObject = CreateNetworkObjectPrefab("ParentObject");
|
||||
var parentNetworkTransform = parentObject.AddComponent<NetworkTransformTestComponent>();
|
||||
parentNetworkTransform.ServerAuthority = m_Authority == Authority.ServerAuthority;
|
||||
m_ParentObject = parentObject.GetComponent<NetworkObject>();
|
||||
|
||||
|
||||
// Now apply local transform values
|
||||
m_ChildObjectToBeParented.transform.position = m_ChildObjectLocalPosition;
|
||||
var childRotation = m_ChildObjectToBeParented.transform.rotation;
|
||||
m_ChildObject.transform.position = m_ChildObjectLocalPosition;
|
||||
var childRotation = m_ChildObject.transform.rotation;
|
||||
childRotation.eulerAngles = m_ChildObjectLocalRotation;
|
||||
m_ChildObjectToBeParented.transform.rotation = childRotation;
|
||||
m_ChildObjectToBeParented.transform.localScale = m_ChildObjectLocalScale;
|
||||
m_ChildObject.transform.rotation = childRotation;
|
||||
m_ChildObject.transform.localScale = m_ChildObjectLocalScale;
|
||||
if (m_EnableVerboseDebug)
|
||||
{
|
||||
m_ServerNetworkManager.LogLevel = LogLevel.Developer;
|
||||
@@ -268,7 +296,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
/// <returns></returns>
|
||||
private bool AllChildObjectInstancesAreSpawned()
|
||||
{
|
||||
if (ChildObjectComponent.ServerInstance == null)
|
||||
if (ChildObjectComponent.AuthorityInstance == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -306,21 +334,34 @@ namespace Unity.Netcode.RuntimeTests
|
||||
/// </summary>
|
||||
private bool AllInstancesKeptLocalTransformValues()
|
||||
{
|
||||
var authorityObjectLocalPosition = m_AuthorityChildObject.transform.localPosition;
|
||||
var authorityObjectLocalRotation = m_AuthorityChildObject.transform.localRotation.eulerAngles;
|
||||
var authorityObjectLocalScale = m_AuthorityChildObject.transform.localScale;
|
||||
|
||||
foreach (var childInstance in ChildObjectComponent.Instances)
|
||||
{
|
||||
var childLocalPosition = childInstance.transform.localPosition;
|
||||
var childLocalRotation = childInstance.transform.localRotation.eulerAngles;
|
||||
var childLocalScale = childInstance.transform.localScale;
|
||||
|
||||
if (!Approximately(childLocalPosition, m_ChildObjectLocalPosition))
|
||||
// Adjust approximation based on precision
|
||||
if (m_Precision == Precision.Half)
|
||||
{
|
||||
m_CurrentHalfPrecision = k_HalfPrecisionPosScale;
|
||||
}
|
||||
if (!Approximately(childLocalPosition, authorityObjectLocalPosition))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!ApproximatelyEuler(childLocalRotation, m_ChildObjectLocalRotation))
|
||||
if (!Approximately(childLocalScale, authorityObjectLocalScale))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!Approximately(childLocalScale, m_ChildObjectLocalScale))
|
||||
// Adjust approximation based on precision
|
||||
if (m_Precision == Precision.Half)
|
||||
{
|
||||
m_CurrentHalfPrecision = k_HalfPrecisionRot;
|
||||
}
|
||||
if (!ApproximatelyEuler(childLocalRotation, authorityObjectLocalRotation))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -333,68 +374,133 @@ namespace Unity.Netcode.RuntimeTests
|
||||
/// If not, it generates a message containing the axial values that did not match
|
||||
/// the target/start local space values.
|
||||
/// </summary>
|
||||
private void WaitForAllChildrenLocalTransformValuesToMatch()
|
||||
private void AllChildrenLocalTransformValuesMatch()
|
||||
{
|
||||
var success = WaitForConditionOrTimeOutWithTimeTravel(AllInstancesKeptLocalTransformValues);
|
||||
var infoMessage = string.Empty;
|
||||
if (s_GlobalTimeoutHelper.TimedOut)
|
||||
//TimeTravelToNextTick();
|
||||
var infoMessage = new System.Text.StringBuilder($"Timed out waiting for all children to have the correct local space values:\n");
|
||||
var authorityObjectLocalPosition = m_AuthorityChildObject.transform.localPosition;
|
||||
var authorityObjectLocalRotation = m_AuthorityChildObject.transform.localRotation.eulerAngles;
|
||||
var authorityObjectLocalScale = m_AuthorityChildObject.transform.localScale;
|
||||
|
||||
if (s_GlobalTimeoutHelper.TimedOut || !success)
|
||||
{
|
||||
foreach (var childInstance in ChildObjectComponent.Instances)
|
||||
{
|
||||
var childLocalPosition = childInstance.transform.localPosition;
|
||||
var childLocalRotation = childInstance.transform.localRotation.eulerAngles;
|
||||
var childLocalScale = childInstance.transform.localScale;
|
||||
// Adjust approximation based on precision
|
||||
if (m_Precision == Precision.Half)
|
||||
{
|
||||
m_CurrentHalfPrecision = k_HalfPrecisionPosScale;
|
||||
}
|
||||
if (!Approximately(childLocalPosition, authorityObjectLocalPosition))
|
||||
{
|
||||
infoMessage.AppendLine($"[{childInstance.name}] Child's Local Position ({childLocalPosition}) | Authority Local Position ({authorityObjectLocalPosition})");
|
||||
success = false;
|
||||
}
|
||||
if (!Approximately(childLocalScale, authorityObjectLocalScale))
|
||||
{
|
||||
infoMessage.AppendLine($"[{childInstance.name}] Child's Local Scale ({childLocalScale}) | Authority Local Scale ({authorityObjectLocalScale})");
|
||||
success = false;
|
||||
}
|
||||
|
||||
if (!Approximately(childLocalPosition, m_ChildObjectLocalPosition))
|
||||
// Adjust approximation based on precision
|
||||
if (m_Precision == Precision.Half)
|
||||
{
|
||||
infoMessage += $"[{childInstance.name}] Child's Local Position ({childLocalPosition}) | Original Local Position ({m_ChildObjectLocalPosition})\n";
|
||||
m_CurrentHalfPrecision = k_HalfPrecisionRot;
|
||||
}
|
||||
if (!ApproximatelyEuler(childLocalRotation, m_ChildObjectLocalRotation))
|
||||
if (!ApproximatelyEuler(childLocalRotation, authorityObjectLocalRotation))
|
||||
{
|
||||
infoMessage += $"[{childInstance.name}] Child's Local Rotation ({childLocalRotation}) | Original Local Rotation ({m_ChildObjectLocalRotation})\n";
|
||||
}
|
||||
if (!Approximately(childLocalScale, m_ChildObjectLocalScale))
|
||||
{
|
||||
infoMessage += $"[{childInstance.name}] Child's Local Scale ({childLocalScale}) | Original Local Rotation ({m_ChildObjectLocalScale})\n";
|
||||
infoMessage.AppendLine($"[{childInstance.name}] Child's Local Rotation ({childLocalRotation}) | Authority Local Rotation ({authorityObjectLocalRotation})");
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
Assert.True(success, $"Timed out waiting for all children to have the correct local space values:\n {infoMessage}");
|
||||
if (!success)
|
||||
{
|
||||
Assert.True(success, infoMessage.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private NetworkObject m_AuthorityParentObject;
|
||||
private NetworkTransformTestComponent m_AuthorityParentNetworkTransform;
|
||||
private NetworkObject m_AuthorityChildObject;
|
||||
private ChildObjectComponent m_AuthorityChildNetworkTransform;
|
||||
|
||||
/// <summary>
|
||||
/// Validates that local space transform values remain the same when a NetworkTransform is
|
||||
/// parented under another NetworkTransform
|
||||
/// Validates that transform values remain the same when a NetworkTransform is
|
||||
/// parented under another NetworkTransform under all of the possible axial conditions
|
||||
/// as well as when the parent has a varying scale.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void NetworkTransformParentedLocalSpaceTest([Values] Interpolation interpolation)
|
||||
public void ParentedNetworkTransformTest([Values] Precision precision, [Values] Rotation rotation,
|
||||
[Values] RotationCompression rotationCompression, [Values] Interpolation interpolation, [Values] bool worldPositionStays,
|
||||
[Values(0.5f, 1.0f, 5.0f)] float scale)
|
||||
{
|
||||
m_AuthoritativeTransform.Interpolate = interpolation == Interpolation.EnableInterpolate;
|
||||
m_NonAuthoritativeTransform.Interpolate = interpolation == Interpolation.EnableInterpolate;
|
||||
var authoritativeChildObject = SpawnObject(m_ChildObjectToBeParented.gameObject, m_AuthoritativeTransform.NetworkManager);
|
||||
// Set the precision being used for threshold adjustments
|
||||
m_Precision = precision;
|
||||
|
||||
// Assure all of the child object instances are spawned
|
||||
// Get the NetworkManager that will have authority in order to spawn with the correct authority
|
||||
var isServerAuthority = m_Authority == Authority.ServerAuthority;
|
||||
var authorityNetworkManager = m_ServerNetworkManager;
|
||||
if (!isServerAuthority)
|
||||
{
|
||||
authorityNetworkManager = m_ClientNetworkManagers[0];
|
||||
}
|
||||
|
||||
// Spawn a parent and child object
|
||||
var serverSideParent = SpawnObject(m_ParentObject.gameObject, authorityNetworkManager).GetComponent<NetworkObject>();
|
||||
var serverSideChild = SpawnObject(m_ChildObject.gameObject, authorityNetworkManager).GetComponent<NetworkObject>();
|
||||
|
||||
// Assure all of the child object instances are spawned before proceeding to parenting
|
||||
var success = WaitForConditionOrTimeOutWithTimeTravel(AllChildObjectInstancesAreSpawned);
|
||||
Assert.True(success, "Timed out waiting for all child instances to be spawned!");
|
||||
// Just a sanity check as it should have timed out before this check
|
||||
Assert.IsNotNull(ChildObjectComponent.ServerInstance, $"The server-side {nameof(ChildObjectComponent)} instance is null!");
|
||||
|
||||
// This determines which parent on the server side should be the parent
|
||||
if (m_AuthoritativeTransform.IsServerAuthoritative())
|
||||
{
|
||||
Assert.True(ChildObjectComponent.ServerInstance.NetworkObject.TrySetParent(m_AuthoritativeTransform.transform, false), "[Authoritative] Failed to parent the child object!");
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.True(ChildObjectComponent.ServerInstance.NetworkObject.TrySetParent(m_NonAuthoritativeTransform.transform, false), "[Non-Authoritative] Failed to parent the child object!");
|
||||
}
|
||||
// Get the authority parent and child instances
|
||||
m_AuthorityParentObject = NetworkTransformTestComponent.AuthorityInstance.NetworkObject;
|
||||
m_AuthorityChildObject = ChildObjectComponent.AuthorityInstance.NetworkObject;
|
||||
|
||||
// The child NetworkTransform will use world space when world position stays and
|
||||
// local space when world position does not stay when parenting.
|
||||
ChildObjectComponent.AuthorityInstance.InLocalSpace = !worldPositionStays;
|
||||
ChildObjectComponent.AuthorityInstance.UseHalfFloatPrecision = precision == Precision.Half;
|
||||
ChildObjectComponent.AuthorityInstance.UseQuaternionSynchronization = rotation == Rotation.Quaternion;
|
||||
ChildObjectComponent.AuthorityInstance.UseQuaternionCompression = rotationCompression == RotationCompression.QuaternionCompress;
|
||||
|
||||
// Set whether we are interpolating or not
|
||||
m_AuthorityParentNetworkTransform = m_AuthorityParentObject.GetComponent<NetworkTransformTestComponent>();
|
||||
m_AuthorityParentNetworkTransform.Interpolate = interpolation == Interpolation.EnableInterpolate;
|
||||
m_AuthorityChildNetworkTransform = m_AuthorityChildObject.GetComponent<ChildObjectComponent>();
|
||||
m_AuthorityChildNetworkTransform.Interpolate = interpolation == Interpolation.EnableInterpolate;
|
||||
|
||||
// Apply a scale to the parent object to make sure the scale on the child is properly updated on
|
||||
// non-authority instances.
|
||||
m_AuthorityParentObject.transform.localScale = new Vector3(scale, scale, scale);
|
||||
|
||||
// Allow one tick for authority to update these changes
|
||||
TimeTravelToNextTick();
|
||||
|
||||
// Parent the child under the parent with the current world position stays setting
|
||||
Assert.True(serverSideChild.TrySetParent(serverSideParent.transform, worldPositionStays), "[Server-Side Child] Failed to set child's parent!");
|
||||
|
||||
// This waits for all child instances to be parented
|
||||
success = WaitForConditionOrTimeOutWithTimeTravel(AllChildObjectInstancesHaveChild);
|
||||
Assert.True(success, "Timed out waiting for all instances to have parented a child!");
|
||||
|
||||
// This validates each child instance has preserved their local space values
|
||||
WaitForAllChildrenLocalTransformValuesToMatch();
|
||||
AllChildrenLocalTransformValuesMatch();
|
||||
|
||||
// Verify that a late joining client will synchronize to the parented NetworkObjects properly
|
||||
CreateAndStartNewClientWithTimeTravel();
|
||||
|
||||
// Assure all of the child object instances are spawned (basically for the newly connected client)
|
||||
success = WaitForConditionOrTimeOutWithTimeTravel(AllChildObjectInstancesAreSpawned);
|
||||
Assert.True(success, "Timed out waiting for all child instances to be spawned!");
|
||||
|
||||
// Assure the newly connected client's child object's transform values are correct
|
||||
AllChildrenLocalTransformValuesMatch();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -143,6 +143,10 @@ namespace Unity.Netcode.RuntimeTests
|
||||
value = new MyTypeOne();
|
||||
reader.ReadValueSafe(out value.Value);
|
||||
};
|
||||
UserNetworkVariableSerialization<MyTypeOne>.DuplicateValue = (in MyTypeOne value, ref MyTypeOne duplicatedValue) =>
|
||||
{
|
||||
duplicatedValue = value;
|
||||
};
|
||||
|
||||
var serverObject = SpawnObject(m_WorkingPrefab, m_ServerNetworkManager);
|
||||
var serverNetworkObject = serverObject.GetComponent<NetworkObject>();
|
||||
@@ -172,6 +176,10 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
UserNetworkVariableSerialization<MyTypeTwo>.WriteValue = NetworkVariableUserSerializableTypesTestsExtensionMethods.WriteValueSafe;
|
||||
UserNetworkVariableSerialization<MyTypeTwo>.ReadValue = NetworkVariableUserSerializableTypesTestsExtensionMethods.ReadValueSafe;
|
||||
UserNetworkVariableSerialization<MyTypeTwo>.DuplicateValue = (in MyTypeTwo value, ref MyTypeTwo duplicatedValue) =>
|
||||
{
|
||||
duplicatedValue = value;
|
||||
};
|
||||
|
||||
var serverObject = SpawnObject(m_ExtensionMethodPrefab, m_ServerNetworkManager);
|
||||
var serverNetworkObject = serverObject.GetComponent<NetworkObject>();
|
||||
|
||||
@@ -4,9 +4,9 @@ using System.Collections.Generic;
|
||||
using NUnit.Framework;
|
||||
using Unity.Collections;
|
||||
using Unity.Netcode.TestHelpers.Runtime;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using Debug = UnityEngine.Debug;
|
||||
using Vector3 = UnityEngine.Vector3;
|
||||
|
||||
namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
@@ -15,7 +15,15 @@ namespace Unity.Netcode.RuntimeTests
|
||||
public class RpcTestNB : NetworkBehaviour
|
||||
{
|
||||
public event Action<ulong, ServerRpcParams> OnServer_Rpc;
|
||||
public event Action<Vector3, Vector3[], FixedString32Bytes> OnTypedServer_Rpc;
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
public event Action<NativeList<ulong>, ServerRpcParams> OnNativeListServer_Rpc;
|
||||
#endif
|
||||
public event Action<Vector3, Vector3[],
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
NativeList<Vector3>,
|
||||
#endif
|
||||
FixedString32Bytes> OnTypedServer_Rpc;
|
||||
|
||||
public event Action OnClient_Rpc;
|
||||
|
||||
[ServerRpc]
|
||||
@@ -24,6 +32,15 @@ namespace Unity.Netcode.RuntimeTests
|
||||
OnServer_Rpc(clientId, param);
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
[ServerRpc]
|
||||
public void MyNativeListServerRpc(NativeList<ulong> clientId, ServerRpcParams param = default)
|
||||
{
|
||||
OnNativeListServer_Rpc(clientId, param);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
[ClientRpc]
|
||||
public void MyClientRpc()
|
||||
{
|
||||
@@ -31,9 +48,17 @@ namespace Unity.Netcode.RuntimeTests
|
||||
}
|
||||
|
||||
[ServerRpc]
|
||||
public void MyTypedServerRpc(Vector3 param1, Vector3[] param2, FixedString32Bytes param3)
|
||||
public void MyTypedServerRpc(Vector3 param1, Vector3[] param2,
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
NativeList<Vector3> param3,
|
||||
#endif
|
||||
FixedString32Bytes param4)
|
||||
{
|
||||
OnTypedServer_Rpc(param1, param2, param3);
|
||||
OnTypedServer_Rpc(param1, param2,
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
param3,
|
||||
#endif
|
||||
param4);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +86,13 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
var vector3 = new Vector3(1, 2, 3);
|
||||
Vector3[] vector3s = new[] { new Vector3(4, 5, 6), new Vector3(7, 8, 9) };
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
using var vector3sNativeList = new NativeList<Vector3>(Allocator.Persistent)
|
||||
{
|
||||
new Vector3(10, 11, 12),
|
||||
new Vector3(13, 14, 15)
|
||||
};
|
||||
#endif
|
||||
|
||||
localClienRpcTestNB.OnClient_Rpc += () =>
|
||||
{
|
||||
@@ -90,14 +122,24 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
var str = new FixedString32Bytes("abcdefg");
|
||||
|
||||
serverClientRpcTestNB.OnTypedServer_Rpc += (param1, param2, param3) =>
|
||||
serverClientRpcTestNB.OnTypedServer_Rpc += (param1, param2,
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
param3,
|
||||
#endif
|
||||
param4) =>
|
||||
{
|
||||
Debug.Log("TypedServerRpc received on server object");
|
||||
Assert.AreEqual(param1, vector3);
|
||||
Assert.AreEqual(param2.Length, vector3s.Length);
|
||||
Assert.AreEqual(param2[0], vector3s[0]);
|
||||
Assert.AreEqual(param2[1], vector3s[1]);
|
||||
Assert.AreEqual(param3, str);
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
Assert.AreEqual(param3.Length, vector3s.Length);
|
||||
Assert.AreEqual(param3[0], vector3sNativeList[0]);
|
||||
Assert.AreEqual(param3[1], vector3sNativeList[1]);
|
||||
#endif
|
||||
Assert.AreEqual(param4, str);
|
||||
hasReceivedTypedServerRpc = true;
|
||||
};
|
||||
|
||||
@@ -105,12 +147,16 @@ namespace Unity.Netcode.RuntimeTests
|
||||
localClienRpcTestNB.MyServerRpc(m_ClientNetworkManagers[0].LocalClientId);
|
||||
|
||||
// Send TypedServerRpc
|
||||
localClienRpcTestNB.MyTypedServerRpc(vector3, vector3s, str);
|
||||
localClienRpcTestNB.MyTypedServerRpc(vector3, vector3s,
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
vector3sNativeList,
|
||||
#endif
|
||||
str);
|
||||
|
||||
// Send ClientRpc
|
||||
serverClientRpcTestNB.MyClientRpc();
|
||||
|
||||
// Validate each NetworkManager relative MessagingSystem received each respective RPC
|
||||
// Validate each NetworkManager relative NetworkMessageManager received each respective RPC
|
||||
var messageHookList = new List<MessageHookEntry>();
|
||||
var serverMessageHookEntry = new MessageHookEntry(m_ServerNetworkManager);
|
||||
serverMessageHookEntry.AssignMessageType<ServerRpcMessage>();
|
||||
@@ -126,6 +172,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
clientMessageHookEntry.AssignMessageType<ClientRpcMessage>();
|
||||
messageHookList.Add(clientMessageHookEntry);
|
||||
}
|
||||
|
||||
var rpcMessageHooks = new MessageHooksConditional(messageHookList);
|
||||
yield return WaitForConditionOrTimeOut(rpcMessageHooks);
|
||||
Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for messages: {rpcMessageHooks.GetHooksStillWaiting()}");
|
||||
|
||||
1987
Tests/Runtime/RpcTypeSerializationTests.cs
Normal file
1987
Tests/Runtime/RpcTypeSerializationTests.cs
Normal file
File diff suppressed because it is too large
Load Diff
3
Tests/Runtime/RpcTypeSerializationTests.cs.meta
Normal file
3
Tests/Runtime/RpcTypeSerializationTests.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fd1b9e10285844d48c86d1930652d22c
|
||||
timeCreated: 1672959718
|
||||
@@ -16,7 +16,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
private struct TriggerData
|
||||
{
|
||||
public FastBufferReader Reader;
|
||||
public MessageHeader Header;
|
||||
public NetworkMessageHeader Header;
|
||||
public ulong SenderId;
|
||||
public float Timestamp;
|
||||
public int SerializedHeaderSize;
|
||||
@@ -29,7 +29,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
foreach (var caughtSpawn in m_CaughtMessages)
|
||||
{
|
||||
// Reader will be disposed within HandleMessage
|
||||
m_OwnerNetworkManager.MessagingSystem.HandleMessage(caughtSpawn.Header, caughtSpawn.Reader, caughtSpawn.SenderId, caughtSpawn.Timestamp, caughtSpawn.SerializedHeaderSize);
|
||||
m_OwnerNetworkManager.ConnectionManager.MessageManager.HandleMessage(caughtSpawn.Header, caughtSpawn.Reader, caughtSpawn.SenderId, caughtSpawn.Timestamp, caughtSpawn.SerializedHeaderSize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,22 @@ namespace Unity.Netcode.RuntimeTests
|
||||
yield return null;
|
||||
}
|
||||
|
||||
// Check that invalid endpoint addresses are detected and return false if detected
|
||||
[Test]
|
||||
public void DetectInvalidEndpoint()
|
||||
{
|
||||
using var netcodeLogAssert = new NetcodeLogAssert(true);
|
||||
InitializeTransport(out m_Server, out m_ServerEvents);
|
||||
InitializeTransport(out m_Clients[0], out m_ClientsEvents[0]);
|
||||
m_Server.ConnectionData.Address = "Fubar";
|
||||
m_Server.ConnectionData.ServerListenAddress = "Fubar";
|
||||
m_Clients[0].ConnectionData.Address = "MoreFubar";
|
||||
Assert.False(m_Server.StartServer(), "Server failed to detect invalid endpoint!");
|
||||
Assert.False(m_Clients[0].StartClient(), "Client failed to detect invalid endpoint!");
|
||||
netcodeLogAssert.LogWasReceived(LogType.Error, $"Network listen address ({m_Server.ConnectionData.Address}) is Invalid!");
|
||||
netcodeLogAssert.LogWasReceived(LogType.Error, $"Target server network address ({m_Clients[0].ConnectionData.Address}) is Invalid!");
|
||||
}
|
||||
|
||||
// Check connection with a single client.
|
||||
[UnityTest]
|
||||
public IEnumerator ConnectSingleClient()
|
||||
|
||||
Reference in New Issue
Block a user