6 Commits

Author SHA1 Message Date
fe746bf2a3 2.2.0 2025-01-10 15:22:38 +01:00
Unity Technologies
8fe07bbad2 com.unity.netcode.gameobjects@2.2.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).

## [2.2.0] - 2024-12-12

### Added

- Added `NetworkObject.OwnershipStatus.SessionOwner` to allow Network Objects to be distributable and only owned by the Session Owner. This flag will override all other `OwnershipStatus` flags. (#3175)
- Added `UnityTransport.GetEndpoint` method to provide a way to obtain `NetworkEndpoint` information of a connection via client identifier. (#3130)
- Added `NetworkTransport.OnEarlyUpdate` and `NetworkTransport.OnPostLateUpdate` methods to provide more control over handling transport related events at the start and end of each frame. (#3113)

### Fixed

- Fixed issue where the server, host, or session owner would not populate the in-scene place `NetworkObject` table if the scene was loaded prior to starting the `NetworkManager`. (#3177)
- Fixed issue where the `NetworkObjectIdHash` value could be incorrect when entering play mode while still in prefab edit mode with pending changes and using MPPM. (#3162)
- Fixed issue where a sever only `NetworkManager` instance would spawn the actual `NetworkPrefab`'s `GameObject` as opposed to creating an instance of it. (#3160)
- Fixed issue where only the session owner (as opposed to all clients) would handle spawning prefab overrides properly when using a distributed authority network topology. (#3160)
- Fixed issue where an exception was thrown when calling `NetworkManager.Shutdown` after calling `UnityTransport.Shutdown`. (#3118)
- Fixed issue where `NetworkList` properties on in-scene placed `NetworkObject`s could cause small memory leaks when entering playmode. (#3147)
- Fixed in-scene `NertworkObject` synchronization issue when loading a scene with currently connected clients connected to a session created by a `NetworkManager` started as a server (i.e. not as a host). (#3133)
- Fixed issue where a `NetworkManager` started as a server would not add itself as an observer to in-scene placed `NetworkObject`s instantiated and spawned by a scene loading event. (#3133)
- Fixed issue where spawning a player using `NetworkObject.InstantiateAndSpawn` or `NetworkSpawnManager.InstantiateAndSpawn` would not update the `NetworkSpawnManager.PlayerObjects` or assign the newly spawned player to the `NetworkClient.PlayerObject`. (#3122)
- Fixed issue where queued UnitTransport (NetworkTransport) message batches were being sent on the next frame. They are now sent at the end of the frame during `PostLateUpdate`.  (#3113)
- Fixed issue where `NotOwnerRpcTarget` or `OwnerRpcTarget` were not using their replacements `NotAuthorityRpcTarget` and `AuthorityRpcTarget` which would invoke a warning. (#3111)
- Fixed issue where client is removed as an observer from spawned objects when their player instance is despawned. (#3110)
- Fixed issue where `NetworkAnimator` would statically allocate write buffer space for `Animator` parameters that could cause a write error if the number of parameters exceeded the space allocated. (#3108)

### Changed

- In-scene placed `NetworkObject`s have been made distributable when balancing object distribution after a connection event. (#3175)
- Optimised `NetworkVariable` and `NetworkTransform` related packets when in Distributed Authority mode.
- The Debug Simulator section of the Unity Transport component was removed. This section was not functional anymore and users are now recommended to use the more featureful [Network Simulator](https://docs-multiplayer.unity3d.com/tools/current/tools-network-simulator/) tool from the Multiplayer Tools package instead. (#3121)
2024-12-12 00:00:00 +00:00
2e3ccb45b7 Make ServerRpc and ClientRpc obsolete. 2024-12-06 18:26:41 +01:00
76d8157fc7 Add connection event documentation. 2024-11-04 06:53:06 +01:00
11e10acc00 Do not write old positions back prevent flickering from old to new positions. 2024-10-22 19:45:43 +02:00
887ec37b67 Remove 2D physics support. 2024-10-22 05:05:54 +02:00
372 changed files with 1223 additions and 53747 deletions

1
.signature Normal file
View File

@@ -0,0 +1 @@
{"timestamp":1734331212,"signature":"mMrBXdBegYd6TPqNVci9OkWh1H10YU8Ug8KlSpiyNzbXlS5z7O7Rdif3gvTdXK0O07HWmIuszcUoljQIaxkGAYq2g9A85IcvhbWsAAqxjSEZfQPsxFZlJQ9PqU4tfMItk7K1VP1YfcBxitxPHcUeO2IwBYVLx51gg6X/0qHWtkifmZ/cBbGTBNEYE+m7KfRYUyu23kOPMGOCBeULivZO9y/2A0qXkMeBiPo3KQFU6481n4GV6fahyLrG2llfM8xtW8YeouPyt/IMD86at8eeY+E5mW0iXGms9IMLf/DH6vjJnuSEfgMXfjcGnRO0m+RP+ig8HzjbPVty7oAOgfm6Oc1frOP4Cmudk97fIEzC10B0lj2uzFudT5UVPk4Hr6Mf/2ka0m+XTdRNHVRyOYBcHsJQYf0HKW/4jJPwWrSCSk2uE0fPn1sTvMb+i4pXCn7J700b7NMLPFJaWeb6kA2e3v8w5FybshFZWCU6fyLWGn1AR60u0BxL88Hx4VO5UjnJ","publicKey":"LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQm9qQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FZOEFNSUlCaWdLQ0FZRUFzdUhXYUhsZ0I1cVF4ZEJjTlJKSAordHR4SmoxcVY1NTdvMlZaRE1XaXhYRVBkRTBEMVFkT1JIRXNSS1RscmplUXlERU83ZlNQS0ZwZ1A3MU5TTnJCCkFHM2NFSU45aHNQVDhOVmllZmdWem5QTkVMenFkVmdEbFhpb2VpUnV6OERKWFgvblpmU1JWKytwbk9ySTRibG4KS0twelJlNW14OTc1SjhxZ1FvRktKT0NNRlpHdkJMR2MxSzZZaEIzOHJFODZCZzgzbUovWjBEYkVmQjBxZm13cgo2ZDVFUXFsd0E5Y3JZT1YyV1VpWXprSnBLNmJZNzRZNmM1TmpBcEFKeGNiaTFOaDlRVEhUcU44N0ZtMDF0R1ZwCjVNd1pXSWZuYVRUemEvTGZLelR5U0pka0tldEZMVGdkYXpMYlpzUEE2aHBSK0FJRTJhc0tLTi84UUk1N3UzU2cKL2xyMnZKS1IvU2l5eEN1Q20vQWJkYnJMbXk0WjlSdm1jMGdpclA4T0lLQWxBRWZ2TzV5Z2hSKy8vd1RpTFlzUQp1SllDM0V2UE16ZGdKUzdGR2FscnFLZzlPTCsxVzROY05yNWdveVdSUUJ0cktKaWlTZEJVWmVxb0RvSUY5NHpCCndGbzJJT1JFdXFqcU51M3diMWZIM3p1dGdtalFra3IxVjJhd3hmcExLWlROQWdNQkFBRT0KLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg"}

View File

@@ -6,6 +6,37 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
## [2.2.0] - 2024-12-12
### Added
- Added `NetworkObject.OwnershipStatus.SessionOwner` to allow Network Objects to be distributable and only owned by the Session Owner. This flag will override all other `OwnershipStatus` flags. (#3175)
- Added `UnityTransport.GetEndpoint` method to provide a way to obtain `NetworkEndpoint` information of a connection via client identifier. (#3130)
- Added `NetworkTransport.OnEarlyUpdate` and `NetworkTransport.OnPostLateUpdate` methods to provide more control over handling transport related events at the start and end of each frame. (#3113)
### Fixed
- Fixed issue where the server, host, or session owner would not populate the in-scene place `NetworkObject` table if the scene was loaded prior to starting the `NetworkManager`. (#3177)
- Fixed issue where the `NetworkObjectIdHash` value could be incorrect when entering play mode while still in prefab edit mode with pending changes and using MPPM. (#3162)
- Fixed issue where a sever only `NetworkManager` instance would spawn the actual `NetworkPrefab`'s `GameObject` as opposed to creating an instance of it. (#3160)
- Fixed issue where only the session owner (as opposed to all clients) would handle spawning prefab overrides properly when using a distributed authority network topology. (#3160)
- Fixed issue where an exception was thrown when calling `NetworkManager.Shutdown` after calling `UnityTransport.Shutdown`. (#3118)
- Fixed issue where `NetworkList` properties on in-scene placed `NetworkObject`s could cause small memory leaks when entering playmode. (#3147)
- Fixed in-scene `NertworkObject` synchronization issue when loading a scene with currently connected clients connected to a session created by a `NetworkManager` started as a server (i.e. not as a host). (#3133)
- Fixed issue where a `NetworkManager` started as a server would not add itself as an observer to in-scene placed `NetworkObject`s instantiated and spawned by a scene loading event. (#3133)
- Fixed issue where spawning a player using `NetworkObject.InstantiateAndSpawn` or `NetworkSpawnManager.InstantiateAndSpawn` would not update the `NetworkSpawnManager.PlayerObjects` or assign the newly spawned player to the `NetworkClient.PlayerObject`. (#3122)
- Fixed issue where queued UnitTransport (NetworkTransport) message batches were being sent on the next frame. They are now sent at the end of the frame during `PostLateUpdate`. (#3113)
- Fixed issue where `NotOwnerRpcTarget` or `OwnerRpcTarget` were not using their replacements `NotAuthorityRpcTarget` and `AuthorityRpcTarget` which would invoke a warning. (#3111)
- Fixed issue where client is removed as an observer from spawned objects when their player instance is despawned. (#3110)
- Fixed issue where `NetworkAnimator` would statically allocate write buffer space for `Animator` parameters that could cause a write error if the number of parameters exceeded the space allocated. (#3108)
### Changed
- In-scene placed `NetworkObject`s have been made distributable when balancing object distribution after a connection event. (#3175)
- Optimised `NetworkVariable` and `NetworkTransform` related packets when in Distributed Authority mode.
- The Debug Simulator section of the Unity Transport component was removed. This section was not functional anymore and users are now recommended to use the more featureful [Network Simulator](https://docs-multiplayer.unity3d.com/tools/current/tools-network-simulator/) tool from the Multiplayer Tools package instead. (#3121)
## [2.1.1] - 2024-10-18
### Added
@@ -187,8 +218,8 @@ Additional documentation and release notes are available at [Multiplayer Documen
## [2.0.0-exp.2] - 2024-04-02
### Added
- Added updates to all internal messages to account for a distributed authority network session connection. (#2863)
- Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863)
- Added updates to all internal messages to account for a distributed authority network session connection. (#2863)
- Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863)
- For a customized `NetworkRigidbodyBase` class:
- `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes.
- `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned.
@@ -324,6 +355,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
- Fixed issue where you could not have multiple source network prefab overrides targeting the same network prefab as their override. (#2710)
### Changed
- Changed the server or host shutdown so it will now perform a "soft shutdown" when `NetworkManager.Shutdown` is invoked. This will send a disconnect notification to all connected clients and the server-host will wait for all connected clients to disconnect or timeout after a 5 second period before completing the shutdown process. (#2789)
- Changed `OnClientDisconnectedCallback` will now return the assigned client identifier on the local client side if the client was approved and assigned one prior to being disconnected. (#2789)
- Changed `NetworkTransform.SetState` (and related methods) now are cumulative during a fractional tick period and sent on the next pending tick. (#2777)
@@ -336,6 +368,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
- Changed in-scene placed `NetworkObject`s now set their `IsSceneObject` value when generating their `GlobalObjectIdHash` value. (#2710)
- Changed the default `NetworkConfig.SpawnTimeout` value from 1.0s to 10.0s. (#2710)
## [1.7.1] - 2023-11-15
### Added
@@ -385,7 +418,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
### Added
- Added a protected virtual method `NetworkTransform.OnInitialize(ref NetworkTransformState replicatedState)` that just returns the replicated state reference.
### Fixed
- Fixed issue where invoking `NetworkManager.Shutdown` within `NetworkManager.OnClientStopped` or `NetworkManager.OnServerStopped` would force `NetworkManager.ShutdownInProgress` to remain true after completing the shutdown process. (#2661)
@@ -443,7 +476,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
- 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
### 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)

View File

@@ -237,7 +237,7 @@ namespace Unity.Netcode.Editor
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority)
{
EditorGUILayout.PropertyField(m_AutoSpawnPlayerPrefabClientSide, new GUIContent("Auto Spawn Player Prefab"));
}
}
#endif
EditorGUILayout.PropertyField(m_PlayerPrefabProperty, new GUIContent("Default Player Prefab"));

View File

@@ -88,6 +88,14 @@ namespace Unity.Netcode.Editor
while (observerClientIds.MoveNext())
{
if (!m_NetworkObject.NetworkManager.ConnectedClients.ContainsKey(observerClientIds.Current))
{
if ((observerClientIds.Current == 0 && m_NetworkObject.NetworkManager.IsHost) || observerClientIds.Current > 0)
{
Debug.LogWarning($"Client-{observerClientIds.Current} is listed as an observer but is not connected!");
}
continue;
}
if (m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject != null)
{
EditorGUILayout.ObjectField($"ClientId: {observerClientIds.Current}", m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject, typeof(GameObject), false);
@@ -107,6 +115,10 @@ namespace Unity.Netcode.Editor
EditorGUI.BeginChangeCheck();
serializedObject.UpdateIfRequiredOrScript();
DrawPropertiesExcluding(serializedObject, k_HiddenFields);
if (m_NetworkObject.IsOwnershipSessionOwner)
{
m_NetworkObject.Ownership = NetworkObject.OwnershipStatus.SessionOwner;
}
serializedObject.ApplyModifiedProperties();
EditorGUI.EndChangeCheck();
@@ -185,9 +197,9 @@ namespace Unity.Netcode.Editor
// The below can cause visual anomalies and/or throws an exception within the EditorGUI itself (index out of bounds of the array). and has
// The visual anomaly is when you select one field it is set in the drop down but then the flags selection in the popup menu selects more items
// even though if you exit the popup menu the flag setting is correct.
//var ownership = (NetworkObject.OwnershipStatus)EditorGUI.EnumFlagsField(position, label, (NetworkObject.OwnershipStatus)property.enumValueFlag);
//property.enumValueFlag = (int)ownership;
// even though if you exit the popup menu the flag setting is correct.
// var ownership = (NetworkObject.OwnershipStatus)EditorGUI.EnumFlagsField(position, label, (NetworkObject.OwnershipStatus)property.enumValueFlag);
// property.enumValueFlag = (int)ownership;
EditorGUI.EndDisabledGroup();
EditorGUI.EndProperty();
}

View File

@@ -34,16 +34,6 @@
"expression": "",
"define": "COM_UNITY_MODULES_ANIMATION"
},
{
"name": "com.unity.modules.physics",
"expression": "",
"define": "COM_UNITY_MODULES_PHYSICS"
},
{
"name": "com.unity.modules.physics2d",
"expression": "",
"define": "COM_UNITY_MODULES_PHYSICS2D"
},
{
"name": "com.unity.services.relay",
"expression": "1.0",

View File

@@ -1,7 +1,5 @@
Unity Companion License (UCL License)
com.unity.netcode.gameobjects copyright © 2021-2024 Unity Technologies
com.unity.netcode.gameobjects copyright © 2024 Unity Technologies
Licensed under the Unity Companion License for Unity-dependent projects (see https://unity3d.com/legal/licenses/unity_companion_license).
Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the license for details on these and other terms and conditions.

View File

@@ -1,558 +0,0 @@
using Unity.Mathematics;
using UnityEngine;
namespace Unity.Netcode.Components
{
#pragma warning disable IDE0001
/// <summary>
/// A subclass of <see cref="NetworkTransform"/> that supports basic client anticipation - the client
/// can set a value on the belief that the server will update it to reflect the same value in a future update
/// (i.e., as the result of an RPC call). This value can then be adjusted as new updates from the server come in,
/// in three basic modes:
///
/// <list type="bullet">
///
/// <item><b>Snap:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="StaleDataHandling.Ignore"/> and no <see cref="NetworkBehaviour.OnReanticipate"/> callback),
/// the moment a more up-to-date value is received from the authority, it will simply replace the anticipated value,
/// resulting in a "snap" to the new value if it is different from the anticipated value.</item>
///
/// <item><b>Smooth:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> callback that calls
/// <see cref="Smooth"/> from the anticipated value to the authority value with an appropriate
/// <see cref="Mathf.Lerp"/>-style smooth function), when a more up-to-date value is received from the authority,
/// it will interpolate over time from an incorrect anticipated value to the correct authoritative value.</item>
///
/// <item><b>Constant Reanticipation:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Reanticipate"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> that calculates a
/// new anticipated value based on the current authoritative value), when a more up-to-date value is received from
/// the authority, user code calculates a new anticipated value, possibly calling <see cref="Smooth"/> to interpolate
/// between the previous anticipation and the new anticipation. This is useful for values that change frequently and
/// need to constantly be re-evaluated, as opposed to values that change only in response to user action and simply
/// need a one-time anticipation when the user performs that action.</item>
///
/// </list>
///
/// Note that these three modes may be combined. For example, if an <see cref="NetworkBehaviour.OnReanticipate"/> callback
/// does not call either <see cref="Smooth"/> or one of the Anticipate methods, the result will be a snap to the
/// authoritative value, enabling for a callback that may conditionally call <see cref="Smooth"/> when the
/// difference between the anticipated and authoritative values is within some threshold, but fall back to
/// snap behavior if the difference is too large.
/// </summary>
#pragma warning restore IDE0001
[DisallowMultipleComponent]
[AddComponentMenu("Netcode/Anticipated Network Transform")]
public class AnticipatedNetworkTransform : NetworkTransform
{
#if UNITY_EDITOR
internal override bool HideInterpolateValue => true;
#endif
public struct TransformState
{
public Vector3 Position;
public Quaternion Rotation;
public Vector3 Scale;
}
private TransformState m_AuthoritativeTransform = new TransformState();
private TransformState m_AnticipatedTransform = new TransformState();
private TransformState m_PreviousAnticipatedTransform = new TransformState();
private ulong m_LastAnticipaionCounter;
private ulong m_LastAuthorityUpdateCounter;
private TransformState m_SmoothFrom;
private TransformState m_SmoothTo;
private float m_SmoothDuration;
private float m_CurrentSmoothTime;
private bool m_OutstandingAuthorityChange = false;
#if UNITY_EDITOR
private void Reset()
{
// Anticipation + smoothing is a form of interpolation, and adding NetworkTransform's buffered interpolation
// makes the anticipation get weird, so we default it to false.
Interpolate = false;
}
#endif
#pragma warning disable IDE0001
/// <summary>
/// Defines what the behavior should be if we receive a value from the server with an earlier associated
/// time value than the anticipation time value.
/// <br/><br/>
/// If this is <see cref="Netcode.StaleDataHandling.Ignore"/>, the stale data will be ignored and the authoritative
/// value will not replace the anticipated value until the anticipation time is reached. <see cref="OnAuthoritativeValueChanged"/>
/// and <see cref="OnReanticipate"/> will also not be invoked for this stale data.
/// <br/><br/>
/// If this is <see cref="Netcode.StaleDataHandling.Reanticipate"/>, the stale data will replace the anticipated data and
/// <see cref="OnAuthoritativeValueChanged"/> and <see cref="OnReanticipate"/> will be invoked.
/// In this case, the authoritativeTime value passed to <see cref="OnReanticipate"/> will be lower than
/// the anticipationTime value, and that callback can be used to calculate a new anticipated value.
/// </summary>
#pragma warning restore IDE0001
public StaleDataHandling StaleDataHandling = StaleDataHandling.Reanticipate;
/// <summary>
/// Contains the current state of this transform on the server side.
/// Note that, on the server side, this gets updated at the end of the frame, and will not immediately reflect
/// changes to the transform.
/// </summary>
public TransformState AuthoritativeState => m_AuthoritativeTransform;
/// <summary>
/// Contains the current anticipated state, which will match the values of this object's
/// actual <see cref="MonoBehaviour.transform"/>. When a server
/// update arrives, this value will be overwritten by the new
/// server value (unless stale data handling is set to "Ignore"
/// and the update is determined to be stale). This value will
/// be duplicated in <see cref="PreviousAnticipatedState"/>, which
/// will NOT be overwritten in server updates.
/// </summary>
public TransformState AnticipatedState => m_AnticipatedTransform;
/// <summary>
/// Indicates whether this transform currently needs
/// reanticipation. If this is true, the anticipated value
/// has been overwritten by the authoritative value from the
/// server; the previous anticipated value is stored in <see cref="PreviousAnticipatedState"/>
/// </summary>
public bool ShouldReanticipate
{
get;
private set;
}
/// <summary>
/// Holds the most recent anticipated state, whatever was
/// most recently set using the Anticipate methods. Unlike
/// <see cref="AnticipatedState"/>, this does not get overwritten
/// when a server update arrives.
/// </summary>
public TransformState PreviousAnticipatedState => m_PreviousAnticipatedTransform;
/// <summary>
/// Anticipate that, at the end of one round trip to the server, this transform will be in the given
/// <see cref="newPosition"/>
/// </summary>
/// <param name="newPosition"></param>
public void AnticipateMove(Vector3 newPosition)
{
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
{
return;
}
transform.position = newPosition;
m_AnticipatedTransform.Position = newPosition;
if (CanCommitToTransform)
{
m_AuthoritativeTransform.Position = newPosition;
}
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
/// <summary>
/// Anticipate that, at the end of one round trip to the server, this transform will have the given
/// <see cref="newRotation"/>
/// </summary>
/// <param name="newRotation"></param>
public void AnticipateRotate(Quaternion newRotation)
{
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
{
return;
}
transform.rotation = newRotation;
m_AnticipatedTransform.Rotation = newRotation;
if (CanCommitToTransform)
{
m_AuthoritativeTransform.Rotation = newRotation;
}
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
/// <summary>
/// Anticipate that, at the end of one round trip to the server, this transform will have the given
/// <see cref="newScale"/>
/// </summary>
/// <param name="newScale"></param>
public void AnticipateScale(Vector3 newScale)
{
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
{
return;
}
transform.localScale = newScale;
m_AnticipatedTransform.Scale = newScale;
if (CanCommitToTransform)
{
m_AuthoritativeTransform.Scale = newScale;
}
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
/// <summary>
/// Anticipate that, at the end of one round trip to the server, the transform will have the given
/// <see cref="newState"/>
/// </summary>
/// <param name="newState"></param>
public void AnticipateState(TransformState newState)
{
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
{
return;
}
var transform_ = transform;
transform_.position = newState.Position;
transform_.rotation = newState.Rotation;
transform_.localScale = newState.Scale;
m_AnticipatedTransform = newState;
if (CanCommitToTransform)
{
m_AuthoritativeTransform = newState;
}
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
private void ProcessSmoothing()
{
// If not spawned or this instance has authority, exit early
if (!IsSpawned)
{
return;
}
if (m_CurrentSmoothTime < m_SmoothDuration)
{
m_CurrentSmoothTime += NetworkManager.RealTimeProvider.DeltaTime;
var transform_ = transform;
var pct = math.min(m_CurrentSmoothTime / m_SmoothDuration, 1f);
m_AnticipatedTransform = new TransformState
{
Position = Vector3.Lerp(m_SmoothFrom.Position, m_SmoothTo.Position, pct),
Rotation = Quaternion.Lerp(m_SmoothFrom.Rotation, m_SmoothTo.Rotation, pct),
Scale = Vector3.Lerp(m_SmoothFrom.Scale, m_SmoothTo.Scale, pct)
};
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
if (!CanCommitToTransform)
{
transform_.position = m_AnticipatedTransform.Position;
transform_.localScale = m_AnticipatedTransform.Scale;
transform_.rotation = m_AnticipatedTransform.Rotation;
}
}
}
// TODO: This does not handle OnFixedUpdate
// This requires a complete overhaul in this class to switch between using
// NetworkRigidbody's position and rotation values.
public override void OnUpdate()
{
ProcessSmoothing();
// Do not call the base class implementation...
// AnticipatedNetworkTransform applies its authoritative state immediately rather than waiting for update
// This is because AnticipatedNetworkTransforms may need to reference each other in reanticipating
// and we will want all reanticipation done before anything else wants to reference the transform in
// OnUpdate()
//base.OnUpdate();
}
/// <summary>
/// Since authority does not subscribe to updates (OnUpdate or OnFixedUpdate),
/// we have to update every frame to assure authority processes soothing.
/// </summary>
private void Update()
{
if (CanCommitToTransform && IsSpawned)
{
ProcessSmoothing();
}
}
internal class AnticipatedObject : IAnticipationEventReceiver, IAnticipatedObject
{
public AnticipatedNetworkTransform Transform;
public void SetupForRender()
{
if (Transform.CanCommitToTransform)
{
var transform_ = Transform.transform;
Transform.m_AuthoritativeTransform = new TransformState
{
Position = transform_.position,
Rotation = transform_.rotation,
Scale = transform_.localScale
};
if (Transform.m_CurrentSmoothTime >= Transform.m_SmoothDuration)
{
// If we've had a call to Smooth() we'll continue interpolating.
// Otherwise we'll go ahead and make the visual and actual locations
// match.
Transform.m_AnticipatedTransform = Transform.m_AuthoritativeTransform;
}
transform_.position = Transform.m_AnticipatedTransform.Position;
transform_.rotation = Transform.m_AnticipatedTransform.Rotation;
transform_.localScale = Transform.m_AnticipatedTransform.Scale;
}
}
public void SetupForUpdate()
{
if (Transform.CanCommitToTransform)
{
var transform_ = Transform.transform;
transform_.position = Transform.m_AuthoritativeTransform.Position;
transform_.rotation = Transform.m_AuthoritativeTransform.Rotation;
transform_.localScale = Transform.m_AuthoritativeTransform.Scale;
}
}
public void Update()
{
// No need to do this, it's handled by NetworkTransform.OnUpdate
}
public void ResetAnticipation()
{
Transform.ShouldReanticipate = false;
}
public NetworkObject OwnerObject => Transform.NetworkObject;
}
private AnticipatedObject m_AnticipatedObject = null;
private void ResetAnticipatedState()
{
var transform_ = transform;
m_AuthoritativeTransform = new TransformState
{
Position = transform_.position,
Rotation = transform_.rotation,
Scale = transform_.localScale
};
m_AnticipatedTransform = m_AuthoritativeTransform;
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
/// <summary>
/// (This replaces the first OnSynchronize for NetworkTransforms)
/// This is needed to initialize when fully synchronized since non-authority instances
/// don't apply the initial synchronization (new client synchronization) until after
/// everything has been spawned and synchronized.
/// </summary>
protected internal override void InternalOnNetworkSessionSynchronized()
{
var wasSynchronizing = SynchronizeState.IsSynchronizing;
base.InternalOnNetworkSessionSynchronized();
if (!CanCommitToTransform && wasSynchronizing && !SynchronizeState.IsSynchronizing)
{
m_OutstandingAuthorityChange = true;
ApplyAuthoritativeState();
ResetAnticipatedState();
m_AnticipatedObject = new AnticipatedObject { Transform = this };
NetworkManager.AnticipationSystem.RegisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
}
}
/// <summary>
/// (This replaces the any subsequent OnSynchronize for NetworkTransforms post client synchronization)
/// This occurs on already connected clients when dynamically spawning a NetworkObject for
/// non-authoritative instances.
/// </summary>
protected internal override void InternalOnNetworkPostSpawn()
{
base.InternalOnNetworkPostSpawn();
if (!CanCommitToTransform && NetworkManager.IsConnectedClient && !SynchronizeState.IsSynchronizing)
{
m_OutstandingAuthorityChange = true;
ApplyAuthoritativeState();
ResetAnticipatedState();
m_AnticipatedObject = new AnticipatedObject { Transform = this };
NetworkManager.AnticipationSystem.RegisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
}
}
public override void OnNetworkSpawn()
{
if (NetworkManager.DistributedAuthorityMode)
{
Debug.LogWarning($"This component is not currently supported in distributed authority.");
}
base.OnNetworkSpawn();
// Non-authoritative instances exit early if the synchronization has yet to
// be applied at this point
if (SynchronizeState.IsSynchronizing && !CanCommitToTransform)
{
return;
}
m_OutstandingAuthorityChange = true;
ApplyAuthoritativeState();
ResetAnticipatedState();
m_AnticipatedObject = new AnticipatedObject { Transform = this };
NetworkManager.AnticipationSystem.RegisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
}
public override void OnNetworkDespawn()
{
if (m_AnticipatedObject != null)
{
NetworkManager.AnticipationSystem.DeregisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject);
NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject);
m_AnticipatedObject = null;
}
ResetAnticipatedState();
base.OnNetworkDespawn();
}
public override void OnDestroy()
{
if (m_AnticipatedObject != null)
{
NetworkManager.AnticipationSystem.DeregisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject);
NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject);
m_AnticipatedObject = null;
}
base.OnDestroy();
}
/// <summary>
/// Interpolate between the transform represented by <see cref="from"/> to the transform represented by
/// <see cref="to"/> over <see cref="durationSeconds"/> of real time. The duration uses
/// <see cref="Time.deltaTime"/>, so it is affected by <see cref="Time.timeScale"/>.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <param name="durationSeconds"></param>
public void Smooth(TransformState from, TransformState to, float durationSeconds)
{
var transform_ = transform;
if (durationSeconds <= 0)
{
m_AnticipatedTransform = to;
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
transform_.position = to.Position;
transform_.rotation = to.Rotation;
transform_.localScale = to.Scale;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
return;
}
m_AnticipatedTransform = from;
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
if (!CanCommitToTransform)
{
transform_.position = from.Position;
transform_.rotation = from.Rotation;
transform_.localScale = from.Scale;
}
m_SmoothFrom = from;
m_SmoothTo = to;
m_SmoothDuration = durationSeconds;
m_CurrentSmoothTime = 0;
}
protected override void OnBeforeUpdateTransformState()
{
// this is called when new data comes from the server
m_LastAuthorityUpdateCounter = NetworkManager.AnticipationSystem.LastAnticipationAck;
m_OutstandingAuthorityChange = true;
}
protected override void OnNetworkTransformStateUpdated(ref NetworkTransformState oldState, ref NetworkTransformState newState)
{
base.OnNetworkTransformStateUpdated(ref oldState, ref newState);
ApplyAuthoritativeState();
}
protected override void OnTransformUpdated()
{
if (CanCommitToTransform || m_AnticipatedObject == null)
{
return;
}
// this is called pretty much every frame and will change the transform
// If we've overridden the transform with an anticipated state, we need to be able to change it back
// to the anticipated state (while updating the authority state accordingly) or else
// mark this transform for reanticipation
var transform_ = transform;
var previousAnticipatedTransform = m_AnticipatedTransform;
// Update authority state to catch any possible interpolation data
m_AuthoritativeTransform.Position = transform_.position;
m_AuthoritativeTransform.Rotation = transform_.rotation;
m_AuthoritativeTransform.Scale = transform_.localScale;
if (!m_OutstandingAuthorityChange)
{
// Keep the anticipated value unchanged, we have no updates from the server at all.
transform_.position = previousAnticipatedTransform.Position;
transform_.localScale = previousAnticipatedTransform.Scale;
transform_.rotation = previousAnticipatedTransform.Rotation;
return;
}
if (StaleDataHandling == StaleDataHandling.Ignore && m_LastAnticipaionCounter > m_LastAuthorityUpdateCounter)
{
// Keep the anticipated value unchanged because it is more recent than the authoritative one.
transform_.position = previousAnticipatedTransform.Position;
transform_.localScale = previousAnticipatedTransform.Scale;
transform_.rotation = previousAnticipatedTransform.Rotation;
return;
}
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
m_OutstandingAuthorityChange = false;
m_AnticipatedTransform = m_AuthoritativeTransform;
ShouldReanticipate = true;
NetworkManager.AnticipationSystem.ObjectsToReanticipate.Add(m_AnticipatedObject);
}
}
}

View File

@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 5abfce83aadd948498d4990c645a017b

View File

@@ -230,6 +230,7 @@ namespace Unity.Netcode.Components
}
}
#if UNITY_EDITOR
private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine)
{
@@ -263,7 +264,6 @@ namespace Unity.Netcode.Components
{
case AnimatorControllerParameterType.Trigger:
{
if (transition.destinationStateMachine != null)
{
var destinationStateMachine = transition.destinationStateMachine;
@@ -297,18 +297,12 @@ namespace Unity.Netcode.Components
}
}
}
#endif
/// <summary>
/// Creates the TransitionStateInfoList table
/// </summary>
private void BuildTransitionStateInfoList()
{
#if UNITY_EDITOR
if (UnityEditor.EditorApplication.isUpdating || UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
{
return;
}
if (m_Animator == null)
{
return;
@@ -326,9 +320,18 @@ namespace Unity.Netcode.Components
var stateMachine = animatorController.layers[x].stateMachine;
ParseStateMachineStates(x, ref animatorController, ref stateMachine);
}
#endif
}
/// <summary>
/// In-Editor Only
/// Virtual OnValidate method for custom derived NetworkAnimator classes.
/// </summary>
protected virtual void OnValidate()
{
BuildTransitionStateInfoList();
}
#endif
public void OnAfterDeserialize()
{
BuildDestinationToTransitionInfoTable();
@@ -336,7 +339,7 @@ namespace Unity.Netcode.Components
public void OnBeforeSerialize()
{
BuildTransitionStateInfoList();
// Do nothing when serializing (handled during OnValidate)
}
internal struct AnimationState : INetworkSerializable
@@ -419,8 +422,8 @@ namespace Unity.Netcode.Components
internal bool HasBeenProcessed;
// This is preallocated/populated in OnNetworkSpawn for all instances in the event ownership or
// authority changes. When serializing, IsDirtyCount determines how many AnimationState entries
// should be serialized from the list. When deserializing the list is created and populated with
// authority changes. When serializing, IsDirtyCount determines how many AnimationState entries
// should be serialized from the list. When deserializing the list is created and populated with
// only the number of AnimationStates received which is dictated by the deserialized IsDirtyCount.
internal List<AnimationState> AnimationStates;
@@ -496,7 +499,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// Override this method and return false to switch to owner authoritative mode
/// Override this method and return false to switch to owner authoritative mode.
/// </summary>
/// <remarks>
/// When using a distributed authority network topology, this will default to
@@ -507,10 +510,6 @@ namespace Unity.Netcode.Components
return NetworkManager ? !NetworkManager.DistributedAuthorityMode : true;
}
// Animators only support up to 32 parameters
// TODO: Look into making this a range limited property
private const int k_MaxAnimationParams = 32;
private int[] m_TransitionHash;
private int[] m_AnimationHash;
private float[] m_LayerWeights;
@@ -534,7 +533,7 @@ namespace Unity.Netcode.Components
}
// 128 bytes per Animator
private FastBufferWriter m_ParameterWriter = new FastBufferWriter(k_MaxAnimationParams * sizeof(float), Allocator.Persistent);
private FastBufferWriter m_ParameterWriter;
private NativeArray<AnimatorParamCache> m_CachedAnimatorParameters;
@@ -586,6 +585,14 @@ namespace Unity.Netcode.Components
protected virtual void Awake()
{
if (!m_Animator)
{
#if !UNITY_EDITOR
Debug.LogError($"{nameof(NetworkAnimator)} {name} does not have an {nameof(UnityEngine.Animator)} assigned to it. The {nameof(NetworkAnimator)} will not initialize properly.");
#endif
return;
}
int layers = m_Animator.layerCount;
// Initializing the below arrays for everyone handles an issue
// when running in owner authoritative mode and the owner changes.
@@ -615,6 +622,9 @@ namespace Unity.Netcode.Components
}
}
// The total initialization size calculated for the m_ParameterWriter write buffer.
var totalParameterSize = sizeof(uint);
// Build our reference parameter values to detect when they change
var parameters = m_Animator.parameters;
m_CachedAnimatorParameters = new NativeArray<AnimatorParamCache>(parameters.Length, Allocator.Persistent);
@@ -655,7 +665,37 @@ namespace Unity.Netcode.Components
}
m_CachedAnimatorParameters[i] = cacheParam;
// Calculate parameter sizes (index + type size)
switch (parameter.type)
{
case AnimatorControllerParameterType.Int:
{
totalParameterSize += sizeof(int) * 2;
break;
}
case AnimatorControllerParameterType.Bool:
case AnimatorControllerParameterType.Trigger:
{
// Bool is serialized to 1 byte
totalParameterSize += sizeof(int) + 1;
break;
}
case AnimatorControllerParameterType.Float:
{
totalParameterSize += sizeof(int) + sizeof(float);
break;
}
}
}
if (m_ParameterWriter.IsInitialized)
{
m_ParameterWriter.Dispose();
}
// Create our parameter write buffer for serialization
m_ParameterWriter = new FastBufferWriter(totalParameterSize, Allocator.Persistent);
}
/// <summary>
@@ -697,7 +737,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// Wries all parameter and state information needed to initially synchronize a client
/// Writes all parameter and state information needed to initially synchronize a client
/// </summary>
private void WriteSynchronizationData<T>(ref BufferSerializer<T> serializer) where T : IReaderWriter
{
@@ -772,8 +812,10 @@ namespace Unity.Netcode.Components
}
}
animationState.Transition = isInTransition; // The only time this could be set to true
animationState.StateHash = stateHash; // When a transition, this is the originating/starting state
// The only time this could be set to true
animationState.Transition = isInTransition;
// When a transition, this is the originating/starting state
animationState.StateHash = stateHash;
animationState.NormalizedTime = normalizedTime;
animationState.Layer = layer;
animationState.Weight = m_LayerWeights[layer];
@@ -847,7 +889,8 @@ namespace Unity.Netcode.Components
{
m_TransitionHash[layer] = nt.fullPathHash;
m_AnimationHash[layer] = 0;
animState.DestinationStateHash = nt.fullPathHash; // Next state is the destination state for cross fade
// Next state is the destination state for cross fade
animState.DestinationStateHash = nt.fullPathHash;
animState.CrossFade = true;
animState.Transition = true;
animState.Duration = tt.duration;
@@ -865,7 +908,8 @@ namespace Unity.Netcode.Components
// first time in this transition for this layer
m_TransitionHash[layer] = tt.fullPathHash;
m_AnimationHash[layer] = 0;
animState.StateHash = tt.fullPathHash; // Transitioning from state
// Transitioning from state
animState.StateHash = tt.fullPathHash;
animState.CrossFade = false;
animState.Transition = true;
animState.NormalizedTime = tt.normalizedTime;
@@ -1081,7 +1125,7 @@ namespace Unity.Netcode.Components
{
writer.Seek(0);
writer.Truncate();
// Write how many parameter entries we are going to write
// Write out how many parameter entries to read
BytePacker.WriteValuePacked(writer, (uint)m_ParametersToUpdate.Count);
foreach (var parameterIndex in m_ParametersToUpdate)
{
@@ -1230,10 +1274,11 @@ namespace Unity.Netcode.Components
NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) sub-table does not contain destination state ({animationState.DestinationStateHash})!");
}
}
else if (NetworkManager.LogLevel == LogLevel.Developer)
{
NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) does not exist!");
}
// For reference, it is valid to have no transition information
//else if (NetworkManager.LogLevel == LogLevel.Developer)
//{
// NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) does not exist!");
//}
}
else if (animationState.Transition && animationState.CrossFade)
{
@@ -1436,7 +1481,7 @@ namespace Unity.Netcode.Components
/// <summary>
/// Distributed Authority: Internally-called RPC client receiving function to update a trigger when the server wants to forward
/// a trigger for a client to play / reset
/// a trigger to a client
/// </summary>
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
[Rpc(SendTo.NotAuthority)]
@@ -1447,7 +1492,7 @@ namespace Unity.Netcode.Components
/// <summary>
/// Client Server: Internally-called RPC client receiving function to update a trigger when the server wants to forward
/// a trigger for a client to play / reset
/// a trigger to a client
/// </summary>
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
/// <param name="clientRpcParams">unused</param>
@@ -1513,7 +1558,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// Resets the trigger for the associated animation. See <see cref="SetTrigger(string)">SetTrigger</see> for more on how triggers are special
/// Resets the trigger for the associated animation. See <see cref="SetTrigger(string)">SetTrigger</see> for more on how triggers are special
/// </summary>
/// <param name="triggerName">The string name of the trigger to reset</param>
public void ResetTrigger(string triggerName)
@@ -1529,4 +1574,5 @@ namespace Unity.Netcode.Components
}
}
}
#endif // COM_UNITY_MODULES_ANIMATION
// COM_UNITY_MODULES_ANIMATION
#endif

View File

@@ -1,884 +0,0 @@
#if COM_UNITY_MODULES_PHYSICS || COM_UNITY_MODULES_PHYSICS2D
using System.Runtime.CompilerServices;
using UnityEngine;
namespace Unity.Netcode.Components
{
/// <summary>
/// NetworkRigidbodyBase is a unified <see cref="Rigidbody"/> and <see cref="Rigidbody2D"/> integration that helps to synchronize physics motion, collision, and interpolation
/// when used with a <see cref="NetworkTransform"/>.
/// </summary>
/// <remarks>
/// For a customizable netcode Rigidbody, create your own component from this class and use <see cref="Initialize(RigidbodyTypes, NetworkTransform, Rigidbody2D, Rigidbody)"/>
/// during instantiation (i.e. invoked from within the Awake method). You can re-initialize after having initialized but only when the <see cref="NetworkObject"/> is not spawned.
/// </remarks>
public abstract class NetworkRigidbodyBase : NetworkBehaviour
{
#if UNITY_EDITOR
[HideInInspector]
[SerializeField]
internal bool NetworkRigidbodyBaseExpanded;
#endif
/// <summary>
/// When enabled, the associated <see cref="NetworkTransform"/> will use the Rigidbody/Rigidbody2D to apply and synchronize changes in position, rotation, and
/// allows for the use of Rigidbody interpolation/extrapolation.
/// </summary>
/// <remarks>
/// If <see cref="NetworkTransform.Interpolate"/> is enabled, non-authoritative instances can only use Rigidbody interpolation. If a network prefab is set to
/// extrapolation and <see cref="NetworkTransform.Interpolate"/> is enabled, then non-authoritative instances will automatically be adjusted to use Rigidbody
/// interpolation while the authoritative instance will still use extrapolation.
/// </remarks>
[Tooltip("When enabled and a NetworkTransform component is attached, the NetworkTransform will use the rigid body for motion and detecting changes in state.")]
public bool UseRigidBodyForMotion;
/// <summary>
/// When enabled (default), automatically set the Kinematic state of the Rigidbody based on ownership.
/// When disabled, Kinematic state needs to be set by external script(s).
/// </summary>
public bool AutoUpdateKinematicState = true;
/// <summary>
/// Primarily applies to the <see cref="AutoUpdateKinematicState"/> property when disabled but you still want
/// the Rigidbody to be automatically set to Kinematic when despawned.
/// </summary>
public bool AutoSetKinematicOnDespawn = true;
// Determines if this is a Rigidbody or Rigidbody2D implementation
private bool m_IsRigidbody2D => RigidbodyType == RigidbodyTypes.Rigidbody2D;
// Used to cache the authority state of this Rigidbody during the last frame
private bool m_IsAuthority;
protected internal Rigidbody m_InternalRigidbody { get; private set; }
protected internal Rigidbody2D m_InternalRigidbody2D { get; private set; }
internal NetworkTransform NetworkTransform;
private float m_TickFrequency;
private float m_TickRate;
private enum InterpolationTypes
{
None,
Interpolate,
Extrapolate
}
private InterpolationTypes m_OriginalInterpolation;
/// <summary>
/// Used to define the type of Rigidbody implemented.
/// <see cref=""/>
/// </summary>
public enum RigidbodyTypes
{
Rigidbody,
Rigidbody2D,
}
public RigidbodyTypes RigidbodyType { get; private set; }
/// <summary>
/// Initializes the networked Rigidbody based on the <see cref="RigidbodyTypes"/>
/// passed in as a parameter.
/// </summary>
/// <remarks>
/// Cannot be initialized while the associated <see cref="NetworkObject"/> is spawned.
/// </remarks>
/// <param name="rigidbodyType">type of rigid body being initialized</param>
/// <param name="rigidbody2D">(optional) The <see cref="Rigidbody2D"/> to be used</param>
/// <param name="rigidbody">(optional) The <see cref="Rigidbody"/> to be used</param>
protected void Initialize(RigidbodyTypes rigidbodyType, NetworkTransform networkTransform = null, Rigidbody2D rigidbody2D = null, Rigidbody rigidbody = null)
{
// Don't initialize if already spawned
if (IsSpawned)
{
Debug.LogError($"[{name}] Attempting to initialize while spawned is not allowed.");
return;
}
RigidbodyType = rigidbodyType;
m_InternalRigidbody2D = rigidbody2D;
m_InternalRigidbody = rigidbody;
NetworkTransform = networkTransform;
if (m_IsRigidbody2D && m_InternalRigidbody2D == null)
{
m_InternalRigidbody2D = GetComponent<Rigidbody2D>();
}
else if (m_InternalRigidbody == null)
{
m_InternalRigidbody = GetComponent<Rigidbody>();
}
SetOriginalInterpolation();
if (NetworkTransform == null)
{
NetworkTransform = GetComponent<NetworkTransform>();
}
if (NetworkTransform != null)
{
NetworkTransform.RegisterRigidbody(this);
}
else
{
throw new System.Exception($"[Missing {nameof(NetworkTransform)}] No {nameof(NetworkTransform)} is assigned or can be found during initialization!");
}
if (AutoUpdateKinematicState)
{
SetIsKinematic(true);
}
}
internal Vector3 GetAdjustedPositionThreshold()
{
// Since the threshold is a measurement of unity world space units per tick, we will allow for the maximum threshold
// to be no greater than the threshold measured in unity world space units per second
var thresholdMax = NetworkTransform.PositionThreshold * m_TickRate;
// Get the velocity in unity world space units per tick
var perTickVelocity = GetLinearVelocity() * m_TickFrequency;
// Since a rigid body can have "micro-motion" when allowed to come to rest (based on friction etc), we will allow for
// no less than 1/10th the threshold value.
var minThreshold = NetworkTransform.PositionThreshold * 0.1f;
// Finally, we adjust the threshold based on the body's current velocity
perTickVelocity.x = Mathf.Clamp(Mathf.Abs(perTickVelocity.x), minThreshold, thresholdMax);
perTickVelocity.y = Mathf.Clamp(Mathf.Abs(perTickVelocity.y), minThreshold, thresholdMax);
// 2D Rigidbody only moves on x & y axis
if (!m_IsRigidbody2D)
{
perTickVelocity.z = Mathf.Clamp(Mathf.Abs(perTickVelocity.z), minThreshold, thresholdMax);
}
return perTickVelocity;
}
internal Vector3 GetAdjustedRotationThreshold()
{
// Since the rotation threshold is a measurement pf degrees per tick, we get the maximum threshold
// by calculating the threshold in degrees per second.
var thresholdMax = NetworkTransform.RotAngleThreshold * m_TickRate;
// Angular velocity is expressed in radians per second where as the rotation being checked is in degrees.
// Convert the angular velocity to degrees per second and then convert that to degrees per tick.
var rotationPerTick = (GetAngularVelocity() * Mathf.Rad2Deg) * m_TickFrequency;
var minThreshold = NetworkTransform.RotAngleThreshold * m_TickFrequency;
// 2D Rigidbody only rotates around Z axis
if (!m_IsRigidbody2D)
{
rotationPerTick.x = Mathf.Clamp(Mathf.Abs(rotationPerTick.x), minThreshold, thresholdMax);
rotationPerTick.y = Mathf.Clamp(Mathf.Abs(rotationPerTick.y), minThreshold, thresholdMax);
}
rotationPerTick.z = Mathf.Clamp(Mathf.Abs(rotationPerTick.z), minThreshold, thresholdMax);
return rotationPerTick;
}
/// <summary>
/// Sets the linear velocity of the Rigidbody.
/// </summary>
/// <remarks>
/// For <see cref="Rigidbody2D"/>, only the x and y components of the <see cref="Vector3"/> are applied.
/// </remarks>
public void SetLinearVelocity(Vector3 linearVelocity)
{
if (m_IsRigidbody2D)
{
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
m_InternalRigidbody2D.linearVelocity = linearVelocity;
#else
m_InternalRigidbody2D.velocity = linearVelocity;
#endif
}
else
{
m_InternalRigidbody.linearVelocity = linearVelocity;
}
}
/// <summary>
/// Gets the linear velocity of the Rigidbody.
/// </summary>
/// <remarks>
/// For <see cref="Rigidbody2D"/>, the <see cref="Vector3"/> velocity returned is only applied to the x and y components.
/// </remarks>
/// <returns><see cref="Vector3"/> as the linear velocity</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector3 GetLinearVelocity()
{
if (m_IsRigidbody2D)
{
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
return m_InternalRigidbody2D.linearVelocity;
#else
return m_InternalRigidbody2D.velocity;
#endif
}
else
{
return m_InternalRigidbody.linearVelocity;
}
}
/// <summary>
/// Sets the angular velocity for the Rigidbody.
/// </summary>
/// <remarks>
/// For <see cref="Rigidbody2D"/>, the z component of <param name="angularVelocity"/> is only used to set the angular velocity.
/// A quick way to pass in a 2D angular velocity component is: <see cref="Vector3.forward"/> * angularVelocity (where angularVelocity is a float)
/// </remarks>
/// <param name="angularVelocity">the angular velocity to apply to the body</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetAngularVelocity(Vector3 angularVelocity)
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.angularVelocity = angularVelocity.z;
}
else
{
m_InternalRigidbody.angularVelocity = angularVelocity;
}
}
/// <summary>
/// Gets the angular velocity for the Rigidbody.
/// </summary>
/// <remarks>
/// For <see cref="Rigidbody2D"/>, the z component of the <see cref="Vector3"/> returned is the angular velocity of the object.
/// </remarks>
/// <returns>angular velocity as a <see cref="Vector3"/></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector3 GetAngularVelocity()
{
if (m_IsRigidbody2D)
{
return Vector3.forward * m_InternalRigidbody2D.angularVelocity;
}
else
{
return m_InternalRigidbody.angularVelocity;
}
}
/// <summary>
/// Gets the position of the Rigidbody
/// </summary>
/// <returns><see cref="Vector3"/></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector3 GetPosition()
{
if (m_IsRigidbody2D)
{
return m_InternalRigidbody2D.position;
}
else
{
return m_InternalRigidbody.position;
}
}
/// <summary>
/// Gets the rotation of the Rigidbody
/// </summary>
/// <returns><see cref="Quaternion"/></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Quaternion GetRotation()
{
if (m_IsRigidbody2D)
{
var quaternion = Quaternion.identity;
var angles = quaternion.eulerAngles;
angles.z = m_InternalRigidbody2D.rotation;
quaternion.eulerAngles = angles;
return quaternion;
}
else
{
return m_InternalRigidbody.rotation;
}
}
/// <summary>
/// Moves the rigid body
/// </summary>
/// <param name="position">The <see cref="Vector3"/> position to move towards</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void MovePosition(Vector3 position)
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.MovePosition(position);
}
else
{
m_InternalRigidbody.MovePosition(position);
}
}
/// <summary>
/// Directly applies a position (like teleporting)
/// </summary>
/// <param name="position"><see cref="Vector3"/> position to apply to the Rigidbody</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetPosition(Vector3 position)
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.position = position;
}
else
{
m_InternalRigidbody.position = position;
}
}
/// <summary>
/// Applies the rotation and position of the <see cref="GameObject"/>'s <see cref="Transform"/>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ApplyCurrentTransform()
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.position = transform.position;
m_InternalRigidbody2D.rotation = transform.eulerAngles.z;
}
else
{
m_InternalRigidbody.position = transform.position;
m_InternalRigidbody.rotation = transform.rotation;
}
}
// Used for Rigidbody only (see info on normalized below)
private Vector4 m_QuaternionCheck = Vector4.zero;
/// <summary>
/// Rotatates the Rigidbody towards a specified rotation
/// </summary>
/// <param name="rotation">The rotation expressed as a <see cref="Quaternion"/></param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void MoveRotation(Quaternion rotation)
{
if (m_IsRigidbody2D)
{
var quaternion = Quaternion.identity;
var angles = quaternion.eulerAngles;
angles.z = m_InternalRigidbody2D.rotation;
quaternion.eulerAngles = angles;
m_InternalRigidbody2D.MoveRotation(quaternion);
}
else
{
// Evidently we need to check to make sure the quaternion is a perfect
// magnitude of 1.0f when applying the rotation to a rigid body.
m_QuaternionCheck.x = rotation.x;
m_QuaternionCheck.y = rotation.y;
m_QuaternionCheck.z = rotation.z;
m_QuaternionCheck.w = rotation.w;
// If the magnitude is greater than 1.0f (even by a very small fractional value), then normalize the quaternion
if (m_QuaternionCheck.magnitude != 1.0f)
{
rotation.Normalize();
}
m_InternalRigidbody.MoveRotation(rotation);
}
}
/// <summary>
/// Applies a rotation to the Rigidbody
/// </summary>
/// <param name="rotation">The rotation to apply expressed as a <see cref="Quaternion"/></param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetRotation(Quaternion rotation)
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.rotation = rotation.eulerAngles.z;
}
else
{
m_InternalRigidbody.rotation = rotation;
}
}
/// <summary>
/// Sets the original interpolation of the Rigidbody while taking the Rigidbody type into consideration
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetOriginalInterpolation()
{
if (m_IsRigidbody2D)
{
switch (m_InternalRigidbody2D.interpolation)
{
case RigidbodyInterpolation2D.None:
{
m_OriginalInterpolation = InterpolationTypes.None;
break;
}
case RigidbodyInterpolation2D.Interpolate:
{
m_OriginalInterpolation = InterpolationTypes.Interpolate;
break;
}
case RigidbodyInterpolation2D.Extrapolate:
{
m_OriginalInterpolation = InterpolationTypes.Extrapolate;
break;
}
}
}
else
{
switch (m_InternalRigidbody.interpolation)
{
case RigidbodyInterpolation.None:
{
m_OriginalInterpolation = InterpolationTypes.None;
break;
}
case RigidbodyInterpolation.Interpolate:
{
m_OriginalInterpolation = InterpolationTypes.Interpolate;
break;
}
case RigidbodyInterpolation.Extrapolate:
{
m_OriginalInterpolation = InterpolationTypes.Extrapolate;
break;
}
}
}
}
/// <summary>
/// Wakes the Rigidbody if it is sleeping
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WakeIfSleeping()
{
if (m_IsRigidbody2D)
{
if (m_InternalRigidbody2D.IsSleeping())
{
m_InternalRigidbody2D.WakeUp();
}
}
else
{
if (m_InternalRigidbody.IsSleeping())
{
m_InternalRigidbody.WakeUp();
}
}
}
/// <summary>
/// Puts the Rigidbody to sleep
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SleepRigidbody()
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.Sleep();
}
else
{
m_InternalRigidbody.Sleep();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsKinematic()
{
if (m_IsRigidbody2D)
{
return m_InternalRigidbody2D.bodyType == RigidbodyType2D.Kinematic;
}
else
{
return m_InternalRigidbody.isKinematic;
}
}
/// <summary>
/// Sets the kinematic state of the Rigidbody and handles updating the Rigidbody's
/// interpolation setting based on the Kinematic state.
/// </summary>
/// <remarks>
/// When using the Rigidbody for <see cref="NetworkTransform"/> motion, this automatically
/// adjusts from extrapolation to interpolation if:
/// - The Rigidbody was originally set to extrapolation
/// - The NetworkTransform is set to interpolate
/// When the two above conditions are true:
/// - When switching from non-kinematic to kinematic this will automatically
/// switch the Rigidbody from extrapolation to interpolate.
/// - When switching from kinematic to non-kinematic this will automatically
/// switch the Rigidbody from interpolation back to extrapolation.
/// </remarks>
/// <param name="isKinematic"></param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetIsKinematic(bool isKinematic)
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.bodyType = isKinematic ? RigidbodyType2D.Kinematic : RigidbodyType2D.Dynamic;
}
else
{
m_InternalRigidbody.isKinematic = isKinematic;
}
// If we are not spawned, then exit early
if (!IsSpawned)
{
return;
}
if (UseRigidBodyForMotion)
{
// Only if the NetworkTransform is set to interpolate do we need to check for extrapolation
if (NetworkTransform.Interpolate && m_OriginalInterpolation == InterpolationTypes.Extrapolate)
{
if (IsKinematic())
{
// If not already set to interpolate then set the Rigidbody to interpolate
if (m_InternalRigidbody.interpolation == RigidbodyInterpolation.Extrapolate)
{
// Sleep until the next fixed update when switching from extrapolation to interpolation
SleepRigidbody();
SetInterpolation(InterpolationTypes.Interpolate);
}
}
else
{
// Switch it back to the original interpolation if non-kinematic (doesn't require sleep).
SetInterpolation(m_OriginalInterpolation);
}
}
}
else
{
SetInterpolation(m_IsAuthority ? m_OriginalInterpolation : (NetworkTransform.Interpolate ? InterpolationTypes.None : m_OriginalInterpolation));
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetInterpolation(InterpolationTypes interpolationType)
{
switch (interpolationType)
{
case InterpolationTypes.None:
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.interpolation = RigidbodyInterpolation2D.None;
}
else
{
m_InternalRigidbody.interpolation = RigidbodyInterpolation.None;
}
break;
}
case InterpolationTypes.Interpolate:
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.interpolation = RigidbodyInterpolation2D.Interpolate;
}
else
{
m_InternalRigidbody.interpolation = RigidbodyInterpolation.Interpolate;
}
break;
}
case InterpolationTypes.Extrapolate:
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.interpolation = RigidbodyInterpolation2D.Extrapolate;
}
else
{
m_InternalRigidbody.interpolation = RigidbodyInterpolation.Extrapolate;
}
break;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ResetInterpolation()
{
SetInterpolation(m_OriginalInterpolation);
}
protected override void OnOwnershipChanged(ulong previous, ulong current)
{
UpdateOwnershipAuthority();
base.OnOwnershipChanged(previous, current);
}
/// <summary>
/// Sets the authority based on whether it is server or owner authoritative
/// </summary>
/// <remarks>
/// Distributed authority sessions will always be owner authoritative.
/// </remarks>
internal void UpdateOwnershipAuthority()
{
if (NetworkManager.DistributedAuthorityMode)
{
// When in distributed authority mode, always use HasAuthority
m_IsAuthority = HasAuthority;
}
else
{
if (NetworkTransform.IsServerAuthoritative())
{
m_IsAuthority = NetworkManager.IsServer;
}
else
{
m_IsAuthority = IsOwner;
}
}
if (AutoUpdateKinematicState)
{
SetIsKinematic(!m_IsAuthority);
}
}
/// <inheritdoc />
public override void OnNetworkSpawn()
{
m_TickFrequency = 1.0f / NetworkManager.NetworkConfig.TickRate;
m_TickRate = NetworkManager.NetworkConfig.TickRate;
UpdateOwnershipAuthority();
}
/// <inheritdoc />
public override void OnNetworkDespawn()
{
if (UseRigidBodyForMotion && HasAuthority)
{
DetachFromFixedJoint();
NetworkRigidbodyConnections.Clear();
}
// If we are automatically handling the kinematic state...
if (AutoUpdateKinematicState || AutoSetKinematicOnDespawn)
{
// Turn off physics for the rigid body until spawned, otherwise
// non-owners can run fixed updates before the first full
// NetworkTransform update and physics will be applied (i.e. gravity, etc)
SetIsKinematic(true);
}
SetInterpolation(m_OriginalInterpolation);
}
// TODO: Possibly provide a NetworkJoint that allows for more options than fixed.
// Rigidbodies do not have the concept of "local space", and as such using a fixed joint will hold the object
// in place relative to the parent so jitter/stutter does not occur.
// Alternately, users can affix the fixed joint to a child GameObject (without a rigid body) of the parent NetworkObject
// and then add a NetworkTransform to that in order to get the parented child NetworkObject to move around in "local space"
public FixedJoint FixedJoint { get; private set; }
public FixedJoint2D FixedJoint2D { get; private set; }
internal System.Collections.Generic.List<NetworkRigidbodyBase> NetworkRigidbodyConnections = new System.Collections.Generic.List<NetworkRigidbodyBase>();
internal NetworkRigidbodyBase ParentBody;
private bool m_FixedJoint2DUsingGravity;
private bool m_OriginalGravitySetting;
private float m_OriginalGravityScale;
/// <summary>
/// When using a custom <see cref="NetworkRigidbodyBase"/>, this virtual method is invoked when the
/// <see cref="FixedJoint"/> is created in the event any additional adjustments are needed.
/// </summary>
protected virtual void OnFixedJointCreated()
{
}
/// <summary>
/// When using a custom <see cref="NetworkRigidbodyBase"/>, this virtual method is invoked when the
/// <see cref="FixedJoint2D"/> is created in the event any additional adjustments are needed.
/// </summary>
protected virtual void OnFixedJoint2DCreated()
{
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyFixedJoint2D(NetworkRigidbodyBase bodyToConnect, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
{
transform.position = position;
m_InternalRigidbody2D.position = position;
m_OriginalGravitySetting = bodyToConnect.m_InternalRigidbody.useGravity;
m_FixedJoint2DUsingGravity = useGravity;
if (!useGravity)
{
m_OriginalGravityScale = m_InternalRigidbody2D.gravityScale;
m_InternalRigidbody2D.gravityScale = 0.0f;
}
if (zeroVelocity)
{
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
m_InternalRigidbody2D.linearVelocity = Vector2.zero;
#else
m_InternalRigidbody2D.velocity = Vector2.zero;
#endif
m_InternalRigidbody2D.angularVelocity = 0.0f;
}
FixedJoint2D = gameObject.AddComponent<FixedJoint2D>();
FixedJoint2D.connectedBody = bodyToConnect.m_InternalRigidbody2D;
OnFixedJoint2DCreated();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyFixedJoint(NetworkRigidbodyBase bodyToConnectTo, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
{
transform.position = position;
m_InternalRigidbody.position = position;
if (zeroVelocity)
{
m_InternalRigidbody.linearVelocity = Vector3.zero;
m_InternalRigidbody.angularVelocity = Vector3.zero;
}
m_OriginalGravitySetting = m_InternalRigidbody.useGravity;
m_InternalRigidbody.useGravity = useGravity;
FixedJoint = gameObject.AddComponent<FixedJoint>();
FixedJoint.connectedBody = bodyToConnectTo.m_InternalRigidbody;
FixedJoint.connectedMassScale = connectedMassScale;
FixedJoint.massScale = massScale;
OnFixedJointCreated();
}
/// <summary>
/// Authority Only:
/// When invoked and not already attached to a fixed joint, this will connect two rigid bodies with <see cref="UseRigidBodyForMotion"/> enabled.
/// Invoke this method on the rigid body you wish to attach to another (i.e. weapon to player, sticky bomb to player/object, etc).
/// <seealso cref="FixedJoint"/>
/// <seealso cref="FixedJoint2D"/>
/// </summary>
/// <remarks>
/// Parenting relative:
/// - This instance can be viewed as the child.
/// - The <param name="objectToConnectTo"/> can be viewed as the parent.
/// <br/>
/// This is the recommended way, as opposed to parenting, to attached/detatch two rigid bodies to one another when <see cref="UseRigidBodyForMotion"/> is enabled.
/// For more details on using <see cref="UnityEngine.FixedJoint"/> and <see cref="UnityEngine.FixedJoint2D"/>.
/// <br/>
/// This provides a simple joint solution between two rigid bodies and serves as an example. You can add different joint types by creating a customized/derived
/// version of <see cref="NetworkRigidbodyBase"/>.
/// </remarks>
/// <param name="objectToConnectTo">The target object to attach to.</param>
/// <param name="positionOfConnection">The position of the connection (i.e. where you want the object to be affixed).</param>
/// <param name="connectedMassScale">The target object's mass scale relative to this object being attached.</param>
/// <param name="massScale">This object's mass scale relative to the target object's.</param>
/// <param name="useGravity">Determines if this object will have gravity applied to it along with the object you are connecting this one to (the default is to not use gravity for this object)</param>
/// <param name="zeroVelocity">When true (the default), both linear and angular velocities of this object are set to zero.</param>
/// <param name="teleportObject">When true (the default), this object will teleport itself to the position of connection.</param>
/// <returns>true (success) false (failed)</returns>
public bool AttachToFixedJoint(NetworkRigidbodyBase objectToConnectTo, Vector3 positionOfConnection, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true, bool teleportObject = true)
{
if (!UseRigidBodyForMotion)
{
Debug.LogError($"[{GetType().Name}] {name} does not have {nameof(UseRigidBodyForMotion)} set! Either enable {nameof(UseRigidBodyForMotion)} on this component or do not use a {nameof(FixedJoint)} when parenting under a {nameof(NetworkObject)}.");
return false;
}
if (IsKinematic())
{
Debug.LogError($"[{GetType().Name}] {name} is currently kinematic! You cannot use a {nameof(FixedJoint)} with Kinematic bodies!");
return false;
}
if (objectToConnectTo != null)
{
if (m_IsRigidbody2D)
{
ApplyFixedJoint2D(objectToConnectTo, positionOfConnection, connectedMassScale, massScale, useGravity, zeroVelocity);
}
else
{
ApplyFixedJoint(objectToConnectTo, positionOfConnection, connectedMassScale, massScale, useGravity, zeroVelocity);
}
ParentBody = objectToConnectTo;
ParentBody.NetworkRigidbodyConnections.Add(this);
if (teleportObject)
{
NetworkTransform.SetState(teleportDisabled: false);
}
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void RemoveFromParentBody()
{
ParentBody.NetworkRigidbodyConnections.Remove(this);
ParentBody = null;
}
/// <summary>
/// Authority Only:
/// When invoked and already connected to an object via <see cref="FixedJoint"/> or <see cref="FixedJoint2D"/> (depending upon the type of rigid body),
/// this will detach from the fixed joint and destroy the fixed joint component.
/// </summary>
/// <remarks>
/// This is the recommended way, as opposed to parenting, to attached/detatch two rigid bodies to one another when <see cref="UseRigidBodyForMotion"/> is enabled.
/// </remarks>
public void DetachFromFixedJoint()
{
if (!HasAuthority)
{
Debug.LogError($"[{name}] Only authority can invoke {nameof(DetachFromFixedJoint)}!");
}
if (UseRigidBodyForMotion)
{
if (m_IsRigidbody2D)
{
if (FixedJoint2D != null)
{
if (!m_FixedJoint2DUsingGravity)
{
FixedJoint2D.connectedBody.gravityScale = m_OriginalGravityScale;
}
FixedJoint2D.connectedBody = null;
Destroy(FixedJoint2D);
FixedJoint2D = null;
ResetInterpolation();
RemoveFromParentBody();
}
}
else
{
if (FixedJoint != null)
{
FixedJoint.connectedBody = null;
m_InternalRigidbody.useGravity = m_OriginalGravitySetting;
Destroy(FixedJoint);
FixedJoint = null;
ResetInterpolation();
RemoveFromParentBody();
}
}
}
}
}
}
#endif // COM_UNITY_MODULES_PHYSICS

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 8c4434f0563fb7f42b3b2993c97ae81a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,24 +0,0 @@
#if COM_UNITY_MODULES_PHYSICS
using UnityEngine;
namespace Unity.Netcode.Components
{
/// <summary>
/// NetworkRigidbody allows for the use of <see cref="Rigidbody"/> on network objects. By controlling the kinematic
/// mode of the <see cref="Rigidbody"/> and disabling it on all peers but the authoritative one.
/// </summary>
[RequireComponent(typeof(NetworkTransform))]
[RequireComponent(typeof(Rigidbody))]
[AddComponentMenu("Netcode/Network Rigidbody")]
public class NetworkRigidbody : NetworkRigidbodyBase
{
public Rigidbody Rigidbody => m_InternalRigidbody;
protected virtual void Awake()
{
Initialize(RigidbodyTypes.Rigidbody);
}
}
}
#endif // COM_UNITY_MODULES_PHYSICS

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: f6c0be61502bb534f922ebb746851216
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,22 +0,0 @@
#if COM_UNITY_MODULES_PHYSICS2D
using UnityEngine;
namespace Unity.Netcode.Components
{
/// <summary>
/// NetworkRigidbody allows for the use of <see cref="Rigidbody2D"/> on network objects. By controlling the kinematic
/// mode of the rigidbody and disabling it on all peers but the authoritative one.
/// </summary>
[RequireComponent(typeof(NetworkTransform))]
[RequireComponent(typeof(Rigidbody2D))]
[AddComponentMenu("Netcode/Network Rigidbody 2D")]
public class NetworkRigidbody2D : NetworkRigidbodyBase
{
public Rigidbody2D Rigidbody2D => m_InternalRigidbody2D;
protected virtual void Awake()
{
Initialize(RigidbodyTypes.Rigidbody2D);
}
}
}
#endif // COM_UNITY_MODULES_PHYSICS2D

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 80d7c879794dfda4687da0e400131852
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -32,7 +32,8 @@ namespace Unity.Netcode.Components
/// </summary>
public struct NetworkTransformState : INetworkSerializable
{
private const int k_InLocalSpaceBit = 0x00000001; // Persists between state updates (authority dictates if this is set)
// Persists between state updates (authority dictates if this is set)
private const int k_InLocalSpaceBit = 0x00000001;
private const int k_PositionXBit = 0x00000002;
private const int k_PositionYBit = 0x00000004;
private const int k_PositionZBit = 0x00000008;
@@ -43,18 +44,25 @@ namespace Unity.Netcode.Components
private const int k_ScaleYBit = 0x00000100;
private const int k_ScaleZBit = 0x00000200;
private const int k_TeleportingBit = 0x00000400;
private const int k_Interpolate = 0x00000800; // Persists between state updates (authority dictates if this is set)
private const int k_QuaternionSync = 0x00001000; // Persists between state updates (authority dictates if this is set)
private const int k_QuaternionCompress = 0x00002000; // Persists between state updates (authority dictates if this is set)
private const int k_UseHalfFloats = 0x00004000; // Persists between state updates (authority dictates if this is set)
// Persists between state updates (authority dictates if this is set)
private const int k_Interpolate = 0x00000800;
// Persists between state updates (authority dictates if this is set)
private const int k_QuaternionSync = 0x00001000;
// Persists between state updates (authority dictates if this is set)
private const int k_QuaternionCompress = 0x00002000;
// Persists between state updates (authority dictates if this is set)
private const int k_UseHalfFloats = 0x00004000;
private const int k_Synchronization = 0x00008000;
private const int k_PositionSlerp = 0x00010000; // Persists between state updates (authority dictates if this is set)
private const int k_IsParented = 0x00020000; // When parented and synchronizing, we need to have both lossy and local scale due to varying spawn order
// Persists between state updates (authority dictates if this is set)
private const int k_PositionSlerp = 0x00010000;
// When parented and synchronizing, we need to have both lossy and local scale due to varying spawn order
private const int k_IsParented = 0x00020000;
private const int k_SynchBaseHalfFloat = 0x00040000;
private const int k_ReliableSequenced = 0x00080000;
private const int k_UseUnreliableDeltas = 0x00100000;
private const int k_UnreliableFrameSync = 0x00200000;
private const int k_TrackStateId = 0x10000000; // (Internal Debugging) When set each state update will contain a state identifier
// (Internal Debugging) When set each state update will contain a state identifier
private const int k_TrackStateId = 0x10000000;
// Stores persistent and state relative flags
private uint m_Bitset;
@@ -409,8 +417,8 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// Returns whether this state update was a frame synchronization when
/// UseUnreliableDeltas is enabled. When set, the entire transform will
/// Returns whether this state update was a frame synchronization when
/// UseUnreliableDeltas is enabled. When set, the entire transform will
/// be or has been synchronized.
/// </summary>
public bool IsUnreliableFrameSync()
@@ -929,8 +937,6 @@ namespace Unity.Netcode.Components
#endregion
#region PROPERTIES AND GENERAL METHODS
public enum AuthorityModes
{
Server,
@@ -1370,7 +1376,8 @@ namespace Unity.Netcode.Components
private BufferedLinearInterpolatorVector3 m_PositionInterpolator;
private BufferedLinearInterpolatorVector3 m_ScaleInterpolator;
private BufferedLinearInterpolatorQuaternion m_RotationInterpolator; // rotation is a single Quaternion since each Euler axis will affect the quaternion's final value
// rotation is a single Quaternion since each Euler axis will affect the quaternion's final value
private BufferedLinearInterpolatorQuaternion m_RotationInterpolator;
// The previous network state
private NetworkTransformState m_OldState = new NetworkTransformState();
@@ -1643,11 +1650,11 @@ namespace Unity.Netcode.Components
Debug.LogException(ex);
}
// The below is part of assuring we only send a frame synch, when sending unreliable deltas, if
// The below is part of assuring we only send a frame synch, when sending unreliable deltas, if
// we have already sent at least one unreliable delta state update. At this point in the callstack,
// a delta state update has just been sent in the above UpdateTransformState() call and as long as
// we didn't send a frame synch and we are not synchronizing then we know at least one unreliable
// delta has been sent. Under this scenario, we should start checking for this instance's alloted
// delta has been sent. Under this scenario, we should start checking for this instance's alloted
// frame synch "tick slot". Once we send a frame synch, if no other deltas occur after that
// (i.e. the object is at rest) then we will stop sending frame synch's until the object begins
// moving, rotating, or scaling again.
@@ -1964,7 +1971,7 @@ namespace Unity.Netcode.Components
networkState.NetworkDeltaPosition = m_HalfPositionState;
// If ownership offset is greater or we are doing an axial synchronization then synchronize the base position
// If ownership offset is greater or we are doing an axial synchronization then synchronize the base position
if ((m_HalfFloatTargetTickOwnership > m_CachedNetworkManager.ServerTime.Tick || isAxisSync) && !networkState.IsTeleportingNextFrame)
{
networkState.SynchronizeBaseHalfFloat = true;
@@ -3403,7 +3410,7 @@ namespace Unity.Netcode.Components
/// - Local space to local space (<see cref="NetworkObject"/> parent to <see cref="NetworkObject"/> parent)
/// Will all smoothly transition while interpolation is enabled.
/// (Does not work if using a <see cref="Rigidbody"/> or <see cref="Rigidbody2D"/> for motion)
///
///
/// When a parent changes, non-authoritative instances should:<br />
/// - Apply the resultant position, rotation, and scale from the parenting action.<br />
/// - Clear interpolators (even if not enabled on this frame)<br />
@@ -3575,7 +3582,7 @@ namespace Unity.Netcode.Components
var transformToCommit = transform;
// Explicit set states are cumulative during a fractional tick period of time (i.e. each SetState invocation will
// Explicit set states are cumulative during a fractional tick period of time (i.e. each SetState invocation will
// update the axial deltas to whatever changes are applied). As such, we need to preserve the dirty and explicit
// state flags.
var stateWasDirty = m_LocalAuthoritativeNetworkState.IsDirty;
@@ -3658,7 +3665,7 @@ namespace Unity.Netcode.Components
var serverTime = m_CachedNetworkManager.ServerTime;
var cachedServerTime = serverTime.Time;
//var offset = (float)serverTime.TickOffset;
// var offset = (float)serverTime.TickOffset;
#if COM_UNITY_MODULES_PHYSICS || COM_UNITY_MODULES_PHYSICS2D
var cachedDeltaTime = m_UseRigidbodyForMotion ? m_CachedNetworkManager.RealTimeProvider.FixedDeltaTime : m_CachedNetworkManager.RealTimeProvider.DeltaTime;
#else
@@ -3669,7 +3676,7 @@ namespace Unity.Netcode.Components
// is to make their cachedRenderTime run 2 ticks behind.
// TODO: This could most likely just always be 2
//var ticksAgo = ((!IsServerAuthoritative() && !IsServer) || m_CachedNetworkManager.DistributedAuthorityMode) && !m_CachedNetworkManager.DAHost ? 2 : 1;
// var ticksAgo = ((!IsServerAuthoritative() && !IsServer) || m_CachedNetworkManager.DistributedAuthorityMode) && !m_CachedNetworkManager.DAHost ? 2 : 1;
var ticksAgo = 2;
var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo).Time;
@@ -3746,7 +3753,7 @@ namespace Unity.Netcode.Components
/// <summary>
/// Determines whether the <see cref="NetworkTransform"/> is <see cref="AuthorityModes.Server"/> or <see cref="AuthorityModes.Owner"/> based on the <see cref="AuthorityMode"/> property.
/// You can override this method to control this logic.
/// You can override this method to control this logic.
/// </summary>
/// <returns><see cref="true"/> or <see cref="false"/></returns>
protected virtual bool OnIsServerAuthoritative()
@@ -3772,7 +3779,6 @@ namespace Unity.Netcode.Components
return OnIsServerAuthoritative();
}
}
#endregion
#region MESSAGE HANDLING
@@ -3964,7 +3970,7 @@ namespace Unity.Netcode.Components
{
return 2 * m_TickFrequency;
// TODO: We need an RTT that updates regularly and not just when the client sends packets
//return Mathf.Max(1.0f, TicksAgo) * m_TickFrequency;
// return Mathf.Max(1.0f, TicksAgo) * m_TickFrequency;
}
/// <summary>
@@ -3974,25 +3980,25 @@ namespace Unity.Netcode.Components
private void TickUpdate()
{
// TODO: We need an RTT that updates regularly and not just when the client sends packets
//if (m_UnityTransport != null)
//{
// // Determine the desired ticks ago by the RTT (this really should be the combination of the
// // authority and non-authority 1/2 RTT but in the end anything beyond 300ms is considered very poor
// // network quality so latent interpolation is going to be expected).
// var rtt = Mathf.Max(m_TickInMS, m_UnityTransport.GetCurrentRtt(NetworkManager.ServerClientId));
// m_TicksAgoSamples[m_TickSampleIndex] = Mathf.Max(1, (int)(rtt * m_TickFrequency));
// var tickAgoSum = 0.0f;
// foreach (var tickAgo in m_TicksAgoSamples)
// {
// tickAgoSum += tickAgo;
// }
// m_PreviousTicksAgo = TicksAgo;
// TicksAgo = Mathf.Lerp(m_PreviousTicksAgo, tickAgoSum / m_TickRate, m_TickFrequency);
// m_TickSampleIndex = (m_TickSampleIndex + 1) % m_TickRate;
// // Get the partial tick value for when this is all calculated to provide an offset for determining
// // the relative starting interpolation point for the next update
// Offset = m_OffsetTickFrequency * (Mathf.Max(2, TicksAgo) - (int)TicksAgo);
//}
// if (m_UnityTransport != null)
// {
// // Determine the desired ticks ago by the RTT (this really should be the combination of the
// // authority and non-authority 1/2 RTT but in the end anything beyond 300ms is considered very poor
// // network quality so latent interpolation is going to be expected).
// var rtt = Mathf.Max(m_TickInMS, m_UnityTransport.GetCurrentRtt(NetworkManager.ServerClientId));
// m_TicksAgoSamples[m_TickSampleIndex] = Mathf.Max(1, (int)(rtt * m_TickFrequency));
// var tickAgoSum = 0.0f;
// foreach (var tickAgo in m_TicksAgoSamples)
// {
// tickAgoSum += tickAgo;
// }
// m_PreviousTicksAgo = TicksAgo;
// TicksAgo = Mathf.Lerp(m_PreviousTicksAgo, tickAgoSum / m_TickRate, m_TickFrequency);
// m_TickSampleIndex = (m_TickSampleIndex + 1) % m_TickRate;
// // Get the partial tick value for when this is all calculated to provide an offset for determining
// // the relative starting interpolation point for the next update
// Offset = m_OffsetTickFrequency * (Mathf.Max(2, TicksAgo) - (int)TicksAgo);
// }
// TODO FIX: The local NetworkTickSystem can invoke with the same network tick as before
if (m_NetworkManager.ServerTime.Tick <= m_LastTick)
@@ -4012,13 +4018,13 @@ namespace Unity.Netcode.Components
private UnityTransport m_UnityTransport;
private float m_TickFrequency;
//private float m_OffsetTickFrequency;
//private ulong m_TickInMS;
//private int m_TickSampleIndex;
// private float m_OffsetTickFrequency;
// private ulong m_TickInMS;
// private int m_TickSampleIndex;
private int m_TickRate;
public float TicksAgo { get; private set; }
//public float Offset { get; private set; }
//private float m_PreviousTicksAgo;
// public float Offset { get; private set; }
// private float m_PreviousTicksAgo;
private List<float> m_TicksAgoSamples = new List<float>();
@@ -4032,16 +4038,16 @@ namespace Unity.Netcode.Components
//// For the offset, it uses the fractional remainder of the tick to determine the offset.
//// In order to keep within tick boundaries, we increment the tick rate by 1 to assure it
//// will always be < the tick frequency.
//m_OffsetTickFrequency = 1.0f / (m_TickRate + 1);
//m_TickInMS = (ulong)(1000 * m_TickFrequency);
//m_UnityTransport = m_NetworkManager.NetworkConfig.NetworkTransport as UnityTransport;
// m_OffsetTickFrequency = 1.0f / (m_TickRate + 1);
// m_TickInMS = (ulong)(1000 * m_TickFrequency);
// m_UnityTransport = m_NetworkManager.NetworkConfig.NetworkTransport as UnityTransport;
//// Fill the sample with a starting value of 1
//for (int i = 0; i < m_TickRate; i++)
//{
// m_TicksAgoSamples.Add(1f);
//}
// for (int i = 0; i < m_TickRate; i++)
// {
// m_TicksAgoSamples.Add(1f);
// }
TicksAgo = 2f;
//m_PreviousTicksAgo = 1f;
// m_PreviousTicksAgo = 1f;
if (networkManager.IsServer)
{
networkManager.OnServerStopped += OnNetworkManagerStopped;

View File

@@ -27,7 +27,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// Default implementation required to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance.
/// Default implementation required to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance.
/// </summary>
/// <remarks>
/// Recommended to implement this method on a <see cref="NetworkBehaviour"/> component
@@ -52,7 +52,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// This is an extended version of <see cref="IContactEventHandler"/> and can be used to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance. <br />
/// This is an extended version of <see cref="IContactEventHandler"/> and can be used to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance.<br />
/// This provides additional <see cref="ContactEventHandlerInfo"/> information to the <see cref="RigidbodyContactEventManager"/> for each set of contact events it is processing.
/// </summary>
public interface IContactEventHandlerWithInfo : IContactEventHandler
@@ -66,9 +66,9 @@ namespace Unity.Netcode.Components
/// <summary>
/// Add this component to an in-scene placed GameObject to provide faster collision event processing between <see cref="Rigidbody"/> instances and optionally static colliders.
/// <see cref="IContactEventHandler"/> <br />
/// <see cref="IContactEventHandlerWithInfo"/> <br />
/// <see cref="ContactEventHandlerInfo"/> <br />
/// <see cref="IContactEventHandler"/><br />
/// <see cref="IContactEventHandlerWithInfo"/><br />
/// <see cref="ContactEventHandlerInfo"/><br />
/// </summary>
[AddComponentMenu("Netcode/Rigidbody Contact Event Manager")]
public class RigidbodyContactEventManager : MonoBehaviour

View File

@@ -13,6 +13,14 @@ namespace Unity.Netcode
[Serializable]
public class NetworkConfig
{
// Clamp spawn time outs to prevent dropping messages during scene events
// Note: The legacy versions of NGO defaulted to 1s which was too low. As
// well, the SpawnTimeOut is now being clamped to within this recommended
// range both via UI and when NetworkManager is validated.
internal const float MinSpawnTimeout = 10.0f;
// Clamp spawn time outs to no more than 1 hour (really that is a bit high)
internal const float MaxSpawnTimeout = 3600.0f;
/// <summary>
/// The protocol version. Different versions doesn't talk to each other.
/// </summary>
@@ -132,6 +140,8 @@ namespace Unity.Netcode
/// The amount of time a message will be held (deferred) if the destination NetworkObject needed to process the message doesn't exist yet. If the NetworkObject is not spawned within this time period, all deferred messages for that NetworkObject will be dropped.
/// </summary>
[Tooltip("The amount of time a message will be held (deferred) if the destination NetworkObject needed to process the message doesn't exist yet. If the NetworkObject is not spawned within this time period, all deferred messages for that NetworkObject will be dropped.")]
[Range(MinSpawnTimeout, MaxSpawnTimeout)]
public float SpawnTimeout = 10f;
/// <summary>
@@ -176,6 +186,21 @@ namespace Unity.Netcode
[Tooltip("Enable (default) if you want to profile network messages with development builds and defaults to being disabled in release builds. When disabled, network messaging profiling will be disabled in development builds.")]
public bool NetworkProfilingMetrics = true;
/// <summary>
/// Invoked by <see cref="NetworkManager"/> when it is validated.
/// </summary>
/// <remarks>
/// Used to check for potential legacy values that have already been serialized and/or
/// runtime modifications to a property outside of the recommended range.
/// For each property checked below, provide a brief description of the reason.
/// </remarks>
internal void OnValidate()
{
// Legacy NGO versions defaulted this value to 1 second that has since been determiend
// any range less than 10 seconds can lead to dropped messages during scene events.
SpawnTimeout = Mathf.Clamp(SpawnTimeout, MinSpawnTimeout, MaxSpawnTimeout);
}
/// <summary>
/// Returns a base64 encoded version of the configuration
/// </summary>

View File

@@ -0,0 +1,58 @@
namespace Unity.Netcode
{
internal class SessionConfig
{
/// <summary>
/// The running list of session versions
/// </summary>
public const uint NoFeatureCompatibility = 0;
public const uint BypassFeatureCompatible = 1;
public const uint ServerDistributionCompatible = 2;
// The most current session version (!!!!set this when you increment!!!!!)
public static uint PackageSessionVersion => ServerDistributionCompatible;
internal uint SessionVersion;
public bool ServiceSideDistribution;
/// <summary>
/// Service to client
/// Set when the client receives a <see cref="ConnectionApprovedMessage"/>
/// </summary>
/// <param name="serviceConfig">the session's settings</param>
public SessionConfig(ServiceConfig serviceConfig)
{
SessionVersion = serviceConfig.SessionVersion;
ServiceSideDistribution = serviceConfig.ServerRedistribution;
}
/// <summary>
/// Can be used to directly set the version.
/// </summary>
/// <remarks>
/// If a client connects that does not support session configuration then
/// this will be invoked. The default values set in the constructor should
/// assume that no features are available.
/// Can also be used for mock/integration testing version handling.
/// </remarks>
/// <param name="version">version to set</param>
public SessionConfig(uint version)
{
SessionVersion = version;
ServiceSideDistribution = false;
}
/// <summary>
/// Client to Service
/// Default package constructor set when <see cref="NetworkManager.Initialize(bool)"/> is invoked.
/// </summary>
public SessionConfig()
{
// The current
SessionVersion = PackageSessionVersion;
ServiceSideDistribution = false;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e0512e5a3e1dc484bbbf98c03a574645

View File

@@ -10,15 +10,54 @@ using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// The connection event type set within <see cref="ConnectionEventData"/> to signify the type of connection event notification received.
/// </summary>
/// <remarks>
/// <see cref="ConnectionEventData"/> is returned as a parameter of the <see cref="NetworkManager.OnConnectionEvent"/> event notification.
/// <see cref="ClientConnected"/> and <see cref="ClientDisconnected"/> event types occur on the client-side of the newly connected client and on the server-side. <br />
/// <see cref="PeerConnected"/> and <see cref="PeerDisconnected"/> event types occur on connected clients to notify that a new client (peer) has joined/connected.
/// </remarks>
public enum ConnectionEvent
{
/// <summary>
/// This event is set on the client-side of the newly connected client and on the server-side.<br />
/// </summary>
/// <remarks>
/// On the newly connected client side, the <see cref="ConnectionEventData.ClientId"/> will be the <see cref="NetworkManager.LocalClientId"/>.<br />
/// On the server side, the <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just connected.
/// </remarks>
ClientConnected,
/// <summary>
/// This event is set on clients that are already connected to the session.
/// </summary>
/// <remarks>
/// The <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just connected.
/// </remarks>
PeerConnected,
/// <summary>
/// This event is set on the client-side of the client that disconnected client and on the server-side.
/// </summary>
/// <remarks>
/// On the disconnected client side, the <see cref="ConnectionEventData.ClientId"/> will be the <see cref="NetworkManager.LocalClientId"/>.<br />
/// On the server side, this will be the ID of the client that disconnected.
/// </remarks>
ClientDisconnected,
/// <summary>
/// This event is set on clients that are already connected to the session.
/// </summary>
/// <remarks>
/// The <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just disconnected.
/// </remarks>
PeerDisconnected
}
/// <summary>
/// Returned as a parameter of the <see cref="NetworkManager.OnConnectionEvent"/> event notification.
/// </summary>
/// <remarks>
/// See <see cref="ConnectionEvent"/> for more details on the types of connection events received.
/// </remarks>
public struct ConnectionEventData
{
public ConnectionEvent EventType;
@@ -563,7 +602,7 @@ namespace Unity.Netcode
{
var message = new ConnectionRequestMessage
{
CMBServiceConnection = NetworkManager.CMBServiceConnection,
DistributedAuthority = NetworkManager.DistributedAuthorityMode,
// Since only a remote client will send a connection request, we should always force the rebuilding of the NetworkConfig hash value
ConfigHash = NetworkManager.NetworkConfig.GetConfig(false),
ShouldSendConnectionData = NetworkManager.NetworkConfig.ConnectionApproval,
@@ -571,8 +610,9 @@ namespace Unity.Netcode
MessageVersions = new NativeArray<MessageVersionData>(MessageManager.MessageHandlers.Length, Allocator.Temp)
};
if (NetworkManager.CMBServiceConnection)
if (NetworkManager.DistributedAuthorityMode)
{
message.ClientConfig.SessionConfig = NetworkManager.SessionConfig;
message.ClientConfig.TickRate = NetworkManager.NetworkConfig.TickRate;
message.ClientConfig.EnableSceneManagement = NetworkManager.NetworkConfig.EnableSceneManagement;
}
@@ -1001,6 +1041,14 @@ namespace Unity.Netcode
}
var distributedAuthority = NetworkManager.DistributedAuthorityMode;
// If not using DA return early or if using DA and scene management is disabled then exit early Since we use NetworkShow to spawn
// objects on the newly connected client side.
if (!distributedAuthority || distributedAuthority && !NetworkManager.NetworkConfig.EnableSceneManagement)
{
return networkClient;
}
var sessionOwnerId = NetworkManager.CurrentSessionOwner;
var isSessionOwner = NetworkManager.LocalClient.IsSessionOwner;
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
@@ -1164,7 +1212,7 @@ namespace Unity.Netcode
{
// Only NetworkObjects that have the OwnershipStatus.Distributable flag set and no parent
// (ownership is transferred to all children) will have their ownership redistributed.
if (ownedObject.IsOwnershipDistributable && ownedObject.GetCachedParent() == null)
if (ownedObject.IsOwnershipDistributable && ownedObject.GetCachedParent() == null && !ownedObject.IsOwnershipSessionOwner)
{
if (ownedObject.IsOwnershipLocked)
{
@@ -1201,6 +1249,11 @@ namespace Unity.Netcode
childObject.SetOwnershipLock(false);
}
// Ignore session owner marked objects
if (childObject.IsOwnershipSessionOwner)
{
continue;
}
NetworkManager.SpawnManager.ChangeOwnership(childObject, targetOwner, true);
if (EnableDistributeLogging)
{

View File

@@ -826,7 +826,7 @@ namespace Unity.Netcode
internal void InternalOnGainedOwnership()
{
UpdateNetworkProperties();
// New owners need to assure any NetworkVariables they have write permissions
// New owners need to assure any NetworkVariables they have write permissions
// to are updated so the previous and original values are aligned with the
// current value (primarily for collections).
if (OwnerClientId == NetworkManager.LocalClientId)
@@ -1181,14 +1181,8 @@ namespace Unity.Netcode
{
// Create any values that require accessing the NetworkManager locally (it is expensive to access it in NetworkBehaviour)
var networkManager = NetworkManager;
var distributedAuthority = networkManager.DistributedAuthorityMode;
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
// Always write the NetworkVariable count even if zero for distributed authority (used by comb server)
if (distributedAuthority)
{
writer.WriteValueSafe((ushort)NetworkVariableFields.Count);
}
// Exit early if there are no NetworkVariables
if (NetworkVariableFields.Count == 0)
@@ -1203,14 +1197,8 @@ namespace Unity.Netcode
if (NetworkVariableFields[j].CanClientRead(targetClientId))
{
// Write additional NetworkVariable information when length safety is enabled or when in distributed authority mode
if (ensureLengthSafety || distributedAuthority)
if (ensureLengthSafety)
{
// Write the type being serialized for distributed authority (only for comb-server)
if (distributedAuthority)
{
writer.WriteValueSafe(NetworkVariableFields[j].Type);
}
var writePos = writer.Position;
// Note: This value can't be packed because we don't know how large it will be in advance
// we reserve space for it, then write the data, then come back and fill in the space
@@ -1261,20 +1249,8 @@ namespace Unity.Netcode
{
// Stack cache any values that requires accessing the NetworkManager (it is expensive to access it in NetworkBehaviour)
var networkManager = NetworkManager;
var distributedAuthority = networkManager.DistributedAuthorityMode;
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
// Always read the NetworkVariable count when in distributed authority (sanity check if comb-server matches what client has locally)
if (distributedAuthority)
{
reader.ReadValueSafe(out ushort variableCount);
if (variableCount != NetworkVariableFields.Count)
{
Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}] NetworkVariable count mismatch! (Read: {variableCount} vs. Expected: {NetworkVariableFields.Count})");
return;
}
}
// Exit early if nothing else to read
if (NetworkVariableFields.Count == 0)
{
@@ -1289,14 +1265,8 @@ namespace Unity.Netcode
// Distributed Authority: All clients have read permissions, always try to read the value
if (NetworkVariableFields[j].CanClientRead(clientId))
{
if (ensureLengthSafety || distributedAuthority)
if (ensureLengthSafety)
{
// Read the type being serialized and discard it (for now) when in a distributed authority network topology (only used by comb-server)
if (distributedAuthority)
{
reader.ReadValueSafe(out NetworkVariableType _);
}
reader.ReadValueSafe(out varSize);
if (varSize == 0)
{
@@ -1320,11 +1290,11 @@ namespace Unity.Netcode
continue;
}
// Read the NetworkVarible value
// Read the NetworkVariable value
NetworkVariableFields[j].ReadField(reader);
// When EnsureNetworkVariableLengthSafety or DistributedAuthorityMode always do a bounds check
if (ensureLengthSafety || distributedAuthority)
// When EnsureNetworkVariableLengthSafety always do a bounds check
if (ensureLengthSafety)
{
if (reader.Position > (readStartPos + varSize))
{

View File

@@ -141,6 +141,9 @@ namespace Unity.Netcode
// Then show any NetworkObjects queued to be made visible/shown
m_NetworkManager.SpawnManager.HandleNetworkObjectShow();
// Handle object redistribution (DA + disabled scene management only)
m_NetworkManager.HandleRedistributionToClients();
}
}
}

View File

@@ -80,6 +80,18 @@ namespace Unity.Netcode
}
#endif
internal SessionConfig SessionConfig;
/// <summary>
/// Used for internal testing purposes
/// </summary>
internal delegate SessionConfig OnGetSessionConfigHandler();
internal OnGetSessionConfigHandler OnGetSessionConfig;
private SessionConfig GetSessionConfig()
{
return OnGetSessionConfig != null ? OnGetSessionConfig.Invoke() : new SessionConfig();
}
internal static bool IsDistributedAuthority;
/// <summary>
@@ -162,10 +174,30 @@ namespace Unity.Netcode
}
}
// DANGO-TODO-MVP: Remove these properties once the service handles object distribution
internal ulong ClientToRedistribute;
internal bool RedistributeToClient;
internal int TickToRedistribute;
// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
internal List<ulong> ClientsToRedistribute = new List<ulong>();
internal bool RedistributeToClients;
/// <summary>
/// Handles object redistribution when scene management is disabled.
/// <see cref="NetworkBehaviourUpdater.NetworkBehaviourUpdater_Tick"/>
/// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
/// </summary>
internal void HandleRedistributionToClients()
{
if (!DistributedAuthorityMode || !RedistributeToClients || NetworkConfig.EnableSceneManagement || ShutdownInProgress)
{
return;
}
foreach (var clientId in ClientsToRedistribute)
{
SpawnManager.DistributeNetworkObjects(clientId);
}
RedistributeToClients = false;
ClientsToRedistribute.Clear();
}
internal List<NetworkObject> DeferredDespawnObjects = new List<NetworkObject>();
@@ -193,11 +225,7 @@ namespace Unity.Netcode
foreach (var networkObjectEntry in SpawnManager.SpawnedObjects)
{
var networkObject = networkObjectEntry.Value;
if (networkObject.IsSceneObject == null || !networkObject.IsSceneObject.Value)
{
continue;
}
if (networkObject.OwnerClientId != LocalClientId)
if (networkObject.IsOwnershipSessionOwner && LocalClient.IsSessionOwner)
{
SpawnManager.ChangeOwnership(networkObject, LocalClientId, true);
}
@@ -291,6 +319,10 @@ namespace Unity.Netcode
case NetworkUpdateStage.EarlyUpdate:
{
UpdateTopology();
// Handle processing any new connections or transport events
NetworkConfig.NetworkTransport.EarlyUpdate();
ConnectionManager.ProcessPendingApprovals();
ConnectionManager.PollAndHandleNetworkEvents();
@@ -298,6 +330,7 @@ namespace Unity.Netcode
AnticipationSystem.SetupForUpdate();
MessageManager.ProcessIncomingMessageQueue();
MessageManager.CleanupDisconnectedClients();
AnticipationSystem.ProcessReanticipation();
}
@@ -379,22 +412,15 @@ namespace Unity.Netcode
// Metrics update needs to be driven by NetworkConnectionManager's update to assure metrics are dispatched after the send queue is processed.
MetricsManager.UpdateMetrics();
// Handle sending any pending transport messages
NetworkConfig.NetworkTransport.PostLateUpdate();
// TODO: Determine a better way to handle this
NetworkObject.VerifyParentingStatus();
// This is "ok" to invoke when not processing messages since it is just cleaning up messages that never got handled within their timeout period.
DeferredMessageManager.CleanupStaleTriggers();
// DANGO-TODO-MVP: Remove this once the service handles object distribution
// NOTE: This needs to be the last thing done and should happen exactly at this point
// in the update
if (RedistributeToClient && ServerTime.Tick <= TickToRedistribute)
{
RedistributeToClient = false;
SpawnManager.DistributeNetworkObjects(ClientToRedistribute);
ClientToRedistribute = 0;
}
if (m_ShuttingDown)
{
// Host-server will disconnect any connected clients prior to finalizing its shutdown
@@ -925,6 +951,9 @@ namespace Unity.Netcode
return; // May occur when the component is added
}
// Do a validation pass on NetworkConfig properties
NetworkConfig.OnValidate();
if (GetComponentInChildren<NetworkObject>() != null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
@@ -993,8 +1022,7 @@ namespace Unity.Netcode
{
if (IsListening && change == PlayModeStateChange.ExitingPlayMode)
{
// Make sure we are not holding onto anything in case domain reload is disabled
ShutdownInternal();
OnApplicationQuit();
}
}
#endif
@@ -1161,6 +1189,12 @@ namespace Unity.Netcode
UpdateTopology();
// Always create a default session config when starting a NetworkManager instance
if (DistributedAuthorityMode)
{
SessionConfig = GetSessionConfig();
}
// Make sure the ServerShutdownState is reset when initializing
if (server)
{

View File

@@ -102,10 +102,22 @@ namespace Unity.Netcode
private const int k_SceneObjectType = 2;
private const int k_SourceAssetObjectType = 3;
// Used to track any InContext or InIsolation prefab being edited.
private static PrefabStage s_PrefabStage;
// The network prefab asset that the edit mode scene has created an instance of (s_PrefabInstance).
private static NetworkObject s_PrefabAsset;
// The InContext or InIsolation edit mode network prefab scene instance of the prefab asset (s_PrefabAsset).
private static NetworkObject s_PrefabInstance;
private static bool s_DebugPrefabIdGeneration;
[ContextMenu("Refresh In-Scene Prefab Instances")]
internal void RefreshAllPrefabInstances()
{
var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
// Assign the currently selected instance to be updated
NetworkObjectRefreshTool.PrefabNetworkObject = this;
if (!PrefabUtility.IsPartOfAnyPrefab(this) || instanceGlobalId.identifierType != k_ImportedAssetObjectType)
{
EditorUtility.DisplayDialog("Network Prefab Assets Only", "This action can only be performed on a network prefab asset.", "Ok");
@@ -132,25 +144,119 @@ namespace Unity.Netcode
NetworkObjectRefreshTool.ProcessScenes();
}
/// <summary>
/// Register for <see cref="PrefabStage"/> opened and closing event notifications.
/// </summary>
[InitializeOnLoadMethod]
private static void OnApplicationStart()
{
PrefabStage.prefabStageOpened -= PrefabStageOpened;
PrefabStage.prefabStageOpened += PrefabStageOpened;
PrefabStage.prefabStageClosing -= PrefabStageClosing;
PrefabStage.prefabStageClosing += PrefabStageClosing;
}
private static void PrefabStageClosing(PrefabStage prefabStage)
{
// If domain reloading is enabled, then this will be null when we return from playmode.
if (s_PrefabStage == null)
{
// Determine if we have a network prefab opened in edit mode or not.
CheckPrefabStage(prefabStage);
}
s_PrefabStage = null;
s_PrefabInstance = null;
s_PrefabAsset = null;
}
private static void PrefabStageOpened(PrefabStage prefabStage)
{
// Determine if we have a network prefab opened in edit mode or not.
CheckPrefabStage(prefabStage);
}
/// <summary>
/// Determines if we have opened a network prefab in edit mode (InContext or InIsolation)
/// </summary>
/// <remarks>
/// InContext: Typically means a are in prefab edit mode for an in-scene placed network prefab instance.
/// (currently no such thing as a network prefab with nested network prefab instances)
///
/// InIsolation: Typically means we are in prefb edit mode for a prefab asset.
/// </remarks>
/// <param name="prefabStage"></param>
private static void CheckPrefabStage(PrefabStage prefabStage)
{
s_PrefabStage = prefabStage;
s_PrefabInstance = prefabStage.prefabContentsRoot?.GetComponent<NetworkObject>();
if (s_PrefabInstance)
{
// We acquire the source prefab that the prefab edit mode scene instance was instantiated from differently for InContext than InSolation.
if (s_PrefabStage.mode == PrefabStage.Mode.InContext && s_PrefabStage.openedFromInstanceRoot != null)
{
// This is needed to handle the scenario where a user completely loads a new scene while in an InContext prefab edit mode.
try
{
s_PrefabAsset = s_PrefabStage.openedFromInstanceRoot?.GetComponent<NetworkObject>();
}
catch
{
s_PrefabAsset = null;
}
}
else
{
// When editing in InIsolation mode, load the original prefab asset from the provided path.
s_PrefabAsset = AssetDatabase.LoadAssetAtPath<NetworkObject>(s_PrefabStage.assetPath);
}
if (s_PrefabInstance.GlobalObjectIdHash != s_PrefabAsset.GlobalObjectIdHash)
{
s_PrefabInstance.GlobalObjectIdHash = s_PrefabAsset.GlobalObjectIdHash;
// For InContext mode, we don't want to record these modifications (the in-scene GlobalObjectIdHash is serialized with the scene).
if (s_PrefabStage.mode == PrefabStage.Mode.InIsolation)
{
PrefabUtility.RecordPrefabInstancePropertyModifications(s_PrefabAsset);
}
}
}
else
{
s_PrefabStage = null;
s_PrefabInstance = null;
s_PrefabAsset = null;
}
}
/// <summary>
/// GlobalObjectIdHash values are generated during validation.
/// </summary>
internal void OnValidate()
{
// do NOT regenerate GlobalObjectIdHash for NetworkPrefabs while Editor is in PlayMode
// Always exit early if we are in prefab edit mode and this instance is the
// prefab instance within the InContext or InIsolation edit scene.
if (s_PrefabInstance == this)
{
return;
}
// Do not regenerate GlobalObjectIdHash for NetworkPrefabs while Editor is in play mode.
if (EditorApplication.isPlaying && !string.IsNullOrEmpty(gameObject.scene.name))
{
return;
}
// do NOT regenerate GlobalObjectIdHash if Editor is transitioning into or out of PlayMode
// Do not regenerate GlobalObjectIdHash if Editor is transitioning into or out of play mode.
if (!EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
{
return;
}
// Get a global object identifier for this network prefab
var globalId = GetGlobalId();
// Get a global object identifier for this network prefab.
var globalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
// if the identifier type is 0, then don't update the GlobalObjectIdHash
// if the identifier type is 0, then don't update the GlobalObjectIdHash.
if (globalId.identifierType == k_NullObjectType)
{
return;
@@ -159,47 +265,34 @@ namespace Unity.Netcode
var oldValue = GlobalObjectIdHash;
GlobalObjectIdHash = globalId.ToString().Hash32();
// If the GlobalObjectIdHash value changed, then mark the asset dirty
// Always check for in-scene placed to assure any previous version scene assets with in-scene place NetworkObjects gets updated.
CheckForInScenePlaced();
// If the GlobalObjectIdHash value changed, then mark the asset dirty.
if (GlobalObjectIdHash != oldValue)
{
// Check if this is an in-scnee placed NetworkObject (Special Case for In-Scene Placed)
if (!IsEditingPrefab() && gameObject.scene.name != null && gameObject.scene.name != gameObject.name)
// Check if this is an in-scnee placed NetworkObject (Special Case for In-Scene Placed).
if (IsSceneObject.HasValue && IsSceneObject.Value)
{
// Sanity check to make sure this is a scene placed object
// Sanity check to make sure this is a scene placed object.
if (globalId.identifierType != k_SceneObjectType)
{
// This should never happen, but in the event it does throw and error
// This should never happen, but in the event it does throw and error.
Debug.LogError($"[{gameObject.name}] is detected as an in-scene placed object but its identifier is of type {globalId.identifierType}! **Report this error**");
}
// If this is a prefab instance
// If this is a prefab instance, then we want to mark it as having been updated in order for the udpated GlobalObjectIdHash value to be saved.
if (PrefabUtility.IsPartOfAnyPrefab(this))
{
// We must invoke this in order for the modifications to get saved with the scene (does not mark scene as dirty)
// We must invoke this in order for the modifications to get saved with the scene (does not mark scene as dirty).
PrefabUtility.RecordPrefabInstancePropertyModifications(this);
}
}
else // Otherwise, this is a standard network prefab asset so we just mark it dirty for the AssetDatabase to update it
else // Otherwise, this is a standard network prefab asset so we just mark it dirty for the AssetDatabase to update it.
{
EditorUtility.SetDirty(this);
}
}
// Always check for in-scene placed to assure any previous version scene assets with in-scene place NetworkObjects gets updated
CheckForInScenePlaced();
}
private bool IsEditingPrefab()
{
// Check if we are directly editing the prefab
var stage = PrefabStageUtility.GetPrefabStage(gameObject);
// if we are not editing the prefab directly (or a sub-prefab), then return the object identifier
if (stage == null || stage.assetPath == null)
{
return false;
}
return true;
}
/// <summary>
@@ -210,13 +303,12 @@ namespace Unity.Netcode
/// <remarks>
/// This NetworkObject is considered an in-scene placed prefab asset instance if it is:
/// - Part of a prefab
/// - Not being directly edited
/// - Within a valid scene that is part of the scenes in build list
/// (In-scene defined NetworkObjects that are not part of a prefab instance are excluded.)
/// </remarks>
private void CheckForInScenePlaced()
{
if (PrefabUtility.IsPartOfAnyPrefab(this) && !IsEditingPrefab() && gameObject.scene.IsValid() && gameObject.scene.isLoaded && gameObject.scene.buildIndex >= 0)
if (PrefabUtility.IsPartOfAnyPrefab(this) && gameObject.scene.IsValid() && gameObject.scene.isLoaded && gameObject.scene.buildIndex >= 0)
{
var prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
var assetPath = AssetDatabase.GetAssetPath(prefab);
@@ -229,55 +321,6 @@ namespace Unity.Netcode
IsSceneObject = true;
}
}
private GlobalObjectId GetGlobalId()
{
var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
// If not editing a prefab, then just use the generated id
if (!IsEditingPrefab())
{
return instanceGlobalId;
}
// If the asset doesn't exist at the given path, then return the object identifier
var prefabStageAssetPath = PrefabStageUtility.GetPrefabStage(gameObject).assetPath;
// If (for some reason) the asset path is null return the generated id
if (prefabStageAssetPath == null)
{
return instanceGlobalId;
}
var theAsset = AssetDatabase.LoadAssetAtPath<NetworkObject>(prefabStageAssetPath);
// If there is no asset at that path (for some odd/edge case reason), return the generated id
if (theAsset == null)
{
return instanceGlobalId;
}
// If we can't get the asset GUID and/or the file identifier, then return the object identifier
if (!AssetDatabase.TryGetGUIDAndLocalFileIdentifier(theAsset, out var guid, out long localFileId))
{
return instanceGlobalId;
}
// Note: If we reached this point, then we are most likely opening a prefab to edit.
// The instanceGlobalId will be constructed as if it is a scene object, however when it
// is serialized its value will be treated as a file asset (the "why" to the below code).
// Construct an imported asset identifier with the type being a source asset object type
var prefabGlobalIdText = string.Format(k_GlobalIdTemplate, k_SourceAssetObjectType, guid, (ulong)localFileId, 0);
// If we can't parse the result log an error and return the instanceGlobalId
if (!GlobalObjectId.TryParse(prefabGlobalIdText, out var prefabGlobalId))
{
Debug.LogError($"[GlobalObjectId Gen] Failed to parse ({prefabGlobalIdText}) returning default ({instanceGlobalId})! ** Please Report This Error **");
return instanceGlobalId;
}
// Otherwise, return the constructed identifier for the source prefab asset
return prefabGlobalId;
}
#endif // UNITY_EDITOR
/// <summary>
@@ -396,6 +439,13 @@ namespace Unity.Netcode
/// </remarks>
public bool IsOwnershipDistributable => Ownership.HasFlag(OwnershipStatus.Distributable);
/// <summary>
/// When true, the <see cref="NetworkObject"/> can only be owned by the current Session Owner.
/// To set <see cref="OwnershipStatus.SessionOwner"/> during runtime, use <see cref="ChangeOwnership(ulong)"/> to ensure the session owner owns the object.
/// Once the session owner owns the object, then use <see cref="SetOwnershipStatus(OwnershipStatus, bool, OwnershipLockActions)"/>.
/// </summary>
public bool IsOwnershipSessionOwner => Ownership.HasFlag(OwnershipStatus.SessionOwner);
/// <summary>
/// Returns true if the <see cref="NetworkObject"/> is has ownership locked.
/// When locked, the <see cref="NetworkObject"/> cannot be redistributed nor can it be transferred by another client.
@@ -438,7 +488,8 @@ namespace Unity.Netcode
/// <see cref="None"/>: If nothing is set, then ownership is considered "static" and cannot be redistributed, requested, or transferred (i.e. a Player would have this).
/// <see cref="Distributable"/>: When set, this instance will be automatically redistributed when a client joins (if not locked or no request is pending) or leaves.
/// <see cref="Transferable"/>: When set, a non-owner can obtain ownership immediately (without requesting and as long as it is not locked).
/// <see cref="RequestRequired"/>: When set, When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred).
/// <see cref="RequestRequired"/>: When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred).
/// <see cref="SessionOwner"/>: When set, only the current session owner may have ownership over this object.
/// </summary>
// Ranges from 1 to 8 bits
[Flags]
@@ -448,6 +499,7 @@ namespace Unity.Netcode
Distributable = 1 << 0,
Transferable = 1 << 1,
RequestRequired = 1 << 2,
SessionOwner = 1 << 3,
}
/// <summary>
@@ -506,7 +558,7 @@ namespace Unity.Netcode
}
// If we don't have the Transferable flag set and it is not a player object, then it is the same as having a static lock on ownership
if (!IsOwnershipTransferable && !IsPlayerObject)
if (!(IsOwnershipTransferable || IsPlayerObject) || IsOwnershipSessionOwner)
{
NetworkLog.LogWarning($"Trying to add or remove ownership lock on [{name}] which does not have the {nameof(OwnershipStatus.Transferable)} flag set!");
return false;
@@ -539,13 +591,15 @@ namespace Unity.Netcode
/// <see cref="RequestRequired"/>: The <see cref="NetworkObject"/> requires an ownership request via <see cref="RequestOwnership"/>.
/// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> is already processing an ownership request and ownership cannot be acquired at this time.
/// <see cref="NotTransferrable"/>: The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired.
/// <see cref="SessionOwnerOnly"/>: The <see cref="NetworkObject"/> has the <see cref="OwnershipStatus.SessionOwner"/> flag set and ownership cannot be acquired.
/// </summary>
public enum OwnershipPermissionsFailureStatus
{
Locked,
RequestRequired,
RequestInProgress,
NotTransferrable
NotTransferrable,
SessionOwnerOnly
}
/// <summary>
@@ -567,6 +621,7 @@ namespace Unity.Netcode
/// <see cref="RequestRequiredNotSet"/>: The <see cref="OwnershipStatus.RequestRequired"/> flag is not set on this <see cref="NetworkObject"/>
/// <see cref="Locked"/>: The current owner has locked ownership which means requests are not available at this time.
/// <see cref="RequestInProgress"/>: There is already a known request in progress. You can scan for ownership changes and try upon
/// <see cref="SessionOwnerOnly"/>: This object is marked as SessionOwnerOnly and therefore cannot be requested
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
/// </summary>
public enum OwnershipRequestStatus
@@ -576,6 +631,7 @@ namespace Unity.Netcode
RequestRequiredNotSet,
Locked,
RequestInProgress,
SessionOwnerOnly,
}
/// <summary>
@@ -588,6 +644,7 @@ namespace Unity.Netcode
/// <see cref="OwnershipRequestStatus.RequestRequiredNotSet"/>: The <see cref="OwnershipStatus.RequestRequired"/> flag is not set on this <see cref="NetworkObject"/>
/// <see cref="OwnershipRequestStatus.Locked"/>: The current owner has locked ownership which means requests are not available at this time.
/// <see cref="OwnershipRequestStatus.RequestInProgress"/>: There is already a known request in progress. You can scan for ownership changes and try upon
/// <see cref="OwnershipRequestStatus.SessionOwnerOnly"/>: This object can only belong the the session owner and so cannot be requested
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
/// </remarks>
/// <returns><see cref="OwnershipRequestStatus"/></returns>
@@ -617,6 +674,12 @@ namespace Unity.Netcode
return OwnershipRequestStatus.RequestInProgress;
}
// Exit early if it has the SessionOwner flag
if (IsOwnershipSessionOwner)
{
return OwnershipRequestStatus.SessionOwnerOnly;
}
// Otherwise, send the request ownership message
var changeOwnership = new ChangeOwnershipMessage
{
@@ -673,7 +736,7 @@ namespace Unity.Netcode
{
response = OwnershipRequestResponseStatus.RequestInProgress;
}
else if (!IsOwnershipRequestRequired && !IsOwnershipTransferable)
else if (!(IsOwnershipRequestRequired || IsOwnershipTransferable) || IsOwnershipSessionOwner)
{
response = OwnershipRequestResponseStatus.CannotRequest;
}
@@ -793,6 +856,12 @@ namespace Unity.Netcode
/// </remarks>
public bool SetOwnershipStatus(OwnershipStatus status, bool clearAndSet = false, OwnershipLockActions lockAction = OwnershipLockActions.None)
{
if (status.HasFlag(OwnershipStatus.SessionOwner) && !NetworkManager.LocalClient.IsSessionOwner)
{
NetworkLog.LogWarning("Only the session owner is allowed to set the ownership status to session owner only.");
return false;
}
// If it already has the flag do nothing
if (!clearAndSet && Ownership.HasFlag(status))
{
@@ -804,13 +873,25 @@ namespace Unity.Netcode
Ownership = OwnershipStatus.None;
}
// Faster to just OR a None status than to check
// if it is !None before "OR'ing".
Ownership |= status;
if (lockAction != OwnershipLockActions.None)
if (status.HasFlag(OwnershipStatus.SessionOwner))
{
SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock);
Ownership = OwnershipStatus.SessionOwner;
}
else if (Ownership.HasFlag(OwnershipStatus.SessionOwner))
{
NetworkLog.LogWarning("No other ownership statuses may be set while SessionOwner is set.");
return false;
}
else
{
// Faster to just OR a None status than to check
// if it is !None before "OR'ing".
Ownership |= status;
if (lockAction != OwnershipLockActions.None)
{
SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock);
}
}
SendOwnershipStatusUpdate();
@@ -1586,7 +1667,7 @@ namespace Unity.Netcode
// DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set
if (NetworkManager.LogLevel == LogLevel.Developer)
{
NetworkLog.LogWarning("DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set. For now, if the NetworkObject does not destroy with the owner it will automatically set DistributeOwnership.");
NetworkLog.LogWarning("DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set. For now, if the NetworkObject does not destroy with the owner it will set ownership to SessionOwner.");
}
}
}
@@ -1964,12 +2045,14 @@ namespace Unity.Netcode
internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true)
{
if (parent != null && (IsSpawned ^ parent.IsSpawned))
if (parent != null && (IsSpawned ^ parent.IsSpawned) && NetworkManager != null && !NetworkManager.ShutdownInProgress)
{
if (NetworkManager != null && !NetworkManager.ShutdownInProgress)
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
return false;
var nameOfNotSpawnedObject = IsSpawned ? $" the parent ({parent.name})" : $"the child ({name})";
NetworkLog.LogWarning($"Parenting failed because {nameOfNotSpawnedObject} is not spawned!");
}
return false;
}
m_CachedWorldPositionStays = worldPositionStays;
@@ -2892,7 +2975,7 @@ namespace Unity.Netcode
SyncObservers = syncObservers,
Observers = syncObservers ? Observers.ToArray() : null,
NetworkSceneHandle = NetworkSceneHandle,
Hash = HostCheckForGlobalObjectIdHashOverride(),
Hash = CheckForGlobalObjectIdHashOverride(),
OwnerObject = this,
TargetClientId = targetClientId
};
@@ -3244,14 +3327,15 @@ namespace Unity.Netcode
}
/// <summary>
/// Only applies to Host mode.
/// Client-Server: Only applies to spawn authority (i.e. Server)
/// Distributed Authority: Applies to all clients since they all have spawn authority.
/// Will return the registered source NetworkPrefab's GlobalObjectIdHash if one exists.
/// Server and Clients will always return the NetworkObject's GlobalObjectIdHash.
/// </summary>
/// <returns></returns>
internal uint HostCheckForGlobalObjectIdHashOverride()
/// <returns>appropriate hash value</returns>
internal uint CheckForGlobalObjectIdHashOverride()
{
if (NetworkManager.IsServer)
if (NetworkManager.IsServer || NetworkManager.DistributedAuthorityMode)
{
if (NetworkManager.PrefabHandler.ContainsHandler(this))
{

View File

@@ -11,7 +11,7 @@ using UnityEngine.SceneManagement;
namespace Unity.Netcode
{
/// <summary>
/// This is a helper tool to update all in-scene placed instances of a prefab that
/// This is a helper tool to update all in-scene placed instances of a prefab that
/// originally did not have a NetworkObject component but one was added to the prefab
/// later.
/// </summary>

View File

@@ -16,7 +16,7 @@ namespace Unity.Netcode
/// <summary>
/// Enum representing the different types of messages that can be sent over the network.
/// The values cannot be changed, as they are used to serialize and deserialize messages.
/// Adding new messages should be done by adding new values to the end of the enum
/// Adding new messages should be done by adding new values to the end of the enum
/// using the next free value.
/// </summary>
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

View File

@@ -17,7 +17,7 @@ namespace Unity.Netcode
/// <summary>
/// When requesting, RequestClientId is the requestor.
/// When approving, RequestClientId is the owner that approved.
/// When responding (only for denied), RequestClientId is the requestor
/// When responding (only for denied), RequestClientId is the requestor
/// </summary>
internal ulong RequestClientId;
internal int ClientIdCount;
@@ -272,7 +272,7 @@ namespace Unity.Netcode
networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, clientId);
}
}
// If the NetworkObject is not visible to the DAHost client, then exit early
// If the NetworkObject is not visible to the DAHost client, then exit early
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
{
return;
@@ -294,7 +294,7 @@ namespace Unity.Netcode
}
/// <summary>
/// Handle the
/// Handle the extended distributed authority ownership updates
/// </summary>
/// <param name="context"></param>
private void HandleExtendedOwnershipUpdate(ref NetworkContext context)
@@ -332,8 +332,8 @@ namespace Unity.Netcode
// Sanity check that we are not sending duplicated change ownership messages
if (networkObject.OwnerClientId == OwnerClientId)
{
UnityEngine.Debug.LogError($"Unnecessary ownership changed message for {NetworkObjectId}.");
// Ignore the message
// Log error and then ignore the message
UnityEngine.Debug.LogError($"Client-{context.SenderId} ({RequestClientId}) sent unnecessary ownership changed message for {NetworkObjectId}.");
return;
}
@@ -351,10 +351,10 @@ namespace Unity.Netcode
networkObject.InvokeBehaviourOnLostOwnership();
}
// If in distributed authority mode
// If in distributed authority mode
if (networkManager.DistributedAuthorityMode)
{
// Always update the network properties in distributed authority mode
// Always update the network properties in distributed authority mode
for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++)
{
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();

View File

@@ -55,19 +55,24 @@ namespace Unity.Netcode
// Don't redistribute for the local instance
if (ClientId != networkManager.LocalClientId)
{
// Synchronize the client with spawned objects (relative to each client)
networkManager.SpawnManager.SynchronizeObjectsToNewlyJoinedClient(ClientId);
// Keeping for reference in case the above doesn't resolve for hidden objects (theoretically it should)
// Show any NetworkObjects that are:
// - Hidden from the session owner
// - Owned by this client
// - Has NetworkObject.SpawnWithObservers set to true (the default)
if (!networkManager.LocalClient.IsSessionOwner)
{
networkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(ClientId);
}
//if (!networkManager.LocalClient.IsSessionOwner)
//{
// networkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(ClientId);
//}
// We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate
networkManager.RedistributeToClient = true;
networkManager.ClientToRedistribute = ClientId;
networkManager.TickToRedistribute = networkManager.ServerTime.Tick + 20;
/// We defer redistribution to happen after NetworkShow has been invoked
/// <see cref="NetworkBehaviourUpdater.NetworkBehaviourUpdater_Tick"/>
/// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
networkManager.RedistributeToClients = true;
networkManager.ClientsToRedistribute.Add(ClientId);
}
}
}

View File

@@ -5,23 +5,38 @@ namespace Unity.Netcode
{
internal struct ServiceConfig : INetworkSerializable
{
public uint Version;
public uint SessionVersion;
public bool IsRestoredSession;
public ulong CurrentSessionOwner;
public bool ServerRedistribution;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
if (serializer.IsWriter)
{
BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), Version);
BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), SessionVersion);
serializer.SerializeValue(ref IsRestoredSession);
BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), CurrentSessionOwner);
if (SessionVersion >= SessionConfig.ServerDistributionCompatible)
{
serializer.SerializeValue(ref ServerRedistribution);
}
}
else
{
ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out Version);
ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out SessionVersion);
serializer.SerializeValue(ref IsRestoredSession);
ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out CurrentSessionOwner);
if (SessionVersion >= SessionConfig.ServerDistributionCompatible)
{
serializer.SerializeValue(ref ServerRedistribution);
}
else
{
ServerRedistribution = false;
}
}
}
}
@@ -190,11 +205,13 @@ namespace Unity.Netcode
if (receivedMessageVersion >= k_AddCMBServiceConfig)
{
reader.ReadNetworkSerializable(out ServiceConfig);
networkManager.SessionConfig = new SessionConfig(ServiceConfig);
}
else
{
reader.ReadValueSafe(out IsRestoredSession);
ByteUnpacker.ReadValueBitPacked(reader, out CurrentSessionOwner);
networkManager.SessionConfig = new SessionConfig(SessionConfig.NoFeatureCompatibility);
}
}

View File

@@ -7,31 +7,28 @@ namespace Unity.Netcode
/// </summary>
internal struct ClientConfig : INetworkSerializable
{
/// <summary>
/// We start at version 1, where anything less than version 1 on the service side
/// is not bypass feature compatible.
/// </summary>
private const int k_BypassFeatureCompatible = 1;
public int Version => k_BypassFeatureCompatible;
public SessionConfig SessionConfig;
public int SessionVersion => (int)SessionConfig.SessionVersion;
public uint TickRate;
public bool EnableSceneManagement;
// Only gets deserialized but should never be used unless testing
public int RemoteClientVersion;
public int RemoteClientSessionVersion;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
// Clients always write
if (serializer.IsWriter)
{
var writer = serializer.GetFastBufferWriter();
BytePacker.WriteValueBitPacked(writer, Version);
BytePacker.WriteValueBitPacked(writer, SessionVersion);
BytePacker.WriteValueBitPacked(writer, TickRate);
writer.WriteValueSafe(EnableSceneManagement);
}
else
{
var reader = serializer.GetFastBufferReader();
ByteUnpacker.ReadValueBitPacked(reader, out RemoteClientVersion);
ByteUnpacker.ReadValueBitPacked(reader, out RemoteClientSessionVersion);
ByteUnpacker.ReadValueBitPacked(reader, out TickRate);
reader.ReadValueSafe(out EnableSceneManagement);
}
@@ -40,6 +37,8 @@ namespace Unity.Netcode
internal struct ConnectionRequestMessage : INetworkMessage
{
internal const string InvalidSessionVersionMessage = "The client version is not compatible with the session version.";
// This version update is unidirectional (client to service) and version
// handling occurs on the service side. This serialized data is never sent
// to a host or server.
@@ -47,7 +46,7 @@ namespace Unity.Netcode
public int Version => k_SendClientConfigToService;
public ulong ConfigHash;
public bool CMBServiceConnection;
public bool DistributedAuthority;
public ClientConfig ClientConfig;
public byte[] ConnectionData;
@@ -72,7 +71,7 @@ namespace Unity.Netcode
// END FORBIDDEN SEGMENT
// ============================================================
if (CMBServiceConnection)
if (DistributedAuthority)
{
writer.WriteNetworkSerializable(ClientConfig);
}
@@ -120,6 +119,11 @@ namespace Unity.Netcode
// END FORBIDDEN SEGMENT
// ============================================================
if (networkManager.DAHost)
{
reader.ReadNetworkSerializable(out ClientConfig);
}
if (networkManager.NetworkConfig.ConnectionApproval)
{
if (!reader.TryBeginRead(FastBufferWriter.GetWriteSize(ConfigHash) + FastBufferWriter.GetWriteSize<int>()))
@@ -182,6 +186,17 @@ namespace Unity.Netcode
var networkManager = (NetworkManager)context.SystemOwner;
var senderId = context.SenderId;
// DAHost mocking the service logic to disconnect clients trying to connect with a lower session version
if (networkManager.DAHost)
{
if (ClientConfig.RemoteClientSessionVersion < networkManager.SessionConfig.SessionVersion)
{
//Disconnect with reason
networkManager.ConnectionManager.DisconnectClient(senderId, InvalidSessionVersionMessage);
return;
}
}
if (networkManager.ConnectionManager.PendingClients.TryGetValue(senderId, out PendingClient client))
{
// Set to pending approval to prevent future connection requests from being approved

View File

@@ -257,7 +257,7 @@ namespace Unity.Netcode
{
// DA - NGO CMB SERVICE NOTES:
// (*** See above notes fist ***)
// If it is a player object freshly spawning and one or more clients all connect at the exact same time (i.e. received on effectively
// If it is a player object freshly spawning and one or more clients all connect at the exact same time (i.e. received on effectively
// the same frame), then we need to check the observers list to make sure all players are visible upon first spawning. At a later date,
// for area of interest we will need to have some form of follow up "observer update" message to cull out players not within each
// player's AOI.

View File

@@ -128,7 +128,7 @@ namespace Unity.Netcode
}
else if (networkManager.DAHost)
{
// Specific to distributed authority mode, the only sender of state updates will be the owner
// Specific to distributed authority mode, the only sender of state updates will be the owner
ownerClientId = context.SenderId;
}

View File

@@ -70,10 +70,6 @@ namespace Unity.Netcode
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.IsClient)
{
return false;
}
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
reader.ReadValueSafe(out m_BitField);

View File

@@ -141,28 +141,6 @@ namespace Unity.Netcode
{
RegisterMessageType(type);
}
#if UNITY_EDITOR
if (EnableMessageOrderConsoleLog)
{
// DANGO-TODO: Remove this when we have some form of message type indices stability in place
// For now, just log the messages and their assigned types for reference purposes.
var networkManager = m_Owner as NetworkManager;
if (networkManager != null)
{
if (networkManager.DistributedAuthorityMode)
{
var messageListing = new StringBuilder();
messageListing.AppendLine("NGO Message Index to Type Listing:");
foreach (var message in m_MessageTypes)
{
messageListing.AppendLine($"[{message.Value}][{message.Key.Name}]");
}
Debug.Log(messageListing);
}
}
}
#endif
}
catch (Exception)
{

View File

@@ -57,7 +57,7 @@ namespace Unity.Netcode
/// <para>Marks a method as ServerRpc.</para>
/// <para>A ServerRpc marked method will be fired by a client but executed on the server.</para>
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[AttributeUsage(AttributeTargets.Method), Obsolete]
public class ServerRpcAttribute : RpcAttribute
{
public new bool RequireOwnership;
@@ -72,7 +72,7 @@ namespace Unity.Netcode
/// <para>Marks a method as ClientRpc.</para>
/// <para>A ClientRpc marked method will be fired by the server but executed on clients.</para>
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
[AttributeUsage(AttributeTargets.Method), Obsolete]
public class ClientRpcAttribute : RpcAttribute
{
public ClientRpcAttribute() : base(SendTo.NotServer)

View File

@@ -17,7 +17,8 @@ namespace Unity.Netcode
// ClientsAndHost sends to everyone who runs any client logic
// So if the server is a host, this target includes it (as hosts run client logic)
// If the server is not a host, this target leaves it out, ergo the selection of NotServer.
if (behaviour.NetworkManager.ServerIsHost)
// If we are in distributed authority mode and connected to a service, then send to all clients.
if (behaviour.NetworkManager.ServerIsHost || (m_NetworkManager.DistributedAuthorityMode && m_NetworkManager.CMBServiceConnection))
{
m_UnderlyingTarget = behaviour.RpcTarget.Everyone;
}

View File

@@ -4,12 +4,14 @@ namespace Unity.Netcode
{
private IGroupRpcTarget m_GroupSendTarget;
private ServerRpcTarget m_ServerRpcTarget;
private NotAuthorityRpcTarget m_NotAuthorityRpcTarget;
private LocalSendRpcTarget m_LocalSendRpcTarget;
public override void Dispose()
{
m_ServerRpcTarget.Dispose();
m_LocalSendRpcTarget.Dispose();
m_NotAuthorityRpcTarget.Dispose();
if (m_GroupSendTarget != null)
{
m_GroupSendTarget.Target.Dispose();
@@ -19,6 +21,13 @@ namespace Unity.Netcode
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
{
// Not owner is the same as not authority in distributed authority mode
if (m_NetworkManager.DistributedAuthorityMode)
{
m_NotAuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
return;
}
if (m_GroupSendTarget == null)
{
if (behaviour.IsServer)
@@ -86,6 +95,7 @@ namespace Unity.Netcode
{
m_ServerRpcTarget = new ServerRpcTarget(manager);
m_LocalSendRpcTarget = new LocalSendRpcTarget(manager);
m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager);
}
}
}

View File

@@ -51,7 +51,13 @@ namespace Unity.Netcode
continue;
}
if (clientId == behaviour.NetworkManager.LocalClientId)
// If we are in distributed authority mode and connected to the service, then we exclude the owner/authority from the list
if (m_NetworkManager.DistributedAuthorityMode && m_NetworkManager.CMBServiceConnection && clientId == behaviour.OwnerClientId)
{
continue;
}
if (clientId == m_NetworkManager.LocalClientId)
{
m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
continue;

View File

@@ -5,9 +5,12 @@ namespace Unity.Netcode
private IIndividualRpcTarget m_UnderlyingTarget;
private LocalSendRpcTarget m_LocalRpcTarget;
private ServerRpcTarget m_ServerRpcTarget;
private AuthorityRpcTarget m_AuthorityRpcTarget;
public override void Dispose()
{
m_AuthorityRpcTarget.Dispose();
m_ServerRpcTarget.Dispose();
m_LocalRpcTarget.Dispose();
if (m_UnderlyingTarget != null)
{
@@ -18,6 +21,13 @@ namespace Unity.Netcode
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
{
// Sending to owner is the same as sending to authority in distributed authority mode
if (m_NetworkManager.DistributedAuthorityMode)
{
m_AuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
return;
}
if (behaviour.OwnerClientId == behaviour.NetworkManager.LocalClientId)
{
m_LocalRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
@@ -49,6 +59,7 @@ namespace Unity.Netcode
{
m_LocalRpcTarget = new LocalSendRpcTarget(manager);
m_ServerRpcTarget = new ServerRpcTarget(manager);
m_AuthorityRpcTarget = new AuthorityRpcTarget(manager);
}
}
}

View File

@@ -79,9 +79,28 @@ namespace Unity.Netcode
SpecifiedInParams
}
/// <summary>
/// This parameter configures a performance optimization. This optimization is not valid in all situations.<br />
/// Because BaseRpcTarget is a managed type, allocating a new one is expensive, as it puts pressure on the garbage collector.
/// </summary>
/// <remarks>
/// When using a <see cref="Temp"/> allocation type for the RPC target(s):<br />
/// You typically don't need to worry about persisting the <see cref="BaseRpcTarget"/> generated.
/// When using a <see cref="Persistent"/> allocation type for the RPC target(s): <br />
/// You will want to use <see cref="RpcTarget"/>, which returns <see cref="BaseRpcTarget"/>, during <see cref="NetworkBehaviour"/> initialization (i.e. <see cref="NetworkBehaviour.OnNetworkPostSpawn"/>) and it to a property.<br />
/// Then, When invoking the RPC, you would use your <see cref="BaseRpcTarget"/> which is a persisted allocation of a given set of client identifiers.
/// !! Important !!<br />
/// You will want to invoke <see cref="BaseRpcTarget.Dispose"/> of any persisted properties created via <see cref="RpcTarget"/> when despawning or destroying the associated <see cref="NetworkBehaviour"/> component's <see cref="NetworkObject"/>. Not doing so will result in small memory leaks.
/// </remarks>
public enum RpcTargetUse
{
/// <summary>
/// Creates a temporary <see cref="BaseRpcTarget"/> used for the frame an <see cref="RpcAttribute"/> decorated method is invoked.
/// </summary>
Temp,
/// <summary>
/// Creates a persisted <see cref="BaseRpcTarget"/> that does not change and will persist until <see cref="BaseRpcTarget.Dispose"/> is called.
/// </summary>
Persistent
}

View File

@@ -1,8 +1,10 @@
using Unity.Collections;
namespace Unity.Netcode
{
internal class ServerRpcTarget : BaseRpcTarget
{
protected BaseRpcTarget m_UnderlyingTarget;
protected ProxyRpcTarget m_ProxyRpcTarget;
public override void Dispose()
{
@@ -11,13 +13,62 @@ namespace Unity.Netcode
m_UnderlyingTarget.Dispose();
m_UnderlyingTarget = null;
}
if (m_ProxyRpcTarget != null)
{
m_ProxyRpcTarget.Dispose();
m_ProxyRpcTarget = null;
}
}
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
{
// For distributed authority the "server" is considered the authority of the object
if (behaviour.NetworkManager.DistributedAuthorityMode && behaviour.NetworkManager.CMBServiceConnection)
{
UnityEngine.Debug.LogWarning("[Invalid Target] There is no server to send to when in Distributed Authority mode!");
// If the local instance is the owner, then invoke the message locally on this behaviour
if (behaviour.IsOwner)
{
var context = new NetworkContext
{
SenderId = m_NetworkManager.LocalClientId,
Timestamp = m_NetworkManager.RealTimeProvider.RealTimeSinceStartup,
SystemOwner = m_NetworkManager,
// header information isn't valid since it's not a real message.
// RpcMessage doesn't access this stuff so it's just left empty.
Header = new NetworkMessageHeader(),
SerializedHeaderSize = 0,
MessageSize = 0
};
using var tempBuffer = new FastBufferReader(message.WriteBuffer, Allocator.None);
message.ReadBuffer = tempBuffer;
message.Handle(ref context);
// If enabled, then add the RPC metrics for this
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
int length = tempBuffer.Length;
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
{
m_NetworkManager.NetworkMetrics.TrackRpcSent(
m_NetworkManager.LocalClientId,
behaviour.NetworkObject,
rpcMethodName,
behaviour.__getTypeName(),
length);
}
#endif
}
else // Otherwise, send a proxied message to the owner of the object
{
if (m_ProxyRpcTarget == null)
{
m_ProxyRpcTarget = new ProxyRpcTarget(behaviour.OwnerClientId, m_NetworkManager);
}
else
{
m_ProxyRpcTarget.SetClientId(behaviour.OwnerClientId);
}
m_ProxyRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
}
return;
}

View File

@@ -24,7 +24,6 @@ namespace Unity.Netcode
/// The callback to be invoked when the list gets changed
/// </summary>
public event OnListChangedDelegate OnListChanged;
internal override NetworkVariableType Type => NetworkVariableType.NetworkList;
/// <summary>
/// Constructor method for <see cref="NetworkList"/>
@@ -50,6 +49,11 @@ namespace Unity.Netcode
}
}
~NetworkList()
{
Dispose();
}
/// <inheritdoc />
public override void ResetDirty()
{
@@ -131,20 +135,6 @@ namespace Unity.Netcode
/// <inheritdoc />
public override void WriteField(FastBufferWriter writer)
{
if (m_NetworkManager.DistributedAuthorityMode)
{
writer.WriteValueSafe(NetworkVariableSerialization<T>.Serializer.Type);
if (NetworkVariableSerialization<T>.Serializer.Type == NetworkVariableType.Unmanaged)
{
// Write the size of the unmanaged serialized type as it has a fixed size. This allows the CMB runtime to correctly read the unmanged type.
var placeholder = new T();
var startPos = writer.Position;
NetworkVariableSerialization<T>.Serializer.Write(writer, ref placeholder);
var size = writer.Position - startPos;
writer.Seek(startPos);
BytePacker.WriteValueBitPacked(writer, size);
}
}
writer.WriteValueSafe((ushort)m_List.Length);
for (int i = 0; i < m_List.Length; i++)
{
@@ -156,15 +146,6 @@ namespace Unity.Netcode
public override void ReadField(FastBufferReader reader)
{
m_List.Clear();
if (m_NetworkManager.DistributedAuthorityMode)
{
SerializationTools.ReadType(reader, NetworkVariableSerialization<T>.Serializer);
// Collection item type is used by the DA server, drop value here.
if (NetworkVariableSerialization<T>.Serializer.Type == NetworkVariableType.Unmanaged)
{
ByteUnpacker.ReadValueBitPacked(reader, out int _);
}
}
reader.ReadValueSafe(out ushort count);
for (int i = 0; i < count; i++)
{
@@ -624,8 +605,16 @@ namespace Unity.Netcode
/// </summary>
public override void Dispose()
{
m_List.Dispose();
m_DirtyEvents.Dispose();
if (m_List.IsCreated)
{
m_List.Dispose();
}
if (m_DirtyEvents.IsCreated)
{
m_DirtyEvents.Dispose();
}
base.Dispose();
}
}

View File

@@ -45,8 +45,6 @@ namespace Unity.Netcode
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
}
internal override NetworkVariableType Type => NetworkVariableType.Value;
/// <summary>
/// Constructor for <see cref="NetworkVariable{T}"/>
/// </summary>
@@ -92,7 +90,7 @@ namespace Unity.Netcode
// The introduction of standard .NET collections caused an issue with permissions since there is no way to detect changes in the
// collection without doing a full comparison. While this approach does consume more memory per collection instance, it is the
// lowest risk approach to resolving the issue where a client with no write permissions could make changes to a collection locally
// which can cause a myriad of issues.
// which can cause a myriad of issues.
private protected T m_InternalOriginalValue;
private protected T m_PreviousValue;
@@ -181,19 +179,26 @@ namespace Unity.Netcode
}
m_IsDisposed = true;
// Dispose the internal value
if (m_InternalValue is IDisposable internalValueDisposable)
{
internalValueDisposable.Dispose();
}
m_InternalValue = default;
// Dispose the internal original value
if (m_InternalOriginalValue is IDisposable internalOriginalValueDisposable)
{
internalOriginalValueDisposable.Dispose();
}
m_InternalOriginalValue = default;
// Dispose the previous value if there is one
if (m_HasPreviousValue && m_PreviousValue is IDisposable previousValueDisposable)
{
m_HasPreviousValue = false;
previousValueDisposable.Dispose();
}
m_PreviousValue = default;
base.Dispose();
@@ -298,7 +303,7 @@ namespace Unity.Netcode
/// This should be always invoked (client & server) to assure the previous values are set
/// !! IMPORTANT !!
/// When a server forwards delta updates to connected clients, it needs to preserve the previous dirty value(s)
/// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked
/// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked
/// after it is done forwarding the deltas at the end of the <see cref="NetworkVariableDeltaMessage.Handle(ref NetworkContext)"/> method.
/// </summary>
internal override void PostDeltaRead()

View File

@@ -35,8 +35,6 @@ namespace Unity.Netcode
private NetworkManager m_InternalNetworkManager;
internal virtual NetworkVariableType Type => NetworkVariableType.Unknown;
internal string GetWritePermissionError()
{
return $"|Client-{m_NetworkManager.LocalClientId}|{m_NetworkBehaviour.name}|{Name}| Write permissions ({WritePerm}) for this client instance is not allowed!";
@@ -351,7 +349,7 @@ namespace Unity.Netcode
/// This should be always invoked (client & server) to assure the previous values are set
/// !! IMPORTANT !!
/// When a server forwards delta updates to connected clients, it needs to preserve the previous dirty value(s)
/// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked
/// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked
/// after it is done forwarding the deltas at the end of the <see cref="NetworkVariableDeltaMessage.Handle(ref NetworkContext)"/> method.
/// </summary>
internal virtual void PostDeltaRead()

View File

@@ -1,40 +0,0 @@
#if UNITY_EDITOR
#endif
namespace Unity.Netcode
{
/// <summary>
/// Enum representing the different types of Network Variables that can be sent over the network.
/// The values cannot be changed, as they are used to serialize and deserialize variables on the DA server.
/// Adding new variables should be done by adding new values to the end of the enum
/// using the next free value.
/// </summary>
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// Add any new Variable types to this table at the END with incremented index value
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal enum NetworkVariableType : byte
{
/// <summary>
/// Value
/// Used for all of the basic NetworkVariables that contain a single value
/// </summary>
Value = 0,
/// <summary>
/// For any type that is not known at runtime
/// </summary>
Unknown = 1,
/// <summary>
/// NetworkList
/// </summary>
NetworkList = 2,
// The following types are valid types inside of NetworkVariable collections
Short = 11,
UShort = 12,
Int = 13,
UInt = 14,
Long = 15,
ULong = 16,
Unmanaged = 17,
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: df4a4005f1c842669f94a404019400ed
timeCreated: 1718292058

View File

@@ -14,9 +14,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
{
public NetworkVariableType Type => NetworkVariableType.Unknown;
public bool IsDistributedAuthorityOptimized => true;
private void ThrowArgumentError()
{
throw new ArgumentException($"Serialization has not been generated for type {typeof(T).FullName}. This can be addressed by adding a [{nameof(GenerateSerializationForGenericParameterAttribute)}] to your generic class that serializes this value (if you are using one), adding [{nameof(GenerateSerializationForTypeAttribute)}(typeof({typeof(T).FullName})] to the class or method that is attempting to serialize it, or creating a field on a {nameof(NetworkBehaviour)} of type {nameof(NetworkVariable<T>)}. If this error continues to appear after doing one of those things and this is a type you can change, then either implement {nameof(INetworkSerializable)} or mark it as serializable by memcpy by adding {nameof(INetworkSerializeByMemcpy)} to its interface list to enable automatic serialization generation. If not, assign serialization code to {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.WriteValue)}, {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.ReadValue)}, and {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.DuplicateValue)}, or if it's serializable by memcpy (contains no pointers), wrap it in {typeof(ForceNetworkSerializeByMemcpy<>).Name}.");
@@ -82,11 +79,6 @@ namespace Unity.Netcode
}
UserNetworkVariableSerialization<T>.DuplicateValue(value, ref duplicatedValue);
}
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value) => ThrowArgumentError();
public void ReadDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError();
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => ThrowArgumentError();
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError();
}
// RuntimeAccessModifiersILPP will make this `public`

View File

@@ -2,28 +2,8 @@ using Unity.Collections;
namespace Unity.Netcode
{
/// <summary>
/// Interface used by NetworkVariables to serialize them with additional information for the DA runtime
/// </summary>
///
/// <typeparam name="T"></typeparam>
internal interface IDistributedAuthoritySerializer<T>
{
/// <summary>
/// The Type tells the DA server how to parse this type.
/// The user should never be able to override this value, as it is meaningful for the DA server
/// </summary>
public NetworkVariableType Type { get; }
public bool IsDistributedAuthorityOptimized { get; }
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value);
public void ReadDistributedAuthority(FastBufferReader reader, ref T value);
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value);
}
/// <typeparam name="T"></typeparam>
internal interface INetworkVariableSerializer<T> : IDistributedAuthoritySerializer<T>
internal interface INetworkVariableSerializer<T>
{
// Write has to be taken by ref here because of INetworkSerializable
// Open Instance Delegates (pointers to methods without an instance attached to them)

View File

@@ -14,8 +14,6 @@ namespace Unity.Netcode
{
internal static INetworkVariableSerializer<T> Serializer = new FallbackSerializer<T>();
internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority;
/// <summary>
/// A callback to check if two values are equal.
/// </summary>
@@ -53,20 +51,7 @@ namespace Unity.Netcode
/// <param name="value"></param>
public static void Write(FastBufferWriter writer, ref T value)
{
if (IsDistributedAuthority)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized)
{
NetworkManager.LogSerializedTypeNotOptimized<T>();
}
#endif
Serializer.WriteDistributedAuthority(writer, ref value);
}
else
{
Serializer.Write(writer, ref value);
}
Serializer.Write(writer, ref value);
}
/// <summary>
@@ -91,14 +76,7 @@ namespace Unity.Netcode
/// <param name="value"></param>
public static void Read(FastBufferReader reader, ref T value)
{
if (IsDistributedAuthority)
{
Serializer.ReadDistributedAuthority(reader, ref value);
}
else
{
Serializer.Read(reader, ref value);
}
Serializer.Read(reader, ref value);
}
/// <summary>
@@ -120,20 +98,7 @@ namespace Unity.Netcode
/// <param name="value"></param>
public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
{
if (IsDistributedAuthority)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized)
{
NetworkManager.LogSerializedTypeNotOptimized<T>();
}
#endif
Serializer.WriteDeltaDistributedAuthority(writer, ref value, ref previousValue);
}
else
{
Serializer.WriteDelta(writer, ref value, ref previousValue);
}
Serializer.WriteDelta(writer, ref value, ref previousValue);
}
/// <summary>
@@ -158,14 +123,7 @@ namespace Unity.Netcode
/// <param name="value"></param>
public static void ReadDelta(FastBufferReader reader, ref T value)
{
if (IsDistributedAuthority)
{
Serializer.ReadDeltaDistributedAuthority(reader, ref value);
}
else
{
Serializer.ReadDelta(reader, ref value);
}
Serializer.ReadDelta(reader, ref value);
}
/// <summary>

View File

@@ -10,21 +10,6 @@ namespace Unity.Netcode
/// </summary>
internal class ShortSerializer : INetworkVariableSerializer<short>
{
public NetworkVariableType Type => NetworkVariableType.Short;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref short value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref short value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref short value, ref short previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref short value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref short value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -61,20 +46,6 @@ namespace Unity.Netcode
/// </summary>
internal class UshortSerializer : INetworkVariableSerializer<ushort>
{
public NetworkVariableType Type => NetworkVariableType.UShort;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref ushort value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref ushort value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref ushort value, ref ushort previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref ushort value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref ushort value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -111,20 +82,6 @@ namespace Unity.Netcode
/// </summary>
internal class IntSerializer : INetworkVariableSerializer<int>
{
public NetworkVariableType Type => NetworkVariableType.Int;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref int value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref int value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref int value, ref int previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref int value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref int value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -161,20 +118,6 @@ namespace Unity.Netcode
/// </summary>
internal class UintSerializer : INetworkVariableSerializer<uint>
{
public NetworkVariableType Type => NetworkVariableType.UInt;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref uint value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref uint value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref uint value, ref uint previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref uint value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref uint value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -211,20 +154,6 @@ namespace Unity.Netcode
/// </summary>
internal class LongSerializer : INetworkVariableSerializer<long>
{
public NetworkVariableType Type => NetworkVariableType.Long;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref long value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref long value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref long value, ref long previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref long value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref long value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -261,21 +190,6 @@ namespace Unity.Netcode
/// </summary>
internal class UlongSerializer : INetworkVariableSerializer<ulong>
{
public NetworkVariableType Type => NetworkVariableType.ULong;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref ulong value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref ulong value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref ulong value, ref ulong previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref ulong value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref ulong value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -317,21 +231,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedTypeSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Unmanaged;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref T value)
{
writer.WriteUnmanagedSafe(value);
@@ -365,20 +264,6 @@ namespace Unity.Netcode
internal class ListSerializer<T> : INetworkVariableSerializer<List<T>>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref List<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref List<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref List<T> value, ref List<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref List<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref List<T> value)
{
var isNull = value == null;
@@ -468,20 +353,6 @@ namespace Unity.Netcode
internal class HashSetSerializer<T> : INetworkVariableSerializer<HashSet<T>> where T : IEquatable<T>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref HashSet<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref HashSet<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref HashSet<T> value, ref HashSet<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref HashSet<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref HashSet<T> value)
{
var isNull = value == null;
@@ -563,20 +434,6 @@ namespace Unity.Netcode
internal class DictionarySerializer<TKey, TVal> : INetworkVariableSerializer<Dictionary<TKey, TVal>>
where TKey : IEquatable<TKey>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref Dictionary<TKey, TVal> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref Dictionary<TKey, TVal> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref Dictionary<TKey, TVal> value, ref Dictionary<TKey, TVal> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref Dictionary<TKey, TVal> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref Dictionary<TKey, TVal> value)
{
var isNull = value == null;
@@ -659,20 +516,6 @@ namespace Unity.Netcode
internal class UnmanagedArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
{
writer.WriteUnmanagedSafe(value);
@@ -718,20 +561,6 @@ namespace Unity.Netcode
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
internal class UnmanagedListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeList<T> value)
{
writer.WriteUnmanagedSafe(value);
@@ -775,21 +604,6 @@ namespace Unity.Netcode
internal class NativeHashSetSerializer<T> : INetworkVariableSerializer<NativeHashSet<T>> where T : unmanaged, IEquatable<T>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashSet<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashSet<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashSet<T> value, ref NativeHashSet<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashSet<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeHashSet<T> value)
{
writer.WriteValueSafe(value);
@@ -835,21 +649,6 @@ namespace Unity.Netcode
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashMap<TKey, TVal> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value, ref NativeHashMap<TKey, TVal> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashMap<TKey, TVal> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value)
{
writer.WriteValueSafe(value);
@@ -897,21 +696,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FixedStringSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref T value)
{
writer.WriteValueSafe(value);
@@ -1019,20 +803,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FixedStringArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
{
writer.WriteValueSafe(value);
@@ -1083,21 +853,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FixedStringListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeList<T> value)
{
writer.WriteValueSafe(value);
@@ -1145,21 +900,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged, INetworkSerializable
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref T value)
{
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));
@@ -1212,20 +952,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedNetworkSerializableArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INetworkSerializable
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
{
writer.WriteNetworkSerializable(value);
@@ -1276,21 +1002,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedNetworkSerializableListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INetworkSerializable
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeList<T> value)
{
writer.WriteNetworkSerializable(value);
@@ -1338,20 +1049,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class ManagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> where T : class, INetworkSerializable, new()
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref T value)
{
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));

View File

@@ -1,54 +0,0 @@
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace Unity.Netcode
{
internal static class SerializationTools
{
public delegate void WriteDelegate<T>(FastBufferWriter writer, ref T value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteWithSize<T>(WriteDelegate<T> writeMethod, FastBufferWriter writer, ref T value)
{
var writePos = writer.Position;
// Note: This value can't be packed because we don't know how large it will be in advance
// we reserve space for it, then write the data, then come back and fill in the space
// to pack here, we'd have to write data to a temporary buffer and copy it in - which
// isn't worth possibly saving one byte if and only if the data is less than 63 bytes long...
// The way we do packing, any value > 63 in a ushort will use the full 2 bytes to represent.
writer.WriteValueSafe((ushort)0);
var startPos = writer.Position;
writeMethod(writer, ref value);
var size = writer.Position - startPos;
writer.Seek(writePos);
writer.WriteValueSafe((ushort)size);
writer.Seek(startPos + size);
}
public delegate void ReadDelegate<T>(FastBufferReader writer, ref T value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ReadWithSize<T>(ReadDelegate<T> readMethod, FastBufferReader reader, ref T value)
{
reader.ReadValueSafe(out ushort _);
readMethod(reader, ref value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteType(FastBufferWriter writer, NetworkVariableType type) => writer.WriteValueSafe(type);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ReadType<T>(FastBufferReader reader, INetworkVariableSerializer<T> serializer)
{
reader.ReadValueSafe(out NetworkVariableType type);
if (type != serializer.Type)
{
throw new SerializationException();
}
}
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 52a4ce368df54b0a8887c08f3402bcd3
timeCreated: 1718300602

View File

@@ -1081,14 +1081,19 @@ namespace Unity.Netcode
}
else
{
var message = new SceneEventMessage
// Send to each individual client to assure only the in-scene placed NetworkObjects being observed by the client
// is serialized
foreach (var clientId in targetClientIds)
{
EventData = sceneEvent,
};
var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, targetClientIds);
NetworkManager.NetworkMetrics.TrackSceneEventSent(targetClientIds, (uint)SceneEventDataStore[sceneEventId].SceneEventType, SceneNameFromHash(SceneEventDataStore[sceneEventId].SceneHash), size);
sceneEvent.TargetClientId = clientId;
var message = new SceneEventMessage
{
EventData = sceneEvent,
};
var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, clientId);
NetworkManager.NetworkMetrics.TrackSceneEventSent(clientId, (uint)sceneEvent.SceneEventType, SceneNameFromHash(sceneEvent.SceneHash), size);
}
}
}
/// <summary>
@@ -1898,10 +1903,12 @@ namespace Unity.Netcode
SendSceneEventData(sceneEventData.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != sessionOwner).ToArray());
m_IsSceneEventActive = false;
sceneEventData.SceneEventType = SceneEventType.LoadComplete;
//First, notify local server that the scene was loaded
OnSceneEvent?.Invoke(new SceneEvent()
{
SceneEventType = SceneEventType.LoadComplete,
SceneEventType = sceneEventData.SceneEventType,
LoadSceneMode = sceneEventData.LoadSceneMode,
SceneName = SceneNameFromHash(sceneEventData.SceneHash),
ClientId = NetworkManager.LocalClientId,

View File

@@ -62,7 +62,7 @@ namespace Unity.Netcode
/// When you know you will be writing multiple fields back-to-back and you know the total size,
/// you can call TryBeginWriteBits() once on the total size, and then follow it with calls to
/// WriteBit() or WriteBits().
///
///
/// Bitwise write operations will throw OverflowException in editor and development builds if you
/// go past the point you've marked using TryBeginWriteBits(). In release builds, OverflowException will not be thrown
/// for performance reasons, since the point of using TryBeginWrite is to avoid bounds checking in the following

View File

@@ -88,6 +88,13 @@ namespace Unity.Netcode
}
}
// Only if spawn with observers is set or we are using a distributed authority network topology and this is the client's player should we add
// the owner as an observer.
if (playerObject.SpawnWithObservers || (NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClientId == playerObject.OwnerClientId))
{
playerObject.Observers.Add(playerObject.OwnerClientId);
}
m_PlayerObjects.Add(playerObject);
if (!m_PlayerObjectsTable.ContainsKey(playerObject.OwnerClientId))
{
@@ -110,8 +117,9 @@ namespace Unity.Netcode
if (playerNetworkClient.PlayerObject != null && m_PlayerObjects.Contains(playerNetworkClient.PlayerObject))
{
// Just remove the previous player object but keep the assigned observers of the NetworkObject
RemovePlayerObject(playerNetworkClient.PlayerObject, true);
RemovePlayerObject(playerNetworkClient.PlayerObject);
}
// Now update the associated NetworkClient's player object
NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].AssignPlayerObject(ref playerObject);
AddPlayerObject(playerObject);
@@ -120,7 +128,7 @@ namespace Unity.Netcode
/// <summary>
/// Removes a player object and updates all other players' observers list
/// </summary>
private void RemovePlayerObject(NetworkObject playerObject, bool keepObservers = false)
private void RemovePlayerObject(NetworkObject playerObject, bool destroyingObject = false)
{
if (!playerObject.IsPlayerObject)
{
@@ -141,16 +149,21 @@ namespace Unity.Netcode
}
}
// If we want to keep the observers, then exit early
if (keepObservers)
if (NetworkManager.ConnectionManager.ConnectedClients.ContainsKey(playerObject.OwnerClientId) && destroyingObject)
{
return;
NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].PlayerObject = null;
}
foreach (var player in m_PlayerObjects)
{
player.Observers.Remove(playerObject.OwnerClientId);
}
// If we want to keep the observers, then exit early
//if (keepObservers)
//{
// return;
//}
//foreach (var player in m_PlayerObjects)
//{
// player.Observers.Remove(playerObject.OwnerClientId);
//}
}
internal void MarkObjectForShowingTo(NetworkObject networkObject, ulong clientId)
@@ -409,27 +422,8 @@ namespace Unity.Netcode
{
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress)
{
if (networkObject.IsOwnershipDistributable || networkObject.IsOwnershipTransferable)
{
if (networkObject.IsOwner || NetworkManager.DAHost)
{
NetworkLog.LogWarning("DANGO-TODO: Determine if removing ownership should make the CMB Service redistribute ownership or if this just isn't a valid thing in DAMode.");
return;
}
else
{
NetworkLog.LogError($"Only the owner is allowed to remove ownership in distributed authority mode!");
return;
}
}
else
{
if (!NetworkManager.DAHost)
{
Debug.LogError($"Only {nameof(NetworkObject)}s with {nameof(NetworkObject.IsOwnershipDistributable)} or {nameof(NetworkObject.IsOwnershipTransferable)} set can perform ownership changes!");
}
return;
}
Debug.LogError($"Removing ownership is invalid in Distributed Authority Mode. Use {nameof(ChangeOwnership)} instead.");
return;
}
ChangeOwnership(networkObject, NetworkManager.ServerClientId, true);
}
@@ -461,6 +455,18 @@ namespace Unity.Netcode
if (NetworkManager.DistributedAuthorityMode)
{
// Ensure only the session owner can change ownership (i.e. acquire) and that the session owner is not trying to assign a non-session owner client
// ownership of a NetworkObject with SessionOwner permissions.
if (networkObject.IsOwnershipSessionOwner && (!NetworkManager.LocalClient.IsSessionOwner || clientId != NetworkManager.CurrentSessionOwner))
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
NetworkLog.LogErrorServer($"[{networkObject.name}][Session Owner Only] You cannot change ownership of a {nameof(NetworkObject)} that has the {NetworkObject.OwnershipStatus.SessionOwner} flag set!");
}
networkObject.OnOwnershipPermissionsFailure?.Invoke(NetworkObject.OwnershipPermissionsFailureStatus.SessionOwnerOnly);
return;
}
// If are not authorized and this is not an approved ownership change, then check to see if we can change ownership
if (!isAuthorized && !isRequestApproval)
{
@@ -567,7 +573,6 @@ namespace Unity.Netcode
{
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();
}
size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, NetworkManager.ServerClientId);
NetworkManager.NetworkMetrics.TrackOwnershipChangeSent(NetworkManager.LocalClientId, networkObject, size);
}
@@ -724,12 +729,20 @@ namespace Unity.Netcode
internal NetworkObject InstantiateAndSpawnNoParameterChecks(NetworkObject networkPrefab, ulong ownerClientId = NetworkManager.ServerClientId, bool destroyWithScene = false, bool isPlayerObject = false, bool forceOverride = false, Vector3 position = default, Quaternion rotation = default)
{
var networkObject = networkPrefab;
// Host spawns the ovveride and server spawns the original prefab unless forceOverride is set to true where both server or host will spawn the override.
// In distributed authority mode, we alaways get the override
if (forceOverride || NetworkManager.IsHost || NetworkManager.DistributedAuthorityMode)
// - Host and clients always instantiate the override if one exists.
// - Server instantiates the original prefab unless:
// -- forceOverride is set to true =or=
// -- The prefab has a registered prefab handler, then we let user code determine what to spawn.
// - Distributed authority mode always spawns the override if one exists.
if (forceOverride || NetworkManager.IsClient || NetworkManager.DistributedAuthorityMode || NetworkManager.PrefabHandler.ContainsHandler(networkPrefab.GlobalObjectIdHash))
{
networkObject = GetNetworkObjectToSpawn(networkPrefab.GlobalObjectIdHash, ownerClientId, position, rotation);
}
else // Under this case, server instantiate the prefab passed in.
{
networkObject = InstantiateNetworkPrefab(networkPrefab.gameObject, networkPrefab.GlobalObjectIdHash, position, rotation);
}
if (networkObject == null)
{
Debug.LogError($"Failed to instantiate and spawn {networkPrefab.name}!");
@@ -738,12 +751,20 @@ namespace Unity.Netcode
networkObject.IsPlayerObject = isPlayerObject;
networkObject.transform.position = position;
networkObject.transform.rotation = rotation;
networkObject.SpawnWithOwnership(ownerClientId, destroyWithScene);
// If spawning as a player, then invoke SpawnAsPlayerObject
if (isPlayerObject)
{
networkObject.SpawnAsPlayerObject(ownerClientId, destroyWithScene);
}
else // Otherwise just spawn with ownership
{
networkObject.SpawnWithOwnership(ownerClientId, destroyWithScene);
}
return networkObject;
}
/// <summary>
/// Gets the right NetworkObject prefab instance to spawn. If a handler is registered or there is an override assigned to the
/// Gets the right NetworkObject prefab instance to spawn. If a handler is registered or there is an override assigned to the
/// passed in globalObjectIdHash value, then that is what will be instantiated, spawned, and returned.
/// </summary>
internal NetworkObject GetNetworkObjectToSpawn(uint globalObjectIdHash, ulong ownerId, Vector3? position, Quaternion? rotation, bool isScenePlaced = false)
@@ -775,8 +796,8 @@ namespace Unity.Netcode
case NetworkPrefabOverride.Hash:
case NetworkPrefabOverride.Prefab:
{
// When scene management is disabled and this is an in-scene placed NetworkObject, we want to always use the
// SourcePrefabToOverride and not any possible prefab override as a user might want to spawn overrides dynamically
// When scene management is disabled and this is an in-scene placed NetworkObject, we want to always use the
// SourcePrefabToOverride and not any possible prefab override as a user might want to spawn overrides dynamically
// but might want to use the same source network prefab as an in-scene placed NetworkObject.
// (When scene management is enabled, clients don't delete their in-scene placed NetworkObjects prior to dynamically
// spawning them so the original prefab placed is preserved and this is not needed)
@@ -804,16 +825,37 @@ namespace Unity.Netcode
else
{
// Create prefab instance while applying any pre-assigned position and rotation values
networkObject = UnityEngine.Object.Instantiate(networkPrefabReference).GetComponent<NetworkObject>();
networkObject.transform.position = position ?? networkObject.transform.position;
networkObject.transform.rotation = rotation ?? networkObject.transform.rotation;
networkObject.NetworkManagerOwner = NetworkManager;
networkObject.PrefabGlobalObjectIdHash = globalObjectIdHash;
networkObject = InstantiateNetworkPrefab(networkPrefabReference, globalObjectIdHash, position, rotation);
}
}
return networkObject;
}
/// <summary>
/// Instantiates a network prefab instance, assigns the base prefab <see cref="NetworkObject.GlobalObjectIdHash"/>, positions, and orients
/// the instance.
/// !!! Should only be invoked by <see cref="GetNetworkObjectToSpawn"/> unless used by an integration test !!!
/// </summary>
/// <remarks>
/// <param name="prefabGlobalObjectIdHash"> should be the base prefab <see cref="NetworkObject.GlobalObjectIdHash"/> value and not the
/// overrided value.
/// (Can be used for integration testing)
/// </remarks>
/// <param name="networkPrefab">prefab to instantiate</param>
/// <param name="prefabGlobalObjectIdHash"><see cref="NetworkObject.GlobalObjectIdHash"/> of the base prefab instance</param>
/// <param name="position">conditional position in place of the network prefab's default position</param>
/// <param name="rotation">conditional rotation in place of the network prefab's default rotation</param>
/// <returns>the instance of the <see cref="NetworkObject"/></returns>
internal NetworkObject InstantiateNetworkPrefab(GameObject networkPrefab, uint prefabGlobalObjectIdHash, Vector3? position, Quaternion? rotation)
{
var networkObject = UnityEngine.Object.Instantiate(networkPrefab).GetComponent<NetworkObject>();
networkObject.transform.position = position ?? networkObject.transform.position;
networkObject.transform.rotation = rotation ?? networkObject.transform.rotation;
networkObject.NetworkManagerOwner = NetworkManager;
networkObject.PrefabGlobalObjectIdHash = prefabGlobalObjectIdHash;
return networkObject;
}
/// <summary>
/// Creates a local NetowrkObject to be spawned.
/// </summary>
@@ -949,7 +991,7 @@ namespace Unity.Netcode
/// - NetworkObject when spawning a newly instantiated NetworkObject for the first time.
/// - NetworkSceneManager after a server/session-owner has loaded a scene to locally spawn the newly instantiated in-scene placed NetworkObjects.
/// - NetworkSpawnManager when spawning any already loaded in-scene placed NetworkObjects (client-server or session owner).
///
///
/// Client-Server:
/// Server is the only instance that invokes this method.
///
@@ -1098,6 +1140,12 @@ namespace Unity.Netcode
// then add all connected clients as observers
if (!NetworkManager.DistributedAuthorityMode && NetworkManager.IsServer && networkObject.SpawnWithObservers)
{
// If running as a server only, then make sure to always add the server's client identifier
if (!NetworkManager.IsHost)
{
networkObject.Observers.Add(NetworkManager.LocalClientId);
}
// Add client observers
for (int i = 0; i < NetworkManager.ConnectedClientsIds.Count; i++)
{
@@ -1321,7 +1369,7 @@ namespace Unity.Netcode
}
}
// If spawned, then despawn and potentially destroy.
// If spawned, then despawn and potentially destroy.
if (networkObjects[i].IsSpawned)
{
OnDespawnObject(networkObjects[i], shouldDestroy);
@@ -1401,6 +1449,15 @@ namespace Unity.Netcode
}
}
// Since we are spawing in-scene placed NetworkObjects for already loaded scenes,
// we need to add any in-scene placed NetworkObject to our tracking table
var clearFirst = true;
foreach (var sceneLoaded in NetworkManager.SceneManager.ScenesLoaded)
{
NetworkManager.SceneManager.PopulateScenePlacedObjects(sceneLoaded.Value, clearFirst);
clearFirst = false;
}
// Notify all in-scene placed NetworkObjects have been spawned
foreach (var networkObject in networkObjectsToSpawn)
{
@@ -1550,23 +1607,9 @@ namespace Unity.Netcode
SpawnedObjectsList.Remove(networkObject);
}
// DANGO-TODO: When we fix the issue with observers not being applied to NetworkObjects,
// (client connect/disconnect) we can remove this hacky way of doing this.
// Basically, when a player disconnects and/or is destroyed they are removed as an observer from all other client
// NetworkOject instances.
if (networkObject.IsPlayerObject && !networkObject.IsOwner && networkObject.OwnerClientId != NetworkManager.LocalClientId)
{
foreach (var netObject in SpawnedObjects)
{
if (netObject.Value.Observers.Contains(networkObject.OwnerClientId))
{
netObject.Value.Observers.Remove(networkObject.OwnerClientId);
}
}
}
if (networkObject.IsPlayerObject)
{
RemovePlayerObject(networkObject);
RemovePlayerObject(networkObject, destroyGameObject);
}
// Always clear out the observers list when despawned
@@ -1705,6 +1748,11 @@ namespace Unity.Netcode
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
{
if (networkObject.IsOwnershipSessionOwner)
{
continue;
}
if (networkObject.IsOwnershipDistributable && !networkObject.IsOwnershipLocked)
{
if (networkObject.transform.parent != null)
@@ -1715,17 +1763,15 @@ namespace Unity.Netcode
continue;
}
}
// We have to check if it is an in-scene placed NetworkObject and if it is get the source prefab asset GlobalObjectIdHash value of the in-scene placed instance
// since all in-scene placed instances use unique GlobalObjectIdHash values.
var globalOjectIdHash = networkObject.IsSceneObject.HasValue && networkObject.IsSceneObject.Value ? networkObject.InScenePlacedSourceGlobalObjectIdHash : networkObject.GlobalObjectIdHash;
if (networkObject.IsSceneObject.Value)
if (!objectTypeCount.ContainsKey(globalOjectIdHash))
{
continue;
objectTypeCount.Add(globalOjectIdHash, 0);
}
if (!objectTypeCount.ContainsKey(networkObject.GlobalObjectIdHash))
{
objectTypeCount.Add(networkObject.GlobalObjectIdHash, 0);
}
objectTypeCount[networkObject.GlobalObjectIdHash] += 1;
objectTypeCount[globalOjectIdHash] += 1;
// DANGO-TODO-MVP: Remove this once the service handles object distribution
if (onlyIncludeOwnedObjects && !networkObject.IsOwner)
@@ -1733,133 +1779,141 @@ namespace Unity.Netcode
continue;
}
// Divide up by prefab type (GlobalObjectIdHash) to get a better distribution of object types
if (!objectByTypeAndOwner.ContainsKey(networkObject.GlobalObjectIdHash))
if (!objectByTypeAndOwner.ContainsKey(globalOjectIdHash))
{
objectByTypeAndOwner.Add(networkObject.GlobalObjectIdHash, new Dictionary<ulong, List<NetworkObject>>());
objectByTypeAndOwner.Add(globalOjectIdHash, new Dictionary<ulong, List<NetworkObject>>());
}
// Sub-divide each type by owner
if (!objectByTypeAndOwner[networkObject.GlobalObjectIdHash].ContainsKey(networkObject.OwnerClientId))
if (!objectByTypeAndOwner[globalOjectIdHash].ContainsKey(networkObject.OwnerClientId))
{
objectByTypeAndOwner[networkObject.GlobalObjectIdHash].Add(networkObject.OwnerClientId, new List<NetworkObject>());
objectByTypeAndOwner[globalOjectIdHash].Add(networkObject.OwnerClientId, new List<NetworkObject>());
}
// Add to the client's spawned object list
objectByTypeAndOwner[networkObject.GlobalObjectIdHash][networkObject.OwnerClientId].Add(networkObject);
objectByTypeAndOwner[globalOjectIdHash][networkObject.OwnerClientId].Add(networkObject);
}
}
}
internal void DistributeNetworkObjects(ulong clientId)
{
// Distributed authority mode ownership distribution
// DANGO-TODO-MVP: Remove the session owner object distribution check once the service handles object distribution
if (NetworkManager.DistributedAuthorityMode && (NetworkManager.DAHost || NetworkManager.CMBServiceConnection))
if (!NetworkManager.DistributedAuthorityMode)
{
// DA-NGO CMB SERVICE NOTES:
// The most basic object distribution should be broken up into a table of spawned object types
// where each type contains a list of each client's owned objects of that type that can be
// distributed.
// The table format:
// [GlobalObjectIdHashValue][ClientId][List of Owned Objects]
var distributedNetworkObjects = new Dictionary<uint, Dictionary<ulong, List<NetworkObject>>>();
return;
}
// DA-NGO CMB SERVICE NOTES:
// This is optional, but I found it easier to get the total count of spawned objects for each prefab
// type contained in the previous table in order to be able to calculate the targeted object distribution
// count of that type per client.
var objectTypeCount = new Dictionary<uint, int>();
if (NetworkManager.SessionConfig.ServiceSideDistribution)
{
return;
}
// Get all spawned objects by type and then by client owner that are spawned and can be distributed
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
var clientCount = NetworkManager.ConnectedClientsIds.Count;
// DA-NGO CMB SERVICE NOTES:
// The most basic object distribution should be broken up into a table of spawned object types
// where each type contains a list of each client's owned objects of that type that can be
// distributed.
// The table format:
// [GlobalObjectIdHashValue][ClientId][List of Owned Objects]
var distributedNetworkObjects = new Dictionary<uint, Dictionary<ulong, List<NetworkObject>>>();
// Cycle through each prefab type
foreach (var objectTypeEntry in distributedNetworkObjects)
// DA-NGO CMB SERVICE NOTES:
// This is optional, but I found it easier to get the total count of spawned objects for each prefab
// type contained in the previous table in order to be able to calculate the targeted object distribution
// count of that type per client.
var objectTypeCount = new Dictionary<uint, int>();
// Get all spawned objects by type and then by client owner that are spawned and can be distributed
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
var clientCount = NetworkManager.ConnectedClientsIds.Count;
// Cycle through each prefab type
foreach (var objectTypeEntry in distributedNetworkObjects)
{
// Calculate the number of objects that should be distributed amongst the clients
var totalObjectsToDistribute = objectTypeCount[objectTypeEntry.Key];
var objPerClientF = totalObjectsToDistribute * (1.0f / clientCount);
var floorValue = (int)Math.Floor(objPerClientF);
var fractional = objPerClientF - floorValue;
var objPerClient = 0;
if (fractional >= 0.556f)
{
// Calculate the number of objects that should be distributed amongst the clients
var totalObjectsToDistribute = objectTypeCount[objectTypeEntry.Key];
var objPerClientF = totalObjectsToDistribute * (1.0f / clientCount);
var floorValue = (int)Math.Floor(objPerClientF);
var fractional = objPerClientF - floorValue;
var objPerClient = 0;
if (fractional >= 0.556f)
{
objPerClient = (int)Math.Round(totalObjectsToDistribute * (1.0f / clientCount));
}
else
{
objPerClient = floorValue;
}
objPerClient = (int)Math.Round(totalObjectsToDistribute * (1.0f / clientCount));
}
else
{
objPerClient = floorValue;
}
// If the object per client count is zero, then move to the next type.
if (objPerClient <= 0)
// If the object per client count is zero, then move to the next type.
if (objPerClient <= 0)
{
continue;
}
// Evenly distribute this object type amongst the clients
foreach (var ownerList in objectTypeEntry.Value)
{
if (ownerList.Value.Count <= 1)
{
continue;
}
// Evenly distribute this object type amongst the clients
foreach (var ownerList in objectTypeEntry.Value)
var maxDistributeCount = Mathf.Max(ownerList.Value.Count - objPerClient, 1);
var distributed = 0;
// For now when we have more players then distributed NetworkObjects that
// a specific client owns, just assign half of the NetworkObjects to the new client
var offsetCount = Mathf.Max((int)Math.Round((float)(ownerList.Value.Count / objPerClient)), 1);
if (EnableDistributeLogging)
{
if (ownerList.Value.Count <= 1)
{
continue;
}
Debug.Log($"[{objPerClient} of {totalObjectsToDistribute}][Client-{ownerList.Key}] Count: {ownerList.Value.Count} | ObjPerClient: {objPerClient} | maxD: {maxDistributeCount} | Offset: {offsetCount}");
}
var maxDistributeCount = Mathf.Max(ownerList.Value.Count - objPerClient, 1);
var distributed = 0;
// For now when we have more players then distributed NetworkObjects that
// a specific client owns, just assign half of the NetworkObjects to the new client
var offsetCount = Mathf.Max((int)Math.Round((float)(ownerList.Value.Count / objPerClient)), 1);
if (EnableDistributeLogging)
for (int i = 0; i < ownerList.Value.Count; i++)
{
if ((i % offsetCount) == 0)
{
Debug.Log($"[{objPerClient} of {totalObjectsToDistribute}][Client-{ownerList.Key}] Count: {ownerList.Value.Count} | ObjPerClient: {objPerClient} | maxD: {maxDistributeCount} | Offset: {offsetCount}");
}
for (int i = 0; i < ownerList.Value.Count; i++)
{
if ((i % offsetCount) == 0)
ChangeOwnership(ownerList.Value[i], clientId, true);
//if (EnableDistributeLogging)
{
ChangeOwnership(ownerList.Value[i], clientId, true);
if (EnableDistributeLogging)
{
Debug.Log($"[Client-{ownerList.Key}][NetworkObjectId-{ownerList.Value[i].NetworkObjectId} Distributed to Client-{clientId}");
}
distributed++;
}
if (distributed == maxDistributeCount)
{
break;
Debug.Log($"[Client-{ownerList.Key}][NetworkObjectId-{ownerList.Value[i].NetworkObjectId} Distributed to Client-{clientId}");
}
distributed++;
}
if (distributed == maxDistributeCount)
{
break;
}
}
}
// If EnableDistributeLogging is enabled, log the object type distribution counts per client
if (EnableDistributeLogging)
{
var builder = new StringBuilder();
distributedNetworkObjects.Clear();
objectTypeCount.Clear();
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
builder.AppendLine($"Client Relative Distributed Object Count: (distribution follows)");
// Cycle through each prefab type
foreach (var objectTypeEntry in distributedNetworkObjects)
{
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}][Total Count: {objectTypeCount[objectTypeEntry.Key]}]");
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}] Distribution:");
// Evenly distribute this type amongst clients
foreach (var ownerList in objectTypeEntry.Value)
{
builder.AppendLine($"[Client-{ownerList.Key}] Count: {ownerList.Value.Count}");
}
}
Debug.Log(builder.ToString());
}
}
// If EnableDistributeLogging is enabled, log the object type distribution counts per client
if (EnableDistributeLogging)
{
var builder = new StringBuilder();
distributedNetworkObjects.Clear();
objectTypeCount.Clear();
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
builder.AppendLine($"Client Relative Distributed Object Count: (distribution follows)");
// Cycle through each prefab type
foreach (var objectTypeEntry in distributedNetworkObjects)
{
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}][Total Count: {objectTypeCount[objectTypeEntry.Key]}]");
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}] Distribution:");
// Evenly distribute this type amongst clients
foreach (var ownerList in objectTypeEntry.Value)
{
builder.AppendLine($"[Client-{ownerList.Key}] Count: {ownerList.Value.Count}");
}
}
Debug.Log(builder.ToString());
}
}
internal struct DeferredDespawnObject
@@ -1969,14 +2023,14 @@ namespace Unity.Netcode
/// synchronizing in order to "show" (spawn) anything that might be currently hidden from
/// the session owner.
/// </summary>
/// <remarks>
/// Replacement is: SynchronizeObjectsToNewlyJoinedClient
/// </remarks>
internal void ShowHiddenObjectsToNewlyJoinedClient(ulong newClientId)
{
if (!NetworkManager.DistributedAuthorityMode)
if (NetworkManager == null || NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer)
{
if (NetworkManager == null || !NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogWarning($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} invoked while !");
}
Debug.LogWarning($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} invoked while shutdown is in progress!");
return;
}
@@ -2012,5 +2066,46 @@ namespace Unity.Netcode
}
}
}
internal void SynchronizeObjectsToNewlyJoinedClient(ulong newClientId)
{
if (NetworkManager == null || NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogWarning($"[Internal Error] {nameof(SynchronizeObjectsToNewlyJoinedClient)} invoked while shutdown is in progress!");
return;
}
if (!NetworkManager.DistributedAuthorityMode)
{
Debug.LogError($"[Internal Error] {nameof(SynchronizeObjectsToNewlyJoinedClient)} should only be invoked when using a distributed authority network topology!");
return;
}
if (NetworkManager.NetworkConfig.EnableSceneManagement)
{
Debug.LogError($"[Internal Error] {nameof(SynchronizeObjectsToNewlyJoinedClient)} should only be invoked when scene management is disabled!");
return;
}
var localClientId = NetworkManager.LocalClient.ClientId;
foreach (var networkObject in SpawnedObjectsList)
{
if (networkObject.SpawnWithObservers && networkObject.OwnerClientId == localClientId)
{
if (networkObject.Observers.Contains(newClientId))
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
// Temporary tracking to make sure we are not showing something already visibile (should never be the case for this)
Debug.LogWarning($"[{nameof(SynchronizeObjectsToNewlyJoinedClient)}][{networkObject.name}] New client as already an observer!");
}
// For now, remove the client (impossible for the new client to have an instance since the session owner doesn't) to make sure newly added
// code to handle this edge case works.
networkObject.Observers.Remove(newClientId);
}
networkObject.NetworkShow(newClientId);
}
}
}
}
}

View File

@@ -107,6 +107,45 @@ namespace Unity.Netcode
/// /// <param name="networkManager">optionally pass in NetworkManager</param>
public abstract void Initialize(NetworkManager networkManager = null);
/// <summary>
/// Invoked by NetworkManager at the beginning of its EarlyUpdate.
/// For order of operations see: <see cref="NetworkManager.NetworkUpdate(NetworkUpdateStage)"/>
/// </summary>
/// Useful to handle processing any transport-layer events such as processing inbound messages or changes in connection state(s).
/// </remarks>
protected virtual void OnEarlyUpdate()
{
}
/// <summary>
/// Invoked by NetworkManager at the beginning of its EarlyUpdate
/// </summary>
internal void EarlyUpdate()
{
OnEarlyUpdate();
}
/// <summary>
/// Invoked by NetworkManager towards the end of the PostLateUpdate.
/// For order of operations see: <see cref="NetworkManager.NetworkUpdate(NetworkUpdateStage)"/>
/// </summary>
/// <remarks>
/// Useful to handle any end of frame transport tasks such as sending queued transport messages.
/// </remarks>
protected virtual void OnPostLateUpdate()
{
}
/// <summary>
/// Invoked by NetworkManager towards the end of the PostLateUpdate
/// </summary>
internal void PostLateUpdate()
{
OnPostLateUpdate();
}
protected virtual NetworkTopologyTypes OnCurrentTopology()
{
return NetworkTopologyTypes.ClientServer;

View File

@@ -405,6 +405,7 @@ namespace Unity.Netcode.Transports.UTP
#if UTP_TRANSPORT_2_0_ABOVE
[Obsolete("DebugSimulator is no longer supported and has no effect. Use Network Simulator from the Multiplayer Tools package.", false)]
[HideInInspector]
#endif
public SimulatorParameters DebugSimulator = new SimulatorParameters
{
@@ -944,17 +945,13 @@ namespace Unity.Netcode.Transports.UTP
return false;
}
private void Update()
/// <summary>
/// Handles accepting new connections and processing transport events.
/// </summary>
protected override void OnEarlyUpdate()
{
if (m_Driver.IsCreated)
{
foreach (var kvp in m_SendQueue)
{
SendBatchedMessages(kvp.Key, kvp.Value);
}
m_Driver.ScheduleUpdate().Complete();
if (m_ProtocolType == ProtocolType.RelayUnityTransport && m_Driver.GetRelayConnectionStatus() == RelayConnectionStatus.AllocationInvalid)
{
Debug.LogError("Transport failure! Relay allocation needs to be recreated, and NetworkManager restarted. " +
@@ -964,15 +961,38 @@ namespace Unity.Netcode.Transports.UTP
return;
}
m_Driver.ScheduleUpdate().Complete();
// Process any new connections
while (AcceptConnection() && m_Driver.IsCreated)
{
;
}
// Process any transport events (i.e. connect, disconnect, data, etc)
while (ProcessEvent() && m_Driver.IsCreated)
{
;
}
}
base.OnEarlyUpdate();
}
/// <summary>
/// Handles sending any queued batched messages.
/// </summary>
protected override void OnPostLateUpdate()
{
if (m_Driver.IsCreated)
{
foreach (var kvp in m_SendQueue)
{
SendBatchedMessages(kvp.Key, kvp.Value);
}
// Schedule a flush send as the last transport action for the
// current frame.
m_Driver.ScheduleFlushSend(default).Complete();
#if MULTIPLAYER_TOOLS_1_0_0_PRE_7
if (m_NetworkManager)
@@ -981,6 +1001,7 @@ namespace Unity.Netcode.Transports.UTP
}
#endif
}
base.OnPostLateUpdate();
}
private void OnDestroy()
@@ -1241,6 +1262,30 @@ namespace Unity.Netcode.Transports.UTP
return (ulong)ExtractRtt(ParseClientId(clientId));
}
/// <summary>
/// Provides the <see cref="NetworkEndpoint"/> for the NGO client identifier specified.
/// </summary>
/// <remarks>
/// - This is only really useful for direct connections.
/// - Relay connections and clients connected using a distributed authority network topology will not provide the client's actual endpoint information.
/// - For LAN topologies this should work as long as it is a direct connection and not a relay connection.
/// </remarks>
/// <param name="clientId">NGO client identifier to get endpoint information about.</param>
/// <returns><see cref="NetworkEndpoint"/></returns>
public NetworkEndpoint GetEndpoint(ulong clientId)
{
if (m_Driver.IsCreated && m_NetworkManager != null && m_NetworkManager.IsListening)
{
var transportId = m_NetworkManager.ConnectionManager.ClientIdToTransportId(clientId);
var networkConnection = ParseClientId(transportId);
if (m_Driver.GetConnectionState(networkConnection) == NetworkConnection.State.Connected)
{
return m_Driver.GetRemoteEndpoint(networkConnection);
}
}
return new NetworkEndpoint();
}
/// <summary>
/// Initializes the transport
/// </summary>
@@ -1450,8 +1495,18 @@ namespace Unity.Netcode.Transports.UTP
/// </summary>
public override void Shutdown()
{
if (m_NetworkManager && !m_NetworkManager.ShutdownInProgress)
{
Debug.LogWarning("Directly calling `UnityTransport.Shutdown()` results in unexpected shutdown behaviour. All pending events will be lost. Use `NetworkManager.Shutdown()` instead.");
}
if (m_Driver.IsCreated)
{
while (ProcessEvent() && m_Driver.IsCreated)
{
;
}
// Flush all send queues to the network. NGO can be configured to flush its message
// queue on shutdown. But this only calls the Send() method, which doesn't actually
// get anything to the network.
@@ -1469,6 +1524,7 @@ namespace Unity.Netcode.Transports.UTP
DisposeInternals();
m_ReliableReceiveQueues.Clear();
m_State = State.Disconnected;
// We must reset this to zero because UTP actually re-uses clientIds if there is a clean disconnect
m_ServerClientId = 0;

View File

@@ -58,16 +58,6 @@
"expression": "",
"define": "COM_UNITY_MODULES_ANIMATION"
},
{
"name": "com.unity.modules.physics",
"expression": "",
"define": "COM_UNITY_MODULES_PHYSICS"
},
{
"name": "com.unity.modules.physics2d",
"expression": "",
"define": "COM_UNITY_MODULES_PHYSICS2D"
},
{
"name": "com.unity.services.multiplayer",
"expression": "0.2.0",

View File

@@ -1,4 +0,0 @@
{
"displayName": "Bootstrap",
"description": "A lightweight sample to get started"
}

View File

@@ -1,7 +1,7 @@
{
"name": "Bootstrap",
"name": "Bootstrap",
"rootNamespace": "Unity.Netcode.Samples",
"references": [
"Unity.Netcode.Runtime"
]
}
}

View File

@@ -87,6 +87,8 @@ namespace Unity.Netcode.TestHelpers.Runtime
return new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max));
}
public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType, HostOrServer hostOrServer) : base(networkTopologyType, hostOrServer) { }
public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { }
public IntegrationTestWithApproximation(HostOrServer hostOrServer) : base(hostOrServer) { }

View File

@@ -1759,6 +1759,13 @@ namespace Unity.Netcode.TestHelpers.Runtime
m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority;
}
public NetcodeIntegrationTest(NetworkTopologyTypes networkTopologyType, HostOrServer hostOrServer)
{
m_NetworkTopologyType = networkTopologyType;
m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority;
m_UseHost = hostOrServer == HostOrServer.Host || hostOrServer == HostOrServer.DAHost;
}
/// <summary>
/// Optional Host or Server integration tests
/// Constructor that allows you To break tests up as a host

View File

@@ -559,6 +559,29 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
}
/// <summary>
/// Creates a <see cref="NetworkObject"/> to be used with integration testing
/// </summary>
/// <param name="baseName">namr of the object</param>
/// <param name="owner">owner of the object</param>
/// <param name="moveToDDOL">when true, the instance is automatically migrated into the DDOL</param>
/// <returns></returns>
internal static GameObject CreateNetworkObject(string baseName, NetworkManager owner, bool moveToDDOL = false)
{
var gameObject = new GameObject
{
name = baseName
};
var networkObject = gameObject.AddComponent<NetworkObject>();
networkObject.NetworkManagerOwner = owner;
MakeNetworkObjectTestPrefab(networkObject);
if (moveToDDOL)
{
Object.DontDestroyOnLoad(gameObject);
}
return gameObject;
}
public static GameObject CreateNetworkObjectPrefab(string baseName, NetworkManager server, params NetworkManager[] clients)
{
void AddNetworkPrefab(NetworkConfig config, NetworkPrefab prefab)
@@ -570,13 +593,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
Assert.IsNotNull(server, prefabCreateAssertError);
Assert.IsFalse(server.IsListening, prefabCreateAssertError);
var gameObject = new GameObject
{
name = baseName
};
var networkObject = gameObject.AddComponent<NetworkObject>();
networkObject.NetworkManagerOwner = server;
MakeNetworkObjectTestPrefab(networkObject);
var gameObject = CreateNetworkObject(baseName, server);
var networkPrefab = new NetworkPrefab() { Prefab = gameObject };
// We could refactor this test framework to share a NetworkPrefabList instance, but at this point it's

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: e5a2c06211b0c224c94202c2cda733fd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: d656bc8bb2502584ab6883d254d64782
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,31 +0,0 @@
using NUnit.Framework;
namespace Unity.Netcode.EditorTests
{
internal class ArithmeticTests
{
[Test]
public void TestCeil()
{
Assert.That(Arithmetic.CeilingExact(10, 5), Is.EqualTo(2));
Assert.That(Arithmetic.CeilingExact(11, 5), Is.EqualTo(3));
Assert.That(Arithmetic.CeilingExact(0, 5), Is.EqualTo(0));
Assert.That(Arithmetic.CeilingExact(1, 5), Is.EqualTo(1));
Assert.That(Arithmetic.CeilingExact(2, 5), Is.EqualTo(1));
Assert.That(Arithmetic.CeilingExact(3, 5), Is.EqualTo(1));
Assert.That(Arithmetic.CeilingExact(4, 5), Is.EqualTo(1));
Assert.That(Arithmetic.CeilingExact(5, 5), Is.EqualTo(1));
Assert.That(Arithmetic.CeilingExact(6, 5), Is.EqualTo(2));
}
[Test]
public void TestZigZag()
{
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(1234)), Is.EqualTo(1234));
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(-1)), Is.EqualTo(-1));
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(0)), Is.EqualTo(0));
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(long.MaxValue)), Is.EqualTo(long.MaxValue));
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(long.MinValue)), Is.EqualTo(long.MinValue));
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: cc0dc1cbf78a5486db1ccbc245d90992
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 2a46bbc7e63044f498612ed996afa274
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,371 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!29 &1
OcclusionCullingSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_OcclusionBakeSettings:
smallestOccluder: 5
smallestHole: 0.25
backfaceThreshold: 100
m_SceneGUID: 00000000000000000000000000000000
m_OcclusionCullingData: {fileID: 0}
--- !u!104 &2
RenderSettings:
m_ObjectHideFlags: 0
serializedVersion: 9
m_Fog: 0
m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}
m_FogMode: 3
m_FogDensity: 0.01
m_LinearFogStart: 0
m_LinearFogEnd: 300
m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}
m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}
m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}
m_AmbientIntensity: 1
m_AmbientMode: 0
m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}
m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}
m_HaloStrength: 0.5
m_FlareStrength: 1
m_FlareFadeSpeed: 3
m_HaloTexture: {fileID: 0}
m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}
m_DefaultReflectionMode: 0
m_DefaultReflectionResolution: 128
m_ReflectionBounces: 1
m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.44657874, g: 0.49641275, b: 0.5748172, a: 1}
m_UseRadianceAmbientProbe: 0
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0
serializedVersion: 12
m_GIWorkflowMode: 1
m_GISettings:
serializedVersion: 2
m_BounceScale: 1
m_IndirectOutputScale: 1
m_AlbedoBoost: 1
m_EnvironmentLightingMode: 0
m_EnableBakedLightmaps: 1
m_EnableRealtimeLightmaps: 0
m_LightmapEditorSettings:
serializedVersion: 12
m_Resolution: 2
m_BakeResolution: 40
m_AtlasSize: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 1
m_CompAOExponentDirect: 0
m_ExtractAmbientOcclusion: 0
m_Padding: 2
m_LightmapParameters: {fileID: 0}
m_LightmapsBakeMode: 1
m_TextureCompression: 1
m_FinalGather: 0
m_FinalGatherFiltering: 1
m_FinalGatherRayCount: 256
m_ReflectionCompression: 2
m_MixedBakeMode: 2
m_BakeBackend: 1
m_PVRSampling: 1
m_PVRDirectSampleCount: 32
m_PVRSampleCount: 512
m_PVRBounces: 2
m_PVREnvironmentSampleCount: 256
m_PVREnvironmentReferencePointCount: 2048
m_PVRFilteringMode: 1
m_PVRDenoiserTypeDirect: 1
m_PVRDenoiserTypeIndirect: 1
m_PVRDenoiserTypeAO: 1
m_PVRFilterTypeDirect: 0
m_PVRFilterTypeIndirect: 0
m_PVRFilterTypeAO: 0
m_PVREnvironmentMIS: 1
m_PVRCulling: 1
m_PVRFilteringGaussRadiusDirect: 1
m_PVRFilteringGaussRadiusIndirect: 5
m_PVRFilteringGaussRadiusAO: 2
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
m_PVRFilteringAtrousPositionSigmaIndirect: 2
m_PVRFilteringAtrousPositionSigmaAO: 1
m_ExportTrainingData: 0
m_TrainingDataDestination: TrainingData
m_LightProbeSampleCountMultiplier: 4
m_LightingDataAsset: {fileID: 0}
m_LightingSettings: {fileID: 0}
--- !u!196 &4
NavMeshSettings:
serializedVersion: 2
m_ObjectHideFlags: 0
m_BuildSettings:
serializedVersion: 2
agentTypeID: 0
agentRadius: 0.5
agentHeight: 2
agentSlope: 45
agentClimb: 0.4
ledgeDropHeight: 0
maxJumpAcrossDistance: 0
minRegionArea: 2
manualCellSize: 0
cellSize: 0.16666667
manualTileSize: 0
tileSize: 256
accuratePlacement: 0
maxJobWorkers: 0
preserveTilesOutsideBounds: 0
debug:
m_Flags: 0
m_NavMeshData: {fileID: 0}
--- !u!1 &1290761662
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1290761665}
- component: {fileID: 1290761664}
- component: {fileID: 1290761663}
m_Layer: 0
m_Name: Main Camera
m_TagString: MainCamera
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!81 &1290761663
AudioListener:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1290761662}
m_Enabled: 1
--- !u!20 &1290761664
Camera:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1290761662}
m_Enabled: 1
serializedVersion: 2
m_ClearFlags: 1
m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}
m_projectionMatrixMode: 1
m_GateFitMode: 2
m_FOVAxisMode: 0
m_SensorSize: {x: 36, y: 24}
m_LensShift: {x: 0, y: 0}
m_FocalLength: 50
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.3
far clip plane: 1000
field of view: 60
orthographic: 0
orthographic size: 5
m_Depth: -1
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 1
m_AllowMSAA: 1
m_AllowDynamicResolution: 0
m_ForceIntoRT: 0
m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!4 &1290761665
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1290761662}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 1, z: -10}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1858588911
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1858588913}
- component: {fileID: 1858588912}
m_Layer: 0
m_Name: Directional Light
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!108 &1858588912
Light:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1858588911}
m_Enabled: 1
serializedVersion: 10
m_Type: 1
m_Shape: 0
m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1}
m_Intensity: 1
m_Range: 10
m_SpotAngle: 30
m_InnerSpotAngle: 21.80208
m_CookieSize: 10
m_Shadows:
m_Type: 2
m_Resolution: -1
m_CustomResolution: -1
m_Strength: 1
m_Bias: 0.05
m_NormalBias: 0.4
m_NearPlane: 0.2
m_CullingMatrixOverride:
e00: 1
e01: 0
e02: 0
e03: 0
e10: 0
e11: 1
e12: 0
e13: 0
e20: 0
e21: 0
e22: 1
e23: 0
e30: 0
e31: 0
e32: 0
e33: 1
m_UseCullingMatrixOverride: 0
m_Cookie: {fileID: 0}
m_DrawHalo: 0
m_Flare: {fileID: 0}
m_RenderMode: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_RenderingLayerMask: 1
m_Lightmapping: 4
m_LightShadowCasterMode: 0
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_ColorTemperature: 6570
m_UseColorTemperature: 0
m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0}
m_UseBoundingSphereOverride: 0
m_UseViewFrustumForShadowCasterCull: 1
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!4 &1858588913
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1858588911}
m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}
m_LocalPosition: {x: 0, y: 3, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}
--- !u!1 &1896907459
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1896907460}
- component: {fileID: 1896907461}
m_Layer: 0
m_Name: '[NetworkManager]'
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &1896907460
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1896907459}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 2
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &1896907461
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 1896907459}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 593a2fe42fa9d37498c96f9a383b6521, type: 3}
m_Name:
m_EditorClassIdentifier:
DontDestroy: 1
RunInBackground: 1
LogLevel: 1
NetworkConfig:
ProtocolVersion: 0
NetworkTransport: {fileID: 0}
RegisteredScenes:
- BuildTestScene
AllowRuntimeSceneChanges: 0
PlayerPrefab: {fileID: 0}
NetworkPrefabs: []
TickRate: 30
ClientConnectionBufferTimeout: 10
ConnectionApproval: 0
ConnectionData:
EnableTimeResync: 0
TimeResyncInterval: 30
EnableNetworkVariable: 1
EnsureNetworkVariableLengthSafety: 0
EnableSceneManagement: 1
ForceSamePrefabs: 1
RecycleNetworkIds: 1
NetworkIdRecycleDelay: 120
RpcHashSize: 0
LoadSceneTimeOut: 120
SpawnTimeout: 20
EnableNetworkLogs: 1

