com.unity.netcode.gameobjects@1.4.0

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.4.0] - 2023-04-10

### Added

- Added a way to access the GlobalObjectIdHash via PrefabIdHash for use in the Connection Approval Callback. (#2437)
- Added `OnServerStarted` and `OnServerStopped` events that will trigger only on the server (or host player) to notify that the server just started or is no longer active (#2420)
- Added `OnClientStarted` and `OnClientStopped` events that will trigger only on the client (or host player) to notify that the client just started or is no longer active (#2420)
- Added `NetworkTransform.UseHalfFloatPrecision` property that, when enabled, will use half float values for position, rotation, and scale. This yields a 50% bandwidth savings a the cost of precision. (#2388)
- Added `NetworkTransform.UseQuaternionSynchronization` property that, when enabled, will synchronize the entire quaternion. (#2388)
- Added `NetworkTransform.UseQuaternionCompression` property that, when enabled, will use a smallest three implementation reducing a full quaternion synchronization update to the size of an unsigned integer. (#2388)
- Added `NetworkTransform.SlerpPosition` property that, when enabled along with interpolation being enabled, will interpolate using `Vector3.Slerp`. (#2388)
- Added `BufferedLinearInterpolatorVector3` that replaces the float version, is now used by `NetworkTransform`, and provides the ability to enable or disable `Slerp`. (#2388)
- Added `HalfVector3` used for scale when half float precision is enabled. (#2388)
- Added `HalfVector4` used for rotation when half float precision and quaternion synchronization is enabled. (#2388)
- Added `HalfVector3DeltaPosition` used for position when half float precision is enabled. This handles loss in position precision by updating only the delta position as opposed to the full position. (#2388)
- Added `NetworkTransform.GetSpaceRelativePosition` and `NetworkTransform.GetSpaceRelativeRotation` helper methods to return the proper values depending upon whether local or world space. (#2388)
- Added `NetworkTransform.OnAuthorityPushTransformState` virtual method that is invoked just prior to sending the `NetworkTransformState` to non-authoritative instances. This provides users with the ability to obtain more precise delta values for prediction related calculations. (#2388)
- Added `NetworkTransform.OnNetworkTransformStateUpdated` virtual method that is invoked just after the authoritative `NetworkTransformState` is applied. This provides users with the ability to obtain more precise delta values for prediction related calculations. (#2388)
- Added `NetworkTransform.OnInitialize`virtual method that is invoked after the `NetworkTransform` has been initialized or re-initialized when ownership changes. This provides for a way to make adjustments when `NetworkTransform` is initialized (i.e. resetting client prediction etc) (#2388)
- Added `NetworkObject.SynchronizeTransform` property (default is true) that provides users with another way to help with bandwidth optimizations where, when set to false, the `NetworkObject`'s associated transform will not be included when spawning and/or synchronizing late joining players. (#2388)
- Added `NetworkSceneManager.ActiveSceneSynchronizationEnabled` property, disabled by default, that enables client synchronization of server-side active scene changes. (#2383)
- Added `NetworkObject.ActiveSceneSynchronization`, disabled by default, that will automatically migrate a `NetworkObject` to a newly assigned active scene. (#2383)
- Added `NetworkObject.SceneMigrationSynchronization`, enabled by default, that will synchronize client(s) when a `NetworkObject` is migrated into a new scene on the server side via `SceneManager.MoveGameObjectToScene`. (#2383)

### Changed

- Made sure the `CheckObjectVisibility` delegate is checked and applied, upon `NetworkShow` attempt. Found while supporting (#2454), although this is not a fix for this (already fixed) issue. (#2463)
- Changed `NetworkTransform` authority handles delta checks on each new network tick and no longer consumes processing cycles checking for deltas for all frames in-between ticks. (#2388)
- Changed the `NetworkTransformState` structure is now public and now has public methods that provide access to key properties of the `NetworkTransformState` structure. (#2388)
- Changed `NetworkTransform` interpolation adjusts its interpolation "ticks ago" to be 2 ticks latent if it is owner authoritative and the instance is not the server or 1 tick latent if the instance is the server and/or is server authoritative. (#2388)
- Updated `NetworkSceneManager` to migrate dynamically spawned `NetworkObject`s with `DestroyWithScene` set to false into the active scene if their current scene is unloaded. (#2383)
- Updated the server to synchronize its local `NetworkSceneManager.ClientSynchronizationMode` during the initial client synchronization. (#2383)

### Fixed

- Fixed issue where during client synchronization the synchronizing client could receive a ObjectSceneChanged message before the client-side NetworkObject instance had been instantiated and spawned. (#2502)
- Fixed issue where `NetworkAnimator` was building client RPC parameters to exclude the host from sending itself messages but was not including it in the ClientRpc parameters. (#2492)
- Fixed issue where `NetworkAnimator` was not properly detecting and synchronizing cross fade initiated transitions. (#2481)
- Fixed issue where `NetworkAnimator` was not properly synchronizing animation state updates. (#2481)
- Fixed float NetworkVariables not being rendered properly in the inspector of NetworkObjects. (#2441)
- Fixed an issue where Named Message Handlers could remove themselves causing an exception when the metrics tried to access the name of the message.(#2426)
- Fixed registry of public `NetworkVariable`s in derived `NetworkBehaviour`s (#2423)
- Fixed issue where runtime association of `Animator` properties to `AnimationCurve`s would cause `NetworkAnimator` to attempt to update those changes. (#2416)
- Fixed issue where `NetworkAnimator` would not check if its associated `Animator` was valid during serialization and would spam exceptions in the editor console. (#2416)
- Fixed issue with a child's rotation rolling over when interpolation is enabled on a `NetworkTransform`. Now using half precision or full quaternion synchronization will always update all axis. (#2388)
- Fixed issue where `NetworkTransform` was not setting the teleport flag when the `NetworkTransform.InLocalSpace` value changed. This issue only impacted `NetworkTransform` when interpolation was enabled. (#2388)
- Fixed issue when the `NetworkSceneManager.ClientSynchronizationMode` is `LoadSceneMode.Additive` and the server changes the currently active scene prior to a client connecting then upon a client connecting and being synchronized the NetworkSceneManager would clear its internal ScenePlacedObjects list that could already be populated. (#2383)
- Fixed issue where a client would load duplicate scenes of already preloaded scenes during the initial client synchronization and `NetworkSceneManager.ClientSynchronizationMode` was set to `LoadSceneMode.Additive`. (#2383)
This commit is contained in:
Unity Technologies
2023-04-10 00:00:00 +00:00
parent 8060718e04
commit b5abc3ff7c
138 changed files with 7892 additions and 1852 deletions

View File

@@ -2,12 +2,14 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using NUnit.Framework;
using Unity.Netcode.RuntimeTests;
using Unity.Netcode.Transports.UTP;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
using System.Runtime.CompilerServices;
using Unity.Netcode.RuntimeTests;
using Object = UnityEngine.Object;
namespace Unity.Netcode.TestHelpers.Runtime
@@ -22,6 +24,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// determine how clients will load scenes
/// </summary>
internal static bool IsRunning { get; private set; }
protected static TimeoutHelper s_GlobalTimeoutHelper = new TimeoutHelper(8.0f);
protected static WaitForSecondsRealtime s_DefaultWaitForTick = new WaitForSecondsRealtime(1.0f / k_DefaultTickRate);
@@ -44,6 +47,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
s_GlobalNetworkObjects.Add(networkObject.NetworkManager.LocalClientId, new Dictionary<ulong, NetworkObject>());
}
if (s_GlobalNetworkObjects[networkObject.NetworkManager.LocalClientId].ContainsKey(networkObject.NetworkObjectId))
{
if (s_GlobalNetworkObjects[networkObject.NetworkManager.LocalClientId] == null)
@@ -100,9 +104,9 @@ namespace Unity.Netcode.TestHelpers.Runtime
public enum NetworkManagerInstatiationMode
{
PerTest, // This will create and destroy new NetworkManagers for each test within a child derived class
AllTests, // This will create one set of NetworkManagers used for all tests within a child derived class (destroyed once all tests are finished)
DoNotCreate // This will not create any NetworkManagers, it is up to the derived class to manage.
PerTest, // This will create and destroy new NetworkManagers for each test within a child derived class
AllTests, // This will create one set of NetworkManagers used for all tests within a child derived class (destroyed once all tests are finished)
DoNotCreate // This will not create any NetworkManagers, it is up to the derived class to manage.
}
public enum HostOrServer
@@ -143,6 +147,75 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </remarks>
protected bool m_BypassConnectionTimeout { get; set; }
/// <summary>
/// Enables "Time Travel" within the test, which swaps the time provider for the SDK from Unity's
/// <see cref="Time"/> class to <see cref="MockTimeProvider"/>, and also swaps the transport implementation
/// from <see cref="UnityTransport"/> to <see cref="MockTransport"/>.
///
/// This enables five important things that help with both performance and determinism of tests that involve a
/// lot of time and waiting:
/// 1) It allows time to move in a completely deterministic way (testing that something happens after n seconds,
/// the test will always move exactly n seconds with no chance of any variability in the timing),
/// 2) It allows skipping periods of time without actually waiting that amount of time, while still simulating
/// SDK frames as if that time were passing,
/// 3) It dissociates the SDK's update loop from Unity's update loop, allowing us to simulate SDK frame updates
/// without waiting for Unity to process things like physics, animation, and rendering that aren't relevant to
/// the test,
/// 4) It dissociates the SDK's messaging system from the networking hardware, meaning there's no delay between
/// a message being sent and it being received, allowing us to deterministically rely on the message being
/// received within specific time frames for the test, and
/// 5) It allows tests to be written without the use of coroutines, which not only improves the test's runtime,
/// but also results in easier-to-read callstacks and removes the possibility for an assertion to result in the
/// test hanging.
///
/// When time travel is enabled, the following methods become available:
///
/// <see cref="TimeTravel"/>: Simulates a specific number of frames passing over a specific time period
/// <see cref="TimeTravelToNextTick"/>: Skips forward to the next tick, siumlating at the current application frame rate
/// <see cref="WaitForConditionOrTimeOutWithTimeTravel(Func{bool},int)"/>: Simulates frames at the application frame rate until the given condition is true
/// <see cref="WaitForMessageReceivedWithTimeTravel{T}"/>: Simulates frames at the application frame rate until the required message is received
/// <see cref="WaitForMessagesReceivedWithTimeTravel"/>: Simulates frames at the application frame rate until the required messages are received
/// <see cref="StartServerAndClientsWithTimeTravel"/>: Starts a server and client and allows them to connect via simulated frames
/// <see cref="CreateAndStartNewClientWithTimeTravel"/>: Creates a client and waits for it to connect via simulated frames
/// <see cref="WaitForClientsConnectedOrTimeOutWithTimeTravel(Unity.Netcode.NetworkManager[])"/> Simulates frames at the application frame rate until the given clients are connected
/// <see cref="StopOneClientWithTimeTravel"/>: Stops a client and simulates frames until it's fully disconnected.
///
/// When time travel is enabled, <see cref="NetcodeIntegrationTest"/> will automatically use these in its methods
/// when doing things like automatically connecting clients during SetUp.
///
/// Additionally, the following methods replace their non-time-travel equivalents with variants that are not coroutines:
/// <see cref="OnTimeTravelStartedServerAndClients"/> - called when server and clients are started
/// <see cref="OnTimeTravelServerAndClientsConnected"/> - called when server and clients are connected
///
/// Note that all of the non-time travel functions can still be used even when time travel is enabled - this is
/// sometimes needed for, e.g., testing NetworkAnimator, where the unity update loop needs to run to process animations.
/// However, it's VERY important to note here that, because the SDK will not be operating based on real-world time
/// but based on the frozen time that's locked in from MockTimeProvider, actions that pass 10 seconds apart by
/// real-world clock time will be perceived by the SDK as having happened simultaneously if you don't call
/// <see cref="MockTimeProvider.TimeTravel"/> to cover the equivalent time span in the mock time provider.
/// (Calling <see cref="MockTimeProvider.TimeTravel"/> instead of <see cref="TimeTravel"/>
/// will move time forward without simulating any frames, which, in the case where real-world time has passed,
/// is likely more desirable). In most cases, this desynch won't affect anything, but it is worth noting that
/// it happens just in case a tested system depends on both the unity update loop happening *and* time moving forward.
/// </summary>
protected virtual bool m_EnableTimeTravel => false;
/// <summary>
/// If this is false, SetUp will call OnInlineSetUp instead of OnSetUp.
/// This is a performance advantage when not using the coroutine functionality, as a coroutine that
/// has no yield instructions in it will nonetheless still result in delaying the continuation of the
/// method that called it for a full frame after it returns.
/// </summary>
protected virtual bool m_SetupIsACoroutine => true;
/// <summary>
/// If this is false, TearDown will call OnInlineTearDown instead of OnTearDown.
/// This is a performance advantage when not using the coroutine functionality, as a coroutine that
/// has no yield instructions in it will nonetheless still result in delaying the continuation of the
/// method that called it for a full frame after it returns.
/// </summary>
protected virtual bool m_TearDownIsACoroutine => true;
/// <summary>
/// Used to display the various integration test
/// stages and can be used to log verbose information
@@ -216,20 +289,54 @@ namespace Unity.Netcode.TestHelpers.Runtime
yield return null;
}
/// <summary>
/// Called before creating and starting the server and clients
/// Note: For <see cref="NetworkManagerInstatiationMode.AllTests"/> and
/// <see cref="NetworkManagerInstatiationMode.PerTest"/> mode integration tests.
/// For those two modes, if you want to have access to the server or client
/// <see cref="NetworkManager"/>s then override <see cref="OnServerAndClientsCreated"/>.
/// <see cref="m_ServerNetworkManager"/> and <see cref="m_ClientNetworkManagers"/>
/// </summary>
protected virtual void OnInlineSetup()
{
}
[UnitySetUp]
public IEnumerator SetUp()
{
VerboseDebug($"Entering {nameof(SetUp)}");
NetcodeLogAssert = new NetcodeLogAssert();
yield return OnSetup();
if (m_SetupIsACoroutine)
{
yield return OnSetup();
}
else
{
OnInlineSetup();
}
if (m_EnableTimeTravel)
{
MockTimeProvider.Reset();
ComponentFactory.Register<IRealTimeProvider>(manager => new MockTimeProvider());
}
if (m_NetworkManagerInstatiationMode == NetworkManagerInstatiationMode.AllTests && m_ServerNetworkManager == null ||
m_NetworkManagerInstatiationMode == NetworkManagerInstatiationMode.PerTest)
{
CreateServerAndClients();
yield return StartServerAndClients();
if (m_EnableTimeTravel)
{
StartServerAndClientsWithTimeTravel();
}
else
{
yield return StartServerAndClients();
}
}
VerboseDebug($"Exiting {nameof(SetUp)}");
}
@@ -294,6 +401,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
clientNetworkManagersList.Remove(networkManager);
}
m_ClientNetworkManagers = clientNetworkManagersList.ToArray();
m_NumberOfClients = clientNetworkManagersList.Count;
}
@@ -304,7 +412,6 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary>
protected virtual void OnNewClientCreated(NetworkManager networkManager)
{
}
/// <summary>
@@ -322,7 +429,6 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary>
protected virtual void OnNewClientStartedAndConnected(NetworkManager networkManager)
{
}
/// <summary>
@@ -331,7 +437,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary>
protected IEnumerator CreateAndStartNewClient()
{
var networkManager = NetcodeIntegrationTestHelpers.CreateNewClient(m_ClientNetworkManagers.Length);
var networkManager = NetcodeIntegrationTestHelpers.CreateNewClient(m_ClientNetworkManagers.Length, m_EnableTimeTravel);
networkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab;
// Notification that the new client (NetworkManager) has been created
@@ -356,13 +462,53 @@ namespace Unity.Netcode.TestHelpers.Runtime
if (s_GlobalTimeoutHelper.TimedOut)
{
AddRemoveNetworkManager(networkManager, false);
Object.Destroy(networkManager.gameObject);
Object.DestroyImmediate(networkManager.gameObject);
}
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for the new client to be connected!");
ClientNetworkManagerPostStart(networkManager);
VerboseDebug($"[{networkManager.name}] Created and connected!");
}
/// <summary>
/// This will create, start, and connect a new client while in the middle of an
/// integration test.
/// </summary>
protected void CreateAndStartNewClientWithTimeTravel()
{
var networkManager = NetcodeIntegrationTestHelpers.CreateNewClient(m_ClientNetworkManagers.Length, m_EnableTimeTravel);
networkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab;
// Notification that the new client (NetworkManager) has been created
// in the event any modifications need to be made before starting the client
OnNewClientCreated(networkManager);
NetcodeIntegrationTestHelpers.StartOneClient(networkManager);
if (LogAllMessages)
{
networkManager.MessagingSystem.Hook(new DebugNetworkHooks());
}
AddRemoveNetworkManager(networkManager, true);
OnNewClientStarted(networkManager);
// Wait for the new client to connect
var connected = WaitForClientsConnectedOrTimeOutWithTimeTravel();
OnNewClientStartedAndConnected(networkManager);
if (!connected)
{
AddRemoveNetworkManager(networkManager, false);
Object.DestroyImmediate(networkManager.gameObject);
}
Assert.IsTrue(connected, $"{nameof(CreateAndStartNewClient)} timed out waiting for the new client to be connected!");
ClientNetworkManagerPostStart(networkManager);
VerboseDebug($"[{networkManager.name}] Created and connected!");
}
/// <summary>
/// This will stop a client while in the middle of an integration test
/// </summary>
@@ -373,6 +519,16 @@ namespace Unity.Netcode.TestHelpers.Runtime
yield return WaitForConditionOrTimeOut(() => !networkManager.IsConnectedClient);
}
/// <summary>
/// This will stop a client while in the middle of an integration test
/// </summary>
protected void StopOneClientWithTimeTravel(NetworkManager networkManager, bool destroy = false)
{
NetcodeIntegrationTestHelpers.StopOneClient(networkManager, destroy);
AddRemoveNetworkManager(networkManager, false);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(() => !networkManager.IsConnectedClient));
}
/// <summary>
/// Creates the server and clients
/// </summary>
@@ -383,8 +539,13 @@ namespace Unity.Netcode.TestHelpers.Runtime
CreatePlayerPrefab();
if (m_EnableTimeTravel)
{
m_TargetFrameRate = -1;
}
// Create multiple NetworkManager instances
if (!NetcodeIntegrationTestHelpers.Create(numberOfClients, out NetworkManager server, out NetworkManager[] clients, m_TargetFrameRate, m_CreateServerFirst))
if (!NetcodeIntegrationTestHelpers.Create(numberOfClients, out NetworkManager server, out NetworkManager[] clients, m_TargetFrameRate, m_CreateServerFirst, m_EnableTimeTravel))
{
Debug.LogError("Failed to create instances");
Assert.Fail("Failed to create instances");
@@ -431,6 +592,14 @@ namespace Unity.Netcode.TestHelpers.Runtime
yield return null;
}
/// <summary>
/// Invoked after the server and clients have started.
/// Note: No connection verification has been done at this point
/// </summary>
protected virtual void OnTimeTravelStartedServerAndClients()
{
}
/// <summary>
/// Invoked after the server and clients have started and verified
/// their connections with each other.
@@ -440,6 +609,14 @@ namespace Unity.Netcode.TestHelpers.Runtime
yield return null;
}
/// <summary>
/// Invoked after the server and clients have started and verified
/// their connections with each other.
/// </summary>
protected virtual void OnTimeTravelServerAndClientsConnected()
{
}
private void ClientNetworkManagerPostStart(NetworkManager networkManager)
{
networkManager.name = $"NetworkManager - Client - {networkManager.LocalClientId}";
@@ -466,6 +643,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
m_PlayerNetworkObjects.Add(playerNetworkObject.NetworkManager.LocalClientId, new Dictionary<ulong, NetworkObject>());
}
if (!m_PlayerNetworkObjects[playerNetworkObject.NetworkManager.LocalClientId].ContainsKey(networkManager.LocalClientId))
{
m_PlayerNetworkObjects[playerNetworkObject.NetworkManager.LocalClientId].Add(networkManager.LocalClientId, playerNetworkObject);
@@ -495,6 +673,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
ClientNetworkManagerPostStart(networkManager);
}
if (m_UseHost)
{
#if UNITY_2023_1_OR_NEWER
@@ -509,6 +688,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
m_PlayerNetworkObjects.Add(playerNetworkObject.NetworkManager.LocalClientId, new Dictionary<ulong, NetworkObject>());
}
if (!m_PlayerNetworkObjects[playerNetworkObject.NetworkManager.LocalClientId].ContainsKey(m_ServerNetworkManager.LocalClientId))
{
m_PlayerNetworkObjects[playerNetworkObject.NetworkManager.LocalClientId].Add(m_ServerNetworkManager.LocalClientId, playerNetworkObject);
@@ -570,6 +750,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
m_PlayerNetworkObjects.Add(playerNetworkObject.NetworkManager.LocalClientId, new Dictionary<ulong, NetworkObject>());
}
m_PlayerNetworkObjects[playerNetworkObject.NetworkManager.LocalClientId].Add(m_ServerNetworkManager.LocalClientId, playerNetworkObject);
}
}
@@ -585,6 +766,73 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
}
/// <summary>
/// This starts the server and clients as long as <see cref="CanStartServerAndClients"/>
/// returns true.
/// </summary>
protected void StartServerAndClientsWithTimeTravel()
{
if (CanStartServerAndClients())
{
VerboseDebug($"Entering {nameof(StartServerAndClientsWithTimeTravel)}");
// Start the instances and pass in our SceneManagerInitialization action that is invoked immediately after host-server
// is started and after each client is started.
if (!NetcodeIntegrationTestHelpers.Start(m_UseHost, m_ServerNetworkManager, m_ClientNetworkManagers))
{
Debug.LogError("Failed to start instances");
Assert.Fail("Failed to start instances");
}
if (LogAllMessages)
{
EnableMessageLogging();
}
RegisterSceneManagerHandler();
// Notification that the server and clients have been started
OnTimeTravelStartedServerAndClients();
// When true, we skip everything else (most likely a connection oriented test)
if (!m_BypassConnectionTimeout)
{
// Wait for all clients to connect
WaitForClientsConnectedOrTimeOutWithTimeTravel();
AssertOnTimeout($"{nameof(StartServerAndClients)} timed out waiting for all clients to be connected!");
if (m_UseHost || m_ServerNetworkManager.IsHost)
{
#if UNITY_2023_1_OR_NEWER
// Add the server player instance to all m_ClientSidePlayerNetworkObjects entries
var serverPlayerClones = Object.FindObjectsByType<NetworkObject>(FindObjectsSortMode.None).Where((c) => c.IsPlayerObject && c.OwnerClientId == m_ServerNetworkManager.LocalClientId);
#else
// Add the server player instance to all m_ClientSidePlayerNetworkObjects entries
var serverPlayerClones = Object.FindObjectsOfType<NetworkObject>().Where((c) => c.IsPlayerObject && c.OwnerClientId == m_ServerNetworkManager.LocalClientId);
#endif
foreach (var playerNetworkObject in serverPlayerClones)
{
if (!m_PlayerNetworkObjects.ContainsKey(playerNetworkObject.NetworkManager.LocalClientId))
{
m_PlayerNetworkObjects.Add(playerNetworkObject.NetworkManager.LocalClientId, new Dictionary<ulong, NetworkObject>());
}
m_PlayerNetworkObjects[playerNetworkObject.NetworkManager.LocalClientId].Add(m_ServerNetworkManager.LocalClientId, playerNetworkObject);
}
}
ClientNetworkManagerPostStartInit();
// Notification that at this time the server and client(s) are instantiated,
// started, and connected on both sides.
OnTimeTravelServerAndClientsConnected();
VerboseDebug($"Exiting {nameof(StartServerAndClients)}");
}
}
}
/// <summary>
/// Override this method to control when clients
/// can fake-load a scene.
@@ -660,12 +908,15 @@ namespace Unity.Netcode.TestHelpers.Runtime
m_PlayerNetworkObjects.Clear();
s_GlobalNetworkObjects.Clear();
}
catch (Exception e) { throw e; }
catch (Exception e)
{
throw e;
}
finally
{
if (m_PlayerPrefab != null)
{
Object.Destroy(m_PlayerPrefab);
Object.DestroyImmediate(m_PlayerPrefab);
m_PlayerPrefab = null;
}
}
@@ -689,17 +940,34 @@ namespace Unity.Netcode.TestHelpers.Runtime
yield return null;
}
protected virtual void OnInlineTearDown()
{
}
[UnityTearDown]
public IEnumerator TearDown()
{
IntegrationTestSceneHandler.SceneNameToSceneHandles.Clear();
VerboseDebug($"Entering {nameof(TearDown)}");
yield return OnTearDown();
if (m_TearDownIsACoroutine)
{
yield return OnTearDown();
}
else
{
OnInlineTearDown();
}
if (m_NetworkManagerInstatiationMode == NetworkManagerInstatiationMode.PerTest)
{
ShutdownAndCleanUp();
}
if (m_EnableTimeTravel)
{
ComponentFactory.Deregister<IRealTimeProvider>();
}
VerboseDebug($"Exiting {nameof(TearDown)}");
LogWaitForMessages();
NetcodeLogAssert.Dispose();
@@ -773,6 +1041,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
continue;
}
if (CanDestroyNetworkObject(networkObject))
{
networkObject.NetworkManagerOwner = m_ServerNetworkManager;
@@ -831,10 +1100,49 @@ namespace Unity.Netcode.TestHelpers.Runtime
// Otherwise wait for 1 tick interval
yield return s_DefaultWaitForTick;
}
// Stop checking for a timeout
timeOutHelper.Stop();
}
/// <summary>
/// Waits for the function condition to return true or it will time out. Uses time travel to simulate this
/// for the given number of frames, simulating delta times at the application frame rate.
/// </summary>
public bool WaitForConditionOrTimeOutWithTimeTravel(Func<bool> checkForCondition, int maxTries = 60)
{
if (checkForCondition == null)
{
throw new ArgumentNullException($"checkForCondition cannot be null!");
}
if (!m_EnableTimeTravel)
{
throw new ArgumentException($"Time travel must be enabled to use {nameof(WaitForConditionOrTimeOutWithTimeTravel)}!");
}
var frameRate = Application.targetFrameRate;
if (frameRate <= 0)
{
frameRate = 60;
}
var updateInterval = 1f / frameRate;
for (var i = 0; i < maxTries; ++i)
{
// Simulate a frame passing on all network managers
TimeTravel(updateInterval, 1);
// Update and check to see if the condition has been met
if (checkForCondition.Invoke())
{
return true;
}
}
return false;
}
/// <summary>
/// This version accepts an IConditionalPredicate implementation to provide
/// more flexibility for checking complex conditional cases.
@@ -857,6 +1165,29 @@ namespace Unity.Netcode.TestHelpers.Runtime
conditionalPredicate.Finished(timeOutHelper.TimedOut);
}
/// <summary>
/// This version accepts an IConditionalPredicate implementation to provide
/// more flexibility for checking complex conditional cases. Uses time travel to simulate this
/// for the given number of frames, simulating delta times at the application frame rate.
/// </summary>
public bool WaitForConditionOrTimeOutWithTimeTravel(IConditionalPredicate conditionalPredicate, int maxTries = 60)
{
if (conditionalPredicate == null)
{
throw new ArgumentNullException($"checkForCondition cannot be null!");
}
if (!m_EnableTimeTravel)
{
throw new ArgumentException($"Time travel must be enabled to use {nameof(WaitForConditionOrTimeOutWithTimeTravel)}!");
}
conditionalPredicate.Started();
var success = WaitForConditionOrTimeOutWithTimeTravel(conditionalPredicate.HasConditionBeenReached, maxTries);
conditionalPredicate.Finished(!success);
return success;
}
/// <summary>
/// Validates that all remote clients (i.e. non-server) detect they are connected
/// to the server and that the server reflects the appropriate number of clients
@@ -869,7 +1200,23 @@ namespace Unity.Netcode.TestHelpers.Runtime
var serverClientCount = m_ServerNetworkManager.IsHost ? remoteClientCount + 1 : remoteClientCount;
yield return WaitForConditionOrTimeOut(() => clientsToCheck.Where((c) => c.IsConnectedClient).Count() == remoteClientCount &&
m_ServerNetworkManager.ConnectedClients.Count == serverClientCount);
m_ServerNetworkManager.ConnectedClients.Count == serverClientCount);
}
/// <summary>
/// Validates that all remote clients (i.e. non-server) detect they are connected
/// to the server and that the server reflects the appropriate number of clients
/// have connected or it will time out. Uses time travel to simulate this
/// for the given number of frames, simulating delta times at the application frame rate.
/// </summary>
/// <param name="clientsToCheck">An array of clients to be checked</param>
protected bool WaitForClientsConnectedOrTimeOutWithTimeTravel(NetworkManager[] clientsToCheck)
{
var remoteClientCount = clientsToCheck.Length;
var serverClientCount = m_ServerNetworkManager.IsHost ? remoteClientCount + 1 : remoteClientCount;
return WaitForConditionOrTimeOutWithTimeTravel(() => clientsToCheck.Where((c) => c.IsConnectedClient).Count() == remoteClientCount &&
m_ServerNetworkManager.ConnectedClients.Count == serverClientCount);
}
/// <summary>
@@ -881,6 +1228,16 @@ namespace Unity.Netcode.TestHelpers.Runtime
yield return WaitForClientsConnectedOrTimeOut(m_ClientNetworkManagers);
}
/// <summary>
/// Overloaded method that just passes in all clients to
/// <see cref="WaitForClientsConnectedOrTimeOut(NetworkManager[])"/> Uses time travel to simulate this
/// for the given number of frames, simulating delta times at the application frame rate.
/// </summary>
protected bool WaitForClientsConnectedOrTimeOutWithTimeTravel()
{
return WaitForClientsConnectedOrTimeOutWithTimeTravel(m_ClientNetworkManagers);
}
internal IEnumerator WaitForMessageReceived<T>(List<NetworkManager> wiatForReceivedBy, ReceiptType type = ReceiptType.Handled) where T : INetworkMessage
{
// Build our message hook entries tables so we can determine if all clients received spawn or ownership messages
@@ -891,17 +1248,18 @@ namespace Unity.Netcode.TestHelpers.Runtime
messageHook.AssignMessageType<T>();
messageHookEntriesForSpawn.Add(messageHook);
}
// Used to determine if all clients received the CreateObjectMessage
var hooks = new MessageHooksConditional(messageHookEntriesForSpawn);
yield return WaitForConditionOrTimeOut(hooks);
Assert.False(s_GlobalTimeoutHelper.TimedOut);
}
internal IEnumerator WaitForMessagesReceived(List<Type> messagesInOrder, List<NetworkManager> wiatForReceivedBy, ReceiptType type = ReceiptType.Handled)
internal IEnumerator WaitForMessagesReceived(List<Type> messagesInOrder, List<NetworkManager> waitForReceivedBy, ReceiptType type = ReceiptType.Handled)
{
// Build our message hook entries tables so we can determine if all clients received spawn or ownership messages
var messageHookEntriesForSpawn = new List<MessageHookEntry>();
foreach (var clientNetworkManager in wiatForReceivedBy)
foreach (var clientNetworkManager in waitForReceivedBy)
{
foreach (var message in messagesInOrder)
{
@@ -910,12 +1268,49 @@ namespace Unity.Netcode.TestHelpers.Runtime
messageHookEntriesForSpawn.Add(messageHook);
}
}
// Used to determine if all clients received the CreateObjectMessage
var hooks = new MessageHooksConditional(messageHookEntriesForSpawn);
yield return WaitForConditionOrTimeOut(hooks);
Assert.False(s_GlobalTimeoutHelper.TimedOut);
}
internal void WaitForMessageReceivedWithTimeTravel<T>(List<NetworkManager> waitForReceivedBy, ReceiptType type = ReceiptType.Handled) where T : INetworkMessage
{
// Build our message hook entries tables so we can determine if all clients received spawn or ownership messages
var messageHookEntriesForSpawn = new List<MessageHookEntry>();
foreach (var clientNetworkManager in waitForReceivedBy)
{
var messageHook = new MessageHookEntry(clientNetworkManager, type);
messageHook.AssignMessageType<T>();
messageHookEntriesForSpawn.Add(messageHook);
}
// Used to determine if all clients received the CreateObjectMessage
var hooks = new MessageHooksConditional(messageHookEntriesForSpawn);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks));
}
internal void WaitForMessagesReceivedWithTimeTravel(List<Type> messagesInOrder, List<NetworkManager> waitForReceivedBy, ReceiptType type = ReceiptType.Handled)
{
// Build our message hook entries tables so we can determine if all clients received spawn or ownership messages
var messageHookEntriesForSpawn = new List<MessageHookEntry>();
foreach (var clientNetworkManager in waitForReceivedBy)
{
foreach (var message in messagesInOrder)
{
var messageHook = new MessageHookEntry(clientNetworkManager, type);
messageHook.AssignMessageType(message);
messageHookEntriesForSpawn.Add(messageHook);
}
}
// Used to determine if all clients received the CreateObjectMessage
var hooks = new MessageHooksConditional(messageHookEntriesForSpawn);
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks));
}
/// <summary>
/// Creates a basic NetworkObject test prefab, assigns it to a new
/// NetworkPrefab entry, and then adds it to the server and client(s)
@@ -926,7 +1321,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
protected GameObject CreateNetworkObjectPrefab(string baseName)
{
var prefabCreateAssertError = $"You can only invoke this method during {nameof(OnServerAndClientsCreated)} " +
$"but before {nameof(OnStartedServerAndClients)}!";
$"but before {nameof(OnStartedServerAndClients)}!";
Assert.IsNotNull(m_ServerNetworkManager, prefabCreateAssertError);
Assert.IsFalse(m_ServerNetworkManager.IsListening, prefabCreateAssertError);
@@ -1000,6 +1395,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
gameObjectsSpawned.Add(SpawnObject(prefabNetworkObject, owner, destroyWithScene));
}
return gameObjectsSpawned;
}
@@ -1008,7 +1404,6 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary>
public NetcodeIntegrationTest()
{
}
/// <summary>
@@ -1038,7 +1433,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary>
protected void AssertOnTimeout(string timeOutErrorMessage, TimeoutHelper assignedTimeoutHelper = null)
{
var timeoutHelper = assignedTimeoutHelper != null ? assignedTimeoutHelper : s_GlobalTimeoutHelper;
var timeoutHelper = assignedTimeoutHelper ?? s_GlobalTimeoutHelper;
Assert.False(timeoutHelper.TimedOut, timeOutErrorMessage);
}
@@ -1054,6 +1449,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
continue;
}
VerboseDebug($"Unloading scene {scene.name}-{scene.handle}");
var asyncOperation = SceneManager.UnloadSceneAsync(scene);
}
@@ -1093,6 +1489,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
}
}
m_WaitForLog.Append($"[NetworkManager-{networkManager.LocalClientId}][WaitForTicks-End] Waited for ({networkManager.NetworkTickSystem.LocalTime.Tick - tickStart}) network ticks and ({frameCount}) frames to pass.\n");
yield break;
}
@@ -1114,5 +1511,83 @@ namespace Unity.Netcode.TestHelpers.Runtime
m_WaitForLog.Append($"[NetworkManager-{networkManager.LocalClientId}][WaitForTicks] TickRate ({networkManager.NetworkConfig.TickRate}) | Tick Wait ({count}) | TargetFrameRate ({Application.targetFrameRate}) | Target Frames ({framesPerTick * count})\n");
yield return WaitForTickAndFrames(networkManager, count, totalFrameCount);
}
/// <summary>
/// Simulate a number of frames passing over a specific amount of time.
/// The delta time simulated for each frame will be evenly divided as time/numFrames
/// This will only simulate the netcode update loop, as well as update events on
/// NetworkBehaviour instances, and will not simulate any Unity update processes (physics, etc)
/// </summary>
/// <param name="amountOfTimeInSeconds"></param>
/// <param name="numFramesToSimulate"></param>
protected static void TimeTravel(double amountOfTimeInSeconds, int numFramesToSimulate)
{
var interval = amountOfTimeInSeconds / numFramesToSimulate;
for (var i = 0; i < numFramesToSimulate; ++i)
{
MockTimeProvider.TimeTravel(interval);
SimulateOneFrame();
}
}
/// <summary>
/// Helper function to time travel exactly one tick's worth of time at the current frame and tick rates.
/// </summary>
public static void TimeTravelToNextTick()
{
var timePassed = 1.0f / k_DefaultTickRate;
var frameRate = Application.targetFrameRate;
if (frameRate <= 0)
{
frameRate = 60;
}
var frames = Math.Max((int)(timePassed / frameRate), 1);
TimeTravel(timePassed, frames);
}
/// <summary>
/// Simulates one SDK frame. This can be used even without TimeTravel, though it's of somewhat less use
/// without TimeTravel, as, without the mock transport, it will likely not provide enough time for any
/// sent messages to be received even if called dozens of times.
/// </summary>
public static void SimulateOneFrame()
{
foreach (NetworkUpdateStage stage in Enum.GetValues(typeof(NetworkUpdateStage)))
{
NetworkUpdateLoop.RunNetworkUpdateStage(stage);
string methodName = string.Empty;
switch (stage)
{
case NetworkUpdateStage.FixedUpdate:
methodName = "FixedUpdate"; // mapping NetworkUpdateStage.FixedUpdate to MonoBehaviour.FixedUpdate
break;
case NetworkUpdateStage.Update:
methodName = "Update"; // mapping NetworkUpdateStage.Update to MonoBehaviour.Update
break;
case NetworkUpdateStage.PreLateUpdate:
methodName = "LateUpdate"; // mapping NetworkUpdateStage.PreLateUpdate to MonoBehaviour.LateUpdate
break;
}
if (!string.IsNullOrEmpty(methodName))
{
#if UNITY_2023_1_OR_NEWER
foreach (var behaviour in Object.FindObjectsByType<NetworkBehaviour>(FindObjectsSortMode.InstanceID))
#else
foreach (var behaviour in Object.FindObjectsOfType<NetworkBehaviour>())
#endif
{
var method = behaviour.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (method == null)
{
method = behaviour.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance);
}
method?.Invoke(behaviour, new object[] { });
}
}
}
}
}
}