From 63c7e4c78a92a968e191931fa590e06c1e487023 Mon Sep 17 00:00:00 2001 From: Unity Technologies <@unity> Date: Fri, 31 May 2024 00:00:00 +0000 Subject: [PATCH] com.unity.netcode.gameobjects@2.0.0-exp.4 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com). ## [2.0.0-exp.4] - 2024-05-31 ### Added - Added `NetworkRigidbodyBase.AttachToFixedJoint` and `NetworkRigidbodyBase.DetachFromFixedJoint` to replace parenting for rigid bodies that have `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled. (#2933) - Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2912) - Added a client-side only `NetworkBehaviour.OnNetworkSessionSynchronized` convenience method that is invoked on all `NetworkBehaviour`s after a newly joined client has finished synchronizing with the network session in progress. (#2912) - Added `NetworkBehaviour.OnInSceneObjectsSpawned` convenience method that is invoked when all in-scene `NetworkObject`s have been spawned after a scene has been loaded or upon a host or server starting. (#2912) ### Fixed - Fixed issue where non-authoritative rigid bodies with `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled would constantly log errors about the renderTime being before `StartTimeConsumed`. (#2933) - Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2924) - Fixed issue where a `NetworkObject` component's associated `NetworkBehaviour` components would not be detected if scene loading is disabled in the editor and the currently loaded scene has in-scene placed `NetworkObject`s. (#2912) - Fixed issue where an in-scene placed `NetworkObject` with `NetworkTransform` that is also parented under a `GameObject` would not properly synchronize when the parent `GameObject` had a world space position other than 0,0,0. (#2898) ### Changed - Change all the access modifiers of test class from Public to Internal (#2930) - Changed messages are now sorted by enum values as opposed to ordinally sorting the messages by their type name. (#2929) - Changed `NetworkClient.SessionModeTypes` to `NetworkClient.NetworkTopologyTypes`. (#2875) - Changed `NetworkClient.SessionModeType` to `NetworkClient.NetworkTopologyType`. (#2875) - Changed `NetworkConfig.SessionMode` to `NeworkConfig.NetworkTopology`. (#2875) --- CHANGELOG.md | 56 +++- Components/AssemblyInfo.cs | 15 - .../Messages/NetworkTransformMessage.cs | 205 ------------ .../com.unity.netcode.components.asmdef | 27 -- Editor/CodeGen/NetworkBehaviourILPP.cs | 3 +- Editor/NetworkManagerEditor.cs | 35 ++- Editor/NetworkObjectEditor.cs | 7 +- Editor/com.unity.netcode.editor.asmdef | 5 + .../Components.meta | 5 +- .../Components}/HalfVector3.cs | 0 .../Components}/HalfVector3.cs.meta | 0 .../Components}/HalfVector4.cs | 0 .../Components}/HalfVector4.cs.meta | 0 .../Components}/Interpolator.meta | 0 .../BufferedLinearInterpolator.cs | 4 +- .../BufferedLinearInterpolator.cs.meta | 0 .../Components}/Messages.meta | 0 .../Components}/NetworkAnimator.cs | 0 .../Components}/NetworkAnimator.cs.meta | 0 .../Components}/NetworkDeltaPosition.cs | 8 +- .../Components}/NetworkDeltaPosition.cs.meta | 0 .../Components}/NetworkRigidBodyBase.cs | 223 +++++++++++-- .../Components}/NetworkRigidBodyBase.cs.meta | 0 .../Components}/NetworkRigidbody.cs | 0 .../Components}/NetworkRigidbody.cs.meta | 0 .../Components}/NetworkRigidbody2D.cs | 0 .../Components}/NetworkRigidbody2D.cs.meta | 0 .../Components}/NetworkTransform.cs | 294 ++++++++++++------ .../Components}/NetworkTransform.cs.meta | 0 .../Components}/QuaternionCompressor.cs | 2 +- .../Components}/QuaternionCompressor.cs.meta | 0 .../RigidbodyContactEventManager.cs | 0 .../RigidbodyContactEventManager.cs.meta | 0 Runtime/Configuration/NetworkConfig.cs | 10 +- Runtime/Connection/NetworkClient.cs | 8 +- Runtime/Core/NetworkBehaviour.cs | 89 ++++++ Runtime/Core/NetworkManager.cs | 85 ++++- Runtime/Core/NetworkObject.cs | 113 ++++++- Runtime/Messaging/CustomMessageManager.cs | 70 ++++- Runtime/Messaging/ILPPMessageProvider.cs | 111 ++++++- .../Messages/ChangeOwnershipMessage.cs | 4 +- .../Messages/ConnectionApprovedMessage.cs | 26 +- .../Messaging/Messages/CreateObjectMessage.cs | 4 +- .../Messages/DestroyObjectMessage.cs | 4 +- .../Messages/NetworkTransformMessage.cs | 190 +++++++++++ .../Messages/NetworkTransformMessage.cs.meta | 0 .../Messages/NetworkVariableDeltaMessage.cs | 4 +- .../Messaging/Messages/ParentSyncMessage.cs | 4 +- Runtime/Messaging/Messages/RpcMessages.cs | 12 +- Runtime/Messaging/NetworkMessageManager.cs | 31 +- .../SceneManagement/NetworkSceneManager.cs | 50 ++- Runtime/SceneManagement/SceneEventData.cs | 25 +- Runtime/Spawning/NetworkSpawnManager.cs | 36 ++- Runtime/Transports/UTP/UnityTransport.cs | 10 +- Runtime/com.unity.netcode.runtime.asmdef | 15 + .../IntegrationTestWithApproximation.cs | 2 +- TestHelpers/Runtime/NetcodeIntegrationTest.cs | 26 +- .../Runtime/NetcodeIntegrationTestHelpers.cs | 3 +- Tests/Editor/ArithmeticTests.cs | 2 +- Tests/Editor/Build/BuildTests.cs | 2 +- Tests/Editor/DisconnectMessageTests.cs | 2 +- Tests/Editor/InterpolatorTests.cs | 2 +- .../Editor/Messaging/DisconnectOnSendTests.cs | 2 +- .../Messaging/MessageCorruptionTests.cs | 2 +- .../Editor/Messaging/MessageReceivingTests.cs | 2 +- .../Messaging/MessageRegistrationTests.cs | 74 +---- Tests/Editor/Messaging/MessageSendingTests.cs | 2 +- .../Messaging/MessageVersioningTests.cs | 2 +- .../NetworkMetricsRegistrationTests.cs | 2 +- Tests/Editor/NetworkBehaviourTests.cs | 6 +- .../NetworkManagerConfigurationTests.cs | 14 +- Tests/Editor/NetworkObjectTests.cs | 6 +- Tests/Editor/NetworkPrefabProcessorTests.cs | 2 +- Tests/Editor/NetworkVar/NetworkVarTests.cs | 4 +- .../BaseFastBufferReaderWriterTest.cs | 2 +- Tests/Editor/Serialization/BitCounterTests.cs | 2 +- Tests/Editor/Serialization/BitReaderTests.cs | 2 +- Tests/Editor/Serialization/BitWriterTests.cs | 2 +- .../Serialization/BufferSerializerTests.cs | 2 +- Tests/Editor/Serialization/BytePackerTests.cs | 2 +- .../Serialization/FastBufferReaderTests.cs | 2 +- .../Serialization/FastBufferWriterTests.cs | 2 +- ...serBitReaderAndBitWriterTests_NCCBUG175.cs | 2 +- .../Timing/ClientNetworkTimeSystemTests.cs | 2 +- Tests/Editor/Timing/NetworkTimeTests.cs | 2 +- .../Timing/ServerNetworkTimeSystemTests.cs | 2 +- Tests/Editor/Timing/TimingTestHelper.cs | 2 +- .../Transports/BatchedReceiveQueueTests.cs | 2 +- .../Transports/BatchedSendQueueTests.cs | 2 +- Tests/Editor/Transports/UNetTransportTests.cs | 2 +- .../Editor/Transports/UnityTransportTests.cs | 14 +- Tests/Editor/XXHashTests.cs | 2 +- Tests/Runtime/AddNetworkPrefabTests.cs | 4 +- Tests/Runtime/ClientApprovalDenied.cs | 2 +- Tests/Runtime/ClientOnlyConnectionTests.cs | 2 +- .../BufferDataValidationComponent.cs | 2 +- .../NetworkVariableTestComponent.cs | 10 +- .../Components/NetworkVisibilityComponent.cs | 2 +- Tests/Runtime/ConnectionApproval.cs | 2 +- .../Runtime/ConnectionApprovalTimeoutTests.cs | 2 +- Tests/Runtime/DeferredMessagingTests.cs | 8 +- Tests/Runtime/DisconnectTests.cs | 2 +- .../DeferredDespawningTests.cs | 4 +- .../DistributeObjectsTests.cs | 10 +- .../DistributedAuthorityCodecTests.cs | 8 +- .../NetworkClientAndPlayerObjectTests.cs | 6 +- .../OwnershipPermissionsTests.cs | 4 +- Tests/Runtime/HiddenVariableTests.cs | 6 +- Tests/Runtime/IntegrationTestExamples.cs | 12 +- Tests/Runtime/InvalidConnectionEventsTest.cs | 2 +- Tests/Runtime/ListChangedTest.cs | 12 +- .../Messaging/DisconnectReasonTests.cs | 4 +- Tests/Runtime/Messaging/NamedMessageTests.cs | 2 +- .../Runtime/Messaging/UnnamedMessageTests.cs | 2 +- .../Runtime/Metrics/ConnectionMetricsTests.cs | 2 +- .../Runtime/Metrics/MessagingMetricsTests.cs | 2 +- Tests/Runtime/Metrics/MetricsDispatchTests.cs | 2 +- .../Runtime/Metrics/PacketLossMetricsTests.cs | 2 +- Tests/Runtime/NestedNetworkManagerTests.cs | 2 +- Tests/Runtime/NetworkBehaviourGenericTests.cs | 4 +- .../NetworkBehaviourPrePostSpawnTests.cs | 143 +++++++++ .../NetworkBehaviourPrePostSpawnTests.cs.meta | 2 +- Tests/Runtime/NetworkBehaviourUpdaterTests.cs | 14 +- ...NetworkManagerCustomMessageManagerTests.cs | 2 +- Tests/Runtime/NetworkManagerEventsTests.cs | 2 +- .../NetworkManagerSceneManagerTests.cs | 2 +- Tests/Runtime/NetworkManagerTransportTests.cs | 4 +- .../NetworkObjectDestroyTests.cs | 10 +- .../NetworkObjectDontDestroyWithOwnerTests.cs | 2 +- ...orkObjectNetworkClientOwnedObjectsTests.cs | 2 +- .../NetworkObjectOnNetworkDespawnTests.cs | 2 +- .../NetworkObjectOnSpawnTests.cs | 12 +- .../NetworkObjectOwnershipPropertiesTests.cs | 10 +- .../NetworkObjectOwnershipTests.cs | 4 +- .../NetworkObjectPropertyTests.cs | 2 +- .../NetworkObjectSpawnManyObjectsTests.cs | 10 +- .../NetworkObjectSynchronizationTests.cs | 12 +- Tests/Runtime/NetworkPrefabHandlerTests.cs | 4 +- Tests/Runtime/NetworkShowHideTests.cs | 10 +- Tests/Runtime/NetworkSpawnManagerTests.cs | 8 +- .../NetworkTransform/NetworkTransformBase.cs | 8 +- .../NetworkTransformGeneral.cs | 4 +- .../NetworkTransformOwnershipTests.cs | 6 +- .../NetworkTransformPacketLossTests.cs | 4 +- .../NetworkTransformStateTests.cs | 2 +- .../NetworkTransform/NetworkTransformTests.cs | 4 +- Tests/Runtime/NetworkUpdateLoopTests.cs | 2 +- Tests/Runtime/NetworkVarBufferCopyTest.cs | 6 +- Tests/Runtime/NetworkVariableTests.cs | 26 +- .../NetworkVariableTestsHelperTypes.cs | 40 +-- ...tworkVariableUserSerializableTypesTests.cs | 16 +- Tests/Runtime/NetworkVisibilityTests.cs | 12 +- Tests/Runtime/OwnerModifiedTests.cs | 4 +- Tests/Runtime/OwnerPermissionTests.cs | 4 +- Tests/Runtime/PeerDisconnectCallbackTests.cs | 2 +- .../Runtime/Physics/NetworkRigidbody2DTest.cs | 4 +- Tests/Runtime/Physics/NetworkRigidbodyTest.cs | 2 +- Tests/Runtime/PlayerObjectTests.cs | 2 +- .../Profiling/NetworkVariableNameTests.cs | 2 +- Tests/Runtime/RpcManyClientsTests.cs | 4 +- Tests/Runtime/RpcQueueTests.cs | 2 +- Tests/Runtime/RpcTests.cs | 12 +- Tests/Runtime/RpcTypeSerializationTests.cs | 4 +- .../NetworkBehaviourReferenceTests.cs | 4 +- .../NetworkObjectReferenceTests.cs | 6 +- Tests/Runtime/StartStopTests.cs | 2 +- Tests/Runtime/StopStartRuntimeTests.cs | 2 +- .../Runtime/Timing/NetworkTimeSystemTests.cs | 6 +- .../Runtime/Timing/TimeInitializationTest.cs | 2 +- Tests/Runtime/Timing/TimeIntegrationTest.cs | 2 +- Tests/Runtime/TransformInterpolationTests.cs | 8 +- .../UnityTransportConnectionTests.cs | 4 +- .../Transports/UnityTransportDriverClient.cs | 2 +- .../Transports/UnityTransportTestHelpers.cs | 6 +- .../Runtime/Transports/UnityTransportTests.cs | 2 +- Tests/Runtime/UniversalRpcTests.cs | 4 +- package.json | 8 +- 177 files changed, 1788 insertions(+), 816 deletions(-) delete mode 100644 Components/AssemblyInfo.cs delete mode 100644 Components/Messages/NetworkTransformMessage.cs delete mode 100644 Components/com.unity.netcode.components.asmdef rename Components/com.unity.netcode.components.asmdef.meta => Runtime/Components.meta (57%) rename {Components => Runtime/Components}/HalfVector3.cs (100%) rename {Components => Runtime/Components}/HalfVector3.cs.meta (100%) rename {Components => Runtime/Components}/HalfVector4.cs (100%) rename {Components => Runtime/Components}/HalfVector4.cs.meta (100%) rename {Components => Runtime/Components}/Interpolator.meta (100%) rename {Components => Runtime/Components}/Interpolator/BufferedLinearInterpolator.cs (99%) rename {Components => Runtime/Components}/Interpolator/BufferedLinearInterpolator.cs.meta (100%) rename {Components => Runtime/Components}/Messages.meta (100%) rename {Components => Runtime/Components}/NetworkAnimator.cs (100%) rename {Components => Runtime/Components}/NetworkAnimator.cs.meta (100%) rename {Components => Runtime/Components}/NetworkDeltaPosition.cs (97%) rename {Components => Runtime/Components}/NetworkDeltaPosition.cs.meta (100%) rename {Components => Runtime/Components}/NetworkRigidBodyBase.cs (63%) rename {Components => Runtime/Components}/NetworkRigidBodyBase.cs.meta (100%) rename {Components => Runtime/Components}/NetworkRigidbody.cs (100%) rename {Components => Runtime/Components}/NetworkRigidbody.cs.meta (100%) rename {Components => Runtime/Components}/NetworkRigidbody2D.cs (100%) rename {Components => Runtime/Components}/NetworkRigidbody2D.cs.meta (100%) rename {Components => Runtime/Components}/NetworkTransform.cs (94%) rename {Components => Runtime/Components}/NetworkTransform.cs.meta (100%) rename {Components => Runtime/Components}/QuaternionCompressor.cs (98%) rename {Components => Runtime/Components}/QuaternionCompressor.cs.meta (100%) rename {Components => Runtime/Components}/RigidbodyContactEventManager.cs (100%) rename {Components => Runtime/Components}/RigidbodyContactEventManager.cs.meta (100%) create mode 100644 Runtime/Messaging/Messages/NetworkTransformMessage.cs rename {Components => Runtime/Messaging}/Messages/NetworkTransformMessage.cs.meta (100%) create mode 100644 Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs rename Components/AssemblyInfo.cs.meta => Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs.meta (83%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5740236..4211f42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,30 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com). +## [2.0.0-exp.4] - 2024-05-31 + +### Added + +- Added `NetworkRigidbodyBase.AttachToFixedJoint` and `NetworkRigidbodyBase.DetachFromFixedJoint` to replace parenting for rigid bodies that have `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled. (#2933) +- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2912) +- Added a client-side only `NetworkBehaviour.OnNetworkSessionSynchronized` convenience method that is invoked on all `NetworkBehaviour`s after a newly joined client has finished synchronizing with the network session in progress. (#2912) +- Added `NetworkBehaviour.OnInSceneObjectsSpawned` convenience method that is invoked when all in-scene `NetworkObject`s have been spawned after a scene has been loaded or upon a host or server starting. (#2912) + +### Fixed + +- Fixed issue where non-authoritative rigid bodies with `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled would constantly log errors about the renderTime being before `StartTimeConsumed`. (#2933) +- Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2924) +- Fixed issue where a `NetworkObject` component's associated `NetworkBehaviour` components would not be detected if scene loading is disabled in the editor and the currently loaded scene has in-scene placed `NetworkObject`s. (#2912) +- Fixed issue where an in-scene placed `NetworkObject` with `NetworkTransform` that is also parented under a `GameObject` would not properly synchronize when the parent `GameObject` had a world space position other than 0,0,0. (#2898) + +### Changed + +- Change all the access modifiers of test class from Public to Internal (#2930) +- Changed messages are now sorted by enum values as opposed to ordinally sorting the messages by their type name. (#2929) +- Changed `NetworkClient.SessionModeTypes` to `NetworkClient.NetworkTopologyTypes`. (#2875) +- Changed `NetworkClient.SessionModeType` to `NetworkClient.NetworkTopologyType`. (#2875) +- Changed `NetworkConfig.SessionMode` to `NeworkConfig.NetworkTopology`. (#2875) + ## [2.0.0-exp.2] - 2024-04-02 ### Added @@ -52,7 +76,7 @@ Additional documentation and release notes are available at [Multiplayer Documen - Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863) - Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863) - Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863) -- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is authomatically the owner of the spawned object). (#2863) +- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is automatically the owner of the spawned object). (#2863) - This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example). - Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863) - Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863) @@ -79,6 +103,36 @@ Additional documentation and release notes are available at [Multiplayer Documen - Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810) - Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807) +## [1.9.1] - 2024-04-18 + +### Added +- Added `AnticipatedNetworkVariable`, which adds support for client anticipation of NetworkVariable values, allowing for more responsive game play (#2820) +- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of `NetworkTransform`s (#2820) +- Added `NetworkVariableBase.ExceedsDirtinessThreshold` to allow network variables to throttle updates by only sending updates when the difference between the current and previous values exceeds a threshold. (This is exposed in NetworkVariable with the callback NetworkVariable.CheckExceedsDirtinessThreshold) (#2820) +- Added `NetworkVariableUpdateTraits`, which add additional throttling support: `MinSecondsBetweenUpdates` will prevent the `NetworkVariable` from sending updates more often than the specified time period (even if it exceeds the dirtiness threshold), while `MaxSecondsBetweenUpdates` will force a dirty `NetworkVariable` to send an update after the specified time period even if it has not yet exceeded the dirtiness threshold. (#2820) +- Added virtual method `NetworkVariableBase.OnInitialize()` which can be used by `NetworkVariable` subclasses to add initialization code (#2820) +- Added virtual method `NetworkVariableBase.Update()`, which is called once per frame to support behaviors such as interpolation between an anticipated value and an authoritative one. (#2820) +- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2820) +- `NetworkVariable` now includes built-in support for `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, and `Dictionary` (#2813) +- `NetworkVariable` now includes delta compression for collection values (`NativeList`, `NativeArray`, `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, `Dictionary`, and `FixedString` types) to save bandwidth by only sending the values that changed. (Note: For `NativeList`, `NativeArray`, and `List`, this algorithm works differently than that used in `NetworkList`. This algorithm will use less bandwidth for "set" and "add" operations, but `NetworkList` is more bandwidth-efficient if you are performing frequent "insert" operations.) (#2813) +- `UserNetworkVariableSerialization` now has optional callbacks for `WriteDelta` and `ReadDelta`. If both are provided, they will be used for all serialization operations on NetworkVariables of that type except for the first one for each client. If either is missing, the existing `Write` and `Read` will always be used. (#2813) +- Network variables wrapping `INetworkSerializable` types can perform delta serialization by setting `UserNetworkVariableSerialization.WriteDelta` and `UserNetworkVariableSerialization.ReadDelta` for those types. The built-in `INetworkSerializable` serializer will continue to be used for all other serialization operations, but if those callbacks are set, it will call into them on all but the initial serialization to perform delta serialization. (This could be useful if you have a large struct where most values do not change regularly and you want to send only the fields that did change.) (#2813) + +### Fixed + +- Fixed issue where `NetworkTransformEditor` would throw and exception if you excluded the physics package. (#2871) +- Fixed issue where `NetworkTransform` could not properly synchronize its base position when using half float precision. (#2845) +- Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822) +- Fixed issue where NetworkTransform could potentially attempt to "unregister" a named message prior to it being registered. (#2807) +- Fixed issue where in-scene placed `NetworkObject`s with complex nested children `NetworkObject`s (more than one child in depth) would not synchronize properly if WorldPositionStays was set to true. (#2796) + +### Changed + +- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2874) +- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2872) +- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810) +- Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807) + ## [1.8.1] - 2024-02-05 ### Fixed diff --git a/Components/AssemblyInfo.cs b/Components/AssemblyInfo.cs deleted file mode 100644 index dca7347..0000000 --- a/Components/AssemblyInfo.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Runtime.CompilerServices; - -#if UNITY_EDITOR -[assembly: InternalsVisibleTo("Unity.Netcode.Editor")] -[assembly: InternalsVisibleTo("Unity.Netcode.Editor.CodeGen")] -#endif // UNITY_EDITOR - -#if UNITY_INCLUDE_TESTS -[assembly: InternalsVisibleTo("Unity.Netcode.RuntimeTests")] -[assembly: InternalsVisibleTo("TestProject.RuntimeTests")] -#if UNITY_EDITOR -[assembly: InternalsVisibleTo("Unity.Netcode.EditorTests")] -[assembly: InternalsVisibleTo("TestProject.EditorTests")] -#endif // UNITY_EDITOR -#endif // UNITY_INCLUDE_TESTS diff --git a/Components/Messages/NetworkTransformMessage.cs b/Components/Messages/NetworkTransformMessage.cs deleted file mode 100644 index 28a423e..0000000 --- a/Components/Messages/NetworkTransformMessage.cs +++ /dev/null @@ -1,205 +0,0 @@ -using Unity.Netcode.Components; -using UnityEngine; - -namespace Unity.Netcode -{ - /// - /// NetworkTransform State Update Message - /// - internal struct NetworkTransformMessage : INetworkMessage - { - public int Version => 0; - public ulong NetworkObjectId; - public int NetworkBehaviourId; - // This is only used when serializing but not serialized - public bool DistributedAuthorityMode; - // Might get removed - public ulong[] TargetIds; - - private int GetTargetIdLength() - { - if (TargetIds != null) - { - return TargetIds.Length; - } - return 0; - } - - public NetworkTransform.NetworkTransformState State; - - private NetworkTransform m_ReceiverNetworkTransform; - private FastBufferReader m_CurrentReader; - - private unsafe void CopyPayload(ref FastBufferWriter writer) - { - writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position); - } - - public void Serialize(FastBufferWriter writer, int targetVersion) - { - if (m_CurrentReader.IsInitialized) - { - CopyPayload(ref writer); - } - else - { - BytePacker.WriteValueBitPacked(writer, NetworkObjectId); - BytePacker.WriteValueBitPacked(writer, NetworkBehaviourId); - writer.WriteNetworkSerializable(State); - if (DistributedAuthorityMode) - { - var length = GetTargetIdLength(); - BytePacker.WriteValuePacked(writer, length); - // If no target ids, then just exit early (DAHost specific) - if (length == 0) - { - return; - } - foreach (var target in TargetIds) - { - BytePacker.WriteValuePacked(writer, target); - } - } - } - } - - public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) - { - var networkManager = context.SystemOwner as NetworkManager; - if (networkManager == null) - { - Debug.LogError($"[{nameof(NetworkTransformMessage)}] System owner context was not of type {nameof(NetworkManager)}!"); - return false; - } - var currentPosition = reader.Position; - ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId); - var isSpawnedLocally = networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId); - - // Only defer if the NetworkObject is not spawned yet and the local NetworkManager is not running as a DAHost. - if (!isSpawnedLocally && !networkManager.DAHost) - { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context); - return false; - } - - // While the below check and assignment might seem out of place, this is specific to running in DAHost mode when a NetworkObject is - // hidden from the DAHost but is visible to other clients. Since the DAHost needs to forward updates to the clients, we ignore processing - // this message locally - var networkObject = (NetworkObject)null; - var isServerAuthoritative = false; - var ownerAuthoritativeServerSide = false; - - // Get the behaviour index - ByteUnpacker.ReadValueBitPacked(reader, out NetworkBehaviourId); - - // Deserialize the state - reader.ReadNetworkSerializableInPlace(ref State); - - if (networkManager.DistributedAuthorityMode) - { - var targetCount = 0; - ByteUnpacker.ReadValueBitPacked(reader, out targetCount); - if (targetCount > 0) - { - TargetIds = new ulong[targetCount]; - } - var targetId = (ulong)0; - for (int i = 0; i < targetCount; i++) - { - ByteUnpacker.ReadValueBitPacked(reader, out targetId); - TargetIds[i] = targetId; - } - } - - if (isSpawnedLocally) - { - networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId]; - // Get the target NetworkTransform - m_ReceiverNetworkTransform = networkObject.ChildNetworkBehaviours[NetworkBehaviourId] as NetworkTransform; - isServerAuthoritative = m_ReceiverNetworkTransform.IsServerAuthoritative(); - ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer; - } - else - { - // If we are the DAHost and the NetworkObject is hidden from the host we still need to forward this message - ownerAuthoritativeServerSide = networkManager.DAHost && !isSpawnedLocally; - } - - if (ownerAuthoritativeServerSide) - { - var ownerClientId = (ulong)0; - - if (networkObject != null) - { - ownerClientId = networkObject.OwnerClientId; - if (ownerClientId == NetworkManager.ServerClientId) - { - // Ownership must have changed, ignore any additional pending messages that might have - // come from a previous owner client. - return true; - } - } - else if (networkManager.DAHost) - { - // Specific to distributed authority mode, the only sender of state updates will be the owner - ownerClientId = context.SenderId; - } - - var networkDelivery = State.IsReliableStateUpdate() ? NetworkDelivery.ReliableSequenced : NetworkDelivery.UnreliableSequenced; - - // Forward the state update if there are any remote clients to foward it to - if (networkManager.ConnectionManager.ConnectedClientsList.Count > (networkManager.IsHost ? 2 : 1)) - { - var clientCount = networkManager.DistributedAuthorityMode ? GetTargetIdLength() : networkManager.ConnectionManager.ConnectedClientsList.Count; - if (clientCount == 0) - { - return true; - } - - // This is only to copy the existing and already serialized struct for forwarding purposes only. - // This will not include any changes made to this struct at this particular stage of processing the message. - var currentMessage = this; - // Create a new reader that replicates this message - currentMessage.m_CurrentReader = new FastBufferReader(reader, Collections.Allocator.None); - // Rewind the new reader to the beginning of the message's payload - currentMessage.m_CurrentReader.Seek(currentPosition); - // Forward the message to all connected clients that are observers of the associated NetworkObject - - for (int i = 0; i < clientCount; i++) - { - var clientId = networkManager.DistributedAuthorityMode ? TargetIds[i] : networkManager.ConnectionManager.ConnectedClientsList[i].ClientId; - if (NetworkManager.ServerClientId == clientId || (!isServerAuthoritative && clientId == ownerClientId) || - (!networkManager.DistributedAuthorityMode && !networkObject.Observers.Contains(clientId))) - { - continue; - } - - networkManager.MessageManager.SendMessage(ref currentMessage, networkDelivery, clientId); - } - // Dispose of the reader used for forwarding - currentMessage.m_CurrentReader.Dispose(); - } - } - return true; - } - - public void Handle(ref NetworkContext context) - { - var networkManager = context.SystemOwner as NetworkManager; - // Only if the local NetworkManager instance is running as the DAHost we just exit if there is no local - // NetworkTransform component to apply the state update to (i.e. it is hidden from the DAHost and it - // just forwarded the state update to any other connected client) - if (networkManager.DAHost && m_ReceiverNetworkTransform == null) - { - return; - } - - if (m_ReceiverNetworkTransform == null) - { - Debug.LogError($"[{nameof(NetworkTransformMessage)}][Dropped] Reciever {nameof(NetworkTransform)} was not set!"); - return; - } - m_ReceiverNetworkTransform.TransformStateUpdate(ref State, context.SenderId); - } - } -} diff --git a/Components/com.unity.netcode.components.asmdef b/Components/com.unity.netcode.components.asmdef deleted file mode 100644 index 3505da5..0000000 --- a/Components/com.unity.netcode.components.asmdef +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "Unity.Netcode.Components", - "rootNamespace": "Unity.Netcode.Components", - "references": [ - "Unity.Netcode.Runtime", - "Unity.Collections", - "Unity.Mathematics" - ], - "allowUnsafeCode": true, - "versionDefines": [ - { - "name": "com.unity.modules.animation", - "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" - } - ] -} \ No newline at end of file diff --git a/Editor/CodeGen/NetworkBehaviourILPP.cs b/Editor/CodeGen/NetworkBehaviourILPP.cs index 974b492..f750f78 100644 --- a/Editor/CodeGen/NetworkBehaviourILPP.cs +++ b/Editor/CodeGen/NetworkBehaviourILPP.cs @@ -27,7 +27,8 @@ internal sealed class NetworkBehaviourILPP : ILPPInterface public override ILPPInterface GetInstance() => this; - public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == CodeGenHelpers.RuntimeAssemblyName); + public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.Name == CodeGenHelpers.RuntimeAssemblyName || + compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == CodeGenHelpers.RuntimeAssemblyName); private readonly List m_Diagnostics = new List(); diff --git a/Editor/NetworkManagerEditor.cs b/Editor/NetworkManagerEditor.cs index 011fe5d..f420592 100644 --- a/Editor/NetworkManagerEditor.cs +++ b/Editor/NetworkManagerEditor.cs @@ -30,7 +30,9 @@ public class NetworkManagerEditor : UnityEditor.Editor private SerializedProperty m_ProtocolVersionProperty; private SerializedProperty m_NetworkTransportProperty; private SerializedProperty m_TickRateProperty; - private SerializedProperty m_SessionModeProperty; +#if MULTIPLAYER_SDK_INSTALLED + private SerializedProperty m_NetworkTopologyProperty; +#endif private SerializedProperty m_ClientConnectionBufferTimeoutProperty; private SerializedProperty m_ConnectionApprovalProperty; private SerializedProperty m_EnsureNetworkVariableLengthSafetyProperty; @@ -43,6 +45,9 @@ public class NetworkManagerEditor : UnityEditor.Editor private SerializedProperty m_LoadSceneTimeOutProperty; private SerializedProperty m_PrefabsList; + private SerializedProperty m_NetworkProfileMetrics; + private SerializedProperty m_NetworkMessageMetrics; + private NetworkManager m_NetworkManager; private bool m_Initialized; @@ -97,7 +102,9 @@ private void Initialize() m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); - m_SessionModeProperty = m_NetworkConfigProperty.FindPropertyRelative("SessionMode"); +#if MULTIPLAYER_SDK_INSTALLED + m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology"); +#endif m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval"); m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); @@ -109,6 +116,11 @@ private void Initialize() m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout"); m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); + m_NetworkProfileMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkProfileMetrics"); +#if MULTIPLAYER_TOOLS + m_NetworkMessageMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkMessageMetrics"); +#endif + m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); m_PrefabsList = m_NetworkConfigProperty @@ -130,7 +142,9 @@ private void CheckNullProperties() m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); - m_SessionModeProperty = m_NetworkConfigProperty.FindPropertyRelative("SessionMode"); +#if MULTIPLAYER_SDK_INSTALLED + m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology"); +#endif m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval"); m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); @@ -143,6 +157,11 @@ private void CheckNullProperties() m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout"); m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); + m_NetworkProfileMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkProfilingMetrics"); +#if MULTIPLAYER_TOOLS + m_NetworkMessageMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkMessageMetrics"); +#endif + m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); m_PrefabsList = m_NetworkConfigProperty .FindPropertyRelative(nameof(NetworkConfig.Prefabs)) @@ -164,9 +183,12 @@ public override void OnInspectorGUI() serializedObject.Update(); EditorGUILayout.PropertyField(m_RunInBackgroundProperty); EditorGUILayout.PropertyField(m_LogLevelProperty); - EditorGUILayout.PropertyField(m_SessionModeProperty); + EditorGUILayout.Space(); EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel); +#if MULTIPLAYER_SDK_INSTALLED + EditorGUILayout.PropertyField(m_NetworkTopologyProperty); +#endif EditorGUILayout.PropertyField(m_ProtocolVersionProperty); EditorGUILayout.PropertyField(m_NetworkTransportProperty); if (m_NetworkTransportProperty.objectReferenceValue == null) @@ -200,6 +222,11 @@ public override void OnInspectorGUI() } EditorGUILayout.PropertyField(m_RpcHashSizeProperty); + EditorGUILayout.PropertyField(m_NetworkProfileMetrics); +#if MULTIPLAYER_TOOLS + EditorGUILayout.PropertyField(m_NetworkMessageMetrics); +#endif + EditorGUILayout.Space(); EditorGUILayout.LabelField("Prefab Settings", EditorStyles.boldLabel); EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty); diff --git a/Editor/NetworkObjectEditor.cs b/Editor/NetworkObjectEditor.cs index cc4b9d3..9975482 100644 --- a/Editor/NetworkObjectEditor.cs +++ b/Editor/NetworkObjectEditor.cs @@ -1,5 +1,7 @@ using System.Collections.Generic; +#if MULTIPLAYER_SDK_INSTALLED using System.Linq; +#endif using UnityEditor; using UnityEngine; @@ -144,7 +146,9 @@ private void OnDestroy() } } - + // Keeping this here just in case, but it appears that in Unity 6 the visual bugs with + // enum flags is resolved +#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SDK_INSTALLED [CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))] public class NetworkObjectOwnership : PropertyDrawer { @@ -188,4 +192,5 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten EditorGUI.EndProperty(); } } +#endif } diff --git a/Editor/com.unity.netcode.editor.asmdef b/Editor/com.unity.netcode.editor.asmdef index 8eb62d0..fb85b90 100644 --- a/Editor/com.unity.netcode.editor.asmdef +++ b/Editor/com.unity.netcode.editor.asmdef @@ -53,6 +53,11 @@ "name": "com.unity.transport", "expression": "2.0", "define": "UTP_TRANSPORT_2_0_ABOVE" + }, + { + "name": "com.unity.services.multiplayer", + "expression": "0.2.0", + "define": "MULTIPLAYER_SDK_INSTALLED" } ], "noEngineReferences": false diff --git a/Components/com.unity.netcode.components.asmdef.meta b/Runtime/Components.meta similarity index 57% rename from Components/com.unity.netcode.components.asmdef.meta rename to Runtime/Components.meta index 3dcf24d..27ca3f3 100644 --- a/Components/com.unity.netcode.components.asmdef.meta +++ b/Runtime/Components.meta @@ -1,6 +1,7 @@ fileFormatVersion: 2 -guid: 3b8ed52f1b5c64994af4c4e0aa4b6c4b -AssemblyDefinitionImporter: +guid: 2e42215d00468b549bbc69ebf8a74a1e +folderAsset: yes +DefaultImporter: externalObjects: {} userData: assetBundleName: diff --git a/Components/HalfVector3.cs b/Runtime/Components/HalfVector3.cs similarity index 100% rename from Components/HalfVector3.cs rename to Runtime/Components/HalfVector3.cs diff --git a/Components/HalfVector3.cs.meta b/Runtime/Components/HalfVector3.cs.meta similarity index 100% rename from Components/HalfVector3.cs.meta rename to Runtime/Components/HalfVector3.cs.meta diff --git a/Components/HalfVector4.cs b/Runtime/Components/HalfVector4.cs similarity index 100% rename from Components/HalfVector4.cs rename to Runtime/Components/HalfVector4.cs diff --git a/Components/HalfVector4.cs.meta b/Runtime/Components/HalfVector4.cs.meta similarity index 100% rename from Components/HalfVector4.cs.meta rename to Runtime/Components/HalfVector4.cs.meta diff --git a/Components/Interpolator.meta b/Runtime/Components/Interpolator.meta similarity index 100% rename from Components/Interpolator.meta rename to Runtime/Components/Interpolator.meta diff --git a/Components/Interpolator/BufferedLinearInterpolator.cs b/Runtime/Components/Interpolator/BufferedLinearInterpolator.cs similarity index 99% rename from Components/Interpolator/BufferedLinearInterpolator.cs rename to Runtime/Components/Interpolator/BufferedLinearInterpolator.cs index a938942..543917b 100644 --- a/Components/Interpolator/BufferedLinearInterpolator.cs +++ b/Runtime/Components/Interpolator/BufferedLinearInterpolator.cs @@ -195,7 +195,9 @@ public T Update(float deltaTime, double renderTime, double serverTime) double range = m_EndTimeConsumed - m_StartTimeConsumed; if (range > k_SmallValue) { - t = (float)((renderTime - m_StartTimeConsumed) / range); + var rangeFactor = 1.0f / (float)range; + + t = ((float)renderTime - (float)m_StartTimeConsumed) * rangeFactor; if (t < 0.0f) { diff --git a/Components/Interpolator/BufferedLinearInterpolator.cs.meta b/Runtime/Components/Interpolator/BufferedLinearInterpolator.cs.meta similarity index 100% rename from Components/Interpolator/BufferedLinearInterpolator.cs.meta rename to Runtime/Components/Interpolator/BufferedLinearInterpolator.cs.meta diff --git a/Components/Messages.meta b/Runtime/Components/Messages.meta similarity index 100% rename from Components/Messages.meta rename to Runtime/Components/Messages.meta diff --git a/Components/NetworkAnimator.cs b/Runtime/Components/NetworkAnimator.cs similarity index 100% rename from Components/NetworkAnimator.cs rename to Runtime/Components/NetworkAnimator.cs diff --git a/Components/NetworkAnimator.cs.meta b/Runtime/Components/NetworkAnimator.cs.meta similarity index 100% rename from Components/NetworkAnimator.cs.meta rename to Runtime/Components/NetworkAnimator.cs.meta diff --git a/Components/NetworkDeltaPosition.cs b/Runtime/Components/NetworkDeltaPosition.cs similarity index 97% rename from Components/NetworkDeltaPosition.cs rename to Runtime/Components/NetworkDeltaPosition.cs index ec5c176..2ed982d 100644 --- a/Components/NetworkDeltaPosition.cs +++ b/Runtime/Components/NetworkDeltaPosition.cs @@ -32,9 +32,13 @@ public struct NetworkDeltaPosition : INetworkSerializable /// public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter { - HalfVector3.NetworkSerialize(serializer); - if (SynchronizeBase) + if (!SynchronizeBase) { + HalfVector3.NetworkSerialize(serializer); + } + else + { + serializer.SerializeValue(ref DeltaPosition); serializer.SerializeValue(ref CurrentBasePosition); } } diff --git a/Components/NetworkDeltaPosition.cs.meta b/Runtime/Components/NetworkDeltaPosition.cs.meta similarity index 100% rename from Components/NetworkDeltaPosition.cs.meta rename to Runtime/Components/NetworkDeltaPosition.cs.meta diff --git a/Components/NetworkRigidBodyBase.cs b/Runtime/Components/NetworkRigidBodyBase.cs similarity index 63% rename from Components/NetworkRigidBodyBase.cs rename to Runtime/Components/NetworkRigidBodyBase.cs index d156314..c2a24eb 100644 --- a/Components/NetworkRigidBodyBase.cs +++ b/Runtime/Components/NetworkRigidBodyBase.cs @@ -23,6 +23,7 @@ public abstract class NetworkRigidbodyBase : NetworkBehaviour /// extrapolation and is enabled, then non-authoritative instances will automatically be adjusted to use Rigidbody /// interpolation while the authoritative instance will still use extrapolation. /// + [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; /// @@ -43,7 +44,7 @@ public abstract class NetworkRigidbodyBase : NetworkBehaviour private bool m_IsAuthority; private Rigidbody m_Rigidbody; private Rigidbody2D m_Rigidbody2D; - private NetworkTransform m_NetworkTransform; + internal NetworkTransform NetworkTransform; private enum InterpolationTypes { None, @@ -85,7 +86,7 @@ protected void Initialize(RigidbodyTypes rigidbodyType, NetworkTransform network RigidbodyType = rigidbodyType; m_Rigidbody2D = rigidbody2D; m_Rigidbody = rigidbody; - m_NetworkTransform = networkTransform; + NetworkTransform = networkTransform; if (m_IsRigidbody2D && m_Rigidbody2D == null) { @@ -99,14 +100,14 @@ protected void Initialize(RigidbodyTypes rigidbodyType, NetworkTransform network SetOriginalInterpolation(); - if (m_NetworkTransform == null) + if (NetworkTransform == null) { - m_NetworkTransform = GetComponent(); + NetworkTransform = GetComponent(); } - if (m_NetworkTransform != null) + if (NetworkTransform != null) { - m_NetworkTransform.RegisterRigidbody(this); + NetworkTransform.RegisterRigidbody(this); } else { @@ -218,7 +219,11 @@ public void MoveRotation(Quaternion rotation) { if (m_IsRigidbody2D) { - m_Rigidbody2D.MoveRotation(rotation); + var quaternion = Quaternion.identity; + var angles = quaternion.eulerAngles; + angles.z = m_Rigidbody2D.rotation; + quaternion.eulerAngles = angles; + m_Rigidbody2D.MoveRotation(quaternion); } else { @@ -381,7 +386,7 @@ public void SetIsKinematic(bool isKinematic) if (UseRigidBodyForMotion) { // Only if the NetworkTransform is set to interpolate do we need to check for extrapolation - if (m_NetworkTransform.Interpolate && m_OriginalInterpolation == InterpolationTypes.Extrapolate) + if (NetworkTransform.Interpolate && m_OriginalInterpolation == InterpolationTypes.Extrapolate) { if (IsKinematic()) { @@ -402,7 +407,7 @@ public void SetIsKinematic(bool isKinematic) } else { - SetInterpolation(m_IsAuthority ? m_OriginalInterpolation : (m_NetworkTransform.Interpolate ? InterpolationTypes.None : m_OriginalInterpolation)); + SetInterpolation(m_IsAuthority ? m_OriginalInterpolation : (NetworkTransform.Interpolate ? InterpolationTypes.None : m_OriginalInterpolation)); } } @@ -477,7 +482,7 @@ internal void UpdateOwnershipAuthority() } else { - if (m_NetworkTransform.IsServerAuthoritative()) + if (NetworkTransform.IsServerAuthoritative()) { m_IsAuthority = NetworkManager.IsServer; } @@ -502,6 +507,12 @@ public override void OnNetworkSpawn() /// public override void OnNetworkDespawn() { + if (UseRigidBodyForMotion && HasAuthority) + { + DetachFromFixedJoint(); + NetworkRigidbodyConnections.Clear(); + } + // If we are automatically handling the kinematic state... if (AutoUpdateKinematicState || AutoSetKinematicOnDespawn) { @@ -513,21 +524,197 @@ public override void OnNetworkDespawn() 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 NetworkRigidbodyConnections = new System.Collections.Generic.List(); + internal NetworkRigidbodyBase ParentBody; + + private bool m_FixedJoint2DUsingGravity; + private bool m_OriginalGravitySetting; + private float m_OriginalGravityScale; + + /// + /// When using a custom , this virtual method is invoked when the + /// is created in the event any additional adjustments are needed. + /// + protected virtual void OnFixedJointCreated() + { + + } + + /// + /// When using a custom , this virtual method is invoked when the + /// is created in the event any additional adjustments are needed. + /// + 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_Rigidbody2D.position = position; + m_OriginalGravitySetting = bodyToConnect.m_Rigidbody.useGravity; + m_FixedJoint2DUsingGravity = useGravity; + + if (!useGravity) + { + m_OriginalGravityScale = m_Rigidbody2D.gravityScale; + m_Rigidbody2D.gravityScale = 0.0f; + } + + if (zeroVelocity) + { + m_Rigidbody2D.velocity = Vector2.zero; + m_Rigidbody2D.angularVelocity = 0.0f; + } + + FixedJoint2D = gameObject.AddComponent(); + FixedJoint2D.connectedBody = bodyToConnect.m_Rigidbody2D; + 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_Rigidbody.position = position; + if (zeroVelocity) + { + m_Rigidbody.linearVelocity = Vector3.zero; + m_Rigidbody.angularVelocity = Vector3.zero; + } + m_OriginalGravitySetting = m_Rigidbody.useGravity; + m_Rigidbody.useGravity = useGravity; + FixedJoint = gameObject.AddComponent(); + FixedJoint.connectedBody = bodyToConnectTo.m_Rigidbody; + FixedJoint.connectedMassScale = connectedMassScale; + FixedJoint.massScale = massScale; + OnFixedJointCreated(); + } + + /// - /// When is enabled, the will update Kinematic instances using - /// the Rigidbody's move methods allowing Rigidbody interpolation settings to be taken into consideration by the physics simulation. + /// Authority Only: + /// When invoked and not already attached to a fixed joint, this will connect two rigid bodies with 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). + /// + /// /// /// - /// This will update the associated during FixedUpdate which also avoids the added expense of adding - /// a FixedUpdate to all instances where some might not be using a Rigidbody. + /// Parenting relative: + /// - This instance can be viewed as the child. + /// - The can be viewed as the parent. + ///
+ /// This is the recommended way, as opposed to parenting, to attached/detatch two rigid bodies to one another when is enabled. + /// For more details on using and . + ///
+ /// 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 . ///
- private void FixedUpdate() + /// The target object to attach to. + /// The position of the connection (i.e. where you want the object to be affixed). + /// The target object's mass scale relative to this object being attached. + /// This object's mass scale relative to the target object's. + /// 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) + /// When true (the default), both linear and angular velocities of this object are set to zero. + /// When true (the default), this object will teleport itself to the position of connection. + /// true (success) false (failed) + 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 (!IsSpawned || m_NetworkTransform == null || !UseRigidBodyForMotion) + if (!UseRigidBodyForMotion) { - return; + 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; + } + + /// + /// Authority Only: + /// When invoked and already connected to an object via or (depending upon the type of rigid body), + /// this will detach from the fixed joint and destroy the fixed joint component. + /// + /// + /// This is the recommended way, as opposed to parenting, to attached/detatch two rigid bodies to one another when is enabled. + /// + 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_Rigidbody.useGravity = m_OriginalGravitySetting; + Destroy(FixedJoint); + FixedJoint = null; + ResetInterpolation(); + RemoveFromParentBody(); + } + } } - m_NetworkTransform.OnFixedUpdate(); } } } diff --git a/Components/NetworkRigidBodyBase.cs.meta b/Runtime/Components/NetworkRigidBodyBase.cs.meta similarity index 100% rename from Components/NetworkRigidBodyBase.cs.meta rename to Runtime/Components/NetworkRigidBodyBase.cs.meta diff --git a/Components/NetworkRigidbody.cs b/Runtime/Components/NetworkRigidbody.cs similarity index 100% rename from Components/NetworkRigidbody.cs rename to Runtime/Components/NetworkRigidbody.cs diff --git a/Components/NetworkRigidbody.cs.meta b/Runtime/Components/NetworkRigidbody.cs.meta similarity index 100% rename from Components/NetworkRigidbody.cs.meta rename to Runtime/Components/NetworkRigidbody.cs.meta diff --git a/Components/NetworkRigidbody2D.cs b/Runtime/Components/NetworkRigidbody2D.cs similarity index 100% rename from Components/NetworkRigidbody2D.cs rename to Runtime/Components/NetworkRigidbody2D.cs diff --git a/Components/NetworkRigidbody2D.cs.meta b/Runtime/Components/NetworkRigidbody2D.cs.meta similarity index 100% rename from Components/NetworkRigidbody2D.cs.meta rename to Runtime/Components/NetworkRigidbody2D.cs.meta diff --git a/Components/NetworkTransform.cs b/Runtime/Components/NetworkTransform.cs similarity index 94% rename from Components/NetworkTransform.cs rename to Runtime/Components/NetworkTransform.cs index 3d0d0c1..5635194 100644 --- a/Components/NetworkTransform.cs +++ b/Runtime/Components/NetworkTransform.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Unity.Mathematics; @@ -16,7 +15,6 @@ namespace Unity.Netcode.Components ///
[DisallowMultipleComponent] [AddComponentMenu("Netcode/Network Transform")] - [DefaultExecutionOrder(100000)] // this is needed to catch the update time after the transform was updated by user scripts public class NetworkTransform : NetworkBehaviour { #region NETWORK TRANSFORM STATE @@ -1186,12 +1184,6 @@ private bool SynchronizeScale /// public bool CanCommitToTransform { get; protected set; } - /// - /// Internally used by to keep track of whether this derived class instance - /// was instantiated on the server side or not. - /// - protected bool m_CachedIsServer; // Note: we no longer use this and are only keeping it until we decide to deprecate it - /// /// Internally used by to keep track of the instance assigned to this /// this derived class instance. @@ -1564,6 +1556,14 @@ private void TryCommitTransform(ref Transform transformToCommit, bool synchroniz NetworkLog.LogError($"[{name}] is trying to commit the transform without authority!"); return; } +#if COM_UNITY_MODULES_PHYSICS + // TODO: Make this an authority flag + // For now, just synchronize with the NetworkRigidbodyBase UseRigidBodyForMotion + if (m_NetworkRigidbodyInternal != null) + { + m_UseRigidbodyForMotion = m_NetworkRigidbodyInternal.UseRigidBodyForMotion; + } +#endif // If the transform has deltas (returns dirty) or if an explicitly set state is pending if (m_LocalAuthoritativeNetworkState.ExplicitSet || CheckForStateChange(ref m_LocalAuthoritativeNetworkState, ref transformToCommit, synchronize)) @@ -1609,6 +1609,17 @@ private void TryCommitTransform(ref Transform transformToCommit, bool synchroniz { m_DeltaSynch = true; } + +#if COM_UNITY_MODULES_PHYSICS + // We handle updating attached bodies when the "parent" body has a state update in order to keep their delta state updates tick synchronized. + if (m_UseRigidbodyForMotion && m_NetworkRigidbodyInternal.NetworkRigidbodyConnections.Count > 0) + { + foreach (var childRigidbody in m_NetworkRigidbodyInternal.NetworkRigidbodyConnections) + { + childRigidbody.NetworkTransform.OnNetworkTick(true); + } + } +#endif } } @@ -1696,6 +1707,26 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra var scale = transformToUse.localScale; networkState.IsSynchronizing = isSynchronization; + // All of the checks below, up to the delta position checking portion, are to determine if the + // authority changed a property during runtime that requires a full synchronizing. +#if COM_UNITY_MODULES_PHYSICS + if (InLocalSpace != networkState.InLocalSpace && !m_UseRigidbodyForMotion) +#else + if (InLocalSpace != networkState.InLocalSpace) +#endif + { + networkState.InLocalSpace = InLocalSpace; + isDirty = true; + networkState.IsTeleportingNextFrame = true; + } +#if COM_UNITY_MODULES_PHYSICS + else if (InLocalSpace && m_UseRigidbodyForMotion) + { + // TODO: Provide more options than just FixedJoint + Debug.LogError($"[Rigidbody] WHen using a Rigidbody for motion, you cannot use {nameof(InLocalSpace)}! If parenting, use the integrated FixedJoint or use a Joint on Authority side."); + } +#endif + // Check for parenting when synchronizing and/or teleporting if (isSynchronization || networkState.IsTeleportingNextFrame) { @@ -1705,11 +1736,13 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra // values are applied. var hasParentNetworkObject = false; + var parentNetworkObject = (NetworkObject)null; + // If the NetworkObject belonging to this NetworkTransform instance has a parent // (i.e. this handles nested NetworkTransforms under a parent at some layer above) if (NetworkObject.transform.parent != null) { - var parentNetworkObject = NetworkObject.transform.parent.GetComponent(); + parentNetworkObject = NetworkObject.transform.parent.GetComponent(); // In-scene placed NetworkObjects parented under a GameObject with no // NetworkObject preserve their lossyScale when synchronizing. @@ -1730,28 +1763,25 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra // the NetworkTransform is using world or local space synchronization. // WorldPositionStays: (always use world space) // !WorldPositionStays: (always use local space) - if (isSynchronization) + // Exception: If it is an in-scene placed NetworkObject and it is parented under a GameObject + // then always use local space unless AutoObjectParentSync is disabled and the NetworkTransform + // is synchronizing in world space. + if (isSynchronization && networkState.IsParented) { - if (NetworkObject.WorldPositionStays()) + var parentedUnderGameObject = NetworkObject.transform.parent != null && !parentNetworkObject && NetworkObject.IsSceneObject.Value; + if (NetworkObject.WorldPositionStays() && (!parentedUnderGameObject || (parentedUnderGameObject && !NetworkObject.AutoObjectParentSync && !InLocalSpace))) { position = transformToUse.position; + networkState.InLocalSpace = false; } else { position = transformToUse.localPosition; + networkState.InLocalSpace = true; } } } - // All of the checks below, up to the delta position checking portion, are to determine if the - // authority changed a property during runtime that requires a full synchronizing. - if (InLocalSpace != networkState.InLocalSpace) - { - networkState.InLocalSpace = InLocalSpace; - isDirty = true; - networkState.IsTeleportingNextFrame = true; - } - if (Interpolate != networkState.UseInterpolation) { networkState.UseInterpolation = Interpolate; @@ -1968,7 +1998,7 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra } if (isRotationDirty) { - networkState.Rotation = InLocalSpace ? transformToUse.localRotation : transformToUse.rotation; + networkState.Rotation = rotation; networkState.HasRotAngleX = true; networkState.HasRotAngleY = true; networkState.HasRotAngleZ = true; @@ -2067,15 +2097,31 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra /// Authority subscribes to network tick events and will invoke /// each network tick. /// - private void OnNetworkTick() + private void OnNetworkTick(bool isCalledFromParent = false) { + // If not active, then ignore the update + if (!gameObject.activeInHierarchy) + { + return; + } + // As long as we are still authority if (CanCommitToTransform) { if (m_CachedNetworkManager.DistributedAuthorityMode && !IsOwner) { Debug.LogError($"Non-owner Client-{m_CachedNetworkManager.LocalClientId} is being updated by network tick still!!!!"); + return; } + +#if COM_UNITY_MODULES_PHYSICS + // Let the parent handle the updating of this to keep the two synchronized + if (!isCalledFromParent && m_UseRigidbodyForMotion && m_NetworkRigidbodyInternal.ParentBody != null && !m_LocalAuthoritativeNetworkState.IsTeleportingNextFrame) + { + return; + } +#endif + // Update any changes to the transform var transformSource = transform; OnUpdateAuthoritativeState(ref transformSource); @@ -2086,10 +2132,9 @@ private void OnNetworkTick() m_TargetPosition = GetSpaceRelativePosition(); #endif } - else // If we are no longer authority, unsubscribe to the tick event - if (NetworkManager != null && NetworkManager.NetworkTickSystem != null) + else // If we are no longer authority, unsubscribe to the tick event { - NetworkManager.NetworkTickSystem.Tick -= OnNetworkTick; + DeregisterForTickUpdate(this); } } #endregion @@ -2119,6 +2164,14 @@ internal void UpdatePositionInterpolator(Vector3 position, double time, bool res /// private void ApplyAuthoritativeState() { +#if COM_UNITY_MODULES_PHYSICS + // TODO: Make this an authority flag + // For now, just synchronize with the NetworkRigidbodyBase UseRigidBodyForMotion + if (m_NetworkRigidbodyInternal != null) + { + m_UseRigidbodyForMotion = m_NetworkRigidbodyInternal.UseRigidBodyForMotion; + } +#endif var networkState = m_LocalAuthoritativeNetworkState; // The m_CurrentPosition, m_CurrentRotation, and m_CurrentScale values are continually updated // at the end of this method and assure that when not interpolating the non-authoritative side @@ -2842,12 +2895,6 @@ protected virtual void Awake() /// public override void OnNetworkSpawn() { - /////////////////////////////////////////////////////////////// - // NOTE: Legacy and no longer used (candidates for deprecation) - m_CachedIsServer = IsServer; - /////////////////////////////////////////////////////////////// - - // Started using this again to avoid the getter processing cost of NetworkBehaviour.NetworkManager m_CachedNetworkManager = NetworkManager; Initialize(); @@ -2860,6 +2907,13 @@ public override void OnNetworkSpawn() private void CleanUpOnDestroyOrDespawn() { + +#if COM_UNITY_MODULES_PHYSICS + var forUpdate = !m_UseRigidbodyForMotion; +#else + var forUpdate = true; +#endif + NetworkManager?.NetworkTransformRegistration(this, forUpdate, false); DeregisterForTickUpdate(this); CanCommitToTransform = false; } @@ -2918,7 +2972,7 @@ private void ResetInterpolatedStateToCurrentAuthoritativeState() m_ScaleInterpolator.ResetTo(transform.localScale, serverTime); m_RotationInterpolator.ResetTo(rotation, serverTime); } - + private NetworkObject m_CachedNetworkObject; /// /// The internal initialzation method to allow for internal API adjustments /// @@ -2929,7 +2983,7 @@ private void InternalInitialization(bool isOwnershipChange = false) { return; } - + m_CachedNetworkObject = NetworkObject; CanCommitToTransform = IsServerAuthoritative() ? IsServer : IsOwner; var currentPosition = GetSpaceRelativePosition(); var currentRotation = GetSpaceRelativeRotation(); @@ -2952,10 +3006,17 @@ private void InternalInitialization(bool isOwnershipChange = false) m_NetworkRigidbodyInternal.SetPosition(currentPosition); m_NetworkRigidbodyInternal.SetRotation(currentRotation); } + + var forUpdate = !m_UseRigidbodyForMotion; +#else + var forUpdate = true; #endif if (CanCommitToTransform) { + + // Make sure authority doesn't get added to updates (no need to do this on the authority side) + m_CachedNetworkManager.NetworkTransformRegistration(this, forUpdate, false); if (UseHalfFloatPrecision) { m_HalfPositionState = new NetworkDeltaPosition(currentPosition, m_CachedNetworkManager.ServerTime.Tick, math.bool3(SyncPositionX, SyncPositionY, SyncPositionZ)); @@ -2973,6 +3034,8 @@ private void InternalInitialization(bool isOwnershipChange = false) } else { + // Non-authority needs to be added to updates for interpolation and applying state purposes + m_CachedNetworkManager.NetworkTransformRegistration(this, forUpdate, true); // Remove this instance from the tick update DeregisterForTickUpdate(this); @@ -3233,7 +3296,7 @@ private void UpdateInterpolation() { var serverTime = m_CachedNetworkManager.ServerTime; var cachedServerTime = serverTime.Time; - var offset = 0f; + var offset = (float)serverTime.TickOffset; #if COM_UNITY_MODULES_PHYSICS var cachedDeltaTime = m_UseRigidbodyForMotion ? m_CachedNetworkManager.RealTimeProvider.FixedDeltaTime : m_CachedNetworkManager.RealTimeProvider.DeltaTime; #else @@ -3242,16 +3305,14 @@ private void UpdateInterpolation() // With owner authoritative mode, non-authority clients can lag behind // by more than 1 tick period of time. The current "solution" for now // is to make their cachedRenderTime run 2 ticks behind. -#if COM_UNITY_MODULES_PHYSICS - var ticksAgo = (!IsServerAuthoritative() && !IsServer) || m_UseRigidbodyForMotion ? 2 : 1; -#else - var ticksAgo = (!IsServerAuthoritative() && !IsServer) ? 2 : 1; -#endif - if (m_CachedNetworkManager.DistributedAuthorityMode) - { - ticksAgo = Mathf.Max(ticksAgo, (int)m_NetworkTransformTickRegistration.TicksAgo); - offset = m_NetworkTransformTickRegistration.Offset; - } + var ticksAgo = (!IsServerAuthoritative() && !IsServer) || m_CachedNetworkManager.DistributedAuthorityMode ? 2 : 1; + // TODO: We need an RTT that updates regularly and not only when the client sends packets + //if (m_CachedNetworkManager.DistributedAuthorityMode) + //{ + //ticksAgo = m_CachedNetworkManager.CMBServiceConnection ? 2 : 3; + //ticksAgo = Mathf.Max(ticksAgo, (int)m_NetworkTransformTickRegistration.TicksAgo); + //offset = m_NetworkTransformTickRegistration.Offset; + //} var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo, offset).Time; @@ -3282,7 +3343,7 @@ private void UpdateInterpolation() /// If you override this method, be sure that: /// - Non-authority always invokes this base class method. /// - protected virtual void Update() + public virtual void OnUpdate() { // If not spawned or this instance has authority, exit early #if COM_UNITY_MODULES_PHYSICS @@ -3303,11 +3364,12 @@ protected virtual void Update() #if COM_UNITY_MODULES_PHYSICS + /// /// When paired with a NetworkRigidbody and NetworkRigidbody.UseRigidBodyForMotion is enabled, /// this will be invoked during . /// - internal void OnFixedUpdate() + public virtual void OnFixedUpdate() { // If not spawned or this instance has authority, exit early if (!m_UseRigidbodyForMotion || !IsSpawned || CanCommitToTransform) @@ -3353,32 +3415,69 @@ public bool IsServerAuthoritative() #endregion #region MESSAGE HANDLING + + internal NetworkTransformState InboundState = new NetworkTransformState(); + internal NetworkTransformState OutboundState + { + get + { + return m_LocalAuthoritativeNetworkState; + } + } + /// /// Invoked by to update the transform state /// /// - internal void TransformStateUpdate(ref NetworkTransformState networkTransformState, ulong senderId) + internal void TransformStateUpdate(ulong senderId) { if (CanCommitToTransform) { - Debug.LogError($"Authority receiving transform update from Client-{senderId}!"); + // TODO: Investigate where this state should be applied or just discarded. + // For now, discard the state if we assumed ownership. + return; } // Store the previous/old state m_OldState = m_LocalAuthoritativeNetworkState; // Assign the new incoming state - m_LocalAuthoritativeNetworkState = networkTransformState; + m_LocalAuthoritativeNetworkState = InboundState; // Apply the state update OnNetworkStateChanged(m_OldState, m_LocalAuthoritativeNetworkState); } + // Used to send outbound messages + private NetworkTransformMessage m_OutboundMessage = new NetworkTransformMessage(); + + + internal void SerializeMessage(FastBufferWriter writer, int targetVersion) + { + var networkObject = NetworkObject; + BytePacker.WriteValueBitPacked(writer, NetworkObjectId); + BytePacker.WriteValueBitPacked(writer, (int)NetworkBehaviourId); + writer.WriteNetworkSerializable(m_LocalAuthoritativeNetworkState); + if (m_CachedNetworkManager.DistributedAuthorityMode) + { + BytePacker.WriteValuePacked(writer, networkObject.Observers.Count - 1); + + foreach (var targetId in networkObject.Observers) + { + if (OwnerClientId == targetId) + { + continue; + } + BytePacker.WriteValuePacked(writer, targetId); + } + } + } + /// /// Invoked by the authoritative instance to sends a containing the /// private void UpdateTransformState() { - if (m_CachedNetworkManager.ShutdownInProgress) + if (m_CachedNetworkManager.ShutdownInProgress || (m_CachedNetworkManager.DistributedAuthorityMode && m_CachedNetworkObject.Observers.Count - 1 == 0)) { return; } @@ -3393,17 +3492,7 @@ private void UpdateTransformState() Debug.LogError($"Owner authoritative {nameof(NetworkTransform)} can only be updated by the owner!"); } var customMessageManager = m_CachedNetworkManager.CustomMessagingManager; - - var networkTransformMessage = new NetworkTransformMessage() - { - NetworkObjectId = NetworkObjectId, - NetworkBehaviourId = NetworkBehaviourId, - State = m_LocalAuthoritativeNetworkState, - DistributedAuthorityMode = m_CachedNetworkManager.DistributedAuthorityMode, - // Don't populate if we are the DAHost as we send directly to each client - TargetIds = m_CachedNetworkManager.DistributedAuthorityMode && !m_CachedNetworkManager.DAHost ? NetworkObject.Observers.Where((c) => c != m_CachedNetworkManager.LocalClientId).ToArray() : null, - }; - + m_OutboundMessage.NetworkTransform = this; // Determine what network delivery method to use: // When to send reliable packets: @@ -3429,13 +3518,13 @@ private void UpdateTransformState() { continue; } - NetworkManager.MessageManager.SendMessage(ref networkTransformMessage, networkDelivery, clientId); + NetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, clientId); } } else { // Clients (owner authoritative) send messages to the server-host - NetworkManager.MessageManager.SendMessage(ref networkTransformMessage, networkDelivery, NetworkManager.ServerClientId); + NetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, NetworkManager.ServerClientId); } } #endregion @@ -3509,7 +3598,9 @@ public void Remove() internal float TicksAgoInSeconds() { - return Mathf.Max(1.0f, TicksAgo) * m_TickFrequency; + 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; } /// @@ -3518,25 +3609,26 @@ internal float TicksAgoInSeconds() /// private void TickUpdate() { - 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: 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); + //} // TODO FIX: The local NetworkTickSystem can invoke with the same network tick as before if (m_NetworkManager.ServerTime.Tick <= m_LastTick) @@ -3556,13 +3648,13 @@ private void TickUpdate() 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 m_TicksAgoSamples = new List(); @@ -3573,19 +3665,19 @@ public NetworkTransformTickRegistration(NetworkManager networkManager) networkManager.NetworkTickSystem.Tick += m_NetworkTickUpdate; m_TickRate = (int)m_NetworkManager.NetworkConfig.TickRate; m_TickFrequency = 1.0f / m_TickRate; - // 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; - // Fill the sample with a starting value of 1 - for (int i = 0; i < m_TickRate; i++) - { - m_TicksAgoSamples.Add(1f); - } - TicksAgo = 1f; - m_PreviousTicksAgo = 1f; + //// 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; + //// Fill the sample with a starting value of 1 + //for (int i = 0; i < m_TickRate; i++) + //{ + // m_TicksAgoSamples.Add(1f); + //} + TicksAgo = 2f; + //m_PreviousTicksAgo = 1f; if (networkManager.IsServer) { networkManager.OnServerStopped += OnNetworkManagerStopped; diff --git a/Components/NetworkTransform.cs.meta b/Runtime/Components/NetworkTransform.cs.meta similarity index 100% rename from Components/NetworkTransform.cs.meta rename to Runtime/Components/NetworkTransform.cs.meta diff --git a/Components/QuaternionCompressor.cs b/Runtime/Components/QuaternionCompressor.cs similarity index 98% rename from Components/QuaternionCompressor.cs rename to Runtime/Components/QuaternionCompressor.cs index 0cdeb13..f4d9b25 100644 --- a/Components/QuaternionCompressor.cs +++ b/Runtime/Components/QuaternionCompressor.cs @@ -14,7 +14,7 @@ namespace Unity.Netcode /// M = 1.0f (which M * M would still yield 1.0f) /// w*w = M*M - (x*x + y*y + z*z) or Mathf.Sqrt(1.0f - (x*x + y*y + z*z)) /// w = Math.Sqrt(1.0f - (x*x + y*y + z*z)) - /// Using the largest the number avoids potential loss of precision in the smallest three values. + /// Using the largest number avoids potential loss of precision in the smallest three values. /// public static class QuaternionCompressor { diff --git a/Components/QuaternionCompressor.cs.meta b/Runtime/Components/QuaternionCompressor.cs.meta similarity index 100% rename from Components/QuaternionCompressor.cs.meta rename to Runtime/Components/QuaternionCompressor.cs.meta diff --git a/Components/RigidbodyContactEventManager.cs b/Runtime/Components/RigidbodyContactEventManager.cs similarity index 100% rename from Components/RigidbodyContactEventManager.cs rename to Runtime/Components/RigidbodyContactEventManager.cs diff --git a/Components/RigidbodyContactEventManager.cs.meta b/Runtime/Components/RigidbodyContactEventManager.cs.meta similarity index 100% rename from Components/RigidbodyContactEventManager.cs.meta rename to Runtime/Components/RigidbodyContactEventManager.cs.meta diff --git a/Runtime/Configuration/NetworkConfig.cs b/Runtime/Configuration/NetworkConfig.cs index ff806c6..9213d24 100644 --- a/Runtime/Configuration/NetworkConfig.cs +++ b/Runtime/Configuration/NetworkConfig.cs @@ -149,8 +149,8 @@ public class NetworkConfig /// public const int RttWindowSize = 64; // number of slots to use for RTT computations (max number of in-flight packets) - [Tooltip("Determines if the network session will run in client-server or distributed authority mode.")] - public SessionModeTypes SessionMode; + [Tooltip("Determines whether to use the client-server or distributed authority network topology.")] + public NetworkTopologyTypes NetworkTopology; [HideInInspector] public bool UseCMBService; @@ -158,6 +158,12 @@ public class NetworkConfig [Tooltip("When enabled (default), the player prefab will automatically be spawned (client-side) upon the client being approved and synchronized.")] public bool AutoSpawnPlayerPrefabClientSide = true; +#if MULTIPLAYER_TOOLS + public bool NetworkMessageMetrics = true; +#endif + + public bool NetworkProfilingMetrics = true; + /// /// Returns a base64 encoded version of the configuration /// diff --git a/Runtime/Connection/NetworkClient.cs b/Runtime/Connection/NetworkClient.cs index 63b24bd..8cee4e0 100644 --- a/Runtime/Connection/NetworkClient.cs +++ b/Runtime/Connection/NetworkClient.cs @@ -4,7 +4,7 @@ namespace Unity.Netcode { - public enum SessionModeTypes + public enum NetworkTopologyTypes { ClientServer, DistributedAuthority @@ -41,7 +41,7 @@ public class NetworkClient /// internal bool IsApproved { get; set; } - public SessionModeTypes SessionModeType { get; internal set; } + public NetworkTopologyTypes NetworkTopologyType { get; internal set; } public bool DAHost { get; internal set; } @@ -77,9 +77,9 @@ internal bool SetRole(bool isServer, bool isClient, NetworkManager networkManage if (networkManager != null) { SpawnManager = networkManager.SpawnManager; - SessionModeType = networkManager.NetworkConfig.SessionMode; + NetworkTopologyType = networkManager.NetworkConfig.NetworkTopology; - if (SessionModeType == SessionModeTypes.DistributedAuthority) + if (NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority) { DAHost = IsClient && IsServer; diff --git a/Runtime/Core/NetworkBehaviour.cs b/Runtime/Core/NetworkBehaviour.cs index ce0f648..5b53f1a 100644 --- a/Runtime/Core/NetworkBehaviour.cs +++ b/Runtime/Core/NetworkBehaviour.cs @@ -660,16 +660,69 @@ internal void UpdateNetworkProperties() /// the future network tick that the will be despawned on non-authoritative instances public virtual void OnDeferringDespawn(int despawnTick) { } + /// Gets called after the is spawned. No NetworkBehaviours associated with the NetworkObject will have had invoked yet. + /// A reference to is passed in as a parameter to determine the context of execution (IsServer/IsClient) + /// + /// + /// a ref to the since this is not yet set on the + /// The will not have anything assigned to it at this point in time. + /// Settings like ownership, NetworkBehaviourId, NetworkManager, and most other spawn related properties will not be set. + /// This can be used to handle things like initializing/instantiating a NetworkVariable or the like. + /// + protected virtual void OnNetworkPreSpawn(ref NetworkManager networkManager) { } + /// /// Gets called when the gets spawned, message handlers are ready to be registered and the network is setup. /// public virtual void OnNetworkSpawn() { } + /// + /// Gets called after the is spawned. All NetworkBehaviours associated with the NetworkObject will have had invoked. + /// + /// + /// Will be invoked on each associated with the being spawned. + /// All associated components will have had invoked on the spawned . + /// + protected virtual void OnNetworkPostSpawn() { } + + /// + /// [Client-Side Only] + /// When a new client joins it is synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all + /// s and scenes (if scene management is enabled) have finished synchronizing, all NetworkBehaviour components associated with spawned s + /// will have this method invoked. + /// + /// + /// This can be used to handle post synchronization actions where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context. + /// This is only invoked on clients during a client-server network topology session. + /// + protected virtual void OnNetworkSessionSynchronized() { } + + /// + /// [Client & Server Side] + /// When a scene is loaded an in-scene placed NetworkObjects are all spawned, this method is invoked on all of the newly spawned in-scene placed NetworkObjects. + /// + /// + /// This can be used to handle post scene loaded actions for in-scene placed NetworkObjcts where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context. + /// + protected virtual void OnInSceneObjectsSpawned() { } + /// /// Gets called when the gets despawned. Is called both on the server and clients. /// public virtual void OnNetworkDespawn() { } + internal void NetworkPreSpawn(ref NetworkManager networkManager) + { + try + { + OnNetworkPreSpawn(ref networkManager); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + internal void InternalOnNetworkSpawn() { IsSpawned = true; @@ -699,6 +752,42 @@ internal void VisibleOnNetworkSpawn() } } + internal void NetworkPostSpawn() + { + try + { + OnNetworkPostSpawn(); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + + internal void NetworkSessionSynchronized() + { + try + { + OnNetworkSessionSynchronized(); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + + internal void InSceneNetworkObjectsSpawned() + { + try + { + OnInSceneObjectsSpawned(); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + internal void InternalOnNetworkDespawn() { IsSpawned = false; diff --git a/Runtime/Core/NetworkManager.cs b/Runtime/Core/NetworkManager.cs index 64637c8..340eced 100644 --- a/Runtime/Core/NetworkManager.cs +++ b/Runtime/Core/NetworkManager.cs @@ -8,6 +8,7 @@ #endif using UnityEngine.SceneManagement; using Debug = UnityEngine.Debug; +using Unity.Netcode.Components; namespace Unity.Netcode { @@ -43,7 +44,7 @@ public bool DistributedAuthorityMode { get { - return NetworkConfig.SessionMode == SessionModeTypes.DistributedAuthority; + return NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority; } } @@ -177,6 +178,45 @@ public void PromoteSessionOwner(ulong clientId) } } + internal Dictionary NetworkTransformUpdate = new Dictionary(); +#if COM_UNITY_MODULES_PHYSICS + internal Dictionary NetworkTransformFixedUpdate = new Dictionary(); +#endif + + internal void NetworkTransformRegistration(NetworkTransform networkTransform, bool forUpdate = true, bool register = true) + { + if (forUpdate) + { + if (register) + { + if (!NetworkTransformUpdate.ContainsKey(networkTransform.NetworkObjectId)) + { + NetworkTransformUpdate.Add(networkTransform.NetworkObjectId, networkTransform); + } + } + else + { + NetworkTransformUpdate.Remove(networkTransform.NetworkObjectId); + } + } +#if COM_UNITY_MODULES_PHYSICS + else + { + if (register) + { + if (!NetworkTransformFixedUpdate.ContainsKey(networkTransform.NetworkObjectId)) + { + NetworkTransformFixedUpdate.Add(networkTransform.NetworkObjectId, networkTransform); + } + } + else + { + NetworkTransformFixedUpdate.Remove(networkTransform.NetworkObjectId); + } + } +#endif + } + public void NetworkUpdate(NetworkUpdateStage updateStage) { switch (updateStage) @@ -192,11 +232,36 @@ public void NetworkUpdate(NetworkUpdateStage updateStage) MessageManager.CleanupDisconnectedClients(); } break; +#if COM_UNITY_MODULES_PHYSICS + case NetworkUpdateStage.FixedUpdate: + { + foreach (var networkTransformEntry in NetworkTransformFixedUpdate) + { + if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned) + { + networkTransformEntry.Value.OnFixedUpdate(); + } + } + } + break; +#endif case NetworkUpdateStage.PreUpdate: { NetworkTimeSystem.UpdateTime(); } break; + case NetworkUpdateStage.PreLateUpdate: + { + // Non-physics based non-authority NetworkTransforms update their states after all other components + foreach (var networkTransformEntry in NetworkTransformUpdate) + { + if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned) + { + networkTransformEntry.Value.OnUpdate(); + } + } + } + break; case NetworkUpdateStage.PostLateUpdate: { // Handle deferred despawning @@ -942,6 +1007,10 @@ public int MaximumFragmentedMessageSize internal void Initialize(bool server) { +#if COM_UNITY_MODULES_PHYSICS + NetworkTransformFixedUpdate.Clear(); +#endif + NetworkTransformUpdate.Clear(); //DANGOEXP TODO: Remove this before finalizing the experimental release NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode; @@ -978,7 +1047,11 @@ internal void Initialize(bool server) } this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate); +#if COM_UNITY_MODULES_PHYSICS + this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate); +#endif this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate); + this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate); // ComponentFactory needs to set its defaults next @@ -994,11 +1067,17 @@ internal void Initialize(bool server) MessageManager.Hook(new NetworkManagerHooks(this)); #if DEVELOPMENT_BUILD || UNITY_EDITOR - MessageManager.Hook(new ProfilingHooks()); + if (NetworkConfig.NetworkProfilingMetrics) + { + MessageManager.Hook(new ProfilingHooks()); + } #endif #if MULTIPLAYER_TOOLS - MessageManager.Hook(new MetricHooks(this)); + if (NetworkConfig.NetworkMessageMetrics) + { + MessageManager.Hook(new MetricHooks(this)); + } #endif // Assures there is a server message queue available diff --git a/Runtime/Core/NetworkObject.cs b/Runtime/Core/NetworkObject.cs index 7aa3a72..3e7ae26 100644 --- a/Runtime/Core/NetworkObject.cs +++ b/Runtime/Core/NetworkObject.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; +using Unity.Netcode.Components; #if UNITY_EDITOR using UnityEditor; #if UNITY_2021_2_OR_NEWER @@ -14,6 +15,7 @@ using UnityEngine.SceneManagement; + namespace Unity.Netcode { /// @@ -55,6 +57,34 @@ public uint PrefabIdHash } } + /// + /// All component instances associated with a component instance. + /// + /// + /// When parented, all child component instances under a component instance that do not have + /// another component instance will be associated with the initial component instance. This list does not contain any parented + /// children instances with one or more component instance(s). + /// + public List NetworkTransforms { get; private set; } + +#if COM_UNITY_MODULES_PHYSICS + /// + /// All component instances associated with a component instance. + /// NOTE: This is only available if a physics package is included. If not, then this will not be available! + /// + /// + /// When parented, all child component instances under a component instance that do not have + /// another component instance will be associated with the initial component instance. This list does not contain any parented + /// child instances with one or more component instance(s). + /// + public List NetworkRigidbodies { get; private set; } +#endif + /// + /// The current parent component instance to this component instance. When there is no parent then + /// this will be . + /// + public NetworkObject CurrentParent { get; private set; } + #if UNITY_EDITOR private const string k_GlobalIdTemplate = "GlobalObjectId_V1-{0}-{1}-{2}-{3}"; @@ -398,8 +428,11 @@ public void DeferDespawn(int tickOffset, bool destroy = true) /// /// Determines whether a NetworkObject can be distributed to other clients during - /// a session. + /// a session. /// +#if !MULTIPLAYER_SDK_INSTALLED + [HideInInspector] +#endif [SerializeField] internal OwnershipStatus Ownership = OwnershipStatus.Distributable; @@ -1894,7 +1927,6 @@ public bool TrySetParent(NetworkObject parent, bool worldPositionStays = true) internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true) { - if (parent != null && (IsSpawned ^ parent.IsSpawned)) { if (NetworkManager != null && !NetworkManager.ShutdownInProgress) @@ -1907,10 +1939,12 @@ internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays if (parent == null) { + CurrentParent = null; transform.SetParent(null, worldPositionStays); } else { + CurrentParent = parent; transform.SetParent(parent.transform, worldPositionStays); } @@ -2209,6 +2243,18 @@ internal static void CheckOrphanChildren() } } + internal void InvokeBehaviourNetworkPreSpawn() + { + var networkManager = NetworkManager; + for (int i = 0; i < ChildNetworkBehaviours.Count; i++) + { + if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy) + { + ChildNetworkBehaviours[i].NetworkPreSpawn(ref networkManager); + } + } + } + internal void InvokeBehaviourNetworkSpawn() { NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId); @@ -2238,6 +2284,42 @@ internal void InvokeBehaviourNetworkSpawn() } } + internal void InvokeBehaviourNetworkPostSpawn() + { + for (int i = 0; i < ChildNetworkBehaviours.Count; i++) + { + if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy) + { + ChildNetworkBehaviours[i].NetworkPostSpawn(); + } + } + } + + + internal void InternalNetworkSessionSynchronized() + { + for (int i = 0; i < ChildNetworkBehaviours.Count; i++) + { + if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy) + { + ChildNetworkBehaviours[i].NetworkSessionSynchronized(); + } + } + } + + internal void InternalInSceneNetworkObjectsSpawned() + { + for (int i = 0; i < ChildNetworkBehaviours.Count; i++) + { + if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy) + { + ChildNetworkBehaviours[i].InSceneNetworkObjectsSpawned(); + } + } + } + + + internal void InvokeBehaviourNetworkDespawn() { NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true); @@ -2271,6 +2353,25 @@ internal List ChildNetworkBehaviours if (networkBehaviours[i].NetworkObject == this) { m_ChildNetworkBehaviours.Add(networkBehaviours[i]); + var type = networkBehaviours[i].GetType(); + if (type.IsInstanceOfType(typeof(NetworkTransform)) || type.IsSubclassOf(typeof(NetworkTransform))) + { + if (NetworkTransforms == null) + { + NetworkTransforms = new List(); + } + NetworkTransforms.Add(networkBehaviours[i] as NetworkTransform); + } +#if COM_UNITY_MODULES_PHYSICS + else if (type.IsSubclassOf(typeof(NetworkRigidbodyBase))) + { + if (NetworkRigidbodies == null) + { + NetworkRigidbodies = new List(); + } + NetworkRigidbodies.Add(networkBehaviours[i] as NetworkRigidbodyBase); + } +#endif } } @@ -2862,6 +2963,9 @@ internal static NetworkObject AddSceneObject(in SceneObject sceneObject, FastBuf // in order to be able to determine which NetworkVariables the client will be allowed to read. networkObject.OwnerClientId = sceneObject.OwnerClientId; + // Special Case: Invoke NetworkBehaviour.OnPreSpawn methods here before SynchronizeNetworkBehaviours + networkObject.InvokeBehaviourNetworkPreSpawn(); + // Synchronize NetworkBehaviours var bufferSerializer = new BufferSerializer(new BufferSerializerReader(reader)); networkObject.SynchronizeNetworkBehaviours(ref bufferSerializer, networkManager.LocalClientId); @@ -3051,6 +3155,11 @@ internal static void UpdateNetworkObjectSceneChanges() private void Awake() { + m_ChildNetworkBehaviours = null; + NetworkTransforms?.Clear(); +#if COM_UNITY_MODULES_PHYSICS + NetworkRigidbodies?.Clear(); +#endif SetCachedParent(transform.parent); SceneOrigin = gameObject.scene; } diff --git a/Runtime/Messaging/CustomMessageManager.cs b/Runtime/Messaging/CustomMessageManager.cs index 1b8626c..dfea03e 100644 --- a/Runtime/Messaging/CustomMessageManager.cs +++ b/Runtime/Messaging/CustomMessageManager.cs @@ -63,16 +63,39 @@ public void SendUnnamedMessageToAll(FastBufferWriter messageBuffer, NetworkDeliv /// The delivery type (QoS) to send data with public void SendUnnamedMessage(IReadOnlyList clientIds, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) { - if (!m_NetworkManager.IsServer) + if (clientIds == null) { - throw new InvalidOperationException("Can not send unnamed messages to multiple users as a client"); + throw new ArgumentNullException(nameof(clientIds), "You must pass in a valid clientId List!"); } - if (clientIds == null) + if (!m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.IsServer) + { + if (clientIds.Count > 1 || (clientIds.Count == 1 && clientIds[0] != NetworkManager.ServerClientId)) + { + Debug.LogError("Clients cannot send unnamed messages to other clients!"); + return; + } + else if (clientIds.Count == 1) + { + SendUnnamedMessage(clientIds[0], messageBuffer, networkDelivery); + } + } + else if (m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.DAHost) + { + if (clientIds.Count > 1) + { + Debug.LogError("Sending an unnamed message to multiple clients is not yet supported in distributed authority."); + return; + } + } + + if (clientIds.Count == 0) { - throw new ArgumentNullException(nameof(clientIds), "You must pass in a valid clientId List"); + Debug.LogError($"{nameof(clientIds)} is empty! No clients to send to."); + return; } + if (m_NetworkManager.IsHost) { for (var i = 0; i < clientIds.Count; ++i) @@ -203,6 +226,14 @@ public void RegisterNamedMessageHandler(string name, HandleNamedMessageDelegate var hash32 = XXHash.Hash32(name); var hash64 = XXHash.Hash64(name); + if (m_NetworkManager.LogLevel <= LogLevel.Developer) + { + if (m_MessageHandlerNameLookup32.ContainsKey(hash32) || m_MessageHandlerNameLookup64.ContainsKey(hash64)) + { + Debug.LogWarning($"Registering {name} named message over existing registration! Your previous registration's callback is being overwritten!"); + } + } + m_NamedMessageHandlers32[hash32] = callback; m_NamedMessageHandlers64[hash64] = callback; @@ -303,14 +334,37 @@ public void SendNamedMessage(string messageName, ulong clientId, FastBufferWrite /// The delivery type (QoS) to send data with public void SendNamedMessage(string messageName, IReadOnlyList clientIds, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) { - if (!m_NetworkManager.IsServer) + if (clientIds == null) { - throw new InvalidOperationException("Can not send unnamed messages to multiple users as a client"); + throw new ArgumentNullException(nameof(clientIds), "Client list is null! You must pass in a valid clientId list to send a named message."); } - if (clientIds == null) + if (!m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.IsServer) { - throw new ArgumentNullException(nameof(clientIds), "You must pass in a valid clientId List"); + if (clientIds.Count > 1 || (clientIds.Count == 1 && clientIds[0] != NetworkManager.ServerClientId)) + { + Debug.LogError("Clients cannot send named messages to other clients!"); + return; + } + else if (clientIds.Count == 1) + { + SendNamedMessage(messageName, clientIds[0], messageStream, networkDelivery); + return; + } + } + else if (m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.DAHost) + { + if (clientIds.Count > 1) + { + Debug.LogError("Sending a named message to multiple clients is not yet supported in distributed authority."); + return; + } + } + + if (clientIds.Count == 0) + { + Debug.LogError($"{nameof(clientIds)} is empty! No clients to send the named message {messageName} to!"); + return; } ulong hash = 0; diff --git a/Runtime/Messaging/ILPPMessageProvider.cs b/Runtime/Messaging/ILPPMessageProvider.cs index 4424550..609cadf 100644 --- a/Runtime/Messaging/ILPPMessageProvider.cs +++ b/Runtime/Messaging/ILPPMessageProvider.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; @@ -12,9 +13,117 @@ internal struct ILPPMessageProvider : INetworkMessageProvider internal static readonly List __network_message_types = new List(); #pragma warning restore IDE1006 // restore naming rule violation check + /// + /// 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 + /// using the next free value. + /// + /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + /// Add any new Message types to this table at the END with incremented index value + /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + internal enum NetworkMessageTypes : uint + { + ConnectionApproved = 0, + ConnectionRequest = 1, + ChangeOwnership = 2, + ClientConnected = 3, + ClientDisconnected = 4, + ClientRpc = 5, + CreateObject = 6, + DestroyObject = 7, + DisconnectReason = 8, + ForwardClientRpc = 9, + ForwardServerRpc = 10, + NamedMessage = 11, + NetworkTransformMessage = 12, + NetworkVariableDelta = 13, + ParentSync = 14, + Proxy = 15, + Rpc = 16, + SceneEvent = 17, + ServerLog = 18, + ServerRpc = 19, + TimeSync = 20, + Unnamed = 21, + SessionOwner = 22 + } + + + // Enable this for integration tests that need no message types defined + internal static bool IntegrationTestNoMessages; + public List GetMessages() { - return __network_message_types; + // return no message types when defined for integration tests + if (IntegrationTestNoMessages) + { + return new List(); + } + var messageTypeCount = Enum.GetValues(typeof(NetworkMessageTypes)).Length; + // Assure the allowed types count is the same as our NetworkMessageType enum count + if (__network_message_types.Count != messageTypeCount) + { + throw new Exception($"Allowed types is not equal to the number of message type indices! Allowed Count: {__network_message_types.Count} | Index Count: {messageTypeCount}"); + } + + // Populate with blanks to be replaced later + var adjustedMessageTypes = new List(); + var blank = new NetworkMessageManager.MessageWithHandler(); + for (int i = 0; i < messageTypeCount; i++) + { + adjustedMessageTypes.Add(blank); + } + + // Create a type to enum index lookup table + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + // Add new Message types to this table paired with its new NetworkMessageTypes enum + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + var messageTypes = new Dictionary + { + { typeof(ConnectionApprovedMessage), NetworkMessageTypes.ConnectionApproved }, // This MUST be first + { typeof(ConnectionRequestMessage), NetworkMessageTypes.ConnectionRequest }, // This MUST be second + { typeof(ChangeOwnershipMessage), NetworkMessageTypes.ChangeOwnership }, + { typeof(ClientConnectedMessage), NetworkMessageTypes.ClientConnected }, + { typeof(ClientDisconnectedMessage), NetworkMessageTypes.ClientDisconnected }, + { typeof(ClientRpcMessage), NetworkMessageTypes.ClientRpc }, + { typeof(CreateObjectMessage), NetworkMessageTypes.CreateObject }, + { typeof(DestroyObjectMessage), NetworkMessageTypes.DestroyObject }, + { typeof(DisconnectReasonMessage), NetworkMessageTypes.DisconnectReason }, + { typeof(ForwardClientRpcMessage), NetworkMessageTypes.ForwardClientRpc }, + { typeof(ForwardServerRpcMessage), NetworkMessageTypes.ForwardServerRpc }, + { typeof(NamedMessage), NetworkMessageTypes.NamedMessage }, + { typeof(NetworkTransformMessage), NetworkMessageTypes.NetworkTransformMessage }, + { typeof(NetworkVariableDeltaMessage), NetworkMessageTypes.NetworkVariableDelta }, + { typeof(ParentSyncMessage), NetworkMessageTypes.ParentSync }, + { typeof(ProxyMessage), NetworkMessageTypes.Proxy }, + { typeof(RpcMessage), NetworkMessageTypes.Rpc }, + { typeof(SceneEventMessage), NetworkMessageTypes.SceneEvent }, + { typeof(ServerLogMessage), NetworkMessageTypes.ServerLog }, + { typeof(ServerRpcMessage), NetworkMessageTypes.ServerRpc }, + { typeof(TimeSyncMessage), NetworkMessageTypes.TimeSync }, + { typeof(UnnamedMessage), NetworkMessageTypes.Unnamed }, + { typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner } + }; + + // Assure the type to lookup table count and NetworkMessageType enum count matches (i.e. to catch human error when adding new messages) + if (messageTypes.Count != messageTypeCount) + { + throw new Exception($"Message type to Message type index count mistmatch! Table Count: {messageTypes.Count} | Index Count: {messageTypeCount}"); + } + + // Now order the allowed types list based on the order of the NetworkMessageType enum + foreach (var messageHandler in __network_message_types) + { + if (!messageTypes.ContainsKey(messageHandler.MessageType)) + { + throw new Exception($"Missing message type from lookup table: {messageHandler.MessageType}"); + } + adjustedMessageTypes[(int)messageTypes[messageHandler.MessageType]] = messageHandler; + } + + // return the NetworkMessageType enum ordered list + return adjustedMessageTypes; } #if UNITY_EDITOR diff --git a/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs b/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs index 7ab41b8..99010be 100644 --- a/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs +++ b/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs @@ -5,6 +5,8 @@ internal struct ChangeOwnershipMessage : INetworkMessage, INetworkSerializeByMem { public int Version => 0; + private const string k_Name = "ChangeOwnershipMessage"; + public ulong NetworkObjectId; public ulong OwnerClientId; // DANGOEXP TODO: Remove these notes or change their format @@ -199,7 +201,7 @@ public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int // authority of the NetworkObject in question. if (!networkManager.DAHost && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId)) { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name); + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, k_Name); return false; } return true; diff --git a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs index 174eba3..89eee0c 100644 --- a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs +++ b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs @@ -222,6 +222,12 @@ public void Handle(ref NetworkContext context) } // When scene management is disabled we notify after everything is synchronized networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId); + + // For convenience, notify all NetworkBehaviours that synchronization is complete. + foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList) + { + networkObject.InternalNetworkSessionSynchronized(); + } } else { @@ -230,16 +236,22 @@ public void Handle(ref NetworkContext context) // Mark the client being connected networkManager.IsConnectedClient = true; - // Spawn any in-scene placed NetworkObjects - networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); + networkManager.SceneManager.IsRestoringSession = IsRestoredSession; - // Spawn the local player of the session owner - if (networkManager.AutoSpawnPlayerPrefabClientSide) + if (!IsRestoredSession) { - networkManager.ConnectionManager.CreateAndSpawnPlayer(OwnerClientId); + // Spawn any in-scene placed NetworkObjects + networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); + + // Spawn the local player of the session owner + if (networkManager.AutoSpawnPlayerPrefabClientSide) + { + networkManager.ConnectionManager.CreateAndSpawnPlayer(OwnerClientId); + } + + // Synchronize the service with the initial session owner's loaded scenes and spawned objects + networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId); } - // Synchronize the service with the initial session owner's loaded scenes and spawned objects - networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId); } } ConnectedClientIds.Dispose(); diff --git a/Runtime/Messaging/Messages/CreateObjectMessage.cs b/Runtime/Messaging/Messages/CreateObjectMessage.cs index 6382cbb..6c0656b 100644 --- a/Runtime/Messaging/Messages/CreateObjectMessage.cs +++ b/Runtime/Messaging/Messages/CreateObjectMessage.cs @@ -7,6 +7,8 @@ internal struct CreateObjectMessage : INetworkMessage { public int Version => 0; + private const string k_Name = "CreateObjectMessage"; + public NetworkObject.SceneObject ObjectInfo; private FastBufferReader m_ReceivedNetworkVariableData; @@ -161,7 +163,7 @@ public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int if (!networkManager.NetworkConfig.ForceSamePrefabs && !networkManager.SpawnManager.HasPrefab(ObjectInfo)) { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, ObjectInfo.Hash, reader, ref context, GetType().Name); + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, ObjectInfo.Hash, reader, ref context, k_Name); return false; } m_ReceivedNetworkVariableData = reader; diff --git a/Runtime/Messaging/Messages/DestroyObjectMessage.cs b/Runtime/Messaging/Messages/DestroyObjectMessage.cs index b3d799a..868d5a2 100644 --- a/Runtime/Messaging/Messages/DestroyObjectMessage.cs +++ b/Runtime/Messaging/Messages/DestroyObjectMessage.cs @@ -6,6 +6,8 @@ internal struct DestroyObjectMessage : INetworkMessage, INetworkSerializeByMemcp { public int Version => 0; + private const string k_Name = "DestroyObjectMessage"; + public ulong NetworkObjectId; public bool DestroyGameObject; private byte m_DestroyFlags; @@ -84,7 +86,7 @@ public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int // Client-Server mode we always defer where in distributed authority mode we only defer if it is not a targeted destroy if (!networkManager.DistributedAuthorityMode || (networkManager.DistributedAuthorityMode && !IsTargetedDestroy)) { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name); + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, k_Name); } } return true; diff --git a/Runtime/Messaging/Messages/NetworkTransformMessage.cs b/Runtime/Messaging/Messages/NetworkTransformMessage.cs new file mode 100644 index 0000000..3fbd869 --- /dev/null +++ b/Runtime/Messaging/Messages/NetworkTransformMessage.cs @@ -0,0 +1,190 @@ +using Unity.Netcode.Components; +using UnityEngine; + +namespace Unity.Netcode +{ + /// + /// NetworkTransform State Update Message + /// + internal struct NetworkTransformMessage : INetworkMessage + { + public int Version => 0; + private const string k_Name = "NetworkTransformMessage"; + + internal NetworkTransform NetworkTransform; + + // Only used for DAHost + internal NetworkTransform.NetworkTransformState State; + private FastBufferReader m_CurrentReader; + + private unsafe void CopyPayload(ref FastBufferWriter writer) + { + writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position); + } + + public void Serialize(FastBufferWriter writer, int targetVersion) + { + if (m_CurrentReader.IsInitialized) + { + CopyPayload(ref writer); + } + else + { + NetworkTransform.SerializeMessage(writer, targetVersion); + } + } + + public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) + { + var networkManager = context.SystemOwner as NetworkManager; + if (networkManager == null) + { + Debug.LogError($"[{nameof(NetworkTransformMessage)}] System owner context was not of type {nameof(NetworkManager)}!"); + return false; + } + var currentPosition = reader.Position; + var networkObjectId = (ulong)0; + var networkBehaviourId = 0; + + ByteUnpacker.ReadValueBitPacked(reader, out networkObjectId); + var isSpawnedLocally = networkManager.SpawnManager.SpawnedObjects.ContainsKey(networkObjectId); + + // Only defer if the NetworkObject is not spawned yet and the local NetworkManager is not running as a DAHost. + if (!isSpawnedLocally && !networkManager.DAHost) + { + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, networkObjectId, reader, ref context, k_Name); + return false; + } + + // While the below check and assignment might seem out of place, this is specific to running in DAHost mode when a NetworkObject is + // hidden from the DAHost but is visible to other clients. Since the DAHost needs to forward updates to the clients, we ignore processing + // this message locally + var networkObject = (NetworkObject)null; + var isServerAuthoritative = false; + var ownerAuthoritativeServerSide = false; + + // Get the behaviour index + ByteUnpacker.ReadValueBitPacked(reader, out networkBehaviourId); + + if (isSpawnedLocally) + { + networkObject = networkManager.SpawnManager.SpawnedObjects[networkObjectId]; + // Get the target NetworkTransform + NetworkTransform = networkObject.ChildNetworkBehaviours[networkBehaviourId] as NetworkTransform; + isServerAuthoritative = NetworkTransform.IsServerAuthoritative(); + ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer; + + reader.ReadNetworkSerializableInPlace(ref NetworkTransform.InboundState); + } + else + { + // Deserialize the state + reader.ReadNetworkSerializableInPlace(ref State); + } + + unsafe + { + if (ownerAuthoritativeServerSide) + { + var targetCount = 1; + + if (networkManager.DistributedAuthorityMode && networkManager.DAHost) + { + ByteUnpacker.ReadValueBitPacked(reader, out targetCount); + } + + var targetIds = stackalloc ulong[targetCount]; + + if (networkManager.DistributedAuthorityMode && networkManager.DAHost) + { + var targetId = (ulong)0; + for (int i = 0; i < targetCount; i++) + { + ByteUnpacker.ReadValueBitPacked(reader, out targetId); + targetIds[i] = targetId; + } + + if (!isSpawnedLocally) + { + // If we are the DAHost and the NetworkObject is hidden from the host we still need to forward this message + ownerAuthoritativeServerSide = networkManager.DAHost && !isSpawnedLocally; + } + } + + var ownerClientId = (ulong)0; + + if (networkObject != null) + { + ownerClientId = networkObject.OwnerClientId; + if (ownerClientId == NetworkManager.ServerClientId) + { + // Ownership must have changed, ignore any additional pending messages that might have + // come from a previous owner client. + return true; + } + } + else if (networkManager.DAHost) + { + // Specific to distributed authority mode, the only sender of state updates will be the owner + ownerClientId = context.SenderId; + } + + var networkDelivery = State.IsReliableStateUpdate() ? NetworkDelivery.ReliableSequenced : NetworkDelivery.UnreliableSequenced; + + // Forward the state update if there are any remote clients to foward it to + if (networkManager.ConnectionManager.ConnectedClientsList.Count > (networkManager.IsHost ? 2 : 1)) + { + var clientCount = networkManager.DistributedAuthorityMode ? targetCount : networkManager.ConnectionManager.ConnectedClientsList.Count; + if (clientCount == 0) + { + return true; + } + + // This is only to copy the existing and already serialized struct for forwarding purposes only. + // This will not include any changes made to this struct at this particular stage of processing the message. + var currentMessage = this; + // Create a new reader that replicates this message + currentMessage.m_CurrentReader = new FastBufferReader(reader, Collections.Allocator.None); + // Rewind the new reader to the beginning of the message's payload + currentMessage.m_CurrentReader.Seek(currentPosition); + // Forward the message to all connected clients that are observers of the associated NetworkObject + + for (int i = 0; i < clientCount; i++) + { + var clientId = networkManager.DistributedAuthorityMode ? targetIds[i] : networkManager.ConnectionManager.ConnectedClientsList[i].ClientId; + if (NetworkManager.ServerClientId == clientId || (!isServerAuthoritative && clientId == ownerClientId) || + (!networkManager.DistributedAuthorityMode && !networkObject.Observers.Contains(clientId))) + { + continue; + } + + networkManager.MessageManager.SendMessage(ref currentMessage, networkDelivery, clientId); + } + // Dispose of the reader used for forwarding + currentMessage.m_CurrentReader.Dispose(); + } + } + } + return true; + } + + public void Handle(ref NetworkContext context) + { + var networkManager = context.SystemOwner as NetworkManager; + // Only if the local NetworkManager instance is running as the DAHost we just exit if there is no local + // NetworkTransform component to apply the state update to (i.e. it is hidden from the DAHost and it + // just forwarded the state update to any other connected client) + if (networkManager.DAHost && NetworkTransform == null) + { + return; + } + + if (NetworkTransform == null) + { + Debug.LogError($"[{nameof(NetworkTransformMessage)}][Dropped] Reciever {nameof(NetworkTransform)} was not set!"); + return; + } + NetworkTransform.TransformStateUpdate(context.SenderId); + } + } +} diff --git a/Components/Messages/NetworkTransformMessage.cs.meta b/Runtime/Messaging/Messages/NetworkTransformMessage.cs.meta similarity index 100% rename from Components/Messages/NetworkTransformMessage.cs.meta rename to Runtime/Messaging/Messages/NetworkTransformMessage.cs.meta diff --git a/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs b/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs index ed6a469..4ca9c64 100644 --- a/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs +++ b/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs @@ -23,6 +23,8 @@ internal struct NetworkVariableDeltaMessage : INetworkMessage private FastBufferReader m_ReceivedNetworkVariableData; + private const string k_Name = "NetworkVariableDeltaMessage"; + // DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety. // Worth either merging or more cleanly separating these codepaths. public void Serialize(FastBufferWriter writer, int targetVersion) @@ -296,7 +298,7 @@ public void Handle(ref NetworkContext context) // DANGO-TODO: Fix me! // When a client-spawned NetworkObject is despawned by the owner client, the owner client will still get messages for deltas and cause this to // log a warning. The issue is primarily how NetworkVariables handle updating and will require some additional re-factoring. - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, m_ReceivedNetworkVariableData, ref context, GetType().Name); + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, m_ReceivedNetworkVariableData, ref context, k_Name); } } } diff --git a/Runtime/Messaging/Messages/ParentSyncMessage.cs b/Runtime/Messaging/Messages/ParentSyncMessage.cs index 473f775..a55767d 100644 --- a/Runtime/Messaging/Messages/ParentSyncMessage.cs +++ b/Runtime/Messaging/Messages/ParentSyncMessage.cs @@ -6,6 +6,8 @@ internal struct ParentSyncMessage : INetworkMessage { public int Version => 0; + private const string k_Name = "DestroyObjectMessage"; + public ulong NetworkObjectId; private byte m_BitField; @@ -92,7 +94,7 @@ public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int // If the target NetworkObject does not exist =or= the target latest parent does not exist then defer the message if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId) || (LatestParent.HasValue && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(LatestParent.Value))) { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name); + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, k_Name); return false; } return true; diff --git a/Runtime/Messaging/Messages/RpcMessages.cs b/Runtime/Messaging/Messages/RpcMessages.cs index a15749e..2b1406c 100644 --- a/Runtime/Messaging/Messages/RpcMessages.cs +++ b/Runtime/Messaging/Messages/RpcMessages.cs @@ -99,6 +99,8 @@ internal struct ServerRpcMessage : INetworkMessage public FastBufferWriter WriteBuffer; public FastBufferReader ReadBuffer; + private const string k_Name = "ServerRpcMessage"; + public unsafe void Serialize(FastBufferWriter writer, int targetVersion) { RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer); @@ -106,7 +108,7 @@ public unsafe void Serialize(FastBufferWriter writer, int targetVersion) public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) { - return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name); + return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, k_Name); } public void Handle(ref NetworkContext context) @@ -134,6 +136,8 @@ internal struct ClientRpcMessage : INetworkMessage public FastBufferWriter WriteBuffer; public FastBufferReader ReadBuffer; + private const string k_Name = "ClientRpcMessage"; + public void Serialize(FastBufferWriter writer, int targetVersion) { RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer); @@ -141,7 +145,7 @@ public void Serialize(FastBufferWriter writer, int targetVersion) public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) { - return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name); + return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, k_Name); } public void Handle(ref NetworkContext context) @@ -169,6 +173,8 @@ internal struct RpcMessage : INetworkMessage public FastBufferWriter WriteBuffer; public FastBufferReader ReadBuffer; + private const string k_Name = "RpcMessage"; + public unsafe void Serialize(FastBufferWriter writer, int targetVersion) { BytePacker.WriteValuePacked(writer, SenderClientId); @@ -179,7 +185,7 @@ public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext conte { ByteUnpacker.ReadValuePacked(reader, out SenderClientId); - return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name); + return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, k_Name); } public void Handle(ref NetworkContext context) diff --git a/Runtime/Messaging/NetworkMessageManager.cs b/Runtime/Messaging/NetworkMessageManager.cs index 7dd4dae..b455c9b 100644 --- a/Runtime/Messaging/NetworkMessageManager.cs +++ b/Runtime/Messaging/NetworkMessageManager.cs @@ -120,49 +120,20 @@ internal struct MessageWithHandler public VersionGetter GetVersion; } - internal List PrioritizeMessageOrder(List allowedTypes) - { - var prioritizedTypes = new List(); - - // First pass puts the priority message in the first indices - // Those are the messages that must be delivered in order to allow re-ordering the others later - foreach (var t in allowedTypes) - { - if (t.MessageType.FullName == typeof(ConnectionRequestMessage).FullName || - t.MessageType.FullName == typeof(ConnectionApprovedMessage).FullName) - { - prioritizedTypes.Add(t); - } - } - - foreach (var t in allowedTypes) - { - if (t.MessageType.FullName != typeof(ConnectionRequestMessage).FullName && - t.MessageType.FullName != typeof(ConnectionApprovedMessage).FullName) - { - prioritizedTypes.Add(t); - } - } - - return prioritizedTypes; - } - public NetworkMessageManager(INetworkMessageSender sender, object owner, INetworkMessageProvider provider = null) { try { m_Sender = sender; m_Owner = owner; - if (provider == null) { provider = new ILPPMessageProvider(); } + // Get the presorted message types returned by the provider var allowedTypes = provider.GetMessages(); - allowedTypes.Sort((a, b) => string.CompareOrdinal(a.MessageType.FullName, b.MessageType.FullName)); - allowedTypes = PrioritizeMessageOrder(allowedTypes); foreach (var type in allowedTypes) { RegisterMessageType(type); diff --git a/Runtime/SceneManagement/NetworkSceneManager.cs b/Runtime/SceneManagement/NetworkSceneManager.cs index 1e6dacf..ec41e5d 100644 --- a/Runtime/SceneManagement/NetworkSceneManager.cs +++ b/Runtime/SceneManagement/NetworkSceneManager.cs @@ -425,7 +425,7 @@ public bool ActiveSceneSynchronizationEnabled /// /// Returns the currently loaded scenes that are synchronized with the session owner or server depending upon the selected - /// NetworkManager session mode. + /// network topology. /// /// /// The scenes loaded returns all scenes loaded where this returns only the scenes that have been @@ -444,6 +444,7 @@ public List GetSynchronizedScenes() internal Dictionary ServerSceneHandleToClientSceneHandle = new Dictionary(); internal Dictionary ClientSceneHandleToServerSceneHandle = new Dictionary(); + internal bool IsRestoringSession; /// /// Add the client to server (and vice versa) scene handle lookup. /// Add the client-side handle to scene entry in the HandleToScene table. @@ -455,7 +456,7 @@ internal bool UpdateServerClientSceneHandle(int serverHandle, int clientHandle, { ServerSceneHandleToClientSceneHandle.Add(serverHandle, clientHandle); } - else + else if (!IsRestoringSession) { return false; } @@ -464,7 +465,7 @@ internal bool UpdateServerClientSceneHandle(int serverHandle, int clientHandle, { ClientSceneHandleToServerSceneHandle.Add(clientHandle, serverHandle); } - else + else if (!IsRestoringSession) { return false; } @@ -1045,7 +1046,7 @@ internal NetworkObject GetSceneRelativeInSceneNetworkObject(uint globalObjectIdH /// array of client identifiers to receive the scene event message private void SendSceneEventData(uint sceneEventId, ulong[] targetClientIds) { - if (targetClientIds.Length == 0) + if (targetClientIds.Length == 0 && !NetworkManager.DistributedAuthorityMode) { // This would be the Host/Server with no clients connected // Silently return as there is nothing to be done @@ -1056,6 +1057,16 @@ private void SendSceneEventData(uint sceneEventId, ulong[] targetClientIds) if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost) { + if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority()) + { + sceneEvent.TargetClientId = NetworkManager.ServerClientId; + var message = new SceneEventMessage + { + EventData = sceneEvent, + }; + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, NetworkManager.ServerClientId); + NetworkManager.NetworkMetrics.TrackSceneEventSent(NetworkManager.ServerClientId, (uint)sceneEvent.SceneEventType, SceneNameFromHash(sceneEvent.SceneHash), size); + } foreach (var clientId in targetClientIds) { sceneEvent.TargetClientId = clientId; @@ -1859,6 +1870,17 @@ private void OnSessionOwnerLoadedScene(uint sceneEventId, Scene scene) } } + foreach (var keyValuePairByGlobalObjectIdHash in ScenePlacedObjects) + { + foreach (var keyValuePairBySceneHandle in keyValuePairByGlobalObjectIdHash.Value) + { + if (!keyValuePairBySceneHandle.Value.IsPlayerObject) + { + keyValuePairBySceneHandle.Value.InternalInSceneNetworkObjectsSpawned(); + } + } + } + // Add any despawned when spawned in-scene placed NetworkObjects to the scene event data sceneEventData.AddDespawnedInSceneNetworkObjects(); @@ -2413,6 +2435,18 @@ private void HandleClientSceneEvent(uint sceneEventId) { NetworkLog.LogInfo($"[Client-{NetworkManager.LocalClientId}][Scene Management Enabled] Synchronization complete!"); } + // For convenience, notify all NetworkBehaviours that synchronization is complete. + foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList) + { + networkObject.InternalNetworkSessionSynchronized(); + } + + if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority() && IsRestoringSession) + { + IsRestoringSession = false; + PostSynchronizationSceneUnloading = m_OriginalPostSynchronizationSceneUnloading; + } + EndSceneEvent(sceneEventId); } break; @@ -2599,6 +2633,8 @@ private void HandleSessionOwnerEvent(uint sceneEventId, ulong clientId) /// internal bool SkipSceneHandling; + private bool m_OriginalPostSynchronizationSceneUnloading; + /// /// Both Client and Server: Incoming scene event entry point /// @@ -2672,6 +2708,12 @@ internal void HandleSceneEvent(ulong clientId, FastBufferReader reader) // Only if ClientSynchronizationMode is Additive and the client receives a synchronize scene event if (ClientSynchronizationMode == LoadSceneMode.Additive) { + if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority() && IsRestoringSession && clientId == NetworkManager.ServerClientId) + { + m_OriginalPostSynchronizationSceneUnloading = PostSynchronizationSceneUnloading; + PostSynchronizationSceneUnloading = true; + } + // Check for scenes already loaded and create a table of scenes already loaded (SceneEntries) that will be // used if the server is synchronizing the same scenes (i.e. if a matching scene is already loaded on the // client side, then that scene will be used as opposed to loading another scene). This allows for clients diff --git a/Runtime/SceneManagement/SceneEventData.cs b/Runtime/SceneManagement/SceneEventData.cs index f0293e4..18ac6a7 100644 --- a/Runtime/SceneManagement/SceneEventData.cs +++ b/Runtime/SceneManagement/SceneEventData.cs @@ -839,7 +839,7 @@ internal void DeserializeScenePlacedObjects() { // is not packed! InternalBuffer.ReadValueSafe(out ushort newObjectsCount); - + var sceneObjects = new List(); for (ushort i = 0; i < newObjectsCount; i++) { var sceneObject = new NetworkObject.SceneObject(); @@ -851,10 +851,22 @@ internal void DeserializeScenePlacedObjects() m_NetworkManager.SceneManager.SetTheSceneBeingSynchronized(sceneObject.NetworkSceneHandle); } - NetworkObject.AddSceneObject(sceneObject, InternalBuffer, m_NetworkManager); + var networkObject = NetworkObject.AddSceneObject(sceneObject, InternalBuffer, m_NetworkManager); + + if (sceneObject.IsSceneObject) + { + sceneObjects.Add(networkObject); + } } // Now deserialize the despawned in-scene placed NetworkObjects list (if any) DeserializeDespawnedInScenePlacedNetworkObjects(); + + // Notify all newly spawned in-scene placed NetworkObjects that all in-scene placed + // NetworkObjects have been spawned. + foreach (var networkObject in sceneObjects) + { + networkObject.InternalInSceneNetworkObjectsSpawned(); + } } finally { @@ -1122,6 +1134,15 @@ internal void SynchronizeSceneNetworkObjects(NetworkManager networkManager) UnityEngine.Debug.Log(builder.ToString()); } + // Notify that all in-scene placed NetworkObjects have been spawned + foreach (var networkObject in m_NetworkObjectsSync) + { + if (networkObject.IsSceneObject.HasValue && networkObject.IsSceneObject.Value) + { + networkObject.InternalInSceneNetworkObjectsSpawned(); + } + } + // Now deserialize the despawned in-scene placed NetworkObjects list (if any) DeserializeDespawnedInScenePlacedNetworkObjects(); diff --git a/Runtime/Spawning/NetworkSpawnManager.cs b/Runtime/Spawning/NetworkSpawnManager.cs index 482b603..e021505 100644 --- a/Runtime/Spawning/NetworkSpawnManager.cs +++ b/Runtime/Spawning/NetworkSpawnManager.cs @@ -810,20 +810,27 @@ internal NetworkObject CreateLocalNetworkObject(NetworkObject.SceneObject sceneO networkObject.DontDestroyWithOwner = sceneObject.DontDestroyWithOwner; networkObject.Ownership = (NetworkObject.OwnershipStatus)sceneObject.OwnershipFlags; + + var nonNetworkObjectParent = false; // SPECIAL CASE FOR IN-SCENE PLACED: (only when the parent has a NetworkObject) // This is a special case scenario where a late joining client has joined and loaded one or // more scenes that contain nested in-scene placed NetworkObject children yet the server's // synchronization information does not indicate the NetworkObject in question has a parent. // Under this scenario, we want to remove the parent before spawning and setting the transform values. - if (sceneObject.IsSceneObject && !sceneObject.HasParent && networkObject.transform.parent != null) + if (sceneObject.IsSceneObject && networkObject.transform.parent != null) { + var parentNetworkObject = networkObject.transform.parent.GetComponent(); // if the in-scene placed NetworkObject has a parent NetworkObject but the synchronization information does not // include parenting, then we need to force the removal of that parent - if (networkObject.transform.parent.GetComponent() != null) + if (!sceneObject.HasParent && parentNetworkObject) { // remove the parent networkObject.ApplyNetworkParenting(true, true); } + else if (sceneObject.HasParent && !parentNetworkObject) + { + nonNetworkObjectParent = true; + } } // Set the transform unless we were spawned by a prefab handler @@ -833,7 +840,7 @@ internal NetworkObject CreateLocalNetworkObject(NetworkObject.SceneObject sceneO { // If world position stays is true or we have auto object parent synchronization disabled // then we want to apply the position and rotation values world space relative - if (worldPositionStays || !networkObject.AutoObjectParentSync) + if ((worldPositionStays && !nonNetworkObjectParent) || !networkObject.AutoObjectParentSync) { networkObject.transform.position = position; networkObject.transform.rotation = rotation; @@ -917,6 +924,8 @@ internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong netwo Debug.LogError("Spawning NetworkObjects with nested NetworkObjects is only supported for scene objects. Child NetworkObjects will not be spawned over the network!"); } } + // Invoke NetworkBehaviour.OnPreSpawn methods + networkObject.InvokeBehaviourNetworkPreSpawn(); // DANGO-TODO: It would be nice to allow users to specify which clients are observers prior to spawning // For now, this is the best place I could find to add all connected clients as observers for newly @@ -957,12 +966,18 @@ internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong netwo } } SpawnNetworkObjectLocallyCommon(networkObject, networkId, sceneObject, playerObject, ownerClientId, destroyWithScene); + + // Invoke NetworkBehaviour.OnPostSpawn methods + networkObject.InvokeBehaviourNetworkPostSpawn(); } /// /// This is only invoked to instantiate a serialized NetworkObject via /// /// + /// + /// IMPORTANT: Pre spawn methods need to be invoked from within . + /// internal void SpawnNetworkObjectLocally(NetworkObject networkObject, in NetworkObject.SceneObject sceneObject, bool destroyWithScene) { if (networkObject == null) @@ -975,7 +990,11 @@ internal void SpawnNetworkObjectLocally(NetworkObject networkObject, in NetworkO throw new SpawnStateException($"[{networkObject.name}] Object-{networkObject.NetworkObjectId} is already spawned!"); } + // Do not invoke Pre spawn here (SynchronizeNetworkBehaviours needs to be invoked prior to this) SpawnNetworkObjectLocallyCommon(networkObject, sceneObject.NetworkObjectId, sceneObject.IsSceneObject, sceneObject.IsPlayerObject, sceneObject.OwnerClientId, destroyWithScene); + + // It is ok to invoke NetworkBehaviour.OnPostSpawn methods + networkObject.InvokeBehaviourNetworkPostSpawn(); } private void SpawnNetworkObjectLocallyCommon(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong ownerClientId, bool destroyWithScene) @@ -1226,7 +1245,7 @@ internal void DespawnAndDestroyNetworkObjects() { // If it is an in-scene placed NetworkObject then just despawn and let it be destroyed when the scene // is unloaded. Otherwise, despawn and destroy it. - var shouldDestroy = !(networkObjects[i].IsSceneObject != null && networkObjects[i].IsSceneObject.Value); + var shouldDestroy = !(networkObjects[i].IsSceneObject == null || (networkObjects[i].IsSceneObject != null && networkObjects[i].IsSceneObject.Value)); // If we are going to destroy this NetworkObject, check for any in-scene placed children that need to be removed if (shouldDestroy) @@ -1307,6 +1326,7 @@ internal void ServerSpawnSceneObjectsOnStartSweep() var networkObjects = UnityEngine.Object.FindObjectsOfType(); #endif var isConnectedCMBService = NetworkManager.CMBServiceConnection; + var networkObjectsToSpawn = new List(); for (int i = 0; i < networkObjects.Length; i++) { if (networkObjects[i].NetworkManager == NetworkManager) @@ -1323,9 +1343,17 @@ internal void ServerSpawnSceneObjectsOnStartSweep() } SpawnNetworkObjectLocally(networkObjects[i], GetNetworkObjectId(), true, false, ownerId, true); + networkObjectsToSpawn.Add(networkObjects[i]); } } } + + // Notify all in-scene placed NetworkObjects have been spawned + foreach (var networkObject in networkObjectsToSpawn) + { + networkObject.InternalInSceneNetworkObjectsSpawned(); + } + networkObjectsToSpawn.Clear(); } internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObject, bool modeDestroy = false) diff --git a/Runtime/Transports/UTP/UnityTransport.cs b/Runtime/Transports/UTP/UnityTransport.cs index bc89e15..6922699 100644 --- a/Runtime/Transports/UTP/UnityTransport.cs +++ b/Runtime/Transports/UTP/UnityTransport.cs @@ -426,10 +426,11 @@ private struct PacketLossCache internal static event Action TransportDisposed; internal NetworkDriver NetworkDriver => m_Driver; + protected NetworkDriver m_Driver; + private PacketLossCache m_PacketLossCache = new PacketLossCache(); private State m_State = State.Disconnected; - private NetworkDriver m_Driver; private NetworkSettings m_NetworkSettings; private ulong m_ServerClientId; @@ -554,12 +555,17 @@ private bool ClientBindAndConnect() return false; } - var serverConnection = m_Driver.Connect(serverEndpoint); + var serverConnection = Connect(serverEndpoint); m_ServerClientId = ParseClientId(serverConnection); return true; } + protected virtual NetworkConnection Connect(NetworkEndpoint serverEndpoint) + { + return m_Driver.Connect(serverEndpoint); + } + private bool ServerBindAndListen(NetworkEndpoint endPoint) { // Verify the endpoint is valid before proceeding diff --git a/Runtime/com.unity.netcode.runtime.asmdef b/Runtime/com.unity.netcode.runtime.asmdef index 3b673da..1577ff0 100644 --- a/Runtime/com.unity.netcode.runtime.asmdef +++ b/Runtime/com.unity.netcode.runtime.asmdef @@ -46,6 +46,21 @@ "name": "Unity", "expression": "2023", "define": "UNITY_DEDICATED_SERVER_ARGUMENTS_PRESENT" + }, + { + "name": "com.unity.modules.animation", + "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" } ] } diff --git a/TestHelpers/Runtime/IntegrationTestWithApproximation.cs b/TestHelpers/Runtime/IntegrationTestWithApproximation.cs index 54f546b..02a5393 100644 --- a/TestHelpers/Runtime/IntegrationTestWithApproximation.cs +++ b/TestHelpers/Runtime/IntegrationTestWithApproximation.cs @@ -87,7 +87,7 @@ protected Vector3 GetRandomVector3(float min, float max) return new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max)); } - public IntegrationTestWithApproximation(SessionModeTypes sessionModeType) : base(sessionModeType) { } + public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { } public IntegrationTestWithApproximation(HostOrServer hostOrServer) : base(hostOrServer) { } diff --git a/TestHelpers/Runtime/NetcodeIntegrationTest.cs b/TestHelpers/Runtime/NetcodeIntegrationTest.cs index 25dd190..3537df2 100644 --- a/TestHelpers/Runtime/NetcodeIntegrationTest.cs +++ b/TestHelpers/Runtime/NetcodeIntegrationTest.cs @@ -139,21 +139,21 @@ public enum HostOrServer protected bool m_UseHost = true; protected bool m_DistributedAuthority; - protected SessionModeTypes m_SessionModeType = SessionModeTypes.ClientServer; + protected NetworkTopologyTypes m_NetworkTopologyType = NetworkTopologyTypes.ClientServer; protected virtual bool UseCMBService() { return false; } - protected virtual SessionModeTypes OnGetSessionmode() + protected virtual NetworkTopologyTypes OnGetNetworkTopologyType() { - return m_SessionModeType; + return m_NetworkTopologyType; } protected void SetDistributedAuthorityProperties(NetworkManager networkManager) { - networkManager.NetworkConfig.SessionMode = m_SessionModeType; + networkManager.NetworkConfig.NetworkTopology = m_NetworkTopologyType; networkManager.NetworkConfig.AutoSpawnPlayerPrefabClientSide = m_DistributedAuthority; networkManager.NetworkConfig.UseCMBService = UseCMBService() && m_DistributedAuthority; } @@ -1567,7 +1567,7 @@ protected GameObject CreateNetworkObjectPrefab(string baseName) Assert.IsFalse(m_ServerNetworkManager.IsListening, prefabCreateAssertError); var prefabObject = NetcodeIntegrationTestHelpers.CreateNetworkObjectPrefab(baseName, m_ServerNetworkManager, m_ClientNetworkManagers); // DANGO-TODO: Ownership flags could require us to change this - // For testing purposes, we default to true for the distribute ownership property when in distirbuted authority session mode. + // For testing purposes, we default to true for the distribute ownership property when in a distirbuted authority network topology. prefabObject.GetComponent().Ownership |= NetworkObject.OwnershipStatus.Distributable; return prefabObject; } @@ -1605,7 +1605,7 @@ private GameObject SpawnObject(NetworkObject prefabNetworkObject, NetworkManager var newInstance = Object.Instantiate(prefabNetworkObject.gameObject); var networkObjectToSpawn = newInstance.GetComponent(); - if (owner.NetworkConfig.SessionMode == SessionModeTypes.DistributedAuthority) + if (owner.NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority) { networkObjectToSpawn.NetworkManagerOwner = owner; // Required to assure the client does the spawning if (isPlayerObject) @@ -1687,15 +1687,15 @@ private List SpawnObjects(NetworkObject prefabNetworkObject, Network /// public NetcodeIntegrationTest() { - m_SessionModeType = OnGetSessionmode(); - m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority; + m_NetworkTopologyType = OnGetNetworkTopologyType(); + m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority; NetworkMessageManager.EnableMessageOrderConsoleLog = false; } - public NetcodeIntegrationTest(SessionModeTypes sessionMode) + public NetcodeIntegrationTest(NetworkTopologyTypes networkTopologyType) { - m_SessionModeType = sessionMode; - m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority; + m_NetworkTopologyType = networkTopologyType; + m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority; } /// @@ -1717,8 +1717,8 @@ public NetcodeIntegrationTest(SessionModeTypes sessionMode) public NetcodeIntegrationTest(HostOrServer hostOrServer) { m_UseHost = hostOrServer == HostOrServer.Host || hostOrServer == HostOrServer.DAHost; - m_SessionModeType = hostOrServer == HostOrServer.DAHost ? SessionModeTypes.DistributedAuthority : SessionModeTypes.ClientServer; - m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority; + m_NetworkTopologyType = hostOrServer == HostOrServer.DAHost ? NetworkTopologyTypes.DistributedAuthority : NetworkTopologyTypes.ClientServer; + m_DistributedAuthority = OnGetNetworkTopologyType() == NetworkTopologyTypes.DistributedAuthority; } /// diff --git a/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs b/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs index a296066..c952ade 100644 --- a/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs +++ b/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs @@ -378,7 +378,8 @@ private static void SceneManagerValidationAndTestRunnerInitialization(NetworkMan { // If VerifySceneBeforeLoading is not already set, then go ahead and set it so the host/server // will not try to synchronize clients to the TestRunner scene. We only need to do this for the server. - if (networkManager.IsServer && networkManager.SceneManager.VerifySceneBeforeLoading == null) + // All clients in distributed authority mode, should have this registered (since any one client can become the session owner). + if ((networkManager.IsServer && networkManager.SceneManager.VerifySceneBeforeLoading == null) || networkManager.DistributedAuthorityMode) { networkManager.SceneManager.VerifySceneBeforeLoading = VerifySceneIsValidForClientsToLoad; diff --git a/Tests/Editor/ArithmeticTests.cs b/Tests/Editor/ArithmeticTests.cs index 45baf5a..2791e4a 100644 --- a/Tests/Editor/ArithmeticTests.cs +++ b/Tests/Editor/ArithmeticTests.cs @@ -2,7 +2,7 @@ namespace Unity.Netcode.EditorTests { - public class ArithmeticTests + internal class ArithmeticTests { [Test] public void TestCeil() diff --git a/Tests/Editor/Build/BuildTests.cs b/Tests/Editor/Build/BuildTests.cs index bbb24a3..563c43b 100644 --- a/Tests/Editor/Build/BuildTests.cs +++ b/Tests/Editor/Build/BuildTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.EditorTests { - public class BuildTests + internal class BuildTests { public const string DefaultBuildScenePath = "Tests/Editor/Build/BuildTestScene.unity"; diff --git a/Tests/Editor/DisconnectMessageTests.cs b/Tests/Editor/DisconnectMessageTests.cs index 644ed70..e30cecc 100644 --- a/Tests/Editor/DisconnectMessageTests.cs +++ b/Tests/Editor/DisconnectMessageTests.cs @@ -3,7 +3,7 @@ namespace Unity.Netcode.EditorTests { - public class DisconnectMessageTests + internal class DisconnectMessageTests { [Test] public void EmptyDisconnectReason() diff --git a/Tests/Editor/InterpolatorTests.cs b/Tests/Editor/InterpolatorTests.cs index 224a25e..4cdd069 100644 --- a/Tests/Editor/InterpolatorTests.cs +++ b/Tests/Editor/InterpolatorTests.cs @@ -3,7 +3,7 @@ namespace Unity.Netcode.EditorTests { - public class InterpolatorTests + internal class InterpolatorTests { private const float k_Precision = 0.00000001f; private const int k_MockTickRate = 1; diff --git a/Tests/Editor/Messaging/DisconnectOnSendTests.cs b/Tests/Editor/Messaging/DisconnectOnSendTests.cs index 9fbf55a..a33e7ac 100644 --- a/Tests/Editor/Messaging/DisconnectOnSendTests.cs +++ b/Tests/Editor/Messaging/DisconnectOnSendTests.cs @@ -3,7 +3,7 @@ namespace Unity.Netcode.EditorTests { - public class DisconnectOnSendTests + internal class DisconnectOnSendTests { private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy { diff --git a/Tests/Editor/Messaging/MessageCorruptionTests.cs b/Tests/Editor/Messaging/MessageCorruptionTests.cs index 96544ac..eb2ed8a 100644 --- a/Tests/Editor/Messaging/MessageCorruptionTests.cs +++ b/Tests/Editor/Messaging/MessageCorruptionTests.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode.EditorTests { - public class MessageCorruptionTests + internal class MessageCorruptionTests { private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy diff --git a/Tests/Editor/Messaging/MessageReceivingTests.cs b/Tests/Editor/Messaging/MessageReceivingTests.cs index 1a9b3f6..d77bf4e 100644 --- a/Tests/Editor/Messaging/MessageReceivingTests.cs +++ b/Tests/Editor/Messaging/MessageReceivingTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.EditorTests { - public class MessageReceivingTests + internal class MessageReceivingTests { private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy { diff --git a/Tests/Editor/Messaging/MessageRegistrationTests.cs b/Tests/Editor/Messaging/MessageRegistrationTests.cs index bb7ab65..6689894 100644 --- a/Tests/Editor/Messaging/MessageRegistrationTests.cs +++ b/Tests/Editor/Messaging/MessageRegistrationTests.cs @@ -3,7 +3,7 @@ namespace Unity.Netcode.EditorTests { - public class MessageRegistrationTests + internal class MessageRegistrationTests { private struct TestMessageOne : INetworkMessage, INetworkSerializeByMemcpy { @@ -191,77 +191,5 @@ public void WhenCreatingMessageSystem_BoundTypeMessageHandlersAreRegistered() Assert.AreEqual(handlerFour, systemThree.MessageHandlers[systemThree.GetMessageType(typeof(TestMessageFour))]); } } - - internal class AAAEarlyLexicographicNetworkMessage : INetworkMessage - { - 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; - } - -#pragma warning disable IDE1006 - internal class zzzLateLexicographicNetworkMessage : AAAEarlyLexicographicNetworkMessage - { - } -#pragma warning restore IDE1006 - - internal class OrderingMessageProvider : INetworkMessageProvider - { - public List GetMessages() - { - var listMessages = new List(); - - var messageWithHandler = new NetworkMessageManager.MessageWithHandler - { - MessageType = typeof(zzzLateLexicographicNetworkMessage), - GetVersion = NetworkMessageManager.CreateMessageAndGetVersion - }; - listMessages.Add(messageWithHandler); - - messageWithHandler.MessageType = typeof(ConnectionRequestMessage); - messageWithHandler.GetVersion = NetworkMessageManager.CreateMessageAndGetVersion; - listMessages.Add(messageWithHandler); - - messageWithHandler.MessageType = typeof(ConnectionApprovedMessage); - messageWithHandler.GetVersion = NetworkMessageManager.CreateMessageAndGetVersion; - listMessages.Add(messageWithHandler); - - messageWithHandler.MessageType = typeof(AAAEarlyLexicographicNetworkMessage); - messageWithHandler.GetVersion = NetworkMessageManager.CreateMessageAndGetVersion; - listMessages.Add(messageWithHandler); - - return listMessages; - } - } - - [Test] - public void MessagesGetPrioritizedCorrectly() - { - var sender = new NopMessageSender(); - var provider = new OrderingMessageProvider(); - using var messageManager = new NetworkMessageManager(sender, null, provider); - - // the 2 priority messages should appear first, in lexicographic order - Assert.AreEqual(messageManager.MessageTypes[0], typeof(ConnectionApprovedMessage)); - Assert.AreEqual(messageManager.MessageTypes[1], typeof(ConnectionRequestMessage)); - - // the other should follow after - Assert.AreEqual(messageManager.MessageTypes[2], typeof(AAAEarlyLexicographicNetworkMessage)); - Assert.AreEqual(messageManager.MessageTypes[3], typeof(zzzLateLexicographicNetworkMessage)); - - // there should not be any extras - Assert.AreEqual(messageManager.MessageHandlerCount, 4); - } } } diff --git a/Tests/Editor/Messaging/MessageSendingTests.cs b/Tests/Editor/Messaging/MessageSendingTests.cs index 81cc7e7..84967b7 100644 --- a/Tests/Editor/Messaging/MessageSendingTests.cs +++ b/Tests/Editor/Messaging/MessageSendingTests.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode.EditorTests { - public class MessageSendingTests + internal class MessageSendingTests { private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy { diff --git a/Tests/Editor/Messaging/MessageVersioningTests.cs b/Tests/Editor/Messaging/MessageVersioningTests.cs index d19c882..222c08b 100644 --- a/Tests/Editor/Messaging/MessageVersioningTests.cs +++ b/Tests/Editor/Messaging/MessageVersioningTests.cs @@ -5,7 +5,7 @@ namespace Unity.Netcode.EditorTests { - public class MessageVersioningTests + internal class MessageVersioningTests { public static int SentVersion; public static int ReceivedVersion; diff --git a/Tests/Editor/Metrics/NetworkMetricsRegistrationTests.cs b/Tests/Editor/Metrics/NetworkMetricsRegistrationTests.cs index e962c86..82b88ec 100644 --- a/Tests/Editor/Metrics/NetworkMetricsRegistrationTests.cs +++ b/Tests/Editor/Metrics/NetworkMetricsRegistrationTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.EditorTests.Metrics { - public class NetworkMetricsRegistrationTests + internal class NetworkMetricsRegistrationTests { private static Type[] s_MetricTypes = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(x => x.GetTypes()) diff --git a/Tests/Editor/NetworkBehaviourTests.cs b/Tests/Editor/NetworkBehaviourTests.cs index 395aa79..29c8279 100644 --- a/Tests/Editor/NetworkBehaviourTests.cs +++ b/Tests/Editor/NetworkBehaviourTests.cs @@ -4,7 +4,7 @@ namespace Unity.Netcode.EditorTests { - public class NetworkBehaviourTests + internal class NetworkBehaviourTests { [Test] public void HasNetworkObjectTest() @@ -66,12 +66,12 @@ public void GivenClassDerivesFromNetworkBehaviourDerivedClass_GetTypeNameReturns // 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 - public class DerivedNetworkBehaviour : EmptyNetworkBehaviour + internal class DerivedNetworkBehaviour : EmptyNetworkBehaviour { } - public class EmptyNetworkBehaviour : NetworkBehaviour + internal class EmptyNetworkBehaviour : NetworkBehaviour { } diff --git a/Tests/Editor/NetworkManagerConfigurationTests.cs b/Tests/Editor/NetworkManagerConfigurationTests.cs index 45ac91c..78b13e3 100644 --- a/Tests/Editor/NetworkManagerConfigurationTests.cs +++ b/Tests/Editor/NetworkManagerConfigurationTests.cs @@ -9,8 +9,20 @@ namespace Unity.Netcode.EditorTests { - public class NetworkManagerConfigurationTests + internal class NetworkManagerConfigurationTests { + [SetUp] + public void OnSetup() + { + ILPPMessageProvider.IntegrationTestNoMessages = true; + } + + [TearDown] + public void OnTearDown() + { + ILPPMessageProvider.IntegrationTestNoMessages = false; + } + /// /// 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 diff --git a/Tests/Editor/NetworkObjectTests.cs b/Tests/Editor/NetworkObjectTests.cs index dd0d930..64dbc53 100644 --- a/Tests/Editor/NetworkObjectTests.cs +++ b/Tests/Editor/NetworkObjectTests.cs @@ -6,7 +6,7 @@ namespace Unity.Netcode.EditorTests { - public class NetworkObjectTests + internal class NetworkObjectTests { [Test] public void NetworkManagerOverrideTest() @@ -146,12 +146,12 @@ private struct ComponentIndices public int NetworkBehaviourIndex; } - public class EmptyNetworkBehaviour : NetworkBehaviour + internal class EmptyNetworkBehaviour : NetworkBehaviour { } - public class EmptyMonoBehaviour : MonoBehaviour + internal class EmptyMonoBehaviour : MonoBehaviour { } diff --git a/Tests/Editor/NetworkPrefabProcessorTests.cs b/Tests/Editor/NetworkPrefabProcessorTests.cs index 275a83d..f50e502 100644 --- a/Tests/Editor/NetworkPrefabProcessorTests.cs +++ b/Tests/Editor/NetworkPrefabProcessorTests.cs @@ -5,7 +5,7 @@ namespace Unity.Netcode.EditorTests { - public class NetworkPrefabProcessorTests + internal class NetworkPrefabProcessorTests { private NetcodeForGameObjectsProjectSettings m_Settings; private bool m_EditorDefaultPrefabSetting; diff --git a/Tests/Editor/NetworkVar/NetworkVarTests.cs b/Tests/Editor/NetworkVar/NetworkVarTests.cs index e871b23..77ad69d 100644 --- a/Tests/Editor/NetworkVar/NetworkVarTests.cs +++ b/Tests/Editor/NetworkVar/NetworkVarTests.cs @@ -3,9 +3,9 @@ namespace Unity.Netcode.EditorTests.NetworkVar { - public class NetworkVarTests + internal class NetworkVarTests { - public class NetworkVarComponent : NetworkBehaviour + internal class NetworkVarComponent : NetworkBehaviour { public NetworkVariable NetworkVariable = new NetworkVariable(); } diff --git a/Tests/Editor/Serialization/BaseFastBufferReaderWriterTest.cs b/Tests/Editor/Serialization/BaseFastBufferReaderWriterTest.cs index a73f151..53e72cf 100644 --- a/Tests/Editor/Serialization/BaseFastBufferReaderWriterTest.cs +++ b/Tests/Editor/Serialization/BaseFastBufferReaderWriterTest.cs @@ -6,7 +6,7 @@ namespace Unity.Netcode.EditorTests { - public abstract class BaseFastBufferReaderWriterTest + internal abstract class BaseFastBufferReaderWriterTest { protected enum ByteEnum : byte { diff --git a/Tests/Editor/Serialization/BitCounterTests.cs b/Tests/Editor/Serialization/BitCounterTests.cs index 5e0f4c8..9200d6b 100644 --- a/Tests/Editor/Serialization/BitCounterTests.cs +++ b/Tests/Editor/Serialization/BitCounterTests.cs @@ -2,7 +2,7 @@ namespace Unity.Netcode.EditorTests { - public class BitCounterTests + internal class BitCounterTests { [Test] public void WhenCountingUsedBitsIn64BitValue_ResultMatchesHighBitSetPlusOne([Range(0, 63)] int highBit) diff --git a/Tests/Editor/Serialization/BitReaderTests.cs b/Tests/Editor/Serialization/BitReaderTests.cs index b6e4ef5..de83183 100644 --- a/Tests/Editor/Serialization/BitReaderTests.cs +++ b/Tests/Editor/Serialization/BitReaderTests.cs @@ -4,7 +4,7 @@ namespace Unity.Netcode.EditorTests { - public class BitReaderTests + internal class BitReaderTests { [Test] public void TestReadingOneBit() diff --git a/Tests/Editor/Serialization/BitWriterTests.cs b/Tests/Editor/Serialization/BitWriterTests.cs index f35f725..b4a84ff 100644 --- a/Tests/Editor/Serialization/BitWriterTests.cs +++ b/Tests/Editor/Serialization/BitWriterTests.cs @@ -4,7 +4,7 @@ namespace Unity.Netcode.EditorTests { - public class BitWriterTests + internal class BitWriterTests { [Test] public unsafe void TestWritingOneBit() diff --git a/Tests/Editor/Serialization/BufferSerializerTests.cs b/Tests/Editor/Serialization/BufferSerializerTests.cs index c36d738..b6684ff 100644 --- a/Tests/Editor/Serialization/BufferSerializerTests.cs +++ b/Tests/Editor/Serialization/BufferSerializerTests.cs @@ -5,7 +5,7 @@ namespace Unity.Netcode.EditorTests { - public class BufferSerializerTests + internal class BufferSerializerTests { [Test] public void TestIsReaderIsWriter() diff --git a/Tests/Editor/Serialization/BytePackerTests.cs b/Tests/Editor/Serialization/BytePackerTests.cs index 99e8582..192f0db 100644 --- a/Tests/Editor/Serialization/BytePackerTests.cs +++ b/Tests/Editor/Serialization/BytePackerTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.EditorTests { - public class BytePackerTests + internal class BytePackerTests { private enum ByteEnum : byte { diff --git a/Tests/Editor/Serialization/FastBufferReaderTests.cs b/Tests/Editor/Serialization/FastBufferReaderTests.cs index 2b4c70e..30b1ba8 100644 --- a/Tests/Editor/Serialization/FastBufferReaderTests.cs +++ b/Tests/Editor/Serialization/FastBufferReaderTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.EditorTests { - public class FastBufferReaderTests : BaseFastBufferReaderWriterTest + internal class FastBufferReaderTests : BaseFastBufferReaderWriterTest { private void WriteCheckBytes(FastBufferWriter writer, int writeSize, string failMessage = "") { diff --git a/Tests/Editor/Serialization/FastBufferWriterTests.cs b/Tests/Editor/Serialization/FastBufferWriterTests.cs index 5967d49..98d4231 100644 --- a/Tests/Editor/Serialization/FastBufferWriterTests.cs +++ b/Tests/Editor/Serialization/FastBufferWriterTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.EditorTests { - public class FastBufferWriterTests : BaseFastBufferReaderWriterTest + internal class FastBufferWriterTests : BaseFastBufferReaderWriterTest { private void WriteCheckBytes(FastBufferWriter writer, int writeSize, string failMessage = "") { diff --git a/Tests/Editor/Serialization/UserBitReaderAndBitWriterTests_NCCBUG175.cs b/Tests/Editor/Serialization/UserBitReaderAndBitWriterTests_NCCBUG175.cs index 5db3db1..f279f4d 100644 --- a/Tests/Editor/Serialization/UserBitReaderAndBitWriterTests_NCCBUG175.cs +++ b/Tests/Editor/Serialization/UserBitReaderAndBitWriterTests_NCCBUG175.cs @@ -3,7 +3,7 @@ namespace Unity.Netcode.EditorTests { - public class UserBitReaderAndBitWriterTests_NCCBUG175 + internal class UserBitReaderAndBitWriterTests_NCCBUG175 { [Test] diff --git a/Tests/Editor/Timing/ClientNetworkTimeSystemTests.cs b/Tests/Editor/Timing/ClientNetworkTimeSystemTests.cs index 8913ebc..275e891 100644 --- a/Tests/Editor/Timing/ClientNetworkTimeSystemTests.cs +++ b/Tests/Editor/Timing/ClientNetworkTimeSystemTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.EditorTests /// /// Tests for running a as a client. /// - public class ClientNetworkTimeSystemTests + internal class ClientNetworkTimeSystemTests { private const double k_AcceptableRttOffset = 0.03d; // 30ms offset is fine diff --git a/Tests/Editor/Timing/NetworkTimeTests.cs b/Tests/Editor/Timing/NetworkTimeTests.cs index be53a0d..2a137bd 100644 --- a/Tests/Editor/Timing/NetworkTimeTests.cs +++ b/Tests/Editor/Timing/NetworkTimeTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.EditorTests { - public class NetworkTimeTests + internal class NetworkTimeTests { [Test] [TestCase(0d, 0u)] diff --git a/Tests/Editor/Timing/ServerNetworkTimeSystemTests.cs b/Tests/Editor/Timing/ServerNetworkTimeSystemTests.cs index ea5fe00..8d5edba 100644 --- a/Tests/Editor/Timing/ServerNetworkTimeSystemTests.cs +++ b/Tests/Editor/Timing/ServerNetworkTimeSystemTests.cs @@ -3,7 +3,7 @@ namespace Unity.Netcode.EditorTests { - public class ServerNetworkTimeSystemTests + internal class ServerNetworkTimeSystemTests { /// diff --git a/Tests/Editor/Timing/TimingTestHelper.cs b/Tests/Editor/Timing/TimingTestHelper.cs index 16c840d..e1dee9b 100644 --- a/Tests/Editor/Timing/TimingTestHelper.cs +++ b/Tests/Editor/Timing/TimingTestHelper.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.EditorTests /// /// Helper functions for timing related tests. Allows to get a set of time steps and simulate time advancing without the need of a full playmode test. /// - public static class TimingTestHelper + internal static class TimingTestHelper { public static List GetRandomTimeSteps(float totalDuration, float min, float max, int seed) { diff --git a/Tests/Editor/Transports/BatchedReceiveQueueTests.cs b/Tests/Editor/Transports/BatchedReceiveQueueTests.cs index e072f3c..fef8a3b 100644 --- a/Tests/Editor/Transports/BatchedReceiveQueueTests.cs +++ b/Tests/Editor/Transports/BatchedReceiveQueueTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.EditorTests { - public class BatchedReceiveQueueTests + internal class BatchedReceiveQueueTests { [Test] public void BatchedReceiveQueue_EmptyReader() diff --git a/Tests/Editor/Transports/BatchedSendQueueTests.cs b/Tests/Editor/Transports/BatchedSendQueueTests.cs index ca6a354..3ad4de1 100644 --- a/Tests/Editor/Transports/BatchedSendQueueTests.cs +++ b/Tests/Editor/Transports/BatchedSendQueueTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.EditorTests { - public class BatchedSendQueueTests + internal class BatchedSendQueueTests { private const int k_TestQueueCapacity = 16 * 1024; private const int k_TestMessageSize = 1020; diff --git a/Tests/Editor/Transports/UNetTransportTests.cs b/Tests/Editor/Transports/UNetTransportTests.cs index f8d7a46..9cb0bda 100644 --- a/Tests/Editor/Transports/UNetTransportTests.cs +++ b/Tests/Editor/Transports/UNetTransportTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.EditorTests { - public class UNetTransportTests + internal class UNetTransportTests { [Test] public void StartServerReturnsFalseOnFailure() diff --git a/Tests/Editor/Transports/UnityTransportTests.cs b/Tests/Editor/Transports/UnityTransportTests.cs index fb61c05..3bf49b6 100644 --- a/Tests/Editor/Transports/UnityTransportTests.cs +++ b/Tests/Editor/Transports/UnityTransportTests.cs @@ -5,8 +5,20 @@ namespace Unity.Netcode.EditorTests { - public class UnityTransportTests + internal class UnityTransportTests { + [SetUp] + public void OnSetup() + { + ILPPMessageProvider.IntegrationTestNoMessages = true; + } + + [TearDown] + public void OnTearDown() + { + ILPPMessageProvider.IntegrationTestNoMessages = false; + } + // Check that starting an IPv4 server succeeds. [Test] public void UnityTransport_BasicInitServer_IPv4() diff --git a/Tests/Editor/XXHashTests.cs b/Tests/Editor/XXHashTests.cs index 342a373..30fbb52 100644 --- a/Tests/Editor/XXHashTests.cs +++ b/Tests/Editor/XXHashTests.cs @@ -2,7 +2,7 @@ namespace Unity.Netcode.EditorTests { - public class XXHashTests + internal class XXHashTests { [Test] public void TestXXHash32Short() diff --git a/Tests/Runtime/AddNetworkPrefabTests.cs b/Tests/Runtime/AddNetworkPrefabTests.cs index c00126e..4627143 100644 --- a/Tests/Runtime/AddNetworkPrefabTests.cs +++ b/Tests/Runtime/AddNetworkPrefabTests.cs @@ -7,9 +7,9 @@ namespace Unity.Netcode.RuntimeTests { - public class AddNetworkPrefabTest : NetcodeIntegrationTest + internal class AddNetworkPrefabTest : NetcodeIntegrationTest { - public class EmptyComponent : NetworkBehaviour + internal class EmptyComponent : NetworkBehaviour { } diff --git a/Tests/Runtime/ClientApprovalDenied.cs b/Tests/Runtime/ClientApprovalDenied.cs index 5b4bc1e..fd0517d 100644 --- a/Tests/Runtime/ClientApprovalDenied.cs +++ b/Tests/Runtime/ClientApprovalDenied.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests { - public class ClientApprovalDenied : NetcodeIntegrationTest + internal class ClientApprovalDenied : NetcodeIntegrationTest { protected override int NumberOfClients => 2; private bool m_ApproveConnection = true; diff --git a/Tests/Runtime/ClientOnlyConnectionTests.cs b/Tests/Runtime/ClientOnlyConnectionTests.cs index 1e1be9e..dbd97fa 100644 --- a/Tests/Runtime/ClientOnlyConnectionTests.cs +++ b/Tests/Runtime/ClientOnlyConnectionTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests { - public class ClientOnlyConnectionTests + internal class ClientOnlyConnectionTests { private NetworkManager m_ClientNetworkManager; private GameObject m_NetworkManagerGameObject; diff --git a/Tests/Runtime/Components/BufferDataValidationComponent.cs b/Tests/Runtime/Components/BufferDataValidationComponent.cs index 3912448..3e46ec4 100644 --- a/Tests/Runtime/Components/BufferDataValidationComponent.cs +++ b/Tests/Runtime/Components/BufferDataValidationComponent.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests /// - Sending and Receiving a continually growing buffer up to (MaximumBufferSize) /// - Default maximum buffer size is 1MB /// - public class BufferDataValidationComponent : NetworkBehaviour + internal class BufferDataValidationComponent : NetworkBehaviour { /// /// Allows the external RPCQueueTest to begin testing or stop it diff --git a/Tests/Runtime/Components/NetworkVariableTestComponent.cs b/Tests/Runtime/Components/NetworkVariableTestComponent.cs index 468600f..346b908 100644 --- a/Tests/Runtime/Components/NetworkVariableTestComponent.cs +++ b/Tests/Runtime/Components/NetworkVariableTestComponent.cs @@ -6,7 +6,7 @@ namespace Unity.Netcode.RuntimeTests { - public class EmbeddedManagedNetworkSerializableType : INetworkSerializable + internal class EmbeddedManagedNetworkSerializableType : INetworkSerializable { public int Int; public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter @@ -14,7 +14,7 @@ public void NetworkSerialize(BufferSerializer serializer) where T : IReade serializer.SerializeValue(ref Int); } } - public class ManagedNetworkSerializableType : INetworkSerializable, IEquatable + internal class ManagedNetworkSerializableType : INetworkSerializable, IEquatable { public string Str = ""; public int[] Ints = Array.Empty(); @@ -104,7 +104,7 @@ public override int GetHashCode() return 0; } } - public struct UnmanagedNetworkSerializableType : INetworkSerializable, IEquatable + internal struct UnmanagedNetworkSerializableType : INetworkSerializable, IEquatable { public FixedString32Bytes Str; public int Int; @@ -143,7 +143,7 @@ public override int GetHashCode() } - public struct UnmanagedTemplateNetworkSerializableType : INetworkSerializable where T : unmanaged, INetworkSerializable + internal struct UnmanagedTemplateNetworkSerializableType : INetworkSerializable where T : unmanaged, INetworkSerializable { public T Value; @@ -153,7 +153,7 @@ public void NetworkSerialize(BufferSerializer : INetworkSerializable where T : class, INetworkSerializable, new() + internal struct ManagedTemplateNetworkSerializableType : INetworkSerializable where T : class, INetworkSerializable, new() { public T Value; diff --git a/Tests/Runtime/Components/NetworkVisibilityComponent.cs b/Tests/Runtime/Components/NetworkVisibilityComponent.cs index 2abf2c8..856e77a 100644 --- a/Tests/Runtime/Components/NetworkVisibilityComponent.cs +++ b/Tests/Runtime/Components/NetworkVisibilityComponent.cs @@ -1,6 +1,6 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkVisibilityComponent : NetworkBehaviour + internal class NetworkVisibilityComponent : NetworkBehaviour { public void Hide() { diff --git a/Tests/Runtime/ConnectionApproval.cs b/Tests/Runtime/ConnectionApproval.cs index bd14cfa..ae60675 100644 --- a/Tests/Runtime/ConnectionApproval.cs +++ b/Tests/Runtime/ConnectionApproval.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.RuntimeTests { - public class ConnectionApprovalTests + internal class ConnectionApprovalTests { private Guid m_ValidationToken; private bool m_IsValidated; diff --git a/Tests/Runtime/ConnectionApprovalTimeoutTests.cs b/Tests/Runtime/ConnectionApprovalTimeoutTests.cs index 0cf9658..d324bad 100644 --- a/Tests/Runtime/ConnectionApprovalTimeoutTests.cs +++ b/Tests/Runtime/ConnectionApprovalTimeoutTests.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests { [TestFixture(ApprovalTimedOutTypes.ServerDoesNotRespond)] [TestFixture(ApprovalTimedOutTypes.ClientDoesNotRequest)] - public class ConnectionApprovalTimeoutTests : NetcodeIntegrationTest + internal class ConnectionApprovalTimeoutTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/DeferredMessagingTests.cs b/Tests/Runtime/DeferredMessagingTests.cs index 564bde6..cda0dd6 100644 --- a/Tests/Runtime/DeferredMessagingTests.cs +++ b/Tests/Runtime/DeferredMessagingTests.cs @@ -116,7 +116,7 @@ public override void CleanupStaleTriggers() } } - public class DeferredMessageTestRpcComponent : NetworkBehaviour + internal class DeferredMessageTestRpcComponent : NetworkBehaviour { public bool ClientRpcCalled; @@ -137,7 +137,7 @@ public override void OnNetworkSpawn() } } - public class DeferredMessageTestNetworkVariableComponent : NetworkBehaviour + internal class DeferredMessageTestNetworkVariableComponent : NetworkBehaviour { public static readonly List ClientInstances = new List(); @@ -158,7 +158,7 @@ public override void OnNetworkSpawn() } } - public class DeferredMessageTestRpcAndNetworkVariableComponent : NetworkBehaviour + internal class DeferredMessageTestRpcAndNetworkVariableComponent : NetworkBehaviour { public static readonly List ClientInstances = new List(); public bool ClientRpcCalled; @@ -185,7 +185,7 @@ public void SendTestClientRpc() } } - public class DeferredMessagingTest : NetcodeIntegrationTest + internal class DeferredMessagingTest : NetcodeIntegrationTest { protected override int NumberOfClients => 0; diff --git a/Tests/Runtime/DisconnectTests.cs b/Tests/Runtime/DisconnectTests.cs index bdc298a..c4997fe 100644 --- a/Tests/Runtime/DisconnectTests.cs +++ b/Tests/Runtime/DisconnectTests.cs @@ -21,7 +21,7 @@ namespace Unity.Netcode.RuntimeTests /// [TestFixture(OwnerPersistence.DestroyWithOwner)] [TestFixture(OwnerPersistence.DontDestroyWithOwner)] - public class DisconnectTests : NetcodeIntegrationTest + internal class DisconnectTests : NetcodeIntegrationTest { public enum OwnerPersistence { diff --git a/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs b/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs index b6abd74..faba405 100644 --- a/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs +++ b/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests { - public class DeferredDespawningTests : IntegrationTestWithApproximation + internal class DeferredDespawningTests : IntegrationTestWithApproximation { private const int k_DaisyChainedCount = 5; protected override int NumberOfClients => 2; @@ -85,7 +85,7 @@ private void ReachedLastChainObject(ulong clientId) /// prefab driven by the authority. This repeats for the number specified in the integration /// test. /// - public class DeferredDespawnDaisyChained : NetworkBehaviour + internal class DeferredDespawnDaisyChained : NetworkBehaviour { public static bool EnableVerbose; public static Action ReachedLastChainInstance; diff --git a/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs b/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs index 75a1e9c..7957e6c 100644 --- a/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs +++ b/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs @@ -17,7 +17,7 @@ namespace Unity.Netcode.RuntimeTests /// Validates that distributable NetworkObjects are distributed upon /// a client connecting or disconnecting. /// - public class DistributeObjectsTests : IntegrationTestWithApproximation + internal class DistributeObjectsTests : IntegrationTestWithApproximation { private GameObject m_DistributeObject; @@ -352,7 +352,7 @@ private void DisplayOwnership() /// This keeps track of each clients perspective of which NetworkObjects are owned by which client. /// It is used to validate that all clients are in synch with ownership updates. /// - public class DistributeObjectsTestHelper : NetworkBehaviour + internal class DistributeObjectsTestHelper : NetworkBehaviour { /// /// [Client Context][Client Owners][NetworkObjectId][NetworkObject] @@ -426,7 +426,7 @@ protected override void OnOwnershipChanged(ulong previous, ulong current) /// This is used to validate that upon distributed ownership changes NetworkTransform sycnhronization /// still works properly. /// - public class DistributeTestTransform : NetworkTransform + internal class DistributeTestTransform : NetworkTransform { private float m_DeltaVarPosition = 0.15f; private float m_DeltaVarQauternion = 0.015f; @@ -475,10 +475,8 @@ protected override void OnOwnershipChanged(ulong previous, ulong current) m_ReachedTarget = false; } - protected override void Update() + public override void OnUpdate() { - base.Update(); - if (CanCommitToTransform) { if (!m_ReachedTarget) diff --git a/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs b/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs index 58dd33b..390455a 100644 --- a/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs +++ b/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs @@ -16,15 +16,15 @@ namespace Unity.Netcode.RuntimeTests { - public class DistributedAuthorityCodecTests : NetcodeIntegrationTest + internal class DistributedAuthorityCodecTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; // Use the CMB Service for all tests protected override bool UseCMBService() => true; - // Set the session mode to distributed authority for all tests - protected override SessionModeTypes OnGetSessionmode() => SessionModeTypes.DistributedAuthority; + // Set the network topology to distributed authority for all tests + protected override NetworkTopologyTypes OnGetNetworkTopologyType() => NetworkTopologyTypes.DistributedAuthority; private CodecTestHooks m_ClientCodecHook; private NetworkManager Client => m_ClientNetworkManagers[0]; @@ -35,7 +35,7 @@ public class DistributedAuthorityCodecTests : NetcodeIntegrationTest private GameObject m_SpawnObject; - public class TestNetworkComponent : NetworkBehaviour + internal class TestNetworkComponent : NetworkBehaviour { public NetworkList MyNetworkList = new NetworkList(new List { 1, 2, 3 }); diff --git a/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs b/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs index fa7a641..d7890c2 100644 --- a/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs +++ b/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs @@ -14,7 +14,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] [TestFixture(HostOrServer.DAHost)] - public class NetworkClientAndPlayerObjectTests : NetcodeIntegrationTest + internal class NetworkClientAndPlayerObjectTests : NetcodeIntegrationTest { private const int k_PlayerPrefabCount = 6; protected override int NumberOfClients => 2; @@ -168,7 +168,7 @@ private bool AllNetworkClientsValidated() [UnityTest] public IEnumerator ValidateNetworkClients() { - // Validate the initial clients created + // Validate the initial clients created yield return WaitForConditionOrTimeOut(AllNetworkClientsValidated); AssertOnTimeout($"[Start] Not all NetworkClients were valid!\n{m_ErrorLogLevel1}"); @@ -190,7 +190,7 @@ public IEnumerator ValidateNetworkClients() } /// - /// Verify that all NetworkClients are pointing to the correct player object, even if + /// Verify that all NetworkClients are pointing to the correct player object, even if /// the player object is changed. /// private bool ValidatePlayerObjectOnClients(NetworkManager clientToValidate) diff --git a/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs b/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs index e56798b..beccbdd 100644 --- a/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs +++ b/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests { - public class OwnershipPermissionsTests : IntegrationTestWithApproximation + internal class OwnershipPermissionsTests : IntegrationTestWithApproximation { private GameObject m_PermissionsObject; @@ -332,7 +332,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() AssertOnTimeout($"[Targeted Owner] Client-{daHostInstance.NetworkManager.LocalClientId} did not get the right request reponse: {daHostInstanceHelper.OwnershipRequestResponseStatus} Expecting: {NetworkObject.OwnershipRequestResponseStatus.Approved}!"); } - public class OwnershipPermissionsTestHelper : NetworkBehaviour + internal class OwnershipPermissionsTestHelper : NetworkBehaviour { public static NetworkObject CurrentOwnedInstance; diff --git a/Tests/Runtime/HiddenVariableTests.cs b/Tests/Runtime/HiddenVariableTests.cs index c87fe80..f110ed1 100644 --- a/Tests/Runtime/HiddenVariableTests.cs +++ b/Tests/Runtime/HiddenVariableTests.cs @@ -7,11 +7,11 @@ namespace Unity.Netcode.RuntimeTests { - public class HiddenVariableTest : NetworkBehaviour + internal class HiddenVariableTest : NetworkBehaviour { } - public class HiddenVariableObject : NetworkBehaviour + internal class HiddenVariableObject : NetworkBehaviour { public static List ClientInstancesSpawned = new List(); @@ -69,7 +69,7 @@ public void ListChanged(NetworkListEvent listEvent) } } - public class HiddenVariableTests : NetcodeIntegrationTest + internal class HiddenVariableTests : NetcodeIntegrationTest { protected override int NumberOfClients => 4; diff --git a/Tests/Runtime/IntegrationTestExamples.cs b/Tests/Runtime/IntegrationTestExamples.cs index 7cba4fb..0318e79 100644 --- a/Tests/Runtime/IntegrationTestExamples.cs +++ b/Tests/Runtime/IntegrationTestExamples.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests { - public class IntegrationTestUpdated : NetcodeIntegrationTest + internal class IntegrationTestUpdated : NetcodeIntegrationTest { private GameObject m_MyNetworkPrefab; protected override int NumberOfClients => 1; @@ -45,7 +45,7 @@ public IEnumerator MyFirstIntegationTest() [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] - public class IntegrationTestExtended : NetcodeIntegrationTest + internal class IntegrationTestExtended : NetcodeIntegrationTest { private GameObject m_MyNetworkPrefab; protected override int NumberOfClients => 1; @@ -84,11 +84,11 @@ public IEnumerator MyFirstIntegationTest() } } - public class ExampleTestComponent : NetworkBehaviour + internal class ExampleTestComponent : NetworkBehaviour { } - public class IntegrationTestPlayers : NetcodeIntegrationTest + internal class IntegrationTestPlayers : NetcodeIntegrationTest { protected override int NumberOfClients => 5; @@ -126,13 +126,13 @@ public void TestClientRelativePlayers() } } - public class SpawnTest : NetworkBehaviour + internal class SpawnTest : NetworkBehaviour { public static int TotalSpawned; public override void OnNetworkSpawn() { TotalSpawned++; } public override void OnNetworkDespawn() { TotalSpawned--; } } - public class IntegrationTestSpawning : NetcodeIntegrationTest + internal class IntegrationTestSpawning : NetcodeIntegrationTest { protected override int NumberOfClients => 2; private GameObject m_NetworkPrefabToSpawn; diff --git a/Tests/Runtime/InvalidConnectionEventsTest.cs b/Tests/Runtime/InvalidConnectionEventsTest.cs index 11d3121..d849bc2 100644 --- a/Tests/Runtime/InvalidConnectionEventsTest.cs +++ b/Tests/Runtime/InvalidConnectionEventsTest.cs @@ -12,7 +12,7 @@ namespace Unity.Netcode.RuntimeTests { - public class InvalidConnectionEventsTest : NetcodeIntegrationTest + internal class InvalidConnectionEventsTest : NetcodeIntegrationTest { protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/ListChangedTest.cs b/Tests/Runtime/ListChangedTest.cs index 45f7081..3f47ae9 100644 --- a/Tests/Runtime/ListChangedTest.cs +++ b/Tests/Runtime/ListChangedTest.cs @@ -6,12 +6,12 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkListChangedTestComponent : NetworkBehaviour + internal class NetworkListChangedTestComponent : NetworkBehaviour { } - public class ListChangedObject : NetworkBehaviour + internal class ListChangedObject : NetworkBehaviour { public int ExpectedPreviousValue = 0; public int ExpectedValue = 0; @@ -46,9 +46,9 @@ public void Changed(NetworkListEvent listEvent) } } - [TestFixture(SessionModeTypes.DistributedAuthority)] - [TestFixture(SessionModeTypes.ClientServer)] - public class NetworkListChangedTests : NetcodeIntegrationTest + [TestFixture(NetworkTopologyTypes.DistributedAuthority)] + [TestFixture(NetworkTopologyTypes.ClientServer)] + internal class NetworkListChangedTests : NetcodeIntegrationTest { protected override int NumberOfClients => 2; @@ -57,7 +57,7 @@ public class NetworkListChangedTests : NetcodeIntegrationTest private NetworkObject m_NetSpawnedObject1; - public NetworkListChangedTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + public NetworkListChangedTests(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { } protected override void OnServerAndClientsCreated() { diff --git a/Tests/Runtime/Messaging/DisconnectReasonTests.cs b/Tests/Runtime/Messaging/DisconnectReasonTests.cs index ce28966..e293be3 100644 --- a/Tests/Runtime/Messaging/DisconnectReasonTests.cs +++ b/Tests/Runtime/Messaging/DisconnectReasonTests.cs @@ -8,12 +8,12 @@ namespace Unity.Netcode.RuntimeTests { - public class DisconnectReasonObject : NetworkBehaviour + internal class DisconnectReasonObject : NetworkBehaviour { } - public class DisconnectReasonTests : NetcodeIntegrationTest + internal class DisconnectReasonTests : NetcodeIntegrationTest { protected override int NumberOfClients => 2; diff --git a/Tests/Runtime/Messaging/NamedMessageTests.cs b/Tests/Runtime/Messaging/NamedMessageTests.cs index ae243cc..541fbb2 100644 --- a/Tests/Runtime/Messaging/NamedMessageTests.cs +++ b/Tests/Runtime/Messaging/NamedMessageTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NamedMessageTests : NetcodeIntegrationTest + internal class NamedMessageTests : NetcodeIntegrationTest { protected override int NumberOfClients => 2; diff --git a/Tests/Runtime/Messaging/UnnamedMessageTests.cs b/Tests/Runtime/Messaging/UnnamedMessageTests.cs index bd583cf..61333ad 100644 --- a/Tests/Runtime/Messaging/UnnamedMessageTests.cs +++ b/Tests/Runtime/Messaging/UnnamedMessageTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.RuntimeTests { - public class UnnamedMessageTests : NetcodeIntegrationTest + internal class UnnamedMessageTests : NetcodeIntegrationTest { protected override int NumberOfClients => 2; diff --git a/Tests/Runtime/Metrics/ConnectionMetricsTests.cs b/Tests/Runtime/Metrics/ConnectionMetricsTests.cs index 35356d4..b94cc47 100644 --- a/Tests/Runtime/Metrics/ConnectionMetricsTests.cs +++ b/Tests/Runtime/Metrics/ConnectionMetricsTests.cs @@ -14,7 +14,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics [TestFixture(ClientCount.TwoClients, HostOrServer.Host)] [TestFixture(ClientCount.OneClient, HostOrServer.Server)] [TestFixture(ClientCount.TwoClients, HostOrServer.Server)] - public class ConnectionMetricsTests : NetcodeIntegrationTest + internal class ConnectionMetricsTests : NetcodeIntegrationTest { protected override int NumberOfClients => m_ClientCount; diff --git a/Tests/Runtime/Metrics/MessagingMetricsTests.cs b/Tests/Runtime/Metrics/MessagingMetricsTests.cs index 06b51c1..6cd827f 100644 --- a/Tests/Runtime/Metrics/MessagingMetricsTests.cs +++ b/Tests/Runtime/Metrics/MessagingMetricsTests.cs @@ -12,7 +12,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics { - public class MessagingMetricsTests : DualClientMetricTestBase + internal class MessagingMetricsTests : DualClientMetricTestBase { private const uint k_MessageNameHashSize = 8; // Header is dynamically sized due to packing, will be 2 bytes for all test messages. diff --git a/Tests/Runtime/Metrics/MetricsDispatchTests.cs b/Tests/Runtime/Metrics/MetricsDispatchTests.cs index 519ddfa..e8a268c 100644 --- a/Tests/Runtime/Metrics/MetricsDispatchTests.cs +++ b/Tests/Runtime/Metrics/MetricsDispatchTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics { - public class MetricsDispatchTests + internal class MetricsDispatchTests { private int m_NbDispatches; diff --git a/Tests/Runtime/Metrics/PacketLossMetricsTests.cs b/Tests/Runtime/Metrics/PacketLossMetricsTests.cs index 4a008cf..91c242b 100644 --- a/Tests/Runtime/Metrics/PacketLossMetricsTests.cs +++ b/Tests/Runtime/Metrics/PacketLossMetricsTests.cs @@ -15,7 +15,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics { - public class PacketLossMetricsTests : NetcodeIntegrationTest + internal class PacketLossMetricsTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; private readonly int m_PacketLossRate = 25; diff --git a/Tests/Runtime/NestedNetworkManagerTests.cs b/Tests/Runtime/NestedNetworkManagerTests.cs index 7ae6ad2..c31f8a8 100644 --- a/Tests/Runtime/NestedNetworkManagerTests.cs +++ b/Tests/Runtime/NestedNetworkManagerTests.cs @@ -6,7 +6,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NestedNetworkManagerTests + internal class NestedNetworkManagerTests { [Test] public void CheckNestedNetworkManager() diff --git a/Tests/Runtime/NetworkBehaviourGenericTests.cs b/Tests/Runtime/NetworkBehaviourGenericTests.cs index ab48aaa..91e3124 100644 --- a/Tests/Runtime/NetworkBehaviourGenericTests.cs +++ b/Tests/Runtime/NetworkBehaviourGenericTests.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode.RuntimeTests /// /// This class is for testing general fixes or functionality of NetworkBehaviours /// - public class NetworkBehaviourGenericTests : NetcodeIntegrationTest + internal class NetworkBehaviourGenericTests : NetcodeIntegrationTest { protected override int NumberOfClients => 0; @@ -21,7 +21,7 @@ protected override bool CanStartServerAndClients() return m_AllowServerToStart; } - public class SimpleNetworkBehaviour : NetworkBehaviour + internal class SimpleNetworkBehaviour : NetworkBehaviour { public bool OnNetworkDespawnCalled; diff --git a/Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs b/Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs new file mode 100644 index 0000000..00d3c08 --- /dev/null +++ b/Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs @@ -0,0 +1,143 @@ +using System.Collections; +using NUnit.Framework; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine; +using UnityEngine.TestTools; + +namespace Unity.Netcode.RuntimeTests +{ + [TestFixture(HostOrServer.Host)] + [TestFixture(HostOrServer.DAHost)] + internal class NetworkBehaviourPrePostSpawnTests : NetcodeIntegrationTest + { + protected override int NumberOfClients => 0; + + private bool m_AllowServerToStart; + + private GameObject m_PrePostSpawnObject; + + public NetworkBehaviourPrePostSpawnTests(HostOrServer hostOrServer) : base(hostOrServer) { } + + protected override void OnServerAndClientsCreated() + { + m_PrePostSpawnObject = CreateNetworkObjectPrefab("PrePostSpawn"); + // Reverse the order of the components to get inverted spawn sequence + m_PrePostSpawnObject.AddComponent(); + m_PrePostSpawnObject.AddComponent(); + base.OnServerAndClientsCreated(); + } + + internal class NetworkBehaviourPreSpawn : NetworkBehaviour + { + public static int ValueToSet; + public bool OnNetworkPreSpawnCalled; + public bool NetworkVarValueMatches; + + public NetworkVariable TestNetworkVariable; + + protected override void OnNetworkPreSpawn(ref NetworkManager networkManager) + { + OnNetworkPreSpawnCalled = true; + // If we are the server, then set the randomly generated value (1-200). + // Otherwise, just set the value to 0. + // TODO: Make adjustments when integrated CMB service testing is added + var val = networkManager.IsServer ? ValueToSet : 0; + // Instantiate the NetworkVariable as everyone read & owner write while also setting the value + TestNetworkVariable = new NetworkVariable(val, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); + base.OnNetworkPreSpawn(ref networkManager); + } + + public override void OnNetworkSpawn() + { + // For both client and server this should match at this point + NetworkVarValueMatches = TestNetworkVariable.Value == ValueToSet; + base.OnNetworkSpawn(); + } + } + + internal class NetworkBehaviourPostSpawn : NetworkBehaviour + { + public bool OnNetworkPostSpawnCalled; + + private NetworkBehaviourPreSpawn m_NetworkBehaviourPreSpawn; + + public int ValueSet; + + public override void OnNetworkSpawn() + { + // Obtain the NetworkBehaviourPreSpawn component + // (could also do this during OnNetworkPreSpawn if we wanted) + m_NetworkBehaviourPreSpawn = GetComponent(); + base.OnNetworkSpawn(); + } + + protected override void OnNetworkPostSpawn() + { + OnNetworkPostSpawnCalled = true; + // We should be able to access the component we got during OnNetworkSpawn and all values should be set + // (i.e. OnNetworkSpawn run on all NetworkObject relative NetworkBehaviours) + ValueSet = m_NetworkBehaviourPreSpawn.TestNetworkVariable.Value; + base.OnNetworkPostSpawn(); + } + + } + + protected override bool CanStartServerAndClients() + { + return m_AllowServerToStart; + } + + protected override IEnumerator OnSetup() + { + m_AllowServerToStart = false; + return base.OnSetup(); + } + + protected override void OnNewClientCreated(NetworkManager networkManager) + { + networkManager.NetworkConfig.Prefabs = m_ServerNetworkManager.NetworkConfig.Prefabs; + base.OnNewClientCreated(networkManager); + } + + /// + /// This validates that pre spawn can be used to instantiate and assign a NetworkVariable (or other prespawn tasks) + /// which can be useful for assigning a NetworkVariable value on the server side when the NetworkVariable has owner write permissions. + /// This also assures that duruing post spawn all associated NetworkBehaviours have run through the OnNetworkSpawn pass (i.e. OnNetworkSpawn order is not an issue) + /// + [UnityTest] + public IEnumerator OnNetworkPreAndPostSpawn() + { + m_AllowServerToStart = true; + NetworkBehaviourPreSpawn.ValueToSet = Random.Range(1, 200); + yield return StartServerAndClients(); + + yield return CreateAndStartNewClient(); + + // Spawn the object with the newly joined client as the owner + var networkManager = m_DistributedAuthority ? m_ServerNetworkManager : m_ClientNetworkManagers[0]; + var authorityInstance = SpawnObject(m_PrePostSpawnObject, networkManager); + var authorityNetworkObject = authorityInstance.GetComponent(); + var authorityPreSpawn = authorityInstance.GetComponent(); + var authorityPostSpawn = authorityInstance.GetComponent(); + + yield return WaitForConditionOrTimeOut(() => s_GlobalNetworkObjects.ContainsKey(m_ClientNetworkManagers[0].LocalClientId) + && s_GlobalNetworkObjects[m_ClientNetworkManagers[0].LocalClientId].ContainsKey(authorityNetworkObject.NetworkObjectId)); + AssertOnTimeout($"Client-{m_ClientNetworkManagers[0].LocalClientId} failed to spawn {nameof(NetworkObject)} id-{authorityNetworkObject.NetworkObjectId}!"); + + var clientNetworkObject = s_GlobalNetworkObjects[m_ClientNetworkManagers[0].LocalClientId][authorityNetworkObject.NetworkObjectId]; + var clientPreSpawn = clientNetworkObject.GetComponent(); + var clientPostSpawn = clientNetworkObject.GetComponent(); + + Assert.IsTrue(authorityPreSpawn.OnNetworkPreSpawnCalled, $"[Authority-side] OnNetworkPreSpawn not invoked!"); + Assert.IsTrue(clientPreSpawn.OnNetworkPreSpawnCalled, $"[Client-side] OnNetworkPreSpawn not invoked!"); + Assert.IsTrue(authorityPostSpawn.OnNetworkPostSpawnCalled, $"[Authority-side] OnNetworkPostSpawn not invoked!"); + Assert.IsTrue(clientPostSpawn.OnNetworkPostSpawnCalled, $"[Client-side] OnNetworkPostSpawn not invoked!"); + + Assert.IsTrue(authorityPreSpawn.NetworkVarValueMatches, $"[Authority-side][PreSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {authorityPreSpawn.TestNetworkVariable.Value}!"); + Assert.IsTrue(clientPreSpawn.NetworkVarValueMatches, $"[Client-side][PreSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {clientPreSpawn.TestNetworkVariable.Value}!"); + + Assert.IsTrue(authorityPostSpawn.ValueSet == NetworkBehaviourPreSpawn.ValueToSet, $"[Authority-side][PostSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {authorityPostSpawn.ValueSet}!"); + Assert.IsTrue(clientPostSpawn.ValueSet == NetworkBehaviourPreSpawn.ValueToSet, $"[Client-side][PostSpawn] Value {NetworkBehaviourPreSpawn.ValueToSet} does not match {clientPostSpawn.ValueSet}!"); + } + } +} diff --git a/Components/AssemblyInfo.cs.meta b/Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs.meta similarity index 83% rename from Components/AssemblyInfo.cs.meta rename to Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs.meta index 36524ba..70ad282 100644 --- a/Components/AssemblyInfo.cs.meta +++ b/Tests/Runtime/NetworkBehaviourPrePostSpawnTests.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5b8086dc75d86473f9e3c928dd773733 +guid: 2263d66f6df15a7428d279dbdaba1519 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Tests/Runtime/NetworkBehaviourUpdaterTests.cs b/Tests/Runtime/NetworkBehaviourUpdaterTests.cs index 9cf021a..a7b0fc9 100644 --- a/Tests/Runtime/NetworkBehaviourUpdaterTests.cs +++ b/Tests/Runtime/NetworkBehaviourUpdaterTests.cs @@ -12,7 +12,7 @@ namespace Unity.Netcode.RuntimeTests /// /// This is a refactor of the original test's NetworkBehaviour INetVarInfo derived NetworkBehaviours /// - public class NetVarContainer : NetworkBehaviour + internal class NetVarContainer : NetworkBehaviour { public enum NetVarsToCheck { @@ -126,7 +126,7 @@ public void SetNetworkVariableValues() /// Used to define how many NetworkVariables to use per NetVarContainer instance. /// There are always two /// - public struct NetVarCombinationTypes + internal struct NetVarCombinationTypes { public NetVarContainer.NetVarsToCheck FirstType; public NetVarContainer.NetVarsToCheck SecondType; @@ -135,7 +135,7 @@ public struct NetVarCombinationTypes /// /// Server and Distributed Authority modes require at least 1 client while the host does not. /// - /// [Session Mode][Number of Clients][First NetVar Type][Second NetVar Type] + /// [Host or Server mode][Number of Clients][First NetVar Type][Second NetVar Type] [TestFixture(HostOrServer.DAHost, 1, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.One)] [TestFixture(HostOrServer.DAHost, 1, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.Two)] [TestFixture(HostOrServer.DAHost, 1, NetVarContainer.NetVarsToCheck.Two, NetVarContainer.NetVarsToCheck.Two)] @@ -157,7 +157,7 @@ public struct NetVarCombinationTypes [TestFixture(HostOrServer.Host, 2, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.One)] [TestFixture(HostOrServer.Host, 2, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.Two)] [TestFixture(HostOrServer.Host, 2, NetVarContainer.NetVarsToCheck.Two, NetVarContainer.NetVarsToCheck.Two)] - public class NetworkBehaviourUpdaterTests : NetcodeIntegrationTest + internal class NetworkBehaviourUpdaterTests : NetcodeIntegrationTest { // Go ahead and create maximum number of clients (not all tests will use them) protected override int NumberOfClients => m_NumberOfClients; @@ -202,7 +202,7 @@ protected override void OnServerAndClientsCreated() // GameObject of this prefab var netVarContainer = m_PrefabToSpawn.AddComponent(); netVarContainer.NumberOfNetVarsToCheck = m_NetVarCombinationTypes.FirstType; - if (m_SessionModeType == SessionModeTypes.DistributedAuthority) + if (m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority) { netVarContainer.SetOwnerWrite(); } @@ -210,7 +210,7 @@ protected override void OnServerAndClientsCreated() netVarContainer.ValueToSetNetVarTo = NetVarValueToSet; netVarContainer = m_PrefabToSpawn.AddComponent(); - if (m_SessionModeType == SessionModeTypes.DistributedAuthority) + if (m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority) { netVarContainer.SetOwnerWrite(); } @@ -243,7 +243,7 @@ public IEnumerator BehaviourUpdaterAllTests([Values(1, 2)] int numToSpawn) // the appropriate number of NetworkObjects with the NetVarContainer behaviour var numberOfObjectsToSpawn = numToSpawn * NumberOfClients; - var authority = m_SessionModeType == SessionModeTypes.DistributedAuthority ? m_ClientNetworkManagers[0] : m_ServerNetworkManager; + var authority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority ? m_ClientNetworkManagers[0] : m_ServerNetworkManager; // spawn the objects for (int i = 0; i < numToSpawn; i++) diff --git a/Tests/Runtime/NetworkManagerCustomMessageManagerTests.cs b/Tests/Runtime/NetworkManagerCustomMessageManagerTests.cs index e3255b9..a43bd24 100644 --- a/Tests/Runtime/NetworkManagerCustomMessageManagerTests.cs +++ b/Tests/Runtime/NetworkManagerCustomMessageManagerTests.cs @@ -3,7 +3,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkManagerCustomMessageManagerTests + internal class NetworkManagerCustomMessageManagerTests { [Test] public void CustomMessageManagerAssigned() diff --git a/Tests/Runtime/NetworkManagerEventsTests.cs b/Tests/Runtime/NetworkManagerEventsTests.cs index 3ae6828..1b872f9 100644 --- a/Tests/Runtime/NetworkManagerEventsTests.cs +++ b/Tests/Runtime/NetworkManagerEventsTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkManagerEventsTests + internal class NetworkManagerEventsTests { private NetworkManager m_ClientManager; private NetworkManager m_ServerManager; diff --git a/Tests/Runtime/NetworkManagerSceneManagerTests.cs b/Tests/Runtime/NetworkManagerSceneManagerTests.cs index dd96132..d7544b7 100644 --- a/Tests/Runtime/NetworkManagerSceneManagerTests.cs +++ b/Tests/Runtime/NetworkManagerSceneManagerTests.cs @@ -3,7 +3,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkManagerSceneManagerTests + internal class NetworkManagerSceneManagerTests { [Test] public void SceneManagerAssigned() diff --git a/Tests/Runtime/NetworkManagerTransportTests.cs b/Tests/Runtime/NetworkManagerTransportTests.cs index fa1fbda..788758c 100644 --- a/Tests/Runtime/NetworkManagerTransportTests.cs +++ b/Tests/Runtime/NetworkManagerTransportTests.cs @@ -6,7 +6,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkManagerTransportTests + internal class NetworkManagerTransportTests { [Test] public void ClientDoesNotStartWhenTransportFails() @@ -106,7 +106,7 @@ public IEnumerator ShutsDownWhenTransportFails() /// /// Does nothing but simulate a transport that can fail at startup and/or when polling events. /// - public class FailedTransport : TestingNetworkTransport + internal class FailedTransport : TestingNetworkTransport { public bool FailOnStart = false; public bool FailOnNextPoll = false; diff --git a/Tests/Runtime/NetworkObject/NetworkObjectDestroyTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectDestroyTests.cs index 7a751b3..6f30706 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectDestroyTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectDestroyTests.cs @@ -14,13 +14,13 @@ namespace Unity.Netcode.RuntimeTests /// - Client destroy spawned => throw exception. /// - [TestFixture(SessionModeTypes.DistributedAuthority)] - [TestFixture(SessionModeTypes.ClientServer)] - public class NetworkObjectDestroyTests : NetcodeIntegrationTest + [TestFixture(NetworkTopologyTypes.DistributedAuthority)] + [TestFixture(NetworkTopologyTypes.ClientServer)] + internal class NetworkObjectDestroyTests : NetcodeIntegrationTest { protected override int NumberOfClients => 2; - public NetworkObjectDestroyTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + public NetworkObjectDestroyTests(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { } /// /// Tests that a server can destroy a NetworkObject and that it gets despawned correctly. @@ -96,7 +96,7 @@ public IEnumerator TestNetworkObjectClientDestroy([Values] ClientDestroyObject c } else { - // Shutdown the + // Shutdown the m_ClientNetworkManagers[0].Shutdown(); } } diff --git a/Tests/Runtime/NetworkObject/NetworkObjectDontDestroyWithOwnerTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectDontDestroyWithOwnerTests.cs index f77a06e..51e86ea 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectDontDestroyWithOwnerTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectDontDestroyWithOwnerTests.cs @@ -11,7 +11,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] - public class NetworkObjectDontDestroyWithOwnerTests : NetcodeIntegrationTest + internal class NetworkObjectDontDestroyWithOwnerTests : NetcodeIntegrationTest { private const int k_NumberObjectsToSpawn = 32; protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/NetworkObject/NetworkObjectNetworkClientOwnedObjectsTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectNetworkClientOwnedObjectsTests.cs index cd31ca2..d9b0521 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectNetworkClientOwnedObjectsTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectNetworkClientOwnedObjectsTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkObjectNetworkClientOwnedObjectsTests : NetcodeIntegrationTest + internal class NetworkObjectNetworkClientOwnedObjectsTests : NetcodeIntegrationTest { private class DummyNetworkBehaviour : NetworkBehaviour { diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOnNetworkDespawnTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOnNetworkDespawnTests.cs index 56adc0a..9a737a4 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectOnNetworkDespawnTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectOnNetworkDespawnTests.cs @@ -13,7 +13,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] - public class NetworkObjectOnNetworkDespawnTests : NetcodeIntegrationTest + internal class NetworkObjectOnNetworkDespawnTests : NetcodeIntegrationTest { private const string k_ObjectName = "TestDespawn"; public enum InstanceTypes diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOnSpawnTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOnSpawnTests.cs index cefdc2d..a7f1340 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectOnSpawnTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectOnSpawnTests.cs @@ -7,9 +7,9 @@ namespace Unity.Netcode.RuntimeTests { - [TestFixture(SessionModeTypes.DistributedAuthority)] - [TestFixture(SessionModeTypes.ClientServer)] - public class NetworkObjectOnSpawnTests : NetcodeIntegrationTest + [TestFixture(NetworkTopologyTypes.DistributedAuthority)] + [TestFixture(NetworkTopologyTypes.ClientServer)] + internal class NetworkObjectOnSpawnTests : NetcodeIntegrationTest { private GameObject m_TestNetworkObjectPrefab; private GameObject m_TestNetworkObjectInstance; @@ -29,7 +29,7 @@ public enum ObserverTestTypes private const string k_WithObserversError = "Not all clients spawned the"; private const string k_WithoutObserversError = "A client spawned the"; - public NetworkObjectOnSpawnTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + public NetworkObjectOnSpawnTests(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { } protected override void OnServerAndClientsCreated() { @@ -43,7 +43,7 @@ private bool CheckClientsSideObserverTestObj() { if (m_ObserverTestType == ObserverTestTypes.WithObservers) { - // When validating this portion of the test and spawning with observers is true, there + // When validating this portion of the test and spawning with observers is true, there // should be spawned objects on the clients. if (!s_GlobalNetworkObjects.ContainsKey(client.LocalClientId)) { @@ -52,7 +52,7 @@ private bool CheckClientsSideObserverTestObj() } else { - // When validating this portion of the test and spawning with observers is false, there + // When validating this portion of the test and spawning with observers is false, there // should be no spawned objects on the clients. if (s_GlobalNetworkObjects.ContainsKey(client.LocalClientId)) { diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs index e198f0d..c91df37 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs @@ -8,9 +8,9 @@ namespace Unity.Netcode.RuntimeTests { - [TestFixture(SessionModeTypes.DistributedAuthority)] - [TestFixture(SessionModeTypes.ClientServer)] - public class NetworkObjectOwnershipPropertiesTests : NetcodeIntegrationTest + [TestFixture(NetworkTopologyTypes.DistributedAuthority)] + [TestFixture(NetworkTopologyTypes.ClientServer)] + internal class NetworkObjectOwnershipPropertiesTests : NetcodeIntegrationTest { private class DummyNetworkBehaviour : NetworkBehaviour { @@ -30,7 +30,7 @@ private class DummyNetworkBehaviour : NetworkBehaviour private bool m_InitialOwnerOwnedBySever; private bool m_TargetOwnerOwnedBySever; - public NetworkObjectOwnershipPropertiesTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + public NetworkObjectOwnershipPropertiesTests(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { } protected override IEnumerator OnTearDown() { @@ -186,7 +186,7 @@ public IEnumerator ValidatePropertiesWithOwnershipChanges([Values(InstanceTypes. yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); } - // Ensure it's the ownership tables are updated + // Ensure it's the ownership tables are updated yield return WaitForConditionOrTimeOut(OwnershipPropagated); AssertOnTimeout($"Timed out waiting for ownership to propagate!\n{m_OwnershipPropagatedFailures}"); diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs index 77d5a93..f1f6e53 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkObjectOwnershipComponent : NetworkBehaviour + internal class NetworkObjectOwnershipComponent : NetworkBehaviour { public static Dictionary SpawnedInstances = new Dictionary(); @@ -45,7 +45,7 @@ public void ResetFlags() [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] - public class NetworkObjectOwnershipTests : NetcodeIntegrationTest + internal class NetworkObjectOwnershipTests : NetcodeIntegrationTest { protected override int NumberOfClients => 9; diff --git a/Tests/Runtime/NetworkObject/NetworkObjectPropertyTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectPropertyTests.cs index 364a7cf..f1557f4 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectPropertyTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectPropertyTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests /// /// Tests properties of NetworkObject for proper functionality. /// - public class NetworkObjectPropertyTests : NetcodeIntegrationTest + internal class NetworkObjectPropertyTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/NetworkObject/NetworkObjectSpawnManyObjectsTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectSpawnManyObjectsTests.cs index 7e41596..7c8b137 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectSpawnManyObjectsTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectSpawnManyObjectsTests.cs @@ -7,9 +7,9 @@ namespace Unity.Netcode.RuntimeTests { - [TestFixture(SessionModeTypes.ClientServer)] - [TestFixture(SessionModeTypes.DistributedAuthority)] - public class NetworkObjectSpawnManyObjectsTests : NetcodeIntegrationTest + [TestFixture(NetworkTopologyTypes.ClientServer)] + [TestFixture(NetworkTopologyTypes.DistributedAuthority)] + internal class NetworkObjectSpawnManyObjectsTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; // "many" in this case means enough to exceed a ushort_max message size written in the header @@ -18,9 +18,9 @@ public class NetworkObjectSpawnManyObjectsTests : NetcodeIntegrationTest private NetworkPrefab m_PrefabToSpawn; - public NetworkObjectSpawnManyObjectsTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + public NetworkObjectSpawnManyObjectsTests(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { } // Using this component assures we will know precisely how many prefabs were spawned on the client - public class SpawnObjecTrackingComponent : NetworkBehaviour + internal class SpawnObjecTrackingComponent : NetworkBehaviour { public static int SpawnedObjects; public override void OnNetworkSpawn() diff --git a/Tests/Runtime/NetworkObject/NetworkObjectSynchronizationTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectSynchronizationTests.cs index 0a907c6..c4714d7 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectSynchronizationTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectSynchronizationTests.cs @@ -14,7 +14,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(VariableLengthSafety.EnabledNetVarSafety, HostOrServer.Host)] [TestFixture(VariableLengthSafety.DisableNetVarSafety, HostOrServer.Server)] [TestFixture(VariableLengthSafety.EnabledNetVarSafety, HostOrServer.Server)] - public class NetworkObjectSynchronizationTests : NetcodeIntegrationTest + internal class NetworkObjectSynchronizationTests : NetcodeIntegrationTest { private const int k_NumberToSpawn = 30; protected override int NumberOfClients => 0; @@ -382,7 +382,7 @@ public IEnumerator NetworkBehaviourOnSynchronize() /// the synchronization process will continue (i.e. it will skip over that block /// of the reader buffer). /// - public class NetworkBehaviourWithNetworkVariables : NetworkBehaviour + internal class NetworkBehaviourWithNetworkVariables : NetworkBehaviour { public static int ServerSpawnCount { get; internal set; } public static readonly Dictionary ClientSpawnCount = new Dictionary(); @@ -442,7 +442,7 @@ public override void OnNetworkSpawn() /// when variable length safety checks are off NetworkVariables still are updated /// properly. /// - public class NetworkBehaviourWithOwnerNetworkVariables : NetworkBehaviour + internal class NetworkBehaviourWithOwnerNetworkVariables : NetworkBehaviour { private NetworkVariableWritePermission m_NetworkVariableWritePermission = NetworkVariableWritePermission.Server; /// @@ -491,7 +491,7 @@ public override void OnNetworkSpawn() /// and provides a synchronization success version to validate that synchronization /// will continue if user synchronization code fails. /// - public class NetworkBehaviourSynchronizeFailureComponent : NetworkBehaviour + internal class NetworkBehaviourSynchronizeFailureComponent : NetworkBehaviour { public static int NumberOfFailureTypes { get; internal set; } public static int ServerSpawnCount { get; internal set; } @@ -661,11 +661,11 @@ protected override void OnSynchronize(ref BufferSerializer serializer) } } - public class NetworkBehaviourOnSynchronizeComponent : NetworkBehaviour + internal class NetworkBehaviourOnSynchronizeComponent : NetworkBehaviour { public SomeCustomSerializationData CustomSerializationData = new SomeCustomSerializationData(); - public struct SomeCustomSerializationData : INetworkSerializable + internal struct SomeCustomSerializationData : INetworkSerializable { public uint Value1; public bool Value2; diff --git a/Tests/Runtime/NetworkPrefabHandlerTests.cs b/Tests/Runtime/NetworkPrefabHandlerTests.cs index 1e2378b..2dc5f60 100644 --- a/Tests/Runtime/NetworkPrefabHandlerTests.cs +++ b/Tests/Runtime/NetworkPrefabHandlerTests.cs @@ -14,7 +14,7 @@ namespace Unity.Netcode.RuntimeTests /// Destroying a newly spawned NetworkObject instance works /// Removing a INetworkPrefabInstanceHandler is removed and can be verified (very last check) /// - public class NetworkPrefabHandlerTests + internal class NetworkPrefabHandlerTests { private const string k_TestPrefabObjectName = "NetworkPrefabTestObject"; @@ -203,7 +203,7 @@ public void TearDown() /// /// The Prefab instance handler to use for this test /// - public class NetworkPrefaInstanceHandler : INetworkPrefabInstanceHandler + internal class NetworkPrefaInstanceHandler : INetworkPrefabInstanceHandler { private NetworkObject m_NetworkObject; diff --git a/Tests/Runtime/NetworkShowHideTests.cs b/Tests/Runtime/NetworkShowHideTests.cs index 3032553..ea01073 100644 --- a/Tests/Runtime/NetworkShowHideTests.cs +++ b/Tests/Runtime/NetworkShowHideTests.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests { - public class ShowHideObject : NetworkBehaviour + internal class ShowHideObject : NetworkBehaviour { public static List ClientTargetedNetworkObjects = new List(); public static ulong ClientIdToTarget; @@ -126,9 +126,9 @@ public void TriggerRpc() } } - [TestFixture(SessionModeTypes.ClientServer)] - [TestFixture(SessionModeTypes.DistributedAuthority)] - public class NetworkShowHideTests : NetcodeIntegrationTest + [TestFixture(NetworkTopologyTypes.ClientServer)] + [TestFixture(NetworkTopologyTypes.DistributedAuthority)] + internal class NetworkShowHideTests : NetcodeIntegrationTest { protected override int NumberOfClients => 4; @@ -143,7 +143,7 @@ public class NetworkShowHideTests : NetcodeIntegrationTest private NetworkObject m_Object2OnClient0; private NetworkObject m_Object3OnClient0; - public NetworkShowHideTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + public NetworkShowHideTests(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { } protected override void OnServerAndClientsCreated() { diff --git a/Tests/Runtime/NetworkSpawnManagerTests.cs b/Tests/Runtime/NetworkSpawnManagerTests.cs index 63a83db..7835bfe 100644 --- a/Tests/Runtime/NetworkSpawnManagerTests.cs +++ b/Tests/Runtime/NetworkSpawnManagerTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests { [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] - public class NetworkSpawnManagerTests : NetcodeIntegrationTest + internal class NetworkSpawnManagerTests : NetcodeIntegrationTest { private ulong serverSideClientId => NetworkManager.ServerClientId; private ulong clientSideClientId => m_ClientNetworkManagers[0].LocalClientId; @@ -52,7 +52,7 @@ public void TestClientCantAccessServerPlayer() { if (m_DistributedAuthority) { - VerboseDebug($"Ignoring test: Clients have access to other player objects in {m_SessionModeType} mode."); + VerboseDebug($"Ignoring test: Clients have access to other player objects in {m_NetworkTopologyType} mode."); return; } // client can't access server player @@ -77,7 +77,7 @@ public void TestClientCanAccessOtherPlayer() if (!m_DistributedAuthority) { - VerboseDebug($"Ignoring test: Clients do not have access to other player objects in {m_SessionModeType} mode."); + VerboseDebug($"Ignoring test: Clients do not have access to other player objects in {m_NetworkTopologyType} mode."); return; } @@ -90,7 +90,7 @@ public void TestClientCantAccessOtherPlayer() { if (m_DistributedAuthority) { - VerboseDebug($"Ignoring test: Clients have access to other player objects in {m_SessionModeType} mode."); + VerboseDebug($"Ignoring test: Clients have access to other player objects in {m_NetworkTopologyType} mode."); return; } diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformBase.cs b/Tests/Runtime/NetworkTransform/NetworkTransformBase.cs index 9d725e0..da35c76 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformBase.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformBase.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkTransformBase : IntegrationTestWithApproximation + internal class NetworkTransformBase : IntegrationTestWithApproximation { // The number of iterations to change position, rotation, and scale for NetworkTransformMultipleChangesOverTime @@ -731,7 +731,7 @@ private void PrintPositionRotationScaleDeltas() /// /// Helper component for all NetworkTransformTests /// - public class NetworkTransformTestComponent : NetworkTransform + internal class NetworkTransformTestComponent : NetworkTransform { public bool ServerAuthority; public bool ReadyToReceivePositionUpdate = false; @@ -794,7 +794,7 @@ public void CommitToTransform() /// Helper component for NetworkTransform parenting tests when /// a child is a parent of another child (i.e. "sub child") /// - public class SubChildObjectComponent : ChildObjectComponent + internal class SubChildObjectComponent : ChildObjectComponent { protected override bool IsSubChild() { @@ -805,7 +805,7 @@ protected override bool IsSubChild() /// /// Helper component for NetworkTransform parenting tests /// - public class ChildObjectComponent : NetworkTransform + internal class ChildObjectComponent : NetworkTransform { public static int TestCount; public static bool EnableChildLog; diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformGeneral.cs b/Tests/Runtime/NetworkTransform/NetworkTransformGeneral.cs index 17475b1..3a7d0be 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformGeneral.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformGeneral.cs @@ -6,7 +6,7 @@ namespace Unity.Netcode.RuntimeTests { [TestFixture(HostOrServer.Host, Authority.OwnerAuthority)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority)] - public class NetworkTransformGeneral : NetworkTransformBase + internal class NetworkTransformGeneral : NetworkTransformBase { public NetworkTransformGeneral(HostOrServer testWithHost, Authority authority) : base(testWithHost, authority, RotationCompression.None, Rotation.Euler, Precision.Full) @@ -66,7 +66,7 @@ public void TestRotationThresholdDeltaCheck([Values] Interpolation interpolation var halfThreshold = m_AuthoritativeTransform.RotAngleThreshold * 0.5001f; // Apply the current state prior to getting reference rotations which assures we have - // applied the most current rotation deltas and that all bitset flags are updated + // applied the most current rotation deltas and that all bitset flags are updated var results = m_AuthoritativeTransform.ApplyState(); TimeTravelAdvanceTick(); diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs index d6d35f3..8f65f34 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs @@ -12,7 +12,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(HostOrServer.DAHost, MotionModels.UseTransform)] [TestFixture(HostOrServer.DAHost, MotionModels.UseRigidbody)] [TestFixture(HostOrServer.Host, MotionModels.UseTransform)] - public class NetworkTransformOwnershipTests : IntegrationTestWithApproximation + internal class NetworkTransformOwnershipTests : IntegrationTestWithApproximation { public enum MotionModels { @@ -447,7 +447,7 @@ public IEnumerator ServerAuthoritativeTest() /// /// NetworkTransformOwnershipTests helper behaviour /// - public class VerifyObjectIsSpawnedOnClient : NetworkBehaviour + internal class VerifyObjectIsSpawnedOnClient : NetworkBehaviour { public static Dictionary NetworkManagerRelativeSpawnedObjects = new Dictionary(); @@ -512,7 +512,7 @@ public override void OnNetworkDespawn() /// This will have to be used to verify the ownership authority /// [DisallowMultipleComponent] - public class TestClientNetworkTransform : NetworkTransform + internal class TestClientNetworkTransform : NetworkTransform { //public override void OnNetworkSpawn() //{ diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs index 69bf8b1..480905c 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs @@ -26,7 +26,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Half)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Full)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Half)] - public class NetworkTransformPacketLossTests : NetworkTransformBase + internal class NetworkTransformPacketLossTests : NetworkTransformBase { private const int k_Latency = 50; private const int k_PacketLoss = 2; @@ -490,7 +490,7 @@ private void OnAuthorityPushedTransformState(ref NetworkTransform.NetworkTransfo // Match the first position update if (Approximately(m_RandomPosition, networkTransformState.GetPosition())) { - // Teleport to the m_RandomPosition plus the + // Teleport to the m_RandomPosition plus the m_AuthoritativeTransform.SetState(m_TeleportOffset + m_RandomPosition, null, null, false); m_AuthoritativeTransform.AuthorityPushedTransformState -= OnAuthorityPushedTransformState; m_Teleported = true; diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs index 6cbc832..0b47dff 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs @@ -15,7 +15,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(TransformSpace.World, Precision.Half, Rotation.Quaternion)] [TestFixture(TransformSpace.Local, Precision.Full, Rotation.Quaternion)] [TestFixture(TransformSpace.Local, Precision.Half, Rotation.Quaternion)] - public class NetworkTransformStateTests + internal class NetworkTransformStateTests { public enum SyncAxis { diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs index abaac55..7b9ac99 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs @@ -33,7 +33,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(HostOrServer.Host, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Full)] [TestFixture(HostOrServer.Host, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Half)] #endif - public class NetworkTransformTests : NetworkTransformBase + internal class NetworkTransformTests : NetworkTransformBase { protected const int k_TickRate = 60; /// @@ -311,7 +311,7 @@ public void NetworkTransformMultipleChangesOverTime([Values] TransformSpace test Assert.True(WaitForConditionOrTimeOutWithTimeTravel(() => m_AuthoritativeTransform.StatePushed && m_NonAuthoritativeTransform.StateUpdated), $"[Non-Interpolate {i}] Timed out waiting for state to be pushed ({m_AuthoritativeTransform.StatePushed}) or state to be updated ({m_NonAuthoritativeTransform.StateUpdated})!"); // For 3 axis, we will skip validating that the non-authority interpolates to its target point at least once. - // This will validate that non-authoritative updates are maintaining their target state axis values if only 2 + // This will validate that non-authoritative updates are maintaining their target state axis values if only 2 // of the axis are being updated to assure interpolation maintains the targeted axial value per axis. // For 2 and 1 axis tests we always validate per delta update if (m_AxisExcluded || axisCount < 3) diff --git a/Tests/Runtime/NetworkUpdateLoopTests.cs b/Tests/Runtime/NetworkUpdateLoopTests.cs index 97f83c1..06d10d4 100644 --- a/Tests/Runtime/NetworkUpdateLoopTests.cs +++ b/Tests/Runtime/NetworkUpdateLoopTests.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkUpdateLoopTests + internal class NetworkUpdateLoopTests { [Test] public void RegisterCustomLoopInTheMiddle() diff --git a/Tests/Runtime/NetworkVarBufferCopyTest.cs b/Tests/Runtime/NetworkVarBufferCopyTest.cs index c7ee2af..892e70d 100644 --- a/Tests/Runtime/NetworkVarBufferCopyTest.cs +++ b/Tests/Runtime/NetworkVarBufferCopyTest.cs @@ -8,9 +8,9 @@ namespace Unity.Netcode.RuntimeTests { [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] - public class NetworkVarBufferCopyTest : NetcodeIntegrationTest + internal class NetworkVarBufferCopyTest : NetcodeIntegrationTest { - public class DummyNetVar : NetworkVariableBase + internal class DummyNetVar : NetworkVariableBase { private const int k_DummyValue = 0x13579BDF; public bool DeltaWritten; @@ -75,7 +75,7 @@ public DummyNetVar( NetworkVariableWritePermission writePerm = DefaultWritePerm) : base(readPerm, writePerm) { } } - public class DummyNetBehaviour : NetworkBehaviour + internal class DummyNetBehaviour : NetworkBehaviour { public static bool DistributedAuthority; public DummyNetVar NetVar; diff --git a/Tests/Runtime/NetworkVariableTests.cs b/Tests/Runtime/NetworkVariableTests.cs index bc62563..83b4633 100644 --- a/Tests/Runtime/NetworkVariableTests.cs +++ b/Tests/Runtime/NetworkVariableTests.cs @@ -13,7 +13,7 @@ namespace Unity.Netcode.RuntimeTests { [TestFixtureSource(nameof(TestDataSource))] - public class NetworkVariablePermissionTests : NetcodeIntegrationTest + internal class NetworkVariablePermissionTests : NetcodeIntegrationTest { public static IEnumerable TestDataSource() { @@ -304,7 +304,7 @@ public IEnumerator ServerCannotChangeOwnerWritableNetVar() } } - public struct TestStruct : INetworkSerializable, IEquatable + internal struct TestStruct : INetworkSerializable, IEquatable { public uint SomeInt; public bool SomeBool; @@ -344,7 +344,7 @@ public override int GetHashCode() } } - public class TestClass : INetworkSerializable, IEquatable + internal class TestClass : INetworkSerializable, IEquatable { public uint SomeInt; public bool SomeBool; @@ -386,12 +386,12 @@ public override int GetHashCode() // Used just to create a NetworkVariable in the templated NetworkBehaviour type that isn't referenced anywhere else // Please do not reference this class anywhere else! - public class TestClass_ReferencedOnlyByTemplateNetworkBehavourType : TestClass + internal class TestClass_ReferencedOnlyByTemplateNetworkBehavourType : TestClass { } - public class NetworkVariableTest : NetworkBehaviour + internal class NetworkVariableTest : NetworkBehaviour { public enum SomeEnum { @@ -440,7 +440,7 @@ public override void OnNetworkSpawn() [TestFixture(true)] #endif [TestFixture(false)] - public class NetworkVariableTests : NetcodeIntegrationTest + internal class NetworkVariableTests : NetcodeIntegrationTest { private const string k_StringTestValue = "abcdefghijklmnopqrstuvwxyz"; private static readonly FixedString32Bytes k_FixedStringTestValue = k_StringTestValue; @@ -5130,7 +5130,7 @@ protected override IEnumerator OnTearDown() /// that accepts anything derived from the class /// as a parameter. /// - public class NetworkListTestPredicate : ConditionalPredicateBase + internal class NetworkListTestPredicate : ConditionalPredicateBase { private const int k_MaxRandomValue = 1000; @@ -5296,7 +5296,7 @@ public NetworkListTestPredicate(NetworkVariableTest player1OnServer, NetworkVari } [TestFixtureSource(nameof(TestDataSource))] - public class NetworkVariableInheritanceTests : NetcodeIntegrationTest + internal class NetworkVariableInheritanceTests : NetcodeIntegrationTest { public NetworkVariableInheritanceTests(HostOrServer hostOrServer) : base(hostOrServer) @@ -5308,7 +5308,7 @@ public NetworkVariableInheritanceTests(HostOrServer hostOrServer) public static IEnumerable TestDataSource() => Enum.GetValues(typeof(HostOrServer)).OfType().Select(x => new TestFixtureData(x)); - public class ComponentA : NetworkBehaviour + internal class ComponentA : NetworkBehaviour { public NetworkVariable PublicFieldA = new NetworkVariable(1); protected NetworkVariable m_ProtectedFieldA = new NetworkVariable(2); @@ -5329,7 +5329,7 @@ public bool CompareValuesA(ComponentA other) } } - public class ComponentB : ComponentA + internal class ComponentB : ComponentA { public NetworkVariable PublicFieldB = new NetworkVariable(11); protected NetworkVariable m_ProtectedFieldB = new NetworkVariable(22); @@ -5350,7 +5350,7 @@ public bool CompareValuesB(ComponentB other) } } - public class ComponentC : ComponentB + internal class ComponentC : ComponentB { public NetworkVariable PublicFieldC = new NetworkVariable(111); protected NetworkVariable m_ProtectedFieldC = new NetworkVariable(222); @@ -5447,7 +5447,7 @@ public IEnumerator TestInheritedFields() } } - public class NetvarDespawnShutdown : NetworkBehaviour + internal class NetvarDespawnShutdown : NetworkBehaviour { private NetworkVariable m_IntNetworkVariable = new NetworkVariable(); private NetworkList m_IntList; @@ -5475,7 +5475,7 @@ public override void OnNetworkDespawn() /// Validates that setting values for NetworkVariable or NetworkList during the /// OnNetworkDespawn method will not cause an exception to occur. /// - public class NetworkVariableModifyOnNetworkDespawn : NetcodeIntegrationTest + internal class NetworkVariableModifyOnNetworkDespawn : NetcodeIntegrationTest { protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/NetworkVariableTestsHelperTypes.cs b/Tests/Runtime/NetworkVariableTestsHelperTypes.cs index 6f2752c..004de73 100644 --- a/Tests/Runtime/NetworkVariableTestsHelperTypes.cs +++ b/Tests/Runtime/NetworkVariableTestsHelperTypes.cs @@ -5,24 +5,24 @@ namespace Unity.Netcode.RuntimeTests { - public class NetVarPermTestComp : NetworkBehaviour + internal class NetVarPermTestComp : NetworkBehaviour { public NetworkVariable OwnerWritable_Position = new NetworkVariable(Vector3.one, NetworkVariableBase.DefaultReadPerm, NetworkVariableWritePermission.Owner); public NetworkVariable ServerWritable_Position = new NetworkVariable(Vector3.one, NetworkVariableBase.DefaultReadPerm, NetworkVariableWritePermission.Server); public NetworkVariable OwnerReadWrite_Position = new NetworkVariable(Vector3.one, NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Owner); } - public class NetworkVariableMiddleclass : NetworkVariable + internal class NetworkVariableMiddleclass : NetworkVariable { } - public class NetworkVariableSubclass : NetworkVariableMiddleclass + internal class NetworkVariableSubclass : NetworkVariableMiddleclass { } - public class NetworkBehaviourWithNetVarArray : NetworkBehaviour + internal class NetworkBehaviourWithNetVarArray : NetworkBehaviour { public NetworkVariable Int0 = new NetworkVariable(); public NetworkVariable Int1 = new NetworkVariable(); @@ -123,7 +123,7 @@ public void Foo() } } - public struct TemplatedValueOnlyReferencedByNetworkVariableSubclass : INetworkSerializeByMemcpy + internal struct TemplatedValueOnlyReferencedByNetworkVariableSubclass : INetworkSerializeByMemcpy where T : unmanaged { public T Value; @@ -178,7 +178,7 @@ public enum ULongEnum : ulong C = ulong.MaxValue } - public struct HashableNetworkVariableTestStruct : INetworkSerializeByMemcpy, IEquatable + internal struct HashableNetworkVariableTestStruct : INetworkSerializeByMemcpy, IEquatable { public byte A; public short B; @@ -220,7 +220,7 @@ public override int GetHashCode() } } - public struct HashMapKeyStruct : INetworkSerializeByMemcpy, IEquatable + internal struct HashMapKeyStruct : INetworkSerializeByMemcpy, IEquatable { public byte A; public short B; @@ -262,7 +262,7 @@ public override int GetHashCode() } } - public struct HashMapValStruct : INetworkSerializeByMemcpy, IEquatable + internal struct HashMapValStruct : INetworkSerializeByMemcpy, IEquatable { public byte A; public short B; @@ -304,7 +304,7 @@ public override int GetHashCode() } } - public struct NetworkVariableTestStruct : INetworkSerializeByMemcpy + internal struct NetworkVariableTestStruct : INetworkSerializeByMemcpy { public byte A; public short B; @@ -342,7 +342,7 @@ public static NetworkVariableTestStruct GetTestStruct() } - public class HashableNetworkVariableTestClass : INetworkSerializable, IEquatable + internal class HashableNetworkVariableTestClass : INetworkSerializable, IEquatable { public HashableNetworkVariableTestStruct Data; @@ -367,7 +367,7 @@ public void NetworkSerialize(BufferSerializer serializer) where T : IReade } } - public class HashMapKeyClass : INetworkSerializable, IEquatable + internal class HashMapKeyClass : INetworkSerializable, IEquatable { public HashMapKeyStruct Data; @@ -392,7 +392,7 @@ public void NetworkSerialize(BufferSerializer serializer) where T : IReade } } - public class HashMapValClass : INetworkSerializable, IEquatable + internal class HashMapValClass : INetworkSerializable, IEquatable { public HashMapValStruct Data; @@ -417,7 +417,7 @@ public void NetworkSerialize(BufferSerializer serializer) where T : IReade } } - public class NetworkVariableTestClass : INetworkSerializable, IEquatable + internal class NetworkVariableTestClass : INetworkSerializable, IEquatable { public NetworkVariableTestStruct Data; @@ -446,7 +446,7 @@ public void NetworkSerialize(BufferSerializer serializer) where T : IReade // The ILPP code for NetworkVariables to determine how to serialize them relies on them existing as fields of a NetworkBehaviour to find them. // Some of the tests below create NetworkVariables on the stack, so this class is here just to make sure the relevant types are all accounted for. - public class NetVarILPPClassForTests : NetworkBehaviour + internal class NetVarILPPClassForTests : NetworkBehaviour { public NetworkVariable ByteVar; public NetworkVariable> ByteArrayVar; @@ -887,34 +887,34 @@ public class NetVarILPPClassForTests : NetworkBehaviour public NetworkVariableSubclass> SubclassVar; } - public class TemplateNetworkBehaviourType : NetworkBehaviour + internal class TemplateNetworkBehaviourType : NetworkBehaviour { public NetworkVariable TheVar; } - public class IntermediateNetworkBehavior : TemplateNetworkBehaviourType + internal class IntermediateNetworkBehavior : TemplateNetworkBehaviourType { public NetworkVariable TheVar2; } #if !NGO_MINIMALPROJECT - public class ClassHavingNetworkBehaviour : IntermediateNetworkBehavior + internal class ClassHavingNetworkBehaviour : IntermediateNetworkBehavior { } // Please do not reference TestClass_ReferencedOnlyByTemplateNetworkBehavourType anywhere other than here! - public class ClassHavingNetworkBehaviour2 : TemplateNetworkBehaviourType + internal class ClassHavingNetworkBehaviour2 : TemplateNetworkBehaviourType { } - public class StructHavingNetworkBehaviour : TemplateNetworkBehaviourType + internal class StructHavingNetworkBehaviour : TemplateNetworkBehaviourType { } #endif - public struct StructUsedOnlyInNetworkList : IEquatable, INetworkSerializeByMemcpy + internal struct StructUsedOnlyInNetworkList : IEquatable, INetworkSerializeByMemcpy { public int Value; diff --git a/Tests/Runtime/NetworkVariableUserSerializableTypesTests.cs b/Tests/Runtime/NetworkVariableUserSerializableTypesTests.cs index 4cc8811..3c61d92 100644 --- a/Tests/Runtime/NetworkVariableUserSerializableTypesTests.cs +++ b/Tests/Runtime/NetworkVariableUserSerializableTypesTests.cs @@ -9,15 +9,15 @@ namespace Unity.Netcode.RuntimeTests { - public struct MyTypeOne + internal struct MyTypeOne { public int Value; } - public struct MyTypeTwo + internal struct MyTypeTwo { public int Value; } - public struct MyTypeThree + internal struct MyTypeThree { public int Value; } @@ -25,7 +25,7 @@ public struct MyTypeThree /// /// Used to help track instances of any child derived class /// - public class WorkingUserNetworkVariableComponentBase : NetworkBehaviour + internal class WorkingUserNetworkVariableComponentBase : NetworkBehaviour { private static Dictionary s_Instances = new Dictionary(); @@ -68,16 +68,16 @@ public override void OnNetworkDespawn() } } - public class WorkingUserNetworkVariableComponent : WorkingUserNetworkVariableComponentBase + internal class WorkingUserNetworkVariableComponent : WorkingUserNetworkVariableComponentBase { public NetworkVariable NetworkVariable = new NetworkVariable(); } - public class WorkingUserNetworkVariableComponentUsingExtensionMethod : WorkingUserNetworkVariableComponentBase + internal class WorkingUserNetworkVariableComponentUsingExtensionMethod : WorkingUserNetworkVariableComponentBase { public NetworkVariable NetworkVariable = new NetworkVariable(); } - public class NonWorkingUserNetworkVariableComponent : NetworkBehaviour + internal class NonWorkingUserNetworkVariableComponent : NetworkBehaviour { public NetworkVariable NetworkVariable = new NetworkVariable(); } @@ -96,7 +96,7 @@ public static void ReadValueSafe(this FastBufferReader reader, out MyTypeTwo val } } - public class NetworkVariableUserSerializableTypesTests : NetcodeIntegrationTest + internal class NetworkVariableUserSerializableTypesTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/NetworkVisibilityTests.cs b/Tests/Runtime/NetworkVisibilityTests.cs index 037481c..f81eb29 100644 --- a/Tests/Runtime/NetworkVisibilityTests.cs +++ b/Tests/Runtime/NetworkVisibilityTests.cs @@ -7,18 +7,18 @@ namespace Unity.Netcode.RuntimeTests { - [TestFixture(SceneManagementState.SceneManagementEnabled, SessionModeTypes.DistributedAuthority)] - [TestFixture(SceneManagementState.SceneManagementDisabled, SessionModeTypes.DistributedAuthority)] - [TestFixture(SceneManagementState.SceneManagementEnabled, SessionModeTypes.ClientServer)] - [TestFixture(SceneManagementState.SceneManagementDisabled, SessionModeTypes.ClientServer)] - public class NetworkVisibilityTests : NetcodeIntegrationTest + [TestFixture(SceneManagementState.SceneManagementEnabled, NetworkTopologyTypes.DistributedAuthority)] + [TestFixture(SceneManagementState.SceneManagementDisabled, NetworkTopologyTypes.DistributedAuthority)] + [TestFixture(SceneManagementState.SceneManagementEnabled, NetworkTopologyTypes.ClientServer)] + [TestFixture(SceneManagementState.SceneManagementDisabled, NetworkTopologyTypes.ClientServer)] + internal class NetworkVisibilityTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; private GameObject m_TestNetworkPrefab; private bool m_SceneManagementEnabled; - public NetworkVisibilityTests(SceneManagementState sceneManagementState, SessionModeTypes sessionModeType) : base(sessionModeType) + public NetworkVisibilityTests(SceneManagementState sceneManagementState, NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { m_SceneManagementEnabled = sceneManagementState == SceneManagementState.SceneManagementEnabled; } diff --git a/Tests/Runtime/OwnerModifiedTests.cs b/Tests/Runtime/OwnerModifiedTests.cs index 6de84b1..3a925b9 100644 --- a/Tests/Runtime/OwnerModifiedTests.cs +++ b/Tests/Runtime/OwnerModifiedTests.cs @@ -12,7 +12,7 @@ namespace Unity.Netcode.RuntimeTests // Where the NetworkVariable updates would be repeated on some clients. // The twist comes fom the updates needing to happens very specifically for the issue to repro in tests - public class OwnerModifiedObject : NetworkBehaviour, INetworkUpdateSystem + internal class OwnerModifiedObject : NetworkBehaviour, INetworkUpdateSystem { public NetworkList MyNetworkList; @@ -76,7 +76,7 @@ public void InitializeLastCient() [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] - public class OwnerModifiedTests : NetcodeIntegrationTest + internal class OwnerModifiedTests : NetcodeIntegrationTest { protected override int NumberOfClients => 2; diff --git a/Tests/Runtime/OwnerPermissionTests.cs b/Tests/Runtime/OwnerPermissionTests.cs index 5f8501d..8ff4098 100644 --- a/Tests/Runtime/OwnerPermissionTests.cs +++ b/Tests/Runtime/OwnerPermissionTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests { - public class OwnerPermissionObject : NetworkBehaviour + internal class OwnerPermissionObject : NetworkBehaviour { // indexed by [object, machine] public static OwnerPermissionObject[,] Objects = new OwnerPermissionObject[3, 3]; @@ -85,7 +85,7 @@ public void ListServerChanged(NetworkListEvent listEvent) } } - public class OwnerPermissionHideTests : NetcodeIntegrationTest + internal class OwnerPermissionHideTests : NetcodeIntegrationTest { protected override int NumberOfClients => 2; diff --git a/Tests/Runtime/PeerDisconnectCallbackTests.cs b/Tests/Runtime/PeerDisconnectCallbackTests.cs index f78dbf6..896aa90 100644 --- a/Tests/Runtime/PeerDisconnectCallbackTests.cs +++ b/Tests/Runtime/PeerDisconnectCallbackTests.cs @@ -21,7 +21,7 @@ namespace Unity.Netcode.RuntimeTests /// [TestFixture(HostOrServer.Server)] [TestFixture(HostOrServer.Host)] - public class PeerDisconnectCallbackTests : NetcodeIntegrationTest + internal class PeerDisconnectCallbackTests : NetcodeIntegrationTest { public enum ClientDisconnectType diff --git a/Tests/Runtime/Physics/NetworkRigidbody2DTest.cs b/Tests/Runtime/Physics/NetworkRigidbody2DTest.cs index f92cab9..089eeee 100644 --- a/Tests/Runtime/Physics/NetworkRigidbody2DTest.cs +++ b/Tests/Runtime/Physics/NetworkRigidbody2DTest.cs @@ -8,12 +8,12 @@ namespace Unity.Netcode.RuntimeTests { - public class NetworkRigidbody2DDynamicTest : NetworkRigidbody2DTestBase + internal class NetworkRigidbody2DDynamicTest : NetworkRigidbody2DTestBase { public override bool Kinematic => false; } - public class NetworkRigidbody2DKinematicTest : NetworkRigidbody2DTestBase + internal class NetworkRigidbody2DKinematicTest : NetworkRigidbody2DTestBase { public override bool Kinematic => true; } diff --git a/Tests/Runtime/Physics/NetworkRigidbodyTest.cs b/Tests/Runtime/Physics/NetworkRigidbodyTest.cs index 0a68e0d..9ec32bc 100644 --- a/Tests/Runtime/Physics/NetworkRigidbodyTest.cs +++ b/Tests/Runtime/Physics/NetworkRigidbodyTest.cs @@ -13,7 +13,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(RigidbodyInterpolation.Extrapolate, false, true)] // This should allow extrapolation on non-auth instances when using Rigidbody & NT has no interpolation [TestFixture(RigidbodyInterpolation.Interpolate, true, false)] // This should not allow kinematic instances to have Rigidbody interpolation enabled [TestFixture(RigidbodyInterpolation.Interpolate, false, false)] // Testing that rigid body interpolation remains the same if NT interpolate is disabled - public class NetworkRigidbodyTest : NetcodeIntegrationTest + internal class NetworkRigidbodyTest : NetcodeIntegrationTest { protected override int NumberOfClients => 1; private bool m_NetworkTransformInterpolate; diff --git a/Tests/Runtime/PlayerObjectTests.cs b/Tests/Runtime/PlayerObjectTests.cs index 2543c4d..8fba758 100644 --- a/Tests/Runtime/PlayerObjectTests.cs +++ b/Tests/Runtime/PlayerObjectTests.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] - public class PlayerObjectTests : NetcodeIntegrationTest + internal class PlayerObjectTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/Profiling/NetworkVariableNameTests.cs b/Tests/Runtime/Profiling/NetworkVariableNameTests.cs index 25d2e3b..1ec8333 100644 --- a/Tests/Runtime/Profiling/NetworkVariableNameTests.cs +++ b/Tests/Runtime/Profiling/NetworkVariableNameTests.cs @@ -4,7 +4,7 @@ namespace Unity.Netcode.RuntimeTests { - public sealed class NetworkVariableNameTests + internal sealed class NetworkVariableNameTests { private NetworkVariableNameComponent m_NetworkVariableNameComponent; diff --git a/Tests/Runtime/RpcManyClientsTests.cs b/Tests/Runtime/RpcManyClientsTests.cs index 40de8a1..5af6daa 100644 --- a/Tests/Runtime/RpcManyClientsTests.cs +++ b/Tests/Runtime/RpcManyClientsTests.cs @@ -7,7 +7,7 @@ namespace Unity.Netcode.RuntimeTests { - public class RpcManyClientsObject : NetworkBehaviour + internal class RpcManyClientsObject : NetworkBehaviour { public int Count = 0; public List ReceivedFrom = new List(); @@ -43,7 +43,7 @@ public void WithParamsClientRpc(ClientRpcParams param) } } - public class RpcManyClientsTests : NetcodeIntegrationTest + internal class RpcManyClientsTests : NetcodeIntegrationTest { protected override int NumberOfClients => 10; diff --git a/Tests/Runtime/RpcQueueTests.cs b/Tests/Runtime/RpcQueueTests.cs index dfa5f5e..5d7775f 100644 --- a/Tests/Runtime/RpcQueueTests.cs +++ b/Tests/Runtime/RpcQueueTests.cs @@ -13,7 +13,7 @@ namespace Unity.Netcode.RuntimeTests /// - That all RPCs invoke at the appropriate `NetworkUpdateStage` (Client and Server) /// - A lower level `MessageQueueContainer` test that validates `MessageQueueFrameItems` after they have been put into the queue /// - public class RpcQueueTests + internal class RpcQueueTests { [SetUp] public void Setup() diff --git a/Tests/Runtime/RpcTests.cs b/Tests/Runtime/RpcTests.cs index ecb9337..23c546e 100644 --- a/Tests/Runtime/RpcTests.cs +++ b/Tests/Runtime/RpcTests.cs @@ -9,14 +9,14 @@ namespace Unity.Netcode.RuntimeTests { - public class RpcTests : NetcodeIntegrationTest + internal class RpcTests : NetcodeIntegrationTest { - public class CompileTimeNoRpcsBaseClassTest : NetworkBehaviour + internal class CompileTimeNoRpcsBaseClassTest : NetworkBehaviour { } - public class CompileTimeHasRpcsChildClassDerivedFromNoRpcsBaseClassTest : CompileTimeNoRpcsBaseClassTest + internal class CompileTimeHasRpcsChildClassDerivedFromNoRpcsBaseClassTest : CompileTimeNoRpcsBaseClassTest { [ServerRpc] public void SomeDummyServerRpc() @@ -25,7 +25,7 @@ public void SomeDummyServerRpc() } } - public class GenericRpcTestNB : NetworkBehaviour where T : unmanaged + internal class GenericRpcTestNB : NetworkBehaviour where T : unmanaged { public event Action OnServer_Rpc; @@ -36,11 +36,11 @@ public void MyServerRpc(T clientId, ServerRpcParams param = default) } } - public class RpcTestNBFloat : GenericRpcTestNB + internal class RpcTestNBFloat : GenericRpcTestNB { } - public class RpcTestNB : GenericRpcTestNB + internal class RpcTestNB : GenericRpcTestNB { #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT public event Action, ServerRpcParams> OnNativeListServer_Rpc; diff --git a/Tests/Runtime/RpcTypeSerializationTests.cs b/Tests/Runtime/RpcTypeSerializationTests.cs index 3d57e4d..8da15cc 100644 --- a/Tests/Runtime/RpcTypeSerializationTests.cs +++ b/Tests/Runtime/RpcTypeSerializationTests.cs @@ -14,14 +14,14 @@ namespace Unity.Netcode.RuntimeTests { - public class RpcTypeSerializationTests : NetcodeIntegrationTest + internal class RpcTypeSerializationTests : NetcodeIntegrationTest { public RpcTypeSerializationTests() { m_UseHost = false; } - public class RpcTestNB : NetworkBehaviour + internal class RpcTestNB : NetworkBehaviour { public delegate void OnReceivedDelegate(object obj); public OnReceivedDelegate OnReceived; diff --git a/Tests/Runtime/Serialization/NetworkBehaviourReferenceTests.cs b/Tests/Runtime/Serialization/NetworkBehaviourReferenceTests.cs index 472d617..c3f63b9 100644 --- a/Tests/Runtime/Serialization/NetworkBehaviourReferenceTests.cs +++ b/Tests/Runtime/Serialization/NetworkBehaviourReferenceTests.cs @@ -13,7 +13,7 @@ namespace Unity.Netcode.RuntimeTests /// - Deserializing NetworkObjectReference to NetworkObject /// - Implicit operators of NetworkObjectReference /// - public class NetworkBehaviourReferenceTests : IDisposable + internal class NetworkBehaviourReferenceTests : IDisposable { private class TestNetworkBehaviour : NetworkBehaviour { @@ -156,7 +156,7 @@ public NetworkBehaviourReferenceTests() /// /// Integration tests for NetworkBehaviourReference /// - public class NetworkBehaviourReferenceIntegrationTests : NetcodeIntegrationTest + internal class NetworkBehaviourReferenceIntegrationTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/Serialization/NetworkObjectReferenceTests.cs b/Tests/Runtime/Serialization/NetworkObjectReferenceTests.cs index 8b29d17..084e4d5 100644 --- a/Tests/Runtime/Serialization/NetworkObjectReferenceTests.cs +++ b/Tests/Runtime/Serialization/NetworkObjectReferenceTests.cs @@ -15,7 +15,7 @@ namespace Unity.Netcode.RuntimeTests /// - Deserializing NetworkObjectReference to NetworkObject /// - Implicit operators of NetworkObjectReference /// - public class NetworkObjectReferenceTests : IDisposable + internal class NetworkObjectReferenceTests : IDisposable { private class TestNetworkBehaviour : NetworkBehaviour { @@ -340,7 +340,7 @@ public NetworkObjectReferenceTests() /// Helper method for tests to create and destroy Unity Objects. /// /// The type of Object this context incorporates. - public class UnityObjectContext : UnityObjectContext where T : Object + internal class UnityObjectContext : UnityObjectContext where T : Object { private T m_Object; @@ -353,7 +353,7 @@ internal UnityObjectContext(T unityObject, Object root) public T Object => m_Object; } - public class UnityObjectContext : IDisposable + internal class UnityObjectContext : IDisposable { private Object m_Root; diff --git a/Tests/Runtime/StartStopTests.cs b/Tests/Runtime/StartStopTests.cs index 403404d..bb928e1 100644 --- a/Tests/Runtime/StartStopTests.cs +++ b/Tests/Runtime/StartStopTests.cs @@ -3,7 +3,7 @@ namespace Unity.Netcode.RuntimeTests { - public class StartStopTests + internal class StartStopTests { private NetworkManager m_NetworkManager; diff --git a/Tests/Runtime/StopStartRuntimeTests.cs b/Tests/Runtime/StopStartRuntimeTests.cs index 8d52f1f..8ec1c37 100644 --- a/Tests/Runtime/StopStartRuntimeTests.cs +++ b/Tests/Runtime/StopStartRuntimeTests.cs @@ -5,7 +5,7 @@ namespace Unity.Netcode.RuntimeTests { - public class StopStartRuntimeTests : NetcodeIntegrationTest + internal class StopStartRuntimeTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/Timing/NetworkTimeSystemTests.cs b/Tests/Runtime/Timing/NetworkTimeSystemTests.cs index 047435f..c38bc86 100644 --- a/Tests/Runtime/Timing/NetworkTimeSystemTests.cs +++ b/Tests/Runtime/Timing/NetworkTimeSystemTests.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode.RuntimeTests /// /// Runtime tests to test the network time system with the Unity player loop. /// - public class NetworkTimeSystemTests + internal class NetworkTimeSystemTests { private MonoBehaviourTest m_PlayerLoopFixedTimeTestComponent; // cache for teardown private MonoBehaviourTest m_PlayerLoopTimeTestComponent; // cache for teardown @@ -117,7 +117,7 @@ public void TearDown() } } - public class PlayerLoopFixedTimeTestComponent : MonoBehaviour, IMonoBehaviourTest + internal class PlayerLoopFixedTimeTestComponent : MonoBehaviour, IMonoBehaviourTest { public const int Passes = 100; @@ -184,7 +184,7 @@ private void FixedUpdate() public bool IsTestFinished => m_UpdatePasses >= Passes; } - public class PlayerLoopTimeTestComponent : MonoBehaviour, IMonoBehaviourTest + internal class PlayerLoopTimeTestComponent : MonoBehaviour, IMonoBehaviourTest { public const int Passes = 100; diff --git a/Tests/Runtime/Timing/TimeInitializationTest.cs b/Tests/Runtime/Timing/TimeInitializationTest.cs index fe7d935..5d8f39c 100644 --- a/Tests/Runtime/Timing/TimeInitializationTest.cs +++ b/Tests/Runtime/Timing/TimeInitializationTest.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests /// /// Tests that the time and tick system are initialized properly /// - public class TimeInitializationTest + internal class TimeInitializationTest { private int m_ClientTickCounter; private int m_ConnectedTick; diff --git a/Tests/Runtime/Timing/TimeIntegrationTest.cs b/Tests/Runtime/Timing/TimeIntegrationTest.cs index e019bb2..f6f8147 100644 --- a/Tests/Runtime/Timing/TimeIntegrationTest.cs +++ b/Tests/Runtime/Timing/TimeIntegrationTest.cs @@ -11,7 +11,7 @@ namespace Unity.Netcode.RuntimeTests /// /// Tests the times of two clients connecting to a server using the SIPTransport (returns 50ms RTT but has no latency simulation) /// - public class TimeIntegrationTest : NetcodeIntegrationTest + internal class TimeIntegrationTest : NetcodeIntegrationTest { private const double k_AdditionalTimeTolerance = 0.3333d; // magic number and in theory not needed but without this mac os test fail in Yamato because it looks like we get random framerate drops during unit test. diff --git a/Tests/Runtime/TransformInterpolationTests.cs b/Tests/Runtime/TransformInterpolationTests.cs index ac64d2c..9c402ef 100644 --- a/Tests/Runtime/TransformInterpolationTests.cs +++ b/Tests/Runtime/TransformInterpolationTests.cs @@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests { - public class TransformInterpolationObject : NetworkTransform + internal class TransformInterpolationObject : NetworkTransform { public static bool TestComplete = false; // Set the minimum threshold which we will use as our margin of error @@ -63,9 +63,9 @@ public void StopMoving() private const int k_MaxThresholdFailures = 4; private int m_ExceededThresholdCount; - protected override void Update() + private void Update() { - base.Update(); + base.OnUpdate(); if (!IsSpawned || TestComplete) { @@ -140,7 +140,7 @@ protected override void Update() } } - public class TransformInterpolationTests : NetcodeIntegrationTest + internal class TransformInterpolationTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; diff --git a/Tests/Runtime/Transports/UnityTransportConnectionTests.cs b/Tests/Runtime/Transports/UnityTransportConnectionTests.cs index 8effb70..ac4c089 100644 --- a/Tests/Runtime/Transports/UnityTransportConnectionTests.cs +++ b/Tests/Runtime/Transports/UnityTransportConnectionTests.cs @@ -10,7 +10,7 @@ namespace Unity.Netcode.RuntimeTests { - public class UnityTransportConnectionTests + internal class UnityTransportConnectionTests { // For tests using multiple clients. private const int k_NumClients = 5; @@ -208,7 +208,7 @@ public IEnumerator ClientDisconnectMultipleClients() m_Clients[i].DisconnectLocalClient(); } - yield return WaitForNetworkEvent(NetworkEvent.Disconnect, m_ServerEvents); + yield return WaitForNetworkEvent(NetworkEvent.Disconnect, m_ServerEvents, 5); // Check that we got the correct number of Disconnect events on the server. Assert.AreEqual(k_NumClients * 2, m_ServerEvents.Count); diff --git a/Tests/Runtime/Transports/UnityTransportDriverClient.cs b/Tests/Runtime/Transports/UnityTransportDriverClient.cs index e2d6ef1..ef8ca26 100644 --- a/Tests/Runtime/Transports/UnityTransportDriverClient.cs +++ b/Tests/Runtime/Transports/UnityTransportDriverClient.cs @@ -15,7 +15,7 @@ namespace Unity.Netcode.RuntimeTests // The only reason it's defined as a MonoBehaviour is that OnDestroy is the only reliable way // to get the driver's Dispose method called from a UnityTest. Making it disposable would be // the preferred solution, but that doesn't always mesh well with coroutines. - public class UnityTransportDriverClient : MonoBehaviour + internal class UnityTransportDriverClient : MonoBehaviour { private NetworkDriver m_Driver; public NetworkDriver Driver => m_Driver; diff --git a/Tests/Runtime/Transports/UnityTransportTestHelpers.cs b/Tests/Runtime/Transports/UnityTransportTestHelpers.cs index 75144f6..62ae2b5 100644 --- a/Tests/Runtime/Transports/UnityTransportTestHelpers.cs +++ b/Tests/Runtime/Transports/UnityTransportTestHelpers.cs @@ -8,7 +8,7 @@ namespace Unity.Netcode.RuntimeTests { - public static class UnityTransportTestHelpers + internal static class UnityTransportTestHelpers { // Half a second might seem like a very long time to wait for a network event, but in CI // many of the machines are underpowered (e.g. old Android devices or Macs) and there are @@ -59,7 +59,7 @@ public static void InitializeTransport(out UnityTransport transport, out List m_Events = new List(); public List Events => m_Events; diff --git a/Tests/Runtime/Transports/UnityTransportTests.cs b/Tests/Runtime/Transports/UnityTransportTests.cs index d2dcddf..4a14206 100644 --- a/Tests/Runtime/Transports/UnityTransportTests.cs +++ b/Tests/Runtime/Transports/UnityTransportTests.cs @@ -12,7 +12,7 @@ namespace Unity.Netcode.RuntimeTests { - public class UnityTransportTests + internal class UnityTransportTests { // No need to test all reliable delivery methods since they all map to the same pipeline. private static readonly NetworkDelivery[] k_DeliveryParameters = diff --git a/Tests/Runtime/UniversalRpcTests.cs b/Tests/Runtime/UniversalRpcTests.cs index a756bd7..3aeb06d 100644 --- a/Tests/Runtime/UniversalRpcTests.cs +++ b/Tests/Runtime/UniversalRpcTests.cs @@ -19,7 +19,7 @@ // I put them in their own namespace so they would be easier to navigate in the test list. namespace Unity.Netcode.RuntimeTests.UniversalRpcTests { - public class UniversalRpcNetworkBehaviour : NetworkBehaviour + internal class UniversalRpcNetworkBehaviour : NetworkBehaviour { public bool Stop = false; public string Received = string.Empty; @@ -534,7 +534,7 @@ public void SelfRecursiveRpc() } } - public class UniversalRpcTestsBase : NetcodeIntegrationTest + internal class UniversalRpcTestsBase : NetcodeIntegrationTest { protected override int NumberOfClients => 2; diff --git a/package.json b/package.json index 075b69c..25d5f00 100644 --- a/package.json +++ b/package.json @@ -2,23 +2,23 @@ "name": "com.unity.netcode.gameobjects", "displayName": "Netcode for GameObjects", "description": "Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.", - "version": "2.0.0-exp.2", + "version": "2.0.0-exp.4", "unity": "6000.0", "dependencies": { "com.unity.nuget.mono-cecil": "1.11.4", "com.unity.transport": "2.2.1" }, "_upm": { - "changelog": "### Added\n- Added updates to all internal messages to account for a distributed authority network session connection. (#2863)\n- 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)\n - For a customized `NetworkRigidbodyBase` class:\n - `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes.\n - `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned.\n - `NetworkRigidbodyBase.Initialize` is a protected method that, when invoked, will initialize the instance. This includes options to:\n - Set whether using a `RigidbodyTypes.Rigidbody` or `RigidbodyTypes.Rigidbody2D`.\n - Includes additional optional parameters to set the `NetworkTransform`, `Rigidbody`, and `Rigidbody2d` to use.\n - Provides additional public methods:\n - `NetworkRigidbodyBase.GetPosition` to return the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.GetRotation` to return the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.MovePosition` to move to the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.MoveRotation` to move to the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.SetPosition` to set the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.SetRotation` to set the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.ApplyCurrentTransform` to set the position and rotation of the `Rigidbody` or `Rigidbody2d` based on the associated `GameObject` transform (depending upon its initialized setting).\n - `NetworkRigidbodyBase.WakeIfSleeping` to wake up the rigid body if sleeping.\n - `NetworkRigidbodyBase.SleepRigidbody` to put the rigid body to sleep.\n - `NetworkRigidbodyBase.IsKinematic` to determine if the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) is currently kinematic.\n - `NetworkRigidbodyBase.SetIsKinematic` to set the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) current kinematic state.\n - `NetworkRigidbodyBase.ResetInterpolation` to reset the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) back to its original interpolation value when initialized.\n - Now includes a `MonoBehaviour.FixedUpdate` implementation that will update the assigned `NetworkTransform` when `NetworkRigidbodyBase.UseRigidBodyForMotion` is true. (#2863)\n- Added `RigidbodyContactEventManager` that provides a more optimized way to process collision enter and collision stay events as opposed to the `Monobehaviour` approach. (#2863)\n - Can be used in client-server and distributed authority modes, but is particularly useful in distributed authority.\n- Added rigid body motion updates to `NetworkTransform` which allows users to set interolation on rigid bodies. (#2863)\n - Extrapolation is only allowed on authoritative instances, but custom class derived from `NetworkRigidbodyBase` or `NetworkRigidbody` or `NetworkRigidbody2D` automatically switches non-authoritative instances to interpolation if set to extrapolation.\n- Added distributed authority mode support to `NetworkAnimator`. (#2863)\n- Added session mode selection to `NetworkManager` inspector view. (#2863)\n- Added distributed authority permissions feature. (#2863)\n- Added distributed authority mode specific `NetworkObject` permissions flags (Distributable, Transferable, and RequestRequired). (#2863)\n- Added distributed authority mode specific `NetworkObject.SetOwnershipStatus` method that applies one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863)\n- Added distributed authority mode specific `NetworkObject.RemoveOwnershipStatus` method that removes one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863)\n- Added distributed authority mode specific `NetworkObject.HasOwnershipStatus` method that will return (true or false) whether one or more ownership flags is set. (#2863)\n- Added distributed authority mode specific `NetworkObject.SetOwnershipLock` method that locks ownership of a `NetworkObject` to prevent ownership from changing until the current owner releases the lock. (#2863)\n- Added distributed authority mode specific `NetworkObject.RequestOwnership` method that sends an ownership request to the current owner of a spawned `NetworkObject` instance. (#2863)\n- Added distributed authority mode specific `NetworkObject.OnOwnershipRequested` callback handler that is invoked on the owner/authoritative side when a non-owner requests ownership. Depending upon the boolean returned value depends upon whether the request is approved or denied. (#2863)\n- Added distributed authority mode specific `NetworkObject.OnOwnershipRequestResponse` callback handler that is invoked when a non-owner's request has been processed. This callback includes a `NetworkObjet.OwnershipRequestResponseStatus` response parameter that describes whether the request was approved or the reason why it was not approved. (#2863)\n- Added distributed authority mode specific `NetworkObject.DeferDespawn` method that defers the despawning of `NetworkObject` instances on non-authoritative clients based on the tick offset parameter. (#2863)\n- Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863)\n- Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863)\n- Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863)\n- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is authomatically the owner of the spawned object). (#2863)\n - This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example).\n- Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863)\n- Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863)\n- Added distributed authority mode specific `NetworkManager.OnFetchLocalPlayerPrefabToSpawn` callback that, when assigned, will allow the local client to provide the player prefab to be spawned for the local client. (#2863)\n - This is only invoked if the `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property is set to true.\n- Added distributed authority mode specific `NetworkBehaviour.HasAuthority` property that determines if the local client has authority over the associated `NetworkObject` instance (typical use case is within a `NetworkBehaviour` script much like that of `IsServer` or `IsClient`). (#2863)\n- Added distributed authority mode specific `NetworkBehaviour.IsSessionOwner` property that determines if the local client is the session owner (typical use case would be to determine if the local client can has scene management authority within a `NetworkBehaviour` script). (#2863)\n- Added support for distributed authority mode scene management where the currently assigned session owner can start scene events (i.e. scene loading and scene unloading). (#2863)\n\n### Fixed\n\n- Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822)\n- Fixed issue where NetworkTransform could potentially attempt to \"unregister\" a named message prior to it being registered. (#2807)\n- Fixed issue where in-scene placed `NetworkObject`s with complex nested children `NetworkObject`s (more than one child in depth) would not synchronize properly if WorldPositionStays was set to true. (#2796)\n\n### Changed\n- Changed client side awareness of other clients is now the same as a server or host. (#2863)\n- Changed `NetworkManager.ConnectedClients` can now be accessed by both server and clients. (#2863)\n- Changed `NetworkManager.ConnectedClientsList` can now be accessed by both server and clients. (#2863)\n- Changed `NetworkTransform` defaults to owner authoritative when connected to a distributed authority session. (#2863)\n- Changed `NetworkVariable` defaults to owner write and everyone read permissions when connected to a distributed authority session (even if declared with server read or write permissions). (#2863)\n- Changed `NetworkObject` no longer implements the `MonoBehaviour.Update` method in order to determine whether a `NetworkObject` instance has been migrated to a different scene. Instead, only `NetworkObjects` with the `SceneMigrationSynchronization` property set will be updated internally during the `NetworkUpdateStage.PostLateUpdate` by `NetworkManager`. (#2863)\n- Changed `NetworkManager` inspector view layout where properties are now organized by category. (#2863)\n- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)\n- Changed `CustomMessageManager` so it no longer attempts to register or \"unregister\" a null or empty string and will log an error if this condition occurs. (#2807)" + "changelog": "### Added\n\n- Added `NetworkRigidbodyBase.AttachToFixedJoint` and `NetworkRigidbodyBase.DetachFromFixedJoint` to replace parenting for rigid bodies that have `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled. (#2933)\n- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2912)\n- Added a client-side only `NetworkBehaviour.OnNetworkSessionSynchronized` convenience method that is invoked on all `NetworkBehaviour`s after a newly joined client has finished synchronizing with the network session in progress. (#2912)\n- Added `NetworkBehaviour.OnInSceneObjectsSpawned` convenience method that is invoked when all in-scene `NetworkObject`s have been spawned after a scene has been loaded or upon a host or server starting. (#2912)\n\n### Fixed\n\n- Fixed issue where non-authoritative rigid bodies with `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled would constantly log errors about the renderTime being before `StartTimeConsumed`. (#2933)\n- Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2924)\n- Fixed issue where a `NetworkObject` component's associated `NetworkBehaviour` components would not be detected if scene loading is disabled in the editor and the currently loaded scene has in-scene placed `NetworkObject`s. (#2912)\n- Fixed issue where an in-scene placed `NetworkObject` with `NetworkTransform` that is also parented under a `GameObject` would not properly synchronize when the parent `GameObject` had a world space position other than 0,0,0. (#2898)\n\n### Changed\n\n- Change all the access modifiers of test class from Public to Internal (#2930)\n- Changed messages are now sorted by enum values as opposed to ordinally sorting the messages by their type name. (#2929)\n- Changed `NetworkClient.SessionModeTypes` to `NetworkClient.NetworkTopologyTypes`. (#2875)\n- Changed `NetworkClient.SessionModeType` to `NetworkClient.NetworkTopologyType`. (#2875)\n- Changed `NetworkConfig.SessionMode` to `NeworkConfig.NetworkTopology`. (#2875)" }, "upmCi": { - "footprint": "30b58dd41527f0745f60a544f04a338712651b16" + "footprint": "3e5693a7baed1b97a205035203bc4da81af55612" }, "documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.0/manual/index.html", "repository": { "url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git", "type": "git", - "revision": "e7ac3c896eea828bced614363711b80dcad4d570" + "revision": "f4917e9cb719980bf229a71484d6f5467a2ad4e0" }, "samples": [ {