View File

@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: d45c09a54b1da466ab6c385ee45fd3e4
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,42 +0,0 @@
#if !MULTIPLAYER_TOOLS
using System.IO;
using System.Reflection;
using NUnit.Framework;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
namespace Unity.Netcode.EditorTests
{
internal class BuildTests
{
public const string DefaultBuildScenePath = "Tests/Editor/Build/BuildTestScene.unity";
[Test]
public void BasicBuildTest()
{
var execAssembly = Assembly.GetExecutingAssembly();
var packagePath = UnityEditor.PackageManager.PackageInfo.FindForAssembly(execAssembly).assetPath;
var buildTarget = EditorUserBuildSettings.activeBuildTarget;
var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(buildTarget);
var buildTargetSupported = BuildPipeline.IsBuildTargetSupported(buildTargetGroup, buildTarget);
if (buildTargetSupported)
{
var buildReport = BuildPipeline.BuildPlayer(
new[] { Path.Combine(packagePath, DefaultBuildScenePath) },
Path.Combine(Path.GetDirectoryName(Application.dataPath), "Builds", nameof(BuildTests)),
buildTarget,
BuildOptions.None
);
Assert.AreEqual(BuildResult.Succeeded, buildReport.summary.result);
}
else
{
Debug.Log($"Skipped building player due to Unsupported Build Target");
}
}
}
}
#endif

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: efb549c2173d5478e93a71fbd05c0392
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,62 +0,0 @@
using NUnit.Framework;
using Unity.Collections;
namespace Unity.Netcode.EditorTests
{
internal class DisconnectMessageTests
{
[Test]
public void EmptyDisconnectReason()
{
var networkContext = new NetworkContext();
var writer = new FastBufferWriter(20, Allocator.Temp, 20);
var msg = new DisconnectReasonMessage
{
Reason = string.Empty
};
msg.Serialize(writer, msg.Version);
var fbr = new FastBufferReader(writer, Allocator.Temp);
var recvMsg = new DisconnectReasonMessage();
recvMsg.Deserialize(fbr, ref networkContext, msg.Version);
Assert.IsEmpty(recvMsg.Reason);
}
[Test]
public void DisconnectReason()
{
var networkContext = new NetworkContext();
var writer = new FastBufferWriter(20, Allocator.Temp, 20);
var msg = new DisconnectReasonMessage
{
Reason = "Foo"
};
msg.Serialize(writer, msg.Version);
var fbr = new FastBufferReader(writer, Allocator.Temp);
var recvMsg = new DisconnectReasonMessage();
recvMsg.Deserialize(fbr, ref networkContext, msg.Version);
Assert.AreEqual("Foo", recvMsg.Reason);
}
[Test]
public void DisconnectReasonTooLong()
{
var networkContext = new NetworkContext();
var writer = new FastBufferWriter(20, Allocator.Temp, 20);
var msg = new DisconnectReasonMessage
{
Reason = "ThisStringIsWayLongerThanTwentyBytes"
};
msg.Serialize(writer, msg.Version);
var fbr = new FastBufferReader(writer, Allocator.Temp);
var recvMsg = new DisconnectReasonMessage();
recvMsg.Deserialize(fbr, ref networkContext, msg.Version);
Assert.IsEmpty(recvMsg.Reason);
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 55a1355c62fe14a118253f8bbee7c3cf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,361 +0,0 @@
using System;
using NUnit.Framework;
namespace Unity.Netcode.EditorTests
{
internal class InterpolatorTests
{
private const float k_Precision = 0.00000001f;
private const int k_MockTickRate = 1;
private NetworkTime T(float time, uint tickRate = k_MockTickRate)
{
return new NetworkTime(tickRate, timeSec: time);
}
[Test]
public void TestReset()
{
var interpolator = new BufferedLinearInterpolatorFloat();
var serverTime = new NetworkTime(k_MockTickRate, 100f);
interpolator.AddMeasurement(5, 1.0f);
var initVal = interpolator.Update(10f, serverTime.Time, serverTime.TimeTicksAgo(1).Time); // big value
Assert.That(initVal, Is.EqualTo(5f));
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(5f));
interpolator.ResetTo(100f, serverTime.Time);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(100f));
var val = interpolator.Update(1f, serverTime.Time, serverTime.TimeTicksAgo(1).Time);
Assert.That(val, Is.EqualTo(100f));
}
[Test]
public void NormalUsage()
{
// Testing float instead of Vector3. The only difference with Vector3 is the lerp method used.
var interpolator = new BufferedLinearInterpolatorFloat();
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0f));
interpolator.AddMeasurement(0f, 1.0f);
interpolator.AddMeasurement(1f, 2.0f);
// too small update, nothing happens, doesn't consume from buffer yet
var serverTime = new NetworkTime(k_MockTickRate, 0.01d); // t = 0.1d
interpolator.Update(.01f, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0f));
// consume first measurement, still can't interpolate with just one tick consumed
serverTime += 1.0d; // t = 1.01
interpolator.Update(1.0f, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0f));
// consume second measurement, start to interpolate
serverTime += 1.0d; // t = 2.01
var valueFromUpdate = interpolator.Update(1.0f, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0.01f).Within(k_Precision));
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0.01f).Within(k_Precision)); // test a second time, to make sure the get doesn't update the value
Assert.That(valueFromUpdate, Is.EqualTo(interpolator.GetInterpolatedValue()).Within(k_Precision));
// continue interpolation
serverTime = new NetworkTime(k_MockTickRate, 2.5d); // t = 2.5d
interpolator.Update(2.5f - 2.01f, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0.5f).Within(k_Precision));
// check when reaching end
serverTime += 0.5d; // t = 3
interpolator.Update(0.5f, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f).Within(k_Precision));
}
/// <summary>
/// Out of order or 'ACB' problem
/// Given two measurements have already arrived A and C, if a new measurement B arrives, the interpolation shouldn't go to B, but continue
/// to C.
/// Adding B should be ignored if interpolation is already interpolating between A and C
/// </summary>
[Test]
public void OutOfOrderShouldStillWork()
{
var serverTime = new NetworkTime(k_MockTickRate, 0.01d);
var interpolator = new BufferedLinearInterpolatorFloat();
double timeStep = 0.5d;
interpolator.AddMeasurement(0f, 0d);
interpolator.AddMeasurement(2f, 2d);
serverTime = new NetworkTime(k_MockTickRate, 1.5d);
interpolator.Update(1.5f, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0f).Within(k_Precision));
serverTime += timeStep; // t = 2.0
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f).Within(k_Precision));
serverTime += timeStep; // t = 2.5
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1.5f).Within(k_Precision));
// makes sure that interpolation still continues in right direction
interpolator.AddMeasurement(1, 1d);
serverTime += timeStep; // t = 3
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(2f).Within(k_Precision));
}
[Ignore("TODO: Fix this test to still handle testing message loss without extrapolation")]
[Test]
public void MessageLoss()
{
var serverTime = new NetworkTime(k_MockTickRate, 0.01d);
var interpolator = new BufferedLinearInterpolatorFloat();
double timeStep = 0.5d;
interpolator.AddMeasurement(1f, 1d);
interpolator.AddMeasurement(2f, 2d);
// message time=3 was lost
interpolator.AddMeasurement(4f, 4d);
interpolator.AddMeasurement(5f, 5d);
// message time=6 was lost
interpolator.AddMeasurement(100f, 7d); // high value to produce a misprediction
// first value teleports interpolator
serverTime = new NetworkTime(k_MockTickRate, 1d);
interpolator.Update(1f, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f));
// nothing happens, not ready to consume second value yet
serverTime += timeStep; // t = 1.5
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f));
// beginning of interpolation, second value consumed, currently at start
serverTime += timeStep; // t = 2
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f));
// interpolation starts
serverTime += timeStep; // t = 2.5
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1.5f));
serverTime += timeStep; // t = 3
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(2f));
// extrapolating to 2.5
serverTime += timeStep; // t = 3.5d
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(2.5f));
// next value skips to where it was supposed to be once buffer time is showing the next value
serverTime += timeStep; // t = 4
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(3f));
// interpolation continues as expected
serverTime += timeStep; // t = 4.5
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(3.5f));
serverTime += timeStep; // t = 5
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(4f));
// lost time=6, extrapolating
serverTime += timeStep; // t = 5.5
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(4.5f));
serverTime += timeStep; // t = 6.0
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(5f));
// misprediction
serverTime += timeStep; // t = 6.5
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(5.5f));
// lerp to right value
serverTime += timeStep; // t = 7.0
interpolator.Update((float)timeStep, serverTime);
Assert.That(interpolator.GetInterpolatedValue(), Is.GreaterThan(6.0f));
Assert.That(interpolator.GetInterpolatedValue(), Is.LessThanOrEqualTo(100f));
}
[Test]
public void AddFirstMeasurement()
{
var interpolator = new BufferedLinearInterpolatorFloat();
var serverTime = new NetworkTime(k_MockTickRate, 0d);
interpolator.AddMeasurement(2f, 1d);
interpolator.AddMeasurement(3f, 2d);
serverTime += 1d; // t = 1
var interpolatedValue = interpolator.Update(1f, serverTime);
// when consuming only one measurement and it's the first one consumed, teleport to it
Assert.That(interpolatedValue, Is.EqualTo(2f));
// then interpolation should work as usual
serverTime += 1d; // t = 2
interpolatedValue = interpolator.Update(1f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(2f));
serverTime += 0.5d; // t = 2.5
interpolatedValue = interpolator.Update(0.5f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(2.5f));
serverTime += 0.5d; // t = 3
interpolatedValue = interpolator.Update(.5f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(3f));
}
[Test]
public void JumpToEachValueIfDeltaTimeTooBig()
{
var interpolator = new BufferedLinearInterpolatorFloat();
var serverTime = new NetworkTime(k_MockTickRate, 0d);
interpolator.AddMeasurement(2f, 1d);
interpolator.AddMeasurement(3f, 2d);
serverTime += 1d; // t = 1
var interpolatedValue = interpolator.Update(1f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(2f));
// big deltaTime, jumping to latest value
serverTime += 9f; // t = 10
interpolatedValue = interpolator.Update(8f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(3));
}
[Test]
public void JumpToLastValueFromStart()
{
var interpolator = new BufferedLinearInterpolatorFloat();
var serverTime = new NetworkTime(k_MockTickRate, 0d);
serverTime += 1d; // t = 1
interpolator.AddMeasurement(1f, serverTime.Time);
serverTime += 1d; // t = 2
interpolator.AddMeasurement(2f, serverTime.Time);
serverTime += 1d; // t = 3
interpolator.AddMeasurement(3f, serverTime.Time);
// big time jump
serverTime += 7d; // t = 10
var interpolatedValue = interpolator.Update(10f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(3f));
// interpolation continues as normal
serverTime = new NetworkTime(k_MockTickRate, 11d); // t = 11
interpolator.AddMeasurement(11f, serverTime.Time); // out of order
serverTime = new NetworkTime(k_MockTickRate, 10.5d); // t = 10.5
interpolatedValue = interpolator.Update(0.5f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(3f));
serverTime += 0.5d; // t = 11
interpolatedValue = interpolator.Update(0.5f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(10f));
serverTime += 0.5d; // t = 11.5
interpolatedValue = interpolator.Update(0.5f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(10.5f));
serverTime += 0.5d; // t = 12
interpolatedValue = interpolator.Update(0.5f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(11f));
}
[Test]
public void TestBufferSizeLimit()
{
var interpolator = new BufferedLinearInterpolatorFloat();
// set first value
var serverTime = new NetworkTime(k_MockTickRate, 0d);
serverTime += 1.0d; // t = 1
interpolator.AddMeasurement(-1f, serverTime.Time);
interpolator.Update(1f, serverTime);
// max + 1
serverTime += 1.0d; // t = 2
interpolator.AddMeasurement(2, serverTime.Time); // +1, this should trigger a burst and teleport to last value
for (int i = 0; i < 100; i++)
{
interpolator.AddMeasurement(i + 3, i + 3d);
}
// client was paused for a while, some time has past, we just got a burst of values from the server that teleported us to the last value received
serverTime = new NetworkTime(k_MockTickRate, 102d);
var interpolatedValue = interpolator.Update(101f, serverTime);
Assert.That(interpolatedValue, Is.EqualTo(102));
}
[Test]
public void TestUpdatingInterpolatorWithNoData()
{
var interpolator = new BufferedLinearInterpolatorFloat();
var serverTime = new NetworkTime(k_MockTickRate, 0.0d);
// invalid case, this is undefined behaviour
Assert.Throws<InvalidOperationException>(() => interpolator.Update(1f, serverTime));
}
[Ignore("TODO: Fix this test to still test duplicated values without extrapolation")]
[Test]
public void TestDuplicatedValues()
{
var interpolator = new BufferedLinearInterpolatorFloat();
var serverTime = new NetworkTime(k_MockTickRate, 0.0d);
serverTime += 1d; // t = 1
interpolator.AddMeasurement(1f, serverTime.Time);
serverTime += 1d; // t = 2
interpolator.AddMeasurement(2f, serverTime.Time);
interpolator.AddMeasurement(2f, serverTime.Time);
// empty interpolator teleports to initial value
serverTime = new NetworkTime(k_MockTickRate, 0.0d);
serverTime += 1d; // t = 1
var interp = interpolator.Update(1f, serverTime);
Assert.That(interp, Is.EqualTo(1f));
// consume value, start interp, currently at start value
serverTime += 1d; // t = 2
interp = interpolator.Update(1f, serverTime);
Assert.That(interp, Is.EqualTo(1f));
// interp
serverTime += 0.5d; // t = 2.5
interp = interpolator.Update(0.5f, serverTime);
Assert.That(interp, Is.EqualTo(1.5f));
// reach end
serverTime += 0.5d; // t = 3
interp = interpolator.Update(0.5f, serverTime);
Assert.That(interp, Is.EqualTo(2f));
// with unclamped interpolation, we continue mispredicting since the two last values are actually treated as the same. Therefore we're not stopping at "2"
serverTime += 0.5d; // t = 3.5
interp = interpolator.Update(0.5f, serverTime);
Assert.That(interp, Is.EqualTo(2.5f));
serverTime += 0.5d; // t = 4
interp = interpolator.Update(0.5f, serverTime);
Assert.That(interp, Is.EqualTo(3f));
// we add a measurement with an updated time
var pastServerTime = new NetworkTime(k_MockTickRate, 3.0d);
interpolator.AddMeasurement(2f, pastServerTime.Time);
interp = interpolator.Update(0.5f, serverTime);
Assert.That(interp, Is.EqualTo(2f));
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: a5cfbc170161c4e95ac6124ee43068b6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 55531000b0344935b665541f089df60e
timeCreated: 1630354914

View File

@@ -1,92 +0,0 @@
using System.Collections.Generic;
using NUnit.Framework;
namespace Unity.Netcode.EditorTests
{
internal class DisconnectOnSendTests
{
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public void Serialize(FastBufferWriter writer, int targetVersion)
{
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
return true;
}
public void Handle(ref NetworkContext context)
{
}
public int Version => 0;
}
private class DisconnectOnSendMessageSender : INetworkMessageSender
{
public NetworkMessageManager MessageManager;
public void Send(ulong clientId, NetworkDelivery delivery, FastBufferWriter batchData)
{
MessageManager.ClientDisconnected(clientId);
}
}
private class TestMessageProvider : INetworkMessageProvider
{
// Keep track of what we sent
private List<NetworkMessageManager.MessageWithHandler> m_MessageList = new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(TestMessage),
Handler = NetworkMessageManager.ReceiveMessage<TestMessage>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessage>
}
};
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return m_MessageList;
}
}
private TestMessageProvider m_TestMessageProvider;
private DisconnectOnSendMessageSender m_MessageSender;
private NetworkMessageManager m_MessageManager;
private ulong[] m_Clients = { 0 };
[SetUp]
public void SetUp()
{
m_MessageSender = new DisconnectOnSendMessageSender();
m_TestMessageProvider = new TestMessageProvider();
m_MessageManager = new NetworkMessageManager(m_MessageSender, this, m_TestMessageProvider);
m_MessageSender.MessageManager = m_MessageManager;
m_MessageManager.ClientConnected(0);
m_MessageManager.SetVersion(0, XXHash.Hash32(typeof(TestMessage).FullName), 0);
}
[TearDown]
public void TearDown()
{
m_MessageManager.Dispose();
}
private TestMessage GetMessage()
{
return new TestMessage();
}
[Test]
public void WhenDisconnectIsCalledDuringSend_NoErrorsOccur()
{
var message = GetMessage();
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
// This is where an exception would be thrown and logged.
m_MessageManager.ProcessSendQueues();
}
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 7984df99de5c4b85a1b8567582d00c64
timeCreated: 1680888331

View File

@@ -1,203 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using NUnit.Framework;
using NUnit.Framework.Internal;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests
{
internal class MessageCorruptionTests
{
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public ForceNetworkSerializeByMemcpy<Guid> Value;
public static bool Handled;
public static bool Deserialized;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
writer.WriteValueSafe(Value);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
Deserialized = true;
reader.ReadValueSafe(out Value);
return true;
}
public void Handle(ref NetworkContext context)
{
Handled = true;
}
public int Version => 0;
}
private class TestMessageProvider : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(TestMessage),
Handler = NetworkMessageManager.ReceiveMessage<TestMessage>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessage>
}
};
}
}
public enum TypeOfCorruption
{
OffsetPlus,
OffsetMinus,
CorruptBytes,
Truncated,
AdditionalGarbageData,
}
private class TestMessageSender : INetworkMessageSender
{
public TypeOfCorruption Corruption;
public List<byte[]> MessageQueue = new List<byte[]>();
public unsafe void Send(ulong clientId, NetworkDelivery delivery, FastBufferWriter batchData)
{
switch (Corruption)
{
case TypeOfCorruption.OffsetPlus:
{
using var subWriter = new FastBufferWriter(batchData.Length + 1, Allocator.Temp);
subWriter.WriteByteSafe(0);
subWriter.WriteBytesSafe(batchData.GetUnsafePtr(), batchData.Length);
MessageQueue.Add(subWriter.ToArray());
break;
}
case TypeOfCorruption.OffsetMinus:
{
using var subWriter = new FastBufferWriter(batchData.Length - 1, Allocator.Temp);
subWriter.WriteBytesSafe(batchData.GetUnsafePtr() + 1, batchData.Length - 1);
MessageQueue.Add(subWriter.ToArray());
break;
}
case TypeOfCorruption.CorruptBytes:
batchData.Seek(batchData.Length - 2);
var currentByte = batchData.GetUnsafePtr()[0];
batchData.WriteByteSafe((byte)(currentByte == 0 ? 1 : 0));
MessageQueue.Add(batchData.ToArray());
break;
case TypeOfCorruption.Truncated:
batchData.Truncate(batchData.Length - 1);
MessageQueue.Add(batchData.ToArray());
break;
case TypeOfCorruption.AdditionalGarbageData:
batchData.Seek(batchData.Length);
batchData.WriteByteSafe(0);
MessageQueue.Add(batchData.ToArray());
break;
}
}
}
private NetworkMessageManager m_MessageManager;
private TestMessageSender m_MessageSender;
[SetUp]
public void SetUp()
{
TestMessage.Handled = false;
TestMessage.Deserialized = false;
m_MessageSender = new TestMessageSender();
m_MessageManager = new NetworkMessageManager(m_MessageSender, this, new TestMessageProvider());
m_MessageManager.ClientConnected(0);
m_MessageManager.SetVersion(0, XXHash.Hash32(typeof(TestMessage).FullName), 0);
}
[TearDown]
public void TearDown()
{
m_MessageManager.Dispose();
}
private TestMessage GetMessage()
{
return new TestMessage
{
Value = Guid.NewGuid()
};
}
[Test]
public unsafe void WhenPacketsAreCorrupted_TheyDontGetProcessed([Values] TypeOfCorruption typeOfCorruption)
{
m_MessageSender.Corruption = typeOfCorruption;
switch (typeOfCorruption)
{
case TypeOfCorruption.OffsetMinus:
case TypeOfCorruption.OffsetPlus:
LogAssert.Expect(LogType.Error, new Regex("Received a packet with an invalid Magic Value\\."));
break;
case TypeOfCorruption.Truncated:
case TypeOfCorruption.AdditionalGarbageData:
LogAssert.Expect(LogType.Error, new Regex("Received a packet with an invalid Batch Size Value\\."));
break;
case TypeOfCorruption.CorruptBytes:
LogAssert.Expect(LogType.Error, new Regex("Received a packet with an invalid Hash Value\\."));
break;
}
// Dummy batch header
var batchHeader = new NetworkBatchHeader
{
BatchCount = 1
};
var messageHeader = new NetworkMessageHeader
{
MessageSize = (ushort)UnsafeUtility.SizeOf<TestMessage>(),
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
};
var message = GetMessage();
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
writer.TryBeginWrite(FastBufferWriter.GetWriteSize(batchHeader) +
FastBufferWriter.GetWriteSize(messageHeader) +
FastBufferWriter.GetWriteSize(message));
writer.WriteValue(batchHeader);
writer.WriteValue(messageHeader);
writer.WriteValue(message);
// Fill out the rest of the batch header
writer.Seek(0);
batchHeader = new NetworkBatchHeader
{
Magic = NetworkBatchHeader.MagicValue,
BatchSize = writer.Length,
BatchHash = XXHash.Hash64(writer.GetUnsafePtr() + sizeof(NetworkBatchHeader), writer.Length - sizeof(NetworkBatchHeader)),
BatchCount = 1
};
writer.WriteValue(batchHeader);
m_MessageSender.Send(0, NetworkDelivery.Reliable, writer);
var receivedMessage = m_MessageSender.MessageQueue[0];
m_MessageSender.MessageQueue.Clear();
m_MessageManager.HandleIncomingData(0, new ArraySegment<byte>(receivedMessage), 0);
Assert.IsFalse(TestMessage.Deserialized);
Assert.IsFalse(TestMessage.Handled);
}
}
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: d3c01a0b5a0e478ebc5182fe339bde04
timeCreated: 1676997550

View File

@@ -1,263 +0,0 @@
using System;
using System.Collections.Generic;
using NUnit.Framework;
using NUnit.Framework.Internal;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Netcode.EditorTests
{
internal class MessageReceivingTests
{
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
public int C;
public static bool Deserialized;
public static bool Handled;
public static List<TestMessage> DeserializedValues = new List<TestMessage>();
public void Serialize(FastBufferWriter writer, int targetVersion)
{
writer.WriteValueSafe(this);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
Deserialized = true;
reader.ReadValueSafe(out this);
return true;
}
public void Handle(ref NetworkContext context)
{
Handled = true;
DeserializedValues.Add(this);
}
public int Version => 0;
}
private class TestMessageProvider : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(TestMessage),
Handler = NetworkMessageManager.ReceiveMessage<TestMessage>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessage>
}
};
}
}
private NetworkMessageManager m_MessageManager;
[SetUp]
public void SetUp()
{
TestMessage.Deserialized = false;
TestMessage.Handled = false;
TestMessage.DeserializedValues.Clear();
m_MessageManager = new NetworkMessageManager(new NopMessageSender(), this, new TestMessageProvider());
m_MessageManager.SetVersion(0, XXHash.Hash32(typeof(TestMessage).FullName), 0);
}
[TearDown]
public void TearDown()
{
m_MessageManager.Dispose();
}
private TestMessage GetMessage()
{
var random = new Random();
return new TestMessage
{
A = random.Next(),
B = random.Next(),
C = random.Next(),
};
}
[Test]
public void WhenHandlingAMessage_ReceiveMethodIsCalled()
{
var messageHeader = new NetworkMessageHeader
{
MessageSize = (ushort)UnsafeUtility.SizeOf<TestMessage>(),
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
};
var message = GetMessage();
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
writer.TryBeginWrite(FastBufferWriter.GetWriteSize(message));
writer.WriteValue(message);
var reader = new FastBufferReader(writer, Allocator.Temp);
using (reader)
{
m_MessageManager.HandleMessage(messageHeader, reader, 0, 0, 0);
Assert.IsTrue(TestMessage.Deserialized);
Assert.IsTrue(TestMessage.Handled);
Assert.AreEqual(1, TestMessage.DeserializedValues.Count);
Assert.AreEqual(message, TestMessage.DeserializedValues[0]);
}
}
}
[Test]
public unsafe void WhenHandlingIncomingData_ReceiveIsNotCalledBeforeProcessingIncomingMessageQueue()
{
var batchHeader = new NetworkBatchHeader
{
BatchCount = 1
};
var messageHeader = new NetworkMessageHeader
{
MessageSize = (ushort)UnsafeUtility.SizeOf<TestMessage>(),
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
};
var message = GetMessage();
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
writer.TryBeginWrite(FastBufferWriter.GetWriteSize(batchHeader) +
FastBufferWriter.GetWriteSize(messageHeader) +
FastBufferWriter.GetWriteSize(message));
writer.WriteValue(batchHeader);
writer.WriteValue(messageHeader);
writer.WriteValue(message);
// Fill out the rest of the batch header
writer.Seek(0);
batchHeader = new NetworkBatchHeader
{
Magic = NetworkBatchHeader.MagicValue,
BatchSize = writer.Length,
BatchHash = XXHash.Hash64(writer.GetUnsafePtr() + sizeof(NetworkBatchHeader), writer.Length - sizeof(NetworkBatchHeader)),
BatchCount = 1
};
writer.WriteValue(batchHeader);
var reader = new FastBufferReader(writer, Allocator.Temp);
using (reader)
{
m_MessageManager.HandleIncomingData(0, new ArraySegment<byte>(writer.ToArray()), 0);
Assert.IsFalse(TestMessage.Deserialized);
Assert.IsFalse(TestMessage.Handled);
Assert.IsEmpty(TestMessage.DeserializedValues);
}
}
}
[Test]
public unsafe void WhenReceivingAMessageAndProcessingMessageQueue_ReceiveMethodIsCalled()
{
var batchHeader = new NetworkBatchHeader
{
BatchCount = 1
};
var messageHeader = new NetworkMessageHeader
{
MessageSize = (uint)UnsafeUtility.SizeOf<TestMessage>(),
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
};
var message = GetMessage();
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
writer.WriteValueSafe(batchHeader);
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageType);
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageSize);
writer.WriteValueSafe(message);
// Fill out the rest of the batch header
writer.Seek(0);
batchHeader = new NetworkBatchHeader
{
Magic = NetworkBatchHeader.MagicValue,
BatchSize = writer.Length,
BatchHash = XXHash.Hash64(writer.GetUnsafePtr() + sizeof(NetworkBatchHeader), writer.Length - sizeof(NetworkBatchHeader)),
BatchCount = 1
};
writer.WriteValue(batchHeader);
var reader = new FastBufferReader(writer, Allocator.Temp);
using (reader)
{
m_MessageManager.HandleIncomingData(0, new ArraySegment<byte>(writer.ToArray()), 0);
m_MessageManager.ProcessIncomingMessageQueue();
Assert.IsTrue(TestMessage.Deserialized);
Assert.IsTrue(TestMessage.Handled);
Assert.AreEqual(1, TestMessage.DeserializedValues.Count);
Assert.AreEqual(message, TestMessage.DeserializedValues[0]);
}
}
}
[Test]
public unsafe void WhenReceivingMultipleMessagesAndProcessingMessageQueue_ReceiveMethodIsCalledMultipleTimes()
{
var batchHeader = new NetworkBatchHeader
{
BatchCount = 2
};
var messageHeader = new NetworkMessageHeader
{
MessageSize = (ushort)UnsafeUtility.SizeOf<TestMessage>(),
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
};
var message = GetMessage();
var message2 = GetMessage();
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
writer.WriteValueSafe(batchHeader);
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageType);
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageSize);
writer.WriteValueSafe(message);
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageType);
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageSize);
writer.WriteValueSafe(message2);
// Fill out the rest of the batch header
writer.Seek(0);
batchHeader = new NetworkBatchHeader
{
Magic = NetworkBatchHeader.MagicValue,
BatchSize = writer.Length,
BatchHash = XXHash.Hash64(writer.GetUnsafePtr() + sizeof(NetworkBatchHeader), writer.Length - sizeof(NetworkBatchHeader)),
BatchCount = 2
};
writer.WriteValue(batchHeader);
var reader = new FastBufferReader(writer, Allocator.Temp);
using (reader)
{
m_MessageManager.HandleIncomingData(0, new ArraySegment<byte>(writer.ToArray()), 0);
Assert.IsFalse(TestMessage.Deserialized);
Assert.IsFalse(TestMessage.Handled);
Assert.IsEmpty(TestMessage.DeserializedValues);
m_MessageManager.ProcessIncomingMessageQueue();
Assert.IsTrue(TestMessage.Deserialized);
Assert.IsTrue(TestMessage.Handled);
Assert.AreEqual(2, TestMessage.DeserializedValues.Count);
Assert.AreEqual(message, TestMessage.DeserializedValues[0]);
Assert.AreEqual(message2, TestMessage.DeserializedValues[1]);
}
}
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: cbc8fb6cf75f52d46a5d74971ce4b240
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,195 +0,0 @@
using System.Collections.Generic;
using NUnit.Framework;
namespace Unity.Netcode.EditorTests
{
internal class MessageRegistrationTests
{
private struct TestMessageOne : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
public int C;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
writer.WriteValue(this);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
return true;
}
public void Handle(ref NetworkContext context)
{
}
public int Version => 0;
}
private struct TestMessageTwo : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
public int C;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
writer.WriteValue(this);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
return true;
}
public void Handle(ref NetworkContext context)
{
}
public int Version => 0;
}
private class TestMessageProviderOne : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(TestMessageOne),
Handler = NetworkMessageManager.ReceiveMessage<TestMessageOne>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessageOne>
},
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(TestMessageTwo),
Handler = NetworkMessageManager.ReceiveMessage<TestMessageTwo>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessageTwo>
}
};
}
}
private struct TestMessageThree : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
public int C;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
writer.WriteValue(this);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
return true;
}
public void Handle(ref NetworkContext context)
{
}
public int Version => 0;
}
private class TestMessageProviderTwo : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(TestMessageThree),
Handler = NetworkMessageManager.ReceiveMessage<TestMessageThree>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessageThree>
}
};
}
}
private struct TestMessageFour : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
public int C;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
writer.WriteValue(this);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
return true;
}
public void Handle(ref NetworkContext context)
{
}
public int Version => 0;
}
private class TestMessageProviderThree : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(TestMessageFour),
Handler = NetworkMessageManager.ReceiveMessage<TestMessageFour>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessageFour>
}
};
}
}
[Test]
public void WhenCreatingMessageSystem_OnlyProvidedTypesAreRegistered()
{
var sender = new NopMessageSender();
using var systemOne = new NetworkMessageManager(sender, null, new TestMessageProviderOne());
using var systemTwo = new NetworkMessageManager(sender, null, new TestMessageProviderTwo());
using var systemThree = new NetworkMessageManager(sender, null, new TestMessageProviderThree());
using (systemOne)
using (systemTwo)
using (systemThree)
{
Assert.AreEqual(2, systemOne.MessageHandlerCount);
Assert.AreEqual(1, systemTwo.MessageHandlerCount);
Assert.AreEqual(1, systemThree.MessageHandlerCount);
Assert.Contains(typeof(TestMessageOne), systemOne.MessageTypes);
Assert.Contains(typeof(TestMessageTwo), systemOne.MessageTypes);
Assert.Contains(typeof(TestMessageThree), systemTwo.MessageTypes);
Assert.Contains(typeof(TestMessageFour), systemThree.MessageTypes);
}
}
[Test]
public void WhenCreatingMessageSystem_BoundTypeMessageHandlersAreRegistered()
{
var sender = new NopMessageSender();
using var systemOne = new NetworkMessageManager(sender, null, new TestMessageProviderOne());
using var systemTwo = new NetworkMessageManager(sender, null, new TestMessageProviderTwo());
using var systemThree = new NetworkMessageManager(sender, null, new TestMessageProviderThree());
using (systemOne)
using (systemTwo)
using (systemThree)
{
NetworkMessageManager.MessageHandler handlerOne = NetworkMessageManager.ReceiveMessage<TestMessageOne>;
NetworkMessageManager.MessageHandler handlerTwo = NetworkMessageManager.ReceiveMessage<TestMessageTwo>;
NetworkMessageManager.MessageHandler handlerThree = NetworkMessageManager.ReceiveMessage<TestMessageThree>;
NetworkMessageManager.MessageHandler handlerFour = NetworkMessageManager.ReceiveMessage<TestMessageFour>;
Assert.AreEqual(handlerOne, systemOne.MessageHandlers[systemOne.GetMessageType(typeof(TestMessageOne))]);
Assert.AreEqual(handlerTwo, systemOne.MessageHandlers[systemOne.GetMessageType(typeof(TestMessageTwo))]);
Assert.AreEqual(handlerThree, systemTwo.MessageHandlers[systemTwo.GetMessageType(typeof(TestMessageThree))]);
Assert.AreEqual(handlerFour, systemThree.MessageHandlers[systemThree.GetMessageType(typeof(TestMessageFour))]);
}
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 03e7cc2b6f0c5c540a529429f48529f5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,369 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.TestTools;
using Random = System.Random;
namespace Unity.Netcode.EditorTests
{
internal class MessageSendingTests
{
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
public int C;
public static bool Serialized;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
Serialized = true;
writer.WriteValueSafe(this);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
return true;
}
public void Handle(ref NetworkContext context)
{
}
public int Version => 0;
}
private class TestMessageSender : INetworkMessageSender
{
public List<byte[]> MessageQueue = new List<byte[]>();
public void Send(ulong clientId, NetworkDelivery delivery, FastBufferWriter batchData)
{
MessageQueue.Add(batchData.ToArray());
}
}
private class TestMessageProvider : INetworkMessageProvider, IDisposable
{
// Keep track of what we sent
private List<List<NetworkMessageManager.MessageWithHandler>> m_CachedMessages = new List<List<NetworkMessageManager.MessageWithHandler>>();
public void Dispose()
{
foreach (var cachedItem in m_CachedMessages)
{
// Clear out any references to NetworkMessageManager.MessageWithHandlers
cachedItem.Clear();
}
m_CachedMessages.Clear();
}
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
var messageList = new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(TestMessage),
Handler = NetworkMessageManager.ReceiveMessage<TestMessage>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessage>
}
};
// Track messages sent
m_CachedMessages.Add(messageList);
return messageList;
}
}
private TestMessageProvider m_TestMessageProvider;
private TestMessageSender m_MessageSender;
private NetworkMessageManager m_MessageManager;
private ulong[] m_Clients = { 0 };
[SetUp]
public void SetUp()
{
TestMessage.Serialized = false;
m_MessageSender = new TestMessageSender();
m_TestMessageProvider = new TestMessageProvider();
m_MessageManager = new NetworkMessageManager(m_MessageSender, this, m_TestMessageProvider);
m_MessageManager.ClientConnected(0);
m_MessageManager.SetVersion(0, XXHash.Hash32(typeof(TestMessage).FullName), 0);
}
[TearDown]
public void TearDown()
{
m_TestMessageProvider.Dispose();
m_MessageManager.Dispose();
}
private TestMessage GetMessage()
{
var random = new Random();
return new TestMessage
{
A = random.Next(),
B = random.Next(),
C = random.Next(),
};
}
[Test]
public void WhenSendingMessage_SerializeIsCalled()
{
var message = GetMessage();
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
Assert.IsTrue(TestMessage.Serialized);
}
[Test]
public void WhenSendingMessage_NothingIsSentBeforeProcessingSendQueue()
{
var message = GetMessage();
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
Assert.IsEmpty(m_MessageSender.MessageQueue);
}
[Test]
public void WhenProcessingSendQueue_MessageIsSent()
{
var message = GetMessage();
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.ProcessSendQueues();
Assert.AreEqual(1, m_MessageSender.MessageQueue.Count);
}
[Test]
public void WhenSendingMultipleMessages_MessagesAreBatched()
{
var message = GetMessage();
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.ProcessSendQueues();
Assert.AreEqual(1, m_MessageSender.MessageQueue.Count);
}
[Test]
public void WhenNotExceedingBatchSize_NewBatchesAreNotCreated()
{
var message = GetMessage();
var size = UnsafeUtility.SizeOf<TestMessage>() + 2; // MessageHeader packed with this message will be 2 bytes
for (var i = 0; i < (m_MessageManager.NonFragmentedMessageMaxSize - UnsafeUtility.SizeOf<NetworkBatchHeader>()) / size; ++i)
{
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
}
m_MessageManager.ProcessSendQueues();
Assert.AreEqual(1, m_MessageSender.MessageQueue.Count);
}
[Test]
public void WhenExceedingBatchSize_NewBatchesAreCreated([Values(500, 1000, 1300, 2000)] int maxMessageSize)
{
var message = GetMessage();
m_MessageManager.NonFragmentedMessageMaxSize = maxMessageSize;
var size = UnsafeUtility.SizeOf<TestMessage>() + 2; // MessageHeader packed with this message will be 2 bytes
for (var i = 0; i < ((m_MessageManager.NonFragmentedMessageMaxSize - UnsafeUtility.SizeOf<NetworkBatchHeader>()) / size) + 1; ++i)
{
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
}
m_MessageManager.ProcessSendQueues();
Assert.AreEqual(2, m_MessageSender.MessageQueue.Count);
}
[Test]
public void WhenExceedingPerClientBatchSizeLessThanDefault_NewBatchesAreCreated([Values(500, 1000, 1300, 2000)] int maxMessageSize)
{
var message = GetMessage();
m_MessageManager.NonFragmentedMessageMaxSize = maxMessageSize * 5;
var clients = new ulong[] { 0, 1, 2 };
m_MessageManager.ClientConnected(1);
m_MessageManager.ClientConnected(2);
m_MessageManager.SetVersion(1, XXHash.Hash32(typeof(TestMessage).FullName), 0);
m_MessageManager.SetVersion(2, XXHash.Hash32(typeof(TestMessage).FullName), 0);
for (var i = 0; i < clients.Length; ++i)
{
m_MessageManager.PeerMTUSizes[clients[i]] = maxMessageSize * (i + 1);
}
var size = UnsafeUtility.SizeOf<TestMessage>() + 2; // MessageHeader packed with this message will be 2 bytes
for (var i = 0; i < clients.Length; ++i)
{
for (var j = 0; j < ((m_MessageManager.PeerMTUSizes[clients[i]] - UnsafeUtility.SizeOf<NetworkBatchHeader>()) / size) + 1; ++j)
{
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, clients[i]);
}
}
m_MessageManager.ProcessSendQueues();
Assert.AreEqual(2 * clients.Length, m_MessageSender.MessageQueue.Count);
}
[Test]
public void WhenExceedingPerClientBatchSizeGreaterThanDefault_OnlyOneNewBatcheIsCreated([Values(500, 1000, 1300, 2000)] int maxMessageSize)
{
var message = GetMessage();
m_MessageManager.NonFragmentedMessageMaxSize = 128;
var clients = new ulong[] { 0, 1, 2 };
m_MessageManager.ClientConnected(1);
m_MessageManager.ClientConnected(2);
m_MessageManager.SetVersion(1, XXHash.Hash32(typeof(TestMessage).FullName), 0);
m_MessageManager.SetVersion(2, XXHash.Hash32(typeof(TestMessage).FullName), 0);
for (var i = 0; i < clients.Length; ++i)
{
m_MessageManager.PeerMTUSizes[clients[i]] = maxMessageSize * (i + 1);
}
var size = UnsafeUtility.SizeOf<TestMessage>() + 2; // MessageHeader packed with this message will be 2 bytes
for (var i = 0; i < clients.Length; ++i)
{
for (var j = 0; j < ((m_MessageManager.PeerMTUSizes[clients[i]] - UnsafeUtility.SizeOf<NetworkBatchHeader>()) / size) + 1; ++j)
{
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, clients[i]);
}
}
m_MessageManager.ProcessSendQueues();
Assert.AreEqual(2 * clients.Length, m_MessageSender.MessageQueue.Count);
}
[Test]
public void WhenExceedingMTUSizeWithFragmentedDelivery_NewBatchesAreNotCreated([Values(500, 1000, 1300, 2000)] int maxMessageSize)
{
var message = GetMessage();
m_MessageManager.NonFragmentedMessageMaxSize = maxMessageSize;
var size = UnsafeUtility.SizeOf<TestMessage>() + 2; // MessageHeader packed with this message will be 2 bytes
for (var i = 0; i < ((m_MessageManager.NonFragmentedMessageMaxSize - UnsafeUtility.SizeOf<NetworkBatchHeader>()) / size) + 1; ++i)
{
m_MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, m_Clients);
}
m_MessageManager.ProcessSendQueues();
Assert.AreEqual(1, m_MessageSender.MessageQueue.Count);
}
[Test]
public void WhenSwitchingDelivery_NewBatchesAreCreated()
{
var message = GetMessage();
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.SendMessage(ref message, NetworkDelivery.Unreliable, m_Clients);
m_MessageManager.ProcessSendQueues();
Assert.AreEqual(2, m_MessageSender.MessageQueue.Count);
}
[Test]
public void WhenSwitchingChannel_NewBatchesAreNotCreated()
{
var message = GetMessage();
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.ProcessSendQueues();
Assert.AreEqual(1, m_MessageSender.MessageQueue.Count);
}
[Test]
public void WhenSendingMessaged_SentDataIsCorrect()
{
var message = GetMessage();
var message2 = GetMessage();
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.SendMessage(ref message2, NetworkDelivery.Reliable, m_Clients);
m_MessageManager.ProcessSendQueues();
var reader = new FastBufferReader(m_MessageSender.MessageQueue[0], Allocator.Temp);
using (reader)
{
reader.ReadValueSafe(out NetworkBatchHeader header);
Assert.AreEqual(2, header.BatchCount);
NetworkMessageHeader messageHeader;
ByteUnpacker.ReadValueBitPacked(reader, out messageHeader.MessageType);
ByteUnpacker.ReadValueBitPacked(reader, out messageHeader.MessageSize);
Assert.AreEqual(m_MessageManager.GetMessageType(typeof(TestMessage)), messageHeader.MessageType);
Assert.AreEqual(UnsafeUtility.SizeOf<TestMessage>(), messageHeader.MessageSize);
reader.ReadValueSafe(out TestMessage receivedMessage);
Assert.AreEqual(message, receivedMessage);
ByteUnpacker.ReadValueBitPacked(reader, out messageHeader.MessageType);
ByteUnpacker.ReadValueBitPacked(reader, out messageHeader.MessageSize);
Assert.AreEqual(m_MessageManager.GetMessageType(typeof(TestMessage)), messageHeader.MessageType);
Assert.AreEqual(UnsafeUtility.SizeOf<TestMessage>(), messageHeader.MessageSize);
reader.ReadValueSafe(out TestMessage receivedMessage2);
Assert.AreEqual(message2, receivedMessage2);
}
}
private class TestNoHandlerMessageProvider : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(TestMessage),
Handler = null,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessage>
}
};
}
}
[Test]
public void WhenReceivingAMessageWithoutAHandler_ExceptionIsLogged()
{
// If a NetworkMessageManager already exists then dispose of it before creating a new NetworkMessageManager (otherwise memory leak)
if (m_MessageManager != null)
{
m_MessageManager.Dispose();
m_MessageManager = null;
}
// Since m_MessageManager is disposed during teardown we don't need to worry about that here.
m_MessageManager = new NetworkMessageManager(new NopMessageSender(), this, new TestNoHandlerMessageProvider());
m_MessageManager.ClientConnected(0);
var messageHeader = new NetworkMessageHeader
{
MessageSize = (ushort)UnsafeUtility.SizeOf<TestMessage>(),
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
};
var message = GetMessage();
var writer = new FastBufferWriter(m_MessageManager.NonFragmentedMessageMaxSize, Allocator.Temp);
using (writer)
{
writer.TryBeginWrite(FastBufferWriter.GetWriteSize(message));
writer.WriteValue(message);
var reader = new FastBufferReader(writer, Allocator.Temp);
using (reader)
{
m_MessageManager.HandleMessage(messageHeader, reader, 0, 0, 0);
LogAssert.Expect(LogType.Exception, new Regex(".*HandlerNotRegisteredException.*"));
}
}
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: ea2fc218c5e07c54795fc9bed4a6a62c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,503 +0,0 @@
using System;
using System.Collections.Generic;
using NUnit.Framework;
using NUnit.Framework.Internal;
namespace Unity.Netcode.EditorTests
{
internal class MessageVersioningTests
{
public static int SentVersion;
public static int ReceivedVersion;
private const int k_DefaultB = 5;
private const int k_DefaultC = 10;
private const int k_DefaultD = 15;
private const long k_DefaultE = 20;
private struct VersionedTestMessageV0 : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
public int C;
public static bool Serialized;
public static bool Deserialized;
public static bool Handled;
public static List<VersionedTestMessageV0> DeserializedValues = new List<VersionedTestMessageV0>();
public void Serialize(FastBufferWriter writer, int targetVersion)
{
SentVersion = Version;
Serialized = true;
writer.WriteValueSafe(A);
writer.WriteValueSafe(B);
writer.WriteValueSafe(C);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
ReceivedVersion = Version;
Deserialized = true;
reader.ReadValueSafe(out A);
reader.ReadValueSafe(out B);
reader.ReadValueSafe(out C);
return true;
}
public void Handle(ref NetworkContext context)
{
Handled = true;
DeserializedValues.Add(this);
}
public int Version => 0;
}
private struct VersionedTestMessageV1 : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
public int C;
public int D;
public static bool Serialized;
public static bool Deserialized;
public static bool Downgraded;
public static bool Upgraded;
public static bool Handled;
public static List<VersionedTestMessageV1> DeserializedValues = new List<VersionedTestMessageV1>();
public void Serialize(FastBufferWriter writer, int targetVersion)
{
if (targetVersion < Version)
{
Downgraded = true;
var v0 = new VersionedTestMessageV0 { A = A, B = B, C = C };
v0.Serialize(writer, targetVersion);
return;
}
SentVersion = Version;
Serialized = true;
writer.WriteValueSafe(C);
writer.WriteValueSafe(D);
writer.WriteValueSafe(A);
writer.WriteValueSafe(B);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
if (receivedMessageVersion < Version)
{
var v0 = new VersionedTestMessageV0();
v0.Deserialize(reader, ref context, receivedMessageVersion);
A = v0.A;
B = v0.B;
C = v0.C;
D = k_DefaultD;
Upgraded = true;
return true;
}
ReceivedVersion = Version;
Deserialized = true;
reader.ReadValueSafe(out C);
reader.ReadValueSafe(out D);
reader.ReadValueSafe(out A);
reader.ReadValueSafe(out B);
return true;
}
public void Handle(ref NetworkContext context)
{
Handled = true;
DeserializedValues.Add(this);
}
public int Version => 1;
}
private struct VersionedTestMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public float D;
public long E;
public static bool Serialized;
public static bool Deserialized;
public static bool Downgraded;
public static bool Upgraded;
public static bool Handled;
public static List<VersionedTestMessage> DeserializedValues = new List<VersionedTestMessage>();
public void Serialize(FastBufferWriter writer, int targetVersion)
{
if (targetVersion < Version)
{
Downgraded = true;
var v1 = new VersionedTestMessageV1 { A = A, B = k_DefaultB, C = k_DefaultC, D = (int)D };
v1.Serialize(writer, targetVersion);
return;
}
SentVersion = Version;
Serialized = true;
writer.WriteValueSafe(D);
writer.WriteValueSafe(A);
writer.WriteValueSafe(E);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
if (receivedMessageVersion < Version)
{
var v1 = new VersionedTestMessageV1();
v1.Deserialize(reader, ref context, receivedMessageVersion);
A = v1.A;
D = v1.D;
E = k_DefaultE;
Upgraded = true;
return true;
}
ReceivedVersion = Version;
Deserialized = true;
reader.ReadValueSafe(out D);
reader.ReadValueSafe(out A);
reader.ReadValueSafe(out E);
return true;
}
public void Handle(ref NetworkContext context)
{
Handled = true;
DeserializedValues.Add(this);
}
public int Version => 2;
}
private class TestMessageProviderV0 : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(VersionedTestMessageV0),
Handler = NetworkMessageManager.ReceiveMessage<VersionedTestMessageV0>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<VersionedTestMessageV0>
}
};
}
}
private class TestMessageProviderV1 : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(VersionedTestMessageV1),
Handler = NetworkMessageManager.ReceiveMessage<VersionedTestMessageV1>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<VersionedTestMessageV1>
}
};
}
}
private class TestMessageProviderV2 : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
return new List<NetworkMessageManager.MessageWithHandler>
{
new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(VersionedTestMessage),
Handler = NetworkMessageManager.ReceiveMessage<VersionedTestMessage>,
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<VersionedTestMessage>
}
};
}
}
private class TestMessageSender : INetworkMessageSender
{
public List<byte[]> MessageQueue = new List<byte[]>();
public void Send(ulong clientId, NetworkDelivery delivery, FastBufferWriter batchData)
{
MessageQueue.Add(batchData.ToArray());
}
}
private NetworkMessageManager m_MessageManagerV0;
private NetworkMessageManager m_MessageManagerV1;
private NetworkMessageManager m_MessageManagerV2;
private TestMessageSender m_MessageSender;
private void CreateFakeClients(NetworkMessageManager system, uint hash)
{
// Create three fake clients for each NetworkMessageManager
// client 0 has version 0, client 1 has version 1, and client 2 has version 2
system.ClientConnected(0);
system.ClientConnected(1);
system.ClientConnected(2);
system.SetVersion(0, hash, 0);
system.SetVersion(1, hash, 1);
system.SetVersion(2, hash, 2);
}
[SetUp]
public void SetUp()
{
VersionedTestMessageV0.Serialized = false;
VersionedTestMessageV0.Deserialized = false;
VersionedTestMessageV0.Handled = false;
VersionedTestMessageV0.DeserializedValues.Clear();
VersionedTestMessageV1.Serialized = false;
VersionedTestMessageV1.Deserialized = false;
VersionedTestMessageV1.Downgraded = false;
VersionedTestMessageV1.Upgraded = false;
VersionedTestMessageV1.Handled = false;
VersionedTestMessageV1.DeserializedValues.Clear();
VersionedTestMessage.Serialized = false;
VersionedTestMessage.Deserialized = false;
VersionedTestMessage.Downgraded = false;
VersionedTestMessage.Upgraded = false;
VersionedTestMessage.Handled = false;
VersionedTestMessage.DeserializedValues.Clear();
m_MessageSender = new TestMessageSender();
m_MessageManagerV0 = new NetworkMessageManager(m_MessageSender, this, new TestMessageProviderV0());
m_MessageManagerV1 = new NetworkMessageManager(m_MessageSender, this, new TestMessageProviderV1());
m_MessageManagerV2 = new NetworkMessageManager(m_MessageSender, this, new TestMessageProviderV2());
CreateFakeClients(m_MessageManagerV0, XXHash.Hash32(typeof(VersionedTestMessageV0).FullName));
CreateFakeClients(m_MessageManagerV1, XXHash.Hash32(typeof(VersionedTestMessageV1).FullName));
CreateFakeClients(m_MessageManagerV2, XXHash.Hash32(typeof(VersionedTestMessage).FullName));
// Make sure that all three messages got the same IDs...
Assert.AreEqual(
m_MessageManagerV0.GetMessageType(typeof(VersionedTestMessageV0)),
m_MessageManagerV1.GetMessageType(typeof(VersionedTestMessageV1)));
Assert.AreEqual(
m_MessageManagerV0.GetMessageType(typeof(VersionedTestMessageV0)),
m_MessageManagerV2.GetMessageType(typeof(VersionedTestMessage)));
}
[TearDown]
public void TearDown()
{
m_MessageManagerV0.Dispose();
m_MessageManagerV1.Dispose();
m_MessageManagerV2.Dispose();
}
private VersionedTestMessageV0 GetMessage_v0()
{
var random = new Random();
return new VersionedTestMessageV0
{
A = random.Next(),
B = random.Next(),
C = random.Next(),
};
}
private VersionedTestMessageV1 GetMessage_v1()
{
var random = new Random();
return new VersionedTestMessageV1
{
A = random.Next(),
B = random.Next(),
C = random.Next(),
D = random.Next(),
};
}
private VersionedTestMessage GetMessage_v2()
{
var random = new Random();
return new VersionedTestMessage
{
A = random.Next(),
D = (float)(random.NextDouble() * 10000),
E = ((long)random.Next() << 32) + random.Next()
};
}
public void CheckPostSendExpectations(int sourceLocalVersion, int remoteVersion)
{
Assert.AreEqual(Math.Min(sourceLocalVersion, remoteVersion) == 0, VersionedTestMessageV0.Serialized);
Assert.AreEqual(Math.Min(sourceLocalVersion, remoteVersion) == 1, VersionedTestMessageV1.Serialized);
Assert.AreEqual(Math.Min(sourceLocalVersion, remoteVersion) == 2, VersionedTestMessage.Serialized);
Assert.AreEqual(sourceLocalVersion >= 1 && remoteVersion < 1, VersionedTestMessageV1.Downgraded);
Assert.AreEqual(sourceLocalVersion >= 2 && remoteVersion < 2, VersionedTestMessage.Downgraded);
Assert.AreEqual(1, m_MessageSender.MessageQueue.Count);
Assert.AreEqual(Math.Min(sourceLocalVersion, remoteVersion), SentVersion);
}
public void CheckPostReceiveExpectations(int sourceLocalVersion, int remoteVersion)
{
Assert.AreEqual(SentVersion == 0, VersionedTestMessageV0.Deserialized);
Assert.AreEqual(SentVersion == 1, VersionedTestMessageV1.Deserialized);
Assert.AreEqual(SentVersion == 2, VersionedTestMessage.Deserialized);
Assert.AreEqual(remoteVersion >= 1 && sourceLocalVersion < 1, VersionedTestMessageV1.Upgraded);
Assert.AreEqual(remoteVersion >= 2 && sourceLocalVersion < 2, VersionedTestMessage.Upgraded);
Assert.AreEqual((remoteVersion == 0 ? 1 : 0), VersionedTestMessageV0.DeserializedValues.Count);
Assert.AreEqual((remoteVersion == 1 ? 1 : 0), VersionedTestMessageV1.DeserializedValues.Count);
Assert.AreEqual((remoteVersion == 2 ? 1 : 0), VersionedTestMessage.DeserializedValues.Count);
Assert.AreEqual(SentVersion, ReceivedVersion);
}
private void SendMessageWithVersions<T>(T message, int fromVersion, int toVersion) where T : unmanaged, INetworkMessage
{
NetworkMessageManager sendSystem;
switch (fromVersion)
{
case 0: sendSystem = m_MessageManagerV0; break;
case 1: sendSystem = m_MessageManagerV1; break;
default: sendSystem = m_MessageManagerV2; break;
}
sendSystem.SendMessage(ref message, NetworkDelivery.Reliable, (ulong)toVersion);
sendSystem.ProcessSendQueues();
CheckPostSendExpectations(fromVersion, toVersion);
NetworkMessageManager receiveSystem;
switch (toVersion)
{
case 0: receiveSystem = m_MessageManagerV0; break;
case 1: receiveSystem = m_MessageManagerV1; break;
default: receiveSystem = m_MessageManagerV2; break;
}
receiveSystem.HandleIncomingData((ulong)fromVersion, new ArraySegment<byte>(m_MessageSender.MessageQueue[0]), 0.0f);
receiveSystem.ProcessIncomingMessageQueue();
CheckPostReceiveExpectations(fromVersion, toVersion);
m_MessageSender.MessageQueue.Clear();
}
[Test]
public void WhenSendingV0ToV0_DataIsReceivedCorrectly()
{
var message = GetMessage_v0();
SendMessageWithVersions(message, 0, 0);
var receivedMessage = VersionedTestMessageV0.DeserializedValues[0];
Assert.AreEqual(message.A, receivedMessage.A);
Assert.AreEqual(message.B, receivedMessage.B);
Assert.AreEqual(message.C, receivedMessage.C);
}
[Test]
public void WhenSendingV0ToV1_DataIsReceivedCorrectly()
{
var message = GetMessage_v0();
SendMessageWithVersions(message, 0, 1);
var receivedMessage = VersionedTestMessageV1.DeserializedValues[0];
Assert.AreEqual(message.A, receivedMessage.A);
Assert.AreEqual(message.B, receivedMessage.B);
Assert.AreEqual(message.C, receivedMessage.C);
Assert.AreEqual(k_DefaultD, receivedMessage.D);
}
[Test]
public void WhenSendingV0ToV2_DataIsReceivedCorrectly()
{
var message = GetMessage_v0();
SendMessageWithVersions(message, 0, 2);
var receivedMessage = VersionedTestMessage.DeserializedValues[0];
Assert.AreEqual(message.A, receivedMessage.A);
Assert.AreEqual((float)k_DefaultD, receivedMessage.D);
Assert.AreEqual(k_DefaultE, receivedMessage.E);
}
[Test]
public void WhenSendingV1ToV0_DataIsReceivedCorrectly()
{
var message = GetMessage_v1();
SendMessageWithVersions(message, 1, 0);
var receivedMessage = VersionedTestMessageV0.DeserializedValues[0];
Assert.AreEqual(message.A, receivedMessage.A);
Assert.AreEqual(message.B, receivedMessage.B);
Assert.AreEqual(message.C, receivedMessage.C);
}
[Test]
public void WhenSendingV1ToV1_DataIsReceivedCorrectly()
{
var message = GetMessage_v1();
SendMessageWithVersions(message, 1, 1);
var receivedMessage = VersionedTestMessageV1.DeserializedValues[0];
Assert.AreEqual(message.A, receivedMessage.A);
Assert.AreEqual(message.B, receivedMessage.B);
Assert.AreEqual(message.C, receivedMessage.C);
Assert.AreEqual(message.D, receivedMessage.D);
}
[Test]
public void WhenSendingV1ToV2_DataIsReceivedCorrectly()
{
var message = GetMessage_v1();
SendMessageWithVersions(message, 1, 2);
var receivedMessage = VersionedTestMessage.DeserializedValues[0];
Assert.AreEqual(message.A, receivedMessage.A);
Assert.AreEqual((float)message.D, receivedMessage.D);
Assert.AreEqual(k_DefaultE, receivedMessage.E);
}
[Test]
public void WhenSendingV2ToV0_DataIsReceivedCorrectly()
{
var message = GetMessage_v2();
SendMessageWithVersions(message, 2, 0);
var receivedMessage = VersionedTestMessageV0.DeserializedValues[0];
Assert.AreEqual(message.A, receivedMessage.A);
Assert.AreEqual(k_DefaultB, receivedMessage.B);
Assert.AreEqual(k_DefaultC, receivedMessage.C);
}
[Test]
public void WhenSendingV2ToV1_DataIsReceivedCorrectly()
{
var message = GetMessage_v2();
SendMessageWithVersions(message, 2, 1);
var receivedMessage = VersionedTestMessageV1.DeserializedValues[0];
Assert.AreEqual(message.A, receivedMessage.A);
Assert.AreEqual(k_DefaultB, receivedMessage.B);
Assert.AreEqual(k_DefaultC, receivedMessage.C);
Assert.AreEqual((int)message.D, receivedMessage.D);
}
[Test]
public void WhenSendingV2ToV2_DataIsReceivedCorrectly()
{
var message = GetMessage_v2();
SendMessageWithVersions(message, 2, 2);
var receivedMessage = VersionedTestMessage.DeserializedValues[0];
Assert.AreEqual(message.A, receivedMessage.A);
Assert.AreEqual(message.D, receivedMessage.D);
Assert.AreEqual(message.E, receivedMessage.E);
}
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: eac9a654aacb4faf91128c9ab6024543
timeCreated: 1667326658

View File

@@ -1,9 +0,0 @@
namespace Unity.Netcode.EditorTests
{
internal class NopMessageSender : INetworkMessageSender
{
public void Send(ulong clientId, NetworkDelivery delivery, FastBufferWriter batchData)
{
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 817c58672ba39a74da57082ed176956e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 87ddfad8823c4fe192fff56b7acc241b
timeCreated: 1629386688

View File

@@ -1,42 +0,0 @@
#if MULTIPLAYER_TOOLS
using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Unity.Multiplayer.Tools.MetricTypes;
using Unity.Multiplayer.Tools.NetStats;
namespace Unity.Netcode.EditorTests.Metrics
{
internal class NetworkMetricsRegistrationTests
{
private static Type[] s_MetricTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => x.GetInterfaces().Contains(typeof(INetworkMetricEvent)))
.ToArray();
[TestCaseSource(nameof(s_MetricTypes))]
[Ignore("Disable test while we reevaluate the assumption that INetworkMetricEvent interfaces must be reported from MLAPI.")]
public void ValidateThatAllMetricTypesAreRegistered(Type metricType)
{
var dispatcher = new NetworkMetrics().Dispatcher as MetricDispatcher;
Assert.NotNull(dispatcher);
var collection = typeof(MetricDispatcher)
.GetField("m_Collection", BindingFlags.NonPublic | BindingFlags.Instance)?
.GetValue(dispatcher) as MetricCollection;
Assert.NotNull(collection);
Assert.That(
collection.Metrics.OfType<IEventMetric>(),
Has.Exactly(2).Matches<IEventMetric>(
eventMetric =>
{
var eventType = eventMetric.GetType().GetGenericArguments()?.FirstOrDefault();
return eventType == metricType;
}));
}
}
}
#endif

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: af741f5e3d4f5544eaa68bb9bcaf54c6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,79 +0,0 @@
using NUnit.Framework;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Unity.Netcode.EditorTests
{
internal class NetworkBehaviourTests
{
[Test]
public void HasNetworkObjectTest()
{
var gameObject = new GameObject(nameof(HasNetworkObjectTest));
var networkBehaviour = gameObject.AddComponent<EmptyNetworkBehaviour>();
Assert.That(networkBehaviour.HasNetworkObject, Is.False);
var networkObject = gameObject.AddComponent<NetworkObject>();
Assert.That(networkBehaviour.HasNetworkObject, Is.True);
Object.DestroyImmediate(networkObject);
Assert.That(networkBehaviour.HasNetworkObject, Is.False);
// Cleanup
Object.DestroyImmediate(gameObject);
}
[Test]
public void AccessNetworkObjectTest()
{
var gameObject = new GameObject(nameof(AccessNetworkObjectTest));
var networkBehaviour = gameObject.AddComponent<EmptyNetworkBehaviour>();
Assert.That(networkBehaviour.NetworkObject, Is.Null);
var networkObject = gameObject.AddComponent<NetworkObject>();
Assert.That(networkBehaviour.NetworkObject, Is.EqualTo(networkObject));
Object.DestroyImmediate(networkObject);
Assert.That(networkBehaviour.NetworkObject, Is.Null);
// Cleanup
Object.DestroyImmediate(gameObject);
}
[Test]
public void GivenClassDerivesFromNetworkBehaviour_GetTypeNameReturnsCorrectValue()
{
var gameObject = new GameObject(nameof(GivenClassDerivesFromNetworkBehaviour_GetTypeNameReturnsCorrectValue));
var networkBehaviour = gameObject.AddComponent<EmptyNetworkBehaviour>();
Assert.AreEqual(nameof(EmptyNetworkBehaviour), networkBehaviour.__getTypeName());
}
[Test]
public void GivenClassDerivesFromNetworkBehaviourDerivedClass_GetTypeNameReturnsCorrectValue()
{
var gameObject = new GameObject(nameof(GivenClassDerivesFromNetworkBehaviourDerivedClass_GetTypeNameReturnsCorrectValue));
var networkBehaviour = gameObject.AddComponent<DerivedNetworkBehaviour>();
Assert.AreEqual(nameof(DerivedNetworkBehaviour), networkBehaviour.__getTypeName());
}
// Note: in order to repro https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/1078
// this child class must be defined before its parent to assure it is processed first by ILPP
internal class DerivedNetworkBehaviour : EmptyNetworkBehaviour
{
}
internal class EmptyNetworkBehaviour : NetworkBehaviour
{
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 73e18571452c102e4b209671741f3b51
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,563 +0,0 @@
using System.Collections.Generic;
using NUnit.Framework;
using Unity.Netcode.Editor;
using Unity.Netcode.Transports.UTP;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests
{
internal class NetworkManagerConfigurationTests
{
[SetUp]
public void OnSetup()
{
ILPPMessageProvider.IntegrationTestNoMessages = true;
}
[TearDown]
public void OnTearDown()
{
ILPPMessageProvider.IntegrationTestNoMessages = false;
}
/// <summary>
/// Does a simple check to make sure the nested network manager will
/// notify the user when in the editor. This is just a unit test to
/// validate this is functioning
/// </summary>
[Test]
public void NestedNetworkManagerCheck()
{
var parent = new GameObject("ParentObject");
var networkManagerObject = new GameObject(nameof(NestedNetworkManagerCheck));
var networkManager = networkManagerObject.AddComponent<NetworkManager>();
// Make our NetworkManager's GameObject nested
networkManagerObject.transform.parent = parent.transform;
// Pre-generate the error message we are expecting to see
var messageToCheck = NetworkManager.GenerateNestedNetworkManagerMessage(networkManagerObject.transform);
// Trap for the nested NetworkManager exception
LogAssert.Expect(LogType.Error, messageToCheck);
// Since this is an in-editor test, we must force this invocation
NetworkManagerHelper.Singleton.NotifyUserOfNestedNetworkManager(networkManager, false, true);
// Clean up
Object.DestroyImmediate(parent);
}
public enum NetworkObjectPlacement
{
Root, // Added to the same root GameObject
Child // Added to a child GameObject
}
[Test]
public void NetworkObjectNotAllowed([Values] NetworkObjectPlacement networkObjectPlacement)
{
var gameObject = new GameObject(nameof(NetworkManager));
var targetforNetworkObject = gameObject;
if (networkObjectPlacement == NetworkObjectPlacement.Child)
{
var childGameObject = new GameObject($"{nameof(NetworkManager)}-Child");
childGameObject.transform.parent = targetforNetworkObject.transform;
targetforNetworkObject = childGameObject;
}
var networkManager = gameObject.AddComponent<NetworkManager>();
// Trap for the error message generated when a NetworkObject is discovered on the same GameObject or any children under it
LogAssert.Expect(LogType.Error, NetworkManagerHelper.Singleton.NetworkManagerAndNetworkObjectNotAllowedMessage());
// Add the NetworkObject
var networkObject = targetforNetworkObject.AddComponent<NetworkObject>();
// Since this is an in-editor test, we must force this invocation
NetworkManagerHelper.Singleton.CheckAndNotifyUserNetworkObjectRemoved(networkManager, true);
// Validate that the NetworkObject has been removed
if (networkObjectPlacement == NetworkObjectPlacement.Root)
{
Assert.IsNull(networkManager.gameObject.GetComponent<NetworkObject>(), $"There is still a {nameof(NetworkObject)} on {nameof(NetworkManager)}'s GameObject!");
}
else
{
Assert.IsNull(networkManager.gameObject.GetComponentInChildren<NetworkObject>(), $"There is still a {nameof(NetworkObject)} on {nameof(NetworkManager)}'s child GameObject!");
}
// Clean up
Object.DestroyImmediate(gameObject);
}
[Test]
public void NestedNetworkObjectPrefabCheck()
{
// Setup
var networkManagerObject = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager = networkManagerObject.AddComponent<NetworkManager>();
networkManager.NetworkConfig = new NetworkConfig();
var parent = new GameObject("Parent").AddComponent<NetworkObject>();
var child = new GameObject("Child").AddComponent<NetworkObject>();
// Set parent
child.transform.SetParent(parent.transform);
// Make it a prefab, warning only applies to prefabs
networkManager.AddNetworkPrefab(parent.gameObject);
// Mark scene as dirty to ensure OnValidate actually runs
EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
// Force OnValidate
networkManager.OnValidate();
// Expect a warning
LogAssert.Expect(LogType.Warning, $"[Netcode] {NetworkPrefabHandler.PrefabDebugHelper(networkManager.NetworkConfig.Prefabs.Prefabs[0])} has child {nameof(NetworkObject)}(s) but they will not be spawned across the network (unsupported {nameof(NetworkPrefab)} setup)");
// Clean up
Object.DestroyImmediate(networkManagerObject);
Object.DestroyImmediate(parent);
}
[Test]
public void WhenNetworkConfigContainsOldPrefabList_TheyMigrateProperlyToTheNewList()
{
var networkConfig = new NetworkConfig();
var regularPrefab = new GameObject("Regular Prefab").AddComponent<NetworkObject>();
var overriddenPrefab = new GameObject("Overridden Prefab").AddComponent<NetworkObject>();
var overridingTargetPrefab = new GameObject("Overriding Target Prefab").AddComponent<NetworkObject>();
var sourcePrefabToOverride = new GameObject("Overriding Source Prefab").AddComponent<NetworkObject>();
regularPrefab.GlobalObjectIdHash = 1;
overriddenPrefab.GlobalObjectIdHash = 2;
overridingTargetPrefab.GlobalObjectIdHash = 3;
sourcePrefabToOverride.GlobalObjectIdHash = 4;
networkConfig.OldPrefabList = new List<NetworkPrefab>
{
new NetworkPrefab { Prefab = regularPrefab.gameObject },
new NetworkPrefab { Prefab = overriddenPrefab.gameObject, Override = NetworkPrefabOverride.Prefab, OverridingTargetPrefab = overridingTargetPrefab.gameObject, SourcePrefabToOverride = sourcePrefabToOverride.gameObject, SourceHashToOverride = 123456 }
};
networkConfig.InitializePrefabs();
Assert.IsNull(networkConfig.OldPrefabList);
Assert.IsNotNull(networkConfig.Prefabs);
Assert.IsNotNull(networkConfig.Prefabs.Prefabs);
Assert.AreEqual(2, networkConfig.Prefabs.Prefabs.Count);
Assert.AreSame(regularPrefab.gameObject, networkConfig.Prefabs.Prefabs[0].Prefab);
Assert.AreEqual(NetworkPrefabOverride.None, networkConfig.Prefabs.Prefabs[0].Override);
Assert.IsNull(networkConfig.Prefabs.Prefabs[0].SourcePrefabToOverride);
Assert.IsNull(networkConfig.Prefabs.Prefabs[0].OverridingTargetPrefab);
Assert.AreSame(overriddenPrefab.gameObject, networkConfig.Prefabs.Prefabs[1].Prefab);
Assert.AreEqual(NetworkPrefabOverride.Prefab, networkConfig.Prefabs.Prefabs[1].Override);
Assert.AreEqual(123456, networkConfig.Prefabs.Prefabs[1].SourceHashToOverride);
Assert.AreSame(sourcePrefabToOverride.gameObject, networkConfig.Prefabs.Prefabs[1].SourcePrefabToOverride);
Assert.AreSame(overridingTargetPrefab.gameObject, networkConfig.Prefabs.Prefabs[1].OverridingTargetPrefab);
}
[Test]
public void WhenModifyingPrefabListUsingNetworkManagerAPI_ModificationIsLocal()
{
// Setup
var networkManagerObject = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager = networkManagerObject.AddComponent<NetworkManager>();
networkManager.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
var networkManagerObject2 = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager2 = networkManagerObject2.AddComponent<NetworkManager>();
networkManager2.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
try
{
var object1 = new GameObject("Object 1").AddComponent<NetworkObject>();
var object2 = new GameObject("Object 2").AddComponent<NetworkObject>();
var object3 = new GameObject("Object 3").AddComponent<NetworkObject>();
object1.GlobalObjectIdHash = 1;
object2.GlobalObjectIdHash = 2;
object3.GlobalObjectIdHash = 3;
var sharedList = ScriptableObject.CreateInstance<NetworkPrefabsList>();
sharedList.List.Add(new NetworkPrefab { Prefab = object1.gameObject });
networkManager.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager2.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager.Initialize(true);
networkManager2.Initialize(false);
networkManager.AddNetworkPrefab(object2.gameObject);
networkManager2.AddNetworkPrefab(object3.gameObject);
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsFalse(networkManager2.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsFalse(networkManager.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsTrue(sharedList.Contains(object1.gameObject));
Assert.IsFalse(sharedList.Contains(object2.gameObject));
Assert.IsFalse(sharedList.Contains(object3.gameObject));
}
finally
{
networkManager.ShutdownInternal();
networkManager2.ShutdownInternal();
// Shutdown doesn't get called correctly because we called Initialize()
// instead of calling StartHost/StartClient/StartServer. See MTT-860 for
// why.
networkManager.NetworkConfig?.NetworkTransport.Shutdown();
networkManager2.NetworkConfig?.NetworkTransport.Shutdown();
}
}
[Test]
public void WhenModifyingPrefabListUsingPrefabsAPI_ModificationIsLocal()
{
// Setup
var networkManagerObject = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager = networkManagerObject.AddComponent<NetworkManager>();
networkManager.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
var networkManagerObject2 = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager2 = networkManagerObject2.AddComponent<NetworkManager>();
networkManager2.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
try
{
var object1 = new GameObject("Object 1").AddComponent<NetworkObject>();
var object2 = new GameObject("Object 2").AddComponent<NetworkObject>();
var object3 = new GameObject("Object 3").AddComponent<NetworkObject>();
object1.GlobalObjectIdHash = 1;
object2.GlobalObjectIdHash = 2;
object3.GlobalObjectIdHash = 3;
var sharedList = ScriptableObject.CreateInstance<NetworkPrefabsList>();
sharedList.List.Add(new NetworkPrefab { Prefab = object1.gameObject });
networkManager.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager2.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager.Initialize(true);
networkManager2.Initialize(false);
networkManager.NetworkConfig.Prefabs.Add(new NetworkPrefab { Prefab = object2.gameObject });
networkManager2.NetworkConfig.Prefabs.Add(new NetworkPrefab { Prefab = object3.gameObject });
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsFalse(networkManager2.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsFalse(networkManager.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsTrue(sharedList.Contains(object1.gameObject));
Assert.IsFalse(sharedList.Contains(object2.gameObject));
Assert.IsFalse(sharedList.Contains(object3.gameObject));
}
finally
{
networkManager.ShutdownInternal();
networkManager2.ShutdownInternal();
// Shutdown doesn't get called correctly because we called Initialize()
// instead of calling StartHost/StartClient/StartServer. See MTT-860 for
// why.
networkManager.NetworkConfig?.NetworkTransport.Shutdown();
networkManager2.NetworkConfig?.NetworkTransport.Shutdown();
}
}
[Test]
public void WhenModifyingPrefabListUsingPrefabsListAPI_ModificationIsShared()
{
// Setup
var networkManagerObject = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager = networkManagerObject.AddComponent<NetworkManager>();
networkManager.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
var networkManagerObject2 = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager2 = networkManagerObject2.AddComponent<NetworkManager>();
networkManager2.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
try
{
var object1 = new GameObject("Object 1").AddComponent<NetworkObject>();
var object2 = new GameObject("Object 2").AddComponent<NetworkObject>();
var object3 = new GameObject("Object 3").AddComponent<NetworkObject>();
object1.GlobalObjectIdHash = 1;
object2.GlobalObjectIdHash = 2;
object3.GlobalObjectIdHash = 3;
var sharedList = ScriptableObject.CreateInstance<NetworkPrefabsList>();
sharedList.List.Add(new NetworkPrefab { Prefab = object1.gameObject });
networkManager.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager2.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager.Initialize(true);
networkManager2.Initialize(false);
networkManager.NetworkConfig.Prefabs.NetworkPrefabsLists[0].Add(new NetworkPrefab { Prefab = object2.gameObject });
networkManager2.NetworkConfig.Prefabs.NetworkPrefabsLists[0].Add(new NetworkPrefab { Prefab = object3.gameObject });
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsTrue(sharedList.Contains(object1.gameObject));
Assert.IsTrue(sharedList.Contains(object2.gameObject));
Assert.IsTrue(sharedList.Contains(object3.gameObject));
}
finally
{
networkManager.ShutdownInternal();
networkManager2.ShutdownInternal();
// Shutdown doesn't get called correctly because we called Initialize()
// instead of calling StartHost/StartClient/StartServer. See MTT-860 for
// why.
networkManager.NetworkConfig?.NetworkTransport.Shutdown();
networkManager2.NetworkConfig?.NetworkTransport.Shutdown();
}
}
[Test]
public void WhenCallingInitializeAfterAddingAPrefabUsingPrefabsAPI_ThePrefabStillExists()
{
// Setup
var networkManagerObject = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager = networkManagerObject.AddComponent<NetworkManager>();
networkManager.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
var networkManagerObject2 = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager2 = networkManagerObject2.AddComponent<NetworkManager>();
networkManager2.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
try
{
var object1 = new GameObject("Object 1").AddComponent<NetworkObject>();
var object2 = new GameObject("Object 2").AddComponent<NetworkObject>();
var object3 = new GameObject("Object 3").AddComponent<NetworkObject>();
object1.GlobalObjectIdHash = 1;
object2.GlobalObjectIdHash = 2;
object3.GlobalObjectIdHash = 3;
var sharedList = ScriptableObject.CreateInstance<NetworkPrefabsList>();
sharedList.List.Add(new NetworkPrefab { Prefab = object1.gameObject });
networkManager.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager2.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager.NetworkConfig.Prefabs.Add(new NetworkPrefab { Prefab = object2.gameObject });
networkManager2.NetworkConfig.Prefabs.Add(new NetworkPrefab { Prefab = object3.gameObject });
networkManager.Initialize(true);
networkManager2.Initialize(false);
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsFalse(networkManager2.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsFalse(networkManager.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsTrue(sharedList.Contains(object1.gameObject));
Assert.IsFalse(sharedList.Contains(object2.gameObject));
Assert.IsFalse(sharedList.Contains(object3.gameObject));
}
finally
{
networkManager.ShutdownInternal();
networkManager2.ShutdownInternal();
// Shutdown doesn't get called correctly because we called Initialize()
// instead of calling StartHost/StartClient/StartServer. See MTT-860 for
// why.
networkManager.NetworkConfig?.NetworkTransport.Shutdown();
networkManager2.NetworkConfig?.NetworkTransport.Shutdown();
}
}
[Test]
public void WhenShuttingDownAndReinitializingPrefabs_RuntimeAddedPrefabsStillExists()
{
// Setup
var networkManagerObject = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager = networkManagerObject.AddComponent<NetworkManager>();
networkManager.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
var networkManagerObject2 = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager2 = networkManagerObject2.AddComponent<NetworkManager>();
networkManager2.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
try
{
var object1 = new GameObject("Object 1").AddComponent<NetworkObject>();
var object2 = new GameObject("Object 2").AddComponent<NetworkObject>();
var object3 = new GameObject("Object 3").AddComponent<NetworkObject>();
object1.GlobalObjectIdHash = 1;
object2.GlobalObjectIdHash = 2;
object3.GlobalObjectIdHash = 3;
var sharedList = ScriptableObject.CreateInstance<NetworkPrefabsList>();
sharedList.List.Add(new NetworkPrefab { Prefab = object1.gameObject });
networkManager.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager2.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager.Initialize(true);
networkManager2.Initialize(false);
networkManager.NetworkConfig.Prefabs.Add(new NetworkPrefab { Prefab = object2.gameObject });
networkManager2.NetworkConfig.Prefabs.Add(new NetworkPrefab { Prefab = object3.gameObject });
networkManager.ShutdownInternal();
networkManager2.ShutdownInternal();
// Shutdown doesn't get called correctly because we called Initialize()
// instead of calling StartHost/StartClient/StartServer. See MTT-860 for
// why.
networkManager.NetworkConfig?.NetworkTransport.Shutdown();
networkManager2.NetworkConfig?.NetworkTransport.Shutdown();
networkManager.Initialize(true);
networkManager2.Initialize(false);
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsFalse(networkManager2.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsFalse(networkManager.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsTrue(sharedList.Contains(object1.gameObject));
Assert.IsFalse(sharedList.Contains(object2.gameObject));
Assert.IsFalse(sharedList.Contains(object3.gameObject));
}
finally
{
networkManager.ShutdownInternal();
networkManager2.ShutdownInternal();
// Shutdown doesn't get called correctly because we called Initialize()
// instead of calling StartHost/StartClient/StartServer. See MTT-860 for
// why.
networkManager.NetworkConfig?.NetworkTransport.Shutdown();
networkManager2.NetworkConfig?.NetworkTransport.Shutdown();
}
}
[Test]
public void WhenCallingInitializeMultipleTimes_NothingBreaks()
{
// Setup
var networkManagerObject = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager = networkManagerObject.AddComponent<NetworkManager>();
networkManager.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
var networkManagerObject2 = new GameObject(nameof(NestedNetworkObjectPrefabCheck));
var networkManager2 = networkManagerObject2.AddComponent<NetworkManager>();
networkManager2.NetworkConfig = new NetworkConfig
{
NetworkTransport = networkManager.gameObject.AddComponent<UnityTransport>()
};
try
{
var object1 = new GameObject("Object 1").AddComponent<NetworkObject>();
var object2 = new GameObject("Object 2").AddComponent<NetworkObject>();
var object3 = new GameObject("Object 3").AddComponent<NetworkObject>();
object1.GlobalObjectIdHash = 1;
object2.GlobalObjectIdHash = 2;
object3.GlobalObjectIdHash = 3;
var sharedList = ScriptableObject.CreateInstance<NetworkPrefabsList>();
sharedList.List.Add(new NetworkPrefab { Prefab = object1.gameObject });
networkManager.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager2.NetworkConfig.Prefabs.NetworkPrefabsLists = new List<NetworkPrefabsList> { sharedList };
networkManager.Initialize(true);
networkManager2.Initialize(false);
networkManager.NetworkConfig.Prefabs.Add(new NetworkPrefab { Prefab = object2.gameObject });
networkManager2.NetworkConfig.Prefabs.Add(new NetworkPrefab { Prefab = object3.gameObject });
networkManager.NetworkConfig.Prefabs.Initialize();
networkManager2.NetworkConfig.Prefabs.Initialize();
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object1.gameObject));
Assert.IsTrue(networkManager.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsFalse(networkManager2.NetworkConfig.Prefabs.Contains(object2.gameObject));
Assert.IsTrue(networkManager2.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsFalse(networkManager.NetworkConfig.Prefabs.Contains(object3.gameObject));
Assert.IsTrue(sharedList.Contains(object1.gameObject));
Assert.IsFalse(sharedList.Contains(object2.gameObject));
Assert.IsFalse(sharedList.Contains(object3.gameObject));
}
finally
{
networkManager.ShutdownInternal();
networkManager2.ShutdownInternal();
// Shutdown doesn't get called correctly because we called Initialize()
// instead of calling StartHost/StartClient/StartServer. See MTT-860 for
// why.
networkManager.NetworkConfig?.NetworkTransport.Shutdown();
networkManager2.NetworkConfig?.NetworkTransport.Shutdown();
}
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 9b84044fccbd3cd49908f0efd5719347
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,159 +0,0 @@
using System.Text.RegularExpressions;
using NUnit.Framework;
using Unity.Netcode.Editor;
using UnityEngine;
using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests
{
internal class NetworkObjectTests
{
[Test]
public void NetworkManagerOverrideTest()
{
// Create "bait"
var singletonNetworkManager = new GameObject(nameof(NetworkManager)).AddComponent<NetworkManager>();
singletonNetworkManager.SetSingleton();
// Create override
var networkManager = new GameObject(nameof(NetworkManager)).AddComponent<NetworkManager>();
// NetworkObject
var gameObject = new GameObject(nameof(NetworkManagerOverrideTest));
var networkObject = gameObject.AddComponent<NetworkObject>();
// Set override
networkObject.NetworkManagerOwner = networkManager;
Debug.Assert(networkObject.NetworkManager == networkManager);
Object.DestroyImmediate(singletonNetworkManager.gameObject);
Object.DestroyImmediate(networkManager.gameObject);
Object.DestroyImmediate(gameObject);
}
[Test]
[TestCase(0)]
[TestCase(1)]
[TestCase(2)]
public void GetBehaviourIndexNone(int index)
{
var gameObject = new GameObject(nameof(GetBehaviourIndexNone));
var networkObject = gameObject.AddComponent<NetworkObject>();
LogAssert.Expect(LogType.Error, new Regex(".*out of bounds.*"));
Assert.That(networkObject.GetNetworkBehaviourAtOrderIndex((ushort)index), Is.Null);
// Cleanup
Object.DestroyImmediate(gameObject);
}
[Test]
public void GetBehaviourIndexOne()
{
var gameObject = new GameObject(nameof(GetBehaviourIndexOne));
var networkObject = gameObject.AddComponent<NetworkObject>();
var networkBehaviour = gameObject.AddComponent<EmptyNetworkBehaviour>();
LogAssert.Expect(LogType.Error, new Regex(".*out of bounds.*"));
Assert.That(networkObject.GetNetworkBehaviourAtOrderIndex(0), Is.EqualTo(networkBehaviour));
Assert.That(networkObject.GetNetworkBehaviourAtOrderIndex(1), Is.Null);
// Cleanup
Object.DestroyImmediate(gameObject);
}
/// <summary>
/// Verifies that a NetworkObject component that is positioned after a NetworkBehaviour component will
/// be migrated to a component index value that is before the lowest NetworkBehaviour component index value.
/// (The lowest NetworkBehaviour component's index value will also change when this happens)
/// </summary>
[Test]
public void NetworkObjectComponentOrder()
{
var gameObject = new GameObject(nameof(GetBehaviourIndexOne));
// Add the Networkbehaviour first
var networkBehaviour = gameObject.AddComponent<EmptyNetworkBehaviour>();
// Add an empty MonoBehaviour inbetween the NetworkBehaviour and NetworkObject
gameObject.AddComponent<EmptyMonoBehaviour>();
// Add the NetworkObject
var networkObject = gameObject.AddComponent<NetworkObject>();
var componentIndices = GetIndices(gameObject);
// Verify the NetworkObject procedes the NetworkBehaviour
Assert.True(componentIndices.NetworkObjectIndex > componentIndices.NetworkBehaviourIndex, $"[Initial Setup] NetworkObject index ({componentIndices.NetworkObjectIndex}) is not greater than the NetworkBehaviour index ({componentIndices.NetworkBehaviourIndex})!");
// Force-Invoke the CheckForNetworkObject method in order to verify the NetworkObject is moved
NetworkBehaviourEditor.CheckForNetworkObject(gameObject);
var adjustedIndices = GetIndices(gameObject);
Assert.True(ValidateComponentIndices(componentIndices, GetIndices(gameObject)), "NetworkObject did not get migrated below the NetworkBehaviour!");
// Cleanup
Object.DestroyImmediate(gameObject);
}
private bool ValidateComponentIndices(ComponentIndices previous, ComponentIndices current)
{
if (previous.NetworkObjectIndex != current.NetworkObjectIndex && previous.NetworkBehaviourIndex != current.NetworkBehaviourIndex)
{
if (current.NetworkObjectIndex < previous.NetworkObjectIndex && current.NetworkObjectIndex < current.NetworkBehaviourIndex)
{
return true;
}
}
return false;
}
private ComponentIndices GetIndices(GameObject gameObject)
{
// Get the index/order values for the added NetworkBehaviour and NetworkObject
var components = gameObject.GetComponents<MonoBehaviour>();
var componentIndices = new ComponentIndices()
{
NetworkObjectIndex = -1,
NetworkBehaviourIndex = -1
};
for (int i = 0; i < components.Length; i++)
{
if (componentIndices.NetworkObjectIndex != -1 && componentIndices.NetworkBehaviourIndex != -1)
{
break;
}
var component = components[i];
var networkObjectComponent = component as NetworkObject;
if (networkObjectComponent != null)
{
componentIndices.NetworkObjectIndex = i;
continue;
}
var networkBehaviourComponent = component as EmptyNetworkBehaviour;
if (networkBehaviourComponent != null)
{
componentIndices.NetworkBehaviourIndex = i;
continue;
}
}
return componentIndices;
}
private struct ComponentIndices
{
public int NetworkObjectIndex;
public int NetworkBehaviourIndex;
}
internal class EmptyNetworkBehaviour : NetworkBehaviour
{
}
internal class EmptyMonoBehaviour : MonoBehaviour
{
}
}
}

Some files were not shown because too many files have changed in this diff Show More