5 Commits

Author SHA1 Message Date
Unity Technologies
48c6a6121c com.unity.netcode.gameobjects@2.0.0
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).

## [2.0.0] - 2024-09-12

### Added

- Added tooltips for all of the `NetworkObject` component's properties. (#3052)
- Added message size validation to named and unnamed message sending functions for better error messages. (#3049)
- Added "Check for NetworkObject Component" property to the Multiplayer->Netcode for GameObjects project settings. When disabled, this will bypass the in-editor `NetworkObject` check on `NetworkBehaviour` components. (#3031)
- Added `NetworkTransform.SwitchTransformSpaceWhenParented` property that, when enabled, will handle the world to local, local to world, and local to local transform space transitions when interpolation is enabled. (#3013)
- Added `NetworkTransform.TickSyncChildren` that, when enabled, will tick synchronize nested and/or child `NetworkTransform` components to eliminate any potential visual jittering that could occur if the `NetworkTransform` instances get into a state where their state updates are landing on different network ticks. (#3013)
- Added `NetworkObject.AllowOwnerToParent` property to provide the ability to allow clients to parent owned objects when running in a client-server network topology. (#3013)
- Added `NetworkObject.SyncOwnerTransformWhenParented` property to provide a way to disable applying the server's transform information in the parenting message on the client owner instance which can be useful for owner authoritative motion models. (#3013)
- Added `NetcodeEditorBase` editor helper class to provide easier modification and extension of the SDK's components. (#3013)

### Fixed

- Fixed issue where `NetworkAnimator` would send updates to non-observer clients. (#3057)
- Fixed issue where an exception could occur when receiving a universal RPC for a `NetworkObject` that has been despawned. (#3052)
- Fixed issue where a NetworkObject hidden from a client that is then promoted to be session owner was not being synchronized with newly joining clients.(#3051)
- Fixed issue where clients could have a wrong time delta on `NetworkVariableBase` which could prevent from sending delta state updates. (#3045)
- Fixed issue where setting a prefab hash value during connection approval but not having a player prefab assigned could cause an exception when spawning a player. (#3042)
- Fixed issue where the `NetworkSpawnManager.HandleNetworkObjectShow` could throw an exception if one of the `NetworkObject` components to show was destroyed during the same frame. (#3030)
- Fixed issue where the `NetworkManagerHelper` was continuing to check for hierarchy changes when in play mode. (#3026)
- Fixed issue with newly/late joined clients and `NetworkTransform` synchronization of parented `NetworkObject` instances. (#3013)
- Fixed issue with smooth transitions between transform spaces when interpolation is enabled (requires `NetworkTransform.SwitchTransformSpaceWhenParented` to be enabled). (#3013)

### Changed

- Changed `NetworkTransformEditor` now uses `NetworkTransform` as the base type class to assure it doesn't display a foldout group when using the base `NetworkTransform` component class. (#3052)
- Changed `NetworkAnimator.Awake` is now a protected virtual method. (#3052)
- Changed  when invoking `NetworkManager.ConnectionManager.DisconnectClient` during a distributed authority session a more appropriate message is logged. (#3052)
- Changed `NetworkTransformEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkRigidbodyBaseEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkManagerEditor` so it now derives from `NetcodeEditorBase`. (#3013)
2024-09-12 00:00:00 +00:00
Unity Technologies
eab996f3ac com.unity.netcode.gameobjects@2.0.0-pre.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-pre.4] - 2024-08-21

### Added

- Added `NetworkVariable.CheckDirtyState` that is to be used in tandem with collections in order to detect whether the collection or an item within the collection has changed. (#3004)

### Fixed

- Fixed issue where nested `NetworkTransform` components were not getting updated. (#3016)
- Fixed issue by adding null checks in `NetworkVariableBase.CanClientRead` and `NetworkVariableBase.CanClientWrite` methods to ensure safe access to `NetworkBehaviour`. (#3012)
- Fixed issue where `FixedStringSerializer<T>` was using `NetworkVariableSerialization<byte>.AreEqual` to determine if two bytes were equal causes an exception to be thrown due to no byte serializer having been defined. (#3009)
- Fixed Issue where a state with dual triggers, inbound and outbound, could cause a false layer to layer state transition message to be sent to non-authority `NetworkAnimator` instances and cause a warning message to be logged. (#3008)
- Fixed issue using collections within `NetworkVariable` where the collection would not detect changes to items or nested items. (#3004)
- Fixed issue where `List`, `Dictionary`, and `HashSet` collections would not uniquely duplicate nested collections. (#3004)
- Fixed issue where `NotAuthorityTarget` would include the service observer in the list of targets to send the RPC to as opposed to excluding the service observer as it should. (#3000)
- Fixed issue where `ProxyRpcTargetGroup` could attempt to send a message if there were no targets to send to. (#3000)

### Changed

- Changed `NetworkAnimator` to automatically switch to owner authoritative mode when using a distributed authority network topology. (#3021)
- Changed permissions exception thrown in `NetworkList` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
- Changed permissions exception thrown in `NetworkVariable.Value` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
2024-08-21 00:00:00 +00:00
Unity Technologies
a813ba0dd6 com.unity.netcode.gameobjects@2.0.0-pre.3
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-pre.3] - 2024-07-23

### Added
- Added: `UnityTransport.GetNetworkDriver` and `UnityTransport.GetLocalEndpoint` methods to expose the driver and local endpoint being used. (#2978)

### Fixed

- Fixed issue where deferred despawn was causing GC allocations when converting an `IEnumerable` to a list. (#2983)
- Fixed issue where the realtime network stats monitor was not able to display RPC traffic in release builds due to those stats being only available in development builds or the editor. (#2979)
- Fixed issue where `NetworkManager.ScenesLoaded` was not being updated if `PostSynchronizationSceneUnloading` was set and any loaded scenes not used during synchronization were unloaded. (#2971)
- Fixed issue where `Rigidbody2d` under Unity 6000.0.11f1 has breaking changes where `velocity` is now `linearVelocity` and `isKinematic` is replaced by `bodyType`. (#2971)
- Fixed issue where `NetworkSpawnManager.InstantiateAndSpawn` and `NetworkObject.InstantiateAndSpawn` were not honoring the ownerClientId parameter when using a client-server network topology. (#2968)
- Fixed issue where internal delta serialization could not have a byte serializer defined when serializing deltas for other types. Added `[GenerateSerializationForType(typeof(byte))]` to both the `NetworkVariable` and `AnticipatedNetworkVariable` classes to assure a byte serializer is defined.(#2962)
- Fixed issue when scene management was disabled and the session owner would still try to synchronize a late joining client. (#2962)
- Fixed issue when using a distributed authority network topology where it would allow a session owner to spawn a `NetworkObject` prior to being approved. Now, an error message is logged and the `NetworkObject` will not be spawned prior to the client being approved.  (#2962)
- Fixed issue where attempting to spawn during `NetworkBehaviour.OnInSceneObjectsSpawned` and `NetworkBehaviour.OnNetworkSessionSynchronized` notifications would throw a collection modified exception.  (#2962)

### Changed

- Changed logic where clients can now set the `NetworkSceneManager` client synchronization mode when using a distributed authority network topology. (#2985)
2024-07-23 00:00:00 +00:00
Unity Technologies
c813386c5c com.unity.netcode.gameobjects@2.0.0-pre.2
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-pre.2] - 2024-06-17

### Added

- Added `AnticipatedNetworkVariable<T>`, which adds support for client anticipation of `NetworkVariable` values, allowing for more responsive gameplay. (#2957)
- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of NetworkTransforms. (#2957)
- 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<T>` with the callback `NetworkVariable<T>.CheckExceedsDirtinessThreshold`). (#2957)
- 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. (#2957)
- Added virtual method `NetworkVariableBase.OnInitialize` which can be used by `NetworkVariable` subclasses to add initialization code. (#2957)
- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2957)
- Added `NetworkTickSystem.AnticipationTick`, which can be helpful with implementation of client anticipation. This value represents the tick the current local client was at at the beginning of the most recent network round trip, which enables it to correlate server update ticks with the client tick that may have triggered them. (#2957)
- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)
- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)
- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)

### Fixed

- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)
- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)
- Fixed issue where Rigidbody micro-motion (i.e. relatively small velocities) would result in non-authority instances slightly stuttering as the body would come to a rest (i.e. no motion). Now, the threshold value can increase at higher velocities and can decrease slightly below the provided threshold to account for this. (#2948)

### Changed

- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2957)
- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2957)
- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)
- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)
- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)
2024-06-17 00:00:00 +00:00
Unity Technologies
ed38a4dcc2 com.unity.netcode.gameobjects@2.0.0-pre.1
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).

## [2.0.0-pre.1] - 2024-06-17

### Added

- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)
- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)
- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)

### Fixed

- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)
- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)
- Fixed issue where Rigidbody micro-motion (i.e. relatively small velocities) would result in non-authority instances slightly stuttering as the body would come to a rest (i.e. no motion). Now, the threshold value can increase at higher velocities and can decrease slightly below the provided threshold to account for this. (#2948)

### Changed

- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)
- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)
- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)
2024-06-17 00:00:00 +00:00
142 changed files with 12224 additions and 3780 deletions

View File

@@ -6,12 +6,130 @@ 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). Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
## [2.0.0] - 2024-09-12
### Added
- Added tooltips for all of the `NetworkObject` component's properties. (#3052)
- Added message size validation to named and unnamed message sending functions for better error messages. (#3049)
- Added "Check for NetworkObject Component" property to the Multiplayer->Netcode for GameObjects project settings. When disabled, this will bypass the in-editor `NetworkObject` check on `NetworkBehaviour` components. (#3031)
- Added `NetworkTransform.SwitchTransformSpaceWhenParented` property that, when enabled, will handle the world to local, local to world, and local to local transform space transitions when interpolation is enabled. (#3013)
- Added `NetworkTransform.TickSyncChildren` that, when enabled, will tick synchronize nested and/or child `NetworkTransform` components to eliminate any potential visual jittering that could occur if the `NetworkTransform` instances get into a state where their state updates are landing on different network ticks. (#3013)
- Added `NetworkObject.AllowOwnerToParent` property to provide the ability to allow clients to parent owned objects when running in a client-server network topology. (#3013)
- Added `NetworkObject.SyncOwnerTransformWhenParented` property to provide a way to disable applying the server's transform information in the parenting message on the client owner instance which can be useful for owner authoritative motion models. (#3013)
- Added `NetcodeEditorBase` editor helper class to provide easier modification and extension of the SDK's components. (#3013)
### Fixed
- Fixed issue where `NetworkAnimator` would send updates to non-observer clients. (#3057)
- Fixed issue where an exception could occur when receiving a universal RPC for a `NetworkObject` that has been despawned. (#3052)
- Fixed issue where a NetworkObject hidden from a client that is then promoted to be session owner was not being synchronized with newly joining clients.(#3051)
- Fixed issue where clients could have a wrong time delta on `NetworkVariableBase` which could prevent from sending delta state updates. (#3045)
- Fixed issue where setting a prefab hash value during connection approval but not having a player prefab assigned could cause an exception when spawning a player. (#3042)
- Fixed issue where the `NetworkSpawnManager.HandleNetworkObjectShow` could throw an exception if one of the `NetworkObject` components to show was destroyed during the same frame. (#3030)
- Fixed issue where the `NetworkManagerHelper` was continuing to check for hierarchy changes when in play mode. (#3026)
- Fixed issue with newly/late joined clients and `NetworkTransform` synchronization of parented `NetworkObject` instances. (#3013)
- Fixed issue with smooth transitions between transform spaces when interpolation is enabled (requires `NetworkTransform.SwitchTransformSpaceWhenParented` to be enabled). (#3013)
### Changed
- Changed `NetworkTransformEditor` now uses `NetworkTransform` as the base type class to assure it doesn't display a foldout group when using the base `NetworkTransform` component class. (#3052)
- Changed `NetworkAnimator.Awake` is now a protected virtual method. (#3052)
- Changed when invoking `NetworkManager.ConnectionManager.DisconnectClient` during a distributed authority session a more appropriate message is logged. (#3052)
- Changed `NetworkTransformEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkRigidbodyBaseEditor` so it now derives from `NetcodeEditorBase`. (#3013)
- Changed `NetworkManagerEditor` so it now derives from `NetcodeEditorBase`. (#3013)
## [2.0.0-pre.4] - 2024-08-21
### Added
- Added `NetworkVariable.CheckDirtyState` that is to be used in tandem with collections in order to detect whether the collection or an item within the collection has changed. (#3004)
### Fixed
- Fixed issue where nested `NetworkTransform` components were not getting updated. (#3016)
- Fixed issue by adding null checks in `NetworkVariableBase.CanClientRead` and `NetworkVariableBase.CanClientWrite` methods to ensure safe access to `NetworkBehaviour`. (#3012)
- Fixed issue where `FixedStringSerializer<T>` was using `NetworkVariableSerialization<byte>.AreEqual` to determine if two bytes were equal causes an exception to be thrown due to no byte serializer having been defined. (#3009)
- Fixed Issue where a state with dual triggers, inbound and outbound, could cause a false layer to layer state transition message to be sent to non-authority `NetworkAnimator` instances and cause a warning message to be logged. (#3008)
- Fixed issue using collections within `NetworkVariable` where the collection would not detect changes to items or nested items. (#3004)
- Fixed issue where `List`, `Dictionary`, and `HashSet` collections would not uniquely duplicate nested collections. (#3004)
- Fixed issue where `NotAuthorityTarget` would include the service observer in the list of targets to send the RPC to as opposed to excluding the service observer as it should. (#3000)
- Fixed issue where `ProxyRpcTargetGroup` could attempt to send a message if there were no targets to send to. (#3000)
### Changed
- Changed `NetworkAnimator` to automatically switch to owner authoritative mode when using a distributed authority network topology. (#3021)
- Changed permissions exception thrown in `NetworkList` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
- Changed permissions exception thrown in `NetworkVariable.Value` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
## [2.0.0-pre.3] - 2024-07-23
### Added
- Added: `UnityTransport.GetNetworkDriver` and `UnityTransport.GetLocalEndpoint` methods to expose the driver and local endpoint being used. (#2978)
### Fixed
- Fixed issue where deferred despawn was causing GC allocations when converting an `IEnumerable` to a list. (#2983)
- Fixed issue where the realtime network stats monitor was not able to display RPC traffic in release builds due to those stats being only available in development builds or the editor. (#2979)
- Fixed issue where `NetworkManager.ScenesLoaded` was not being updated if `PostSynchronizationSceneUnloading` was set and any loaded scenes not used during synchronization were unloaded. (#2971)
- Fixed issue where `Rigidbody2d` under Unity 6000.0.11f1 has breaking changes where `velocity` is now `linearVelocity` and `isKinematic` is replaced by `bodyType`. (#2971)
- Fixed issue where `NetworkSpawnManager.InstantiateAndSpawn` and `NetworkObject.InstantiateAndSpawn` were not honoring the ownerClientId parameter when using a client-server network topology. (#2968)
- Fixed issue where internal delta serialization could not have a byte serializer defined when serializing deltas for other types. Added `[GenerateSerializationForType(typeof(byte))]` to both the `NetworkVariable` and `AnticipatedNetworkVariable` classes to assure a byte serializer is defined.(#2962)
- Fixed issue when scene management was disabled and the session owner would still try to synchronize a late joining client. (#2962)
- Fixed issue when using a distributed authority network topology where it would allow a session owner to spawn a `NetworkObject` prior to being approved. Now, an error message is logged and the `NetworkObject` will not be spawned prior to the client being approved. (#2962)
- Fixed issue where attempting to spawn during `NetworkBehaviour.OnInSceneObjectsSpawned` and `NetworkBehaviour.OnNetworkSessionSynchronized` notifications would throw a collection modified exception. (#2962)
### Changed
- Changed logic where clients can now set the `NetworkSceneManager` client synchronization mode when using a distributed authority network topology. (#2985)
## [2.0.0-pre.2] - 2024-06-17
### Added
- Added `AnticipatedNetworkVariable<T>`, which adds support for client anticipation of `NetworkVariable` values, allowing for more responsive gameplay. (#2957)
- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of NetworkTransforms. (#2957)
- 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<T>` with the callback `NetworkVariable<T>.CheckExceedsDirtinessThreshold`). (#2957)
- 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. (#2957)
- Added virtual method `NetworkVariableBase.OnInitialize` which can be used by `NetworkVariable` subclasses to add initialization code. (#2957)
- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2957)
- Added `NetworkTickSystem.AnticipationTick`, which can be helpful with implementation of client anticipation. This value represents the tick the current local client was at at the beginning of the most recent network round trip, which enables it to correlate server update ticks with the client tick that may have triggered them. (#2957)
- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)
- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)
- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)
### Fixed
- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)
- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)
- Fixed issue where Rigidbody micro-motion (i.e. relatively small velocities) would result in non-authority instances slightly stuttering as the body would come to a rest (i.e. no motion). Now, the threshold value can increase at higher velocities and can decrease slightly below the provided threshold to account for this. (#2948)
### Changed
- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2957)
- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2957)
- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)
- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)
- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)
## [2.0.0-exp.5] - 2024-06-03 ## [2.0.0-exp.5] - 2024-06-03
### Added
### Fixed ### Fixed
- Fixed issue where SessionOwner message was being treated as a new entry for the new message indexing when it should have been ordinally sorted with the legacy message indices. (#2942) - Fixed issue where SessionOwner message was being treated as a new entry for the new message indexing when it should have been ordinally sorted with the legacy message indices. (#2942)
### Changed
- Changed `FastBufferReader` and `FastBufferWriter` so that they always ensure the length of items serialized is always serialized as an `uint` and added a check before casting for safe reading and writing.(#2946)
## [2.0.0-exp.4] - 2024-05-31 ## [2.0.0-exp.4] - 2024-05-31
### Added ### Added

View File

@@ -409,6 +409,7 @@ namespace Unity.Netcode.Editor.CodeGen
} }
else else
{ {
m_Diagnostics.AddError($"{type}: Managed type in NetworkVariable must implement IEquatable<{type}>");
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef); equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef);
} }
@@ -721,7 +722,7 @@ namespace Unity.Netcode.Editor.CodeGen
continue; continue;
} }
if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypes)) if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypedInitializers))
{ {
networkVariableSerializationTypesTypeDef = netcodeTypeDef; networkVariableSerializationTypesTypeDef = netcodeTypeDef;
continue; continue;
@@ -1007,103 +1008,103 @@ namespace Unity.Netcode.Editor.CodeGen
switch (method.Name) switch (method.Name)
{ {
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpy):
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyArray): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyArray):
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyArray_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyArray_MethodRef = method;
break; break;
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyList): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyList):
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyList_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyList_MethodRef = method;
break; break;
#endif #endif
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializable): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializable):
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableArray): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableArray):
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableArray_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableArray_MethodRef = method;
break; break;
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableList): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableList):
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableList_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableList_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashSet): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashSet):
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashMap): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashMap):
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef = method;
break; break;
#endif #endif
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_List): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_List):
m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_HashSet): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_HashSet):
m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_Dictionary): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_Dictionary):
m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_ManagedINetworkSerializable): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_ManagedINetworkSerializable):
m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedString): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedString):
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringArray): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringArray):
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringArray_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringArray_MethodRef = method;
break; break;
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringList): case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringList):
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringList_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringList_MethodRef = method;
break; break;
#endif #endif
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedIEquatable): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedIEquatable):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatable):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableArray): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableArray):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableArray_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableArray_MethodRef = method;
break; break;
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableList): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableList):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableList_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableList_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashSet): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashSet):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashMap): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashMap):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef = method;
break; break;
#endif #endif
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_List): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_List):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_HashSet): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_HashSet):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_Dictionary): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_Dictionary):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEquals):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef = method;
break; break;
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsArray): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsArray):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsArray_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsArray_MethodRef = method;
break; break;
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsList): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsList):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsList_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsList_MethodRef = method;
break; break;
#endif #endif
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedClassEquals): case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedClassEquals):
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef = method; m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef = method;
break; break;
} }

View File

@@ -5,6 +5,7 @@ namespace Unity.Netcode.Editor.Configuration
internal class NetcodeForGameObjectsEditorSettings internal class NetcodeForGameObjectsEditorSettings
{ {
internal const string AutoAddNetworkObjectIfNoneExists = "AutoAdd-NetworkObject-When-None-Exist"; internal const string AutoAddNetworkObjectIfNoneExists = "AutoAdd-NetworkObject-When-None-Exist";
internal const string CheckForNetworkObject = "NetworkBehaviour-Check-For-NetworkObject";
internal const string InstallMultiplayerToolsTipDismissedPlayerPrefKey = "Netcode_Tip_InstallMPTools_Dismissed"; internal const string InstallMultiplayerToolsTipDismissedPlayerPrefKey = "Netcode_Tip_InstallMPTools_Dismissed";
internal static int GetNetcodeInstallMultiplayerToolTips() internal static int GetNetcodeInstallMultiplayerToolTips()
@@ -28,7 +29,7 @@ namespace Unity.Netcode.Editor.Configuration
{ {
return EditorPrefs.GetBool(AutoAddNetworkObjectIfNoneExists); return EditorPrefs.GetBool(AutoAddNetworkObjectIfNoneExists);
} }
// Default for this is false
return false; return false;
} }
@@ -36,5 +37,20 @@ namespace Unity.Netcode.Editor.Configuration
{ {
EditorPrefs.SetBool(AutoAddNetworkObjectIfNoneExists, autoAddSetting); EditorPrefs.SetBool(AutoAddNetworkObjectIfNoneExists, autoAddSetting);
} }
internal static bool GetCheckForNetworkObjectSetting()
{
if (EditorPrefs.HasKey(CheckForNetworkObject))
{
return EditorPrefs.GetBool(CheckForNetworkObject);
}
// Default for this is true
return true;
}
internal static void SetCheckForNetworkObjectSetting(bool checkForNetworkObject)
{
EditorPrefs.SetBool(CheckForNetworkObject, checkForNetworkObject);
}
} }
} }

View File

@@ -81,6 +81,7 @@ namespace Unity.Netcode.Editor.Configuration
internal static NetcodeSettingsLabel NetworkObjectsSectionLabel; internal static NetcodeSettingsLabel NetworkObjectsSectionLabel;
internal static NetcodeSettingsToggle AutoAddNetworkObjectToggle; internal static NetcodeSettingsToggle AutoAddNetworkObjectToggle;
internal static NetcodeSettingsToggle CheckForNetworkObjectToggle;
internal static NetcodeSettingsLabel MultiplayerToolsLabel; internal static NetcodeSettingsLabel MultiplayerToolsLabel;
internal static NetcodeSettingsToggle MultiplayerToolTipStatusToggle; internal static NetcodeSettingsToggle MultiplayerToolTipStatusToggle;
@@ -103,6 +104,11 @@ namespace Unity.Netcode.Editor.Configuration
AutoAddNetworkObjectToggle = new NetcodeSettingsToggle("Auto-Add NetworkObject Component", "When enabled, NetworkObject components are automatically added to GameObjects when NetworkBehaviour components are added first.", 20); AutoAddNetworkObjectToggle = new NetcodeSettingsToggle("Auto-Add NetworkObject Component", "When enabled, NetworkObject components are automatically added to GameObjects when NetworkBehaviour components are added first.", 20);
} }
if (CheckForNetworkObjectToggle == null)
{
CheckForNetworkObjectToggle = new NetcodeSettingsToggle("Check for NetworkObject Component", "When disabled, the automatic check on NetworkBehaviours for an associated NetworkObject component will not be performed and Auto-Add NetworkObject Component will be disabled.", 20);
}
if (MultiplayerToolsLabel == null) if (MultiplayerToolsLabel == null)
{ {
MultiplayerToolsLabel = new NetcodeSettingsLabel("Multiplayer Tools", 20); MultiplayerToolsLabel = new NetcodeSettingsLabel("Multiplayer Tools", 20);
@@ -120,7 +126,9 @@ namespace Unity.Netcode.Editor.Configuration
CheckForInitialize(); CheckForInitialize();
var autoAddNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetAutoAddNetworkObjectSetting(); var autoAddNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetAutoAddNetworkObjectSetting();
var checkForNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetCheckForNetworkObjectSetting();
var multiplayerToolsTipStatus = NetcodeForGameObjectsEditorSettings.GetNetcodeInstallMultiplayerToolTips() == 0; var multiplayerToolsTipStatus = NetcodeForGameObjectsEditorSettings.GetNetcodeInstallMultiplayerToolTips() == 0;
var settings = NetcodeForGameObjectsProjectSettings.instance; var settings = NetcodeForGameObjectsProjectSettings.instance;
var generateDefaultPrefabs = settings.GenerateDefaultNetworkPrefabs; var generateDefaultPrefabs = settings.GenerateDefaultNetworkPrefabs;
var networkPrefabsPath = settings.TempNetworkPrefabsPath; var networkPrefabsPath = settings.TempNetworkPrefabsPath;
@@ -134,7 +142,13 @@ namespace Unity.Netcode.Editor.Configuration
{ {
GUILayout.BeginVertical("Box"); GUILayout.BeginVertical("Box");
NetworkObjectsSectionLabel.DrawLabel(); NetworkObjectsSectionLabel.DrawLabel();
autoAddNetworkObjectSetting = AutoAddNetworkObjectToggle.DrawToggle(autoAddNetworkObjectSetting);
autoAddNetworkObjectSetting = AutoAddNetworkObjectToggle.DrawToggle(autoAddNetworkObjectSetting, checkForNetworkObjectSetting);
checkForNetworkObjectSetting = CheckForNetworkObjectToggle.DrawToggle(checkForNetworkObjectSetting);
if (autoAddNetworkObjectSetting && !checkForNetworkObjectSetting)
{
autoAddNetworkObjectSetting = false;
}
GUILayout.EndVertical(); GUILayout.EndVertical();
GUILayout.BeginVertical("Box"); GUILayout.BeginVertical("Box");
@@ -184,6 +198,7 @@ namespace Unity.Netcode.Editor.Configuration
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
NetcodeForGameObjectsEditorSettings.SetAutoAddNetworkObjectSetting(autoAddNetworkObjectSetting); NetcodeForGameObjectsEditorSettings.SetAutoAddNetworkObjectSetting(autoAddNetworkObjectSetting);
NetcodeForGameObjectsEditorSettings.SetCheckForNetworkObjectSetting(checkForNetworkObjectSetting);
NetcodeForGameObjectsEditorSettings.SetNetcodeInstallMultiplayerToolTips(multiplayerToolsTipStatus ? 0 : 1); NetcodeForGameObjectsEditorSettings.SetNetcodeInstallMultiplayerToolTips(multiplayerToolsTipStatus ? 0 : 1);
settings.GenerateDefaultNetworkPrefabs = generateDefaultPrefabs; settings.GenerateDefaultNetworkPrefabs = generateDefaultPrefabs;
settings.TempNetworkPrefabsPath = networkPrefabsPath; settings.TempNetworkPrefabsPath = networkPrefabsPath;
@@ -213,10 +228,13 @@ namespace Unity.Netcode.Editor.Configuration
{ {
private GUIContent m_ToggleContent; private GUIContent m_ToggleContent;
public bool DrawToggle(bool currentSetting) public bool DrawToggle(bool currentSetting, bool enabled = true)
{ {
EditorGUIUtility.labelWidth = m_LabelSize; EditorGUIUtility.labelWidth = m_LabelSize;
return EditorGUILayout.Toggle(m_ToggleContent, currentSetting, m_LayoutWidth); GUI.enabled = enabled;
var returnValue = EditorGUILayout.Toggle(m_ToggleContent, currentSetting, m_LayoutWidth);
GUI.enabled = true;
return returnValue;
} }
public NetcodeSettingsToggle(string labelText, string toolTip, float layoutOffset) public NetcodeSettingsToggle(string labelText, string toolTip, float layoutOffset)

View File

@@ -0,0 +1,62 @@
using System;
using UnityEditor;
using UnityEngine;
namespace Unity.Netcode.Editor
{
/// <summary>
/// The base Netcode Editor helper class to display derived <see cref="MonoBehaviour"/> based components <br />
/// where each child generation's properties will be displayed within a FoldoutHeaderGroup.
/// </summary>
[CanEditMultipleObjects]
public partial class NetcodeEditorBase<TT> : UnityEditor.Editor where TT : MonoBehaviour
{
/// <inheritdoc/>
public virtual void OnEnable()
{
}
/// <summary>
/// Helper method to draw the properties of the specified child type <typeparamref name="T"/> component within a FoldoutHeaderGroup.
/// </summary>
/// <typeparam name="T">The specific child type that should have its properties drawn.</typeparam>
/// <param name="type">The component type of the <see cref="UnityEditor.Editor.target"/>.</param>
/// <param name="displayProperties">The <see cref="Action"/> to invoke that will draw the type <typeparamref name="T"/> properties.</param>
/// <param name="expanded">The <typeparamref name="T"/> current expanded property value</param>
/// <param name="setExpandedProperty">The <see cref="Action{bool}"/> invoked to apply the updated <paramref name="expanded"/> value.</param>
protected void DrawFoldOutGroup<T>(Type type, Action displayProperties, bool expanded, Action<bool> setExpandedProperty)
{
var baseClass = target as TT;
EditorGUI.BeginChangeCheck();
serializedObject.Update();
var currentClass = typeof(T);
if (type.IsSubclassOf(currentClass) || (!type.IsSubclassOf(currentClass) && currentClass.IsSubclassOf(typeof(TT))))
{
var expandedValue = EditorGUILayout.BeginFoldoutHeaderGroup(expanded, $"{currentClass.Name} Properties");
if (expandedValue)
{
EditorGUILayout.EndFoldoutHeaderGroup();
displayProperties.Invoke();
}
else
{
EditorGUILayout.EndFoldoutHeaderGroup();
}
EditorGUILayout.Space();
setExpandedProperty.Invoke(expandedValue);
}
else
{
displayProperties.Invoke();
}
serializedObject.ApplyModifiedProperties();
EditorGUI.EndChangeCheck();
}
/// <inheritdoc/>
public override void OnInspectorGUI()
{
serializedObject.ApplyModifiedProperties();
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4ce97256a2d80f94bb340e13c71a24b8

View File

@@ -301,9 +301,8 @@ namespace Unity.Netcode.Editor
expanded = false; expanded = false;
} }
serializedObject.ApplyModifiedProperties();
EditorGUI.EndChangeCheck(); EditorGUI.EndChangeCheck();
serializedObject.ApplyModifiedProperties();
} }
/// <summary> /// <summary>
@@ -352,6 +351,12 @@ namespace Unity.Netcode.Editor
return; return;
} }
// If this automatic check is disabled, then do not perform this check.
if (!NetcodeForGameObjectsEditorSettings.GetCheckForNetworkObjectSetting())
{
return;
}
// Now get the root parent transform to the current GameObject (or itself) // Now get the root parent transform to the current GameObject (or itself)
var rootTransform = GetRootParentTransform(gameObject.transform); var rootTransform = GetRootParentTransform(gameObject.transform);
if (!rootTransform.TryGetComponent<NetworkManager>(out var networkManager)) if (!rootTransform.TryGetComponent<NetworkManager>(out var networkManager))

View File

@@ -13,7 +13,7 @@ namespace Unity.Netcode.Editor
/// </summary> /// </summary>
[CustomEditor(typeof(NetworkManager), true)] [CustomEditor(typeof(NetworkManager), true)]
[CanEditMultipleObjects] [CanEditMultipleObjects]
public class NetworkManagerEditor : UnityEditor.Editor public class NetworkManagerEditor : NetcodeEditorBase<NetworkManager>
{ {
private static GUIStyle s_CenteredWordWrappedLabelStyle; private static GUIStyle s_CenteredWordWrappedLabelStyle;
private static GUIStyle s_HelpBoxStyle; private static GUIStyle s_HelpBoxStyle;
@@ -30,7 +30,7 @@ namespace Unity.Netcode.Editor
private SerializedProperty m_ProtocolVersionProperty; private SerializedProperty m_ProtocolVersionProperty;
private SerializedProperty m_NetworkTransportProperty; private SerializedProperty m_NetworkTransportProperty;
private SerializedProperty m_TickRateProperty; private SerializedProperty m_TickRateProperty;
#if MULTIPLAYER_SDK_INSTALLED #if MULTIPLAYER_SERVICES_SDK_INSTALLED
private SerializedProperty m_NetworkTopologyProperty; private SerializedProperty m_NetworkTopologyProperty;
#endif #endif
private SerializedProperty m_ClientConnectionBufferTimeoutProperty; private SerializedProperty m_ClientConnectionBufferTimeoutProperty;
@@ -102,7 +102,7 @@ namespace Unity.Netcode.Editor
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
#if MULTIPLAYER_SDK_INSTALLED #if MULTIPLAYER_SERVICES_SDK_INSTALLED
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology"); m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
#endif #endif
m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
@@ -142,7 +142,7 @@ namespace Unity.Netcode.Editor
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
#if MULTIPLAYER_SDK_INSTALLED #if MULTIPLAYER_SERVICES_SDK_INSTALLED
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology"); m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
#endif #endif
m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
@@ -168,16 +168,8 @@ namespace Unity.Netcode.Editor
.FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists)); .FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists));
} }
/// <inheritdoc/> private void DisplayNetworkManagerProperties()
public override void OnInspectorGUI()
{ {
Initialize();
CheckNullProperties();
#if !MULTIPLAYER_TOOLS
DrawInstallMultiplayerToolsTip();
#endif
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient) if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
{ {
serializedObject.Update(); serializedObject.Update();
@@ -186,7 +178,7 @@ namespace Unity.Netcode.Editor
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel); EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel);
#if MULTIPLAYER_SDK_INSTALLED #if MULTIPLAYER_SERVICES_SDK_INSTALLED
EditorGUILayout.PropertyField(m_NetworkTopologyProperty); EditorGUILayout.PropertyField(m_NetworkTopologyProperty);
#endif #endif
EditorGUILayout.PropertyField(m_ProtocolVersionProperty); EditorGUILayout.PropertyField(m_ProtocolVersionProperty);
@@ -298,18 +290,23 @@ namespace Unity.Netcode.Editor
} }
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();
}
}
private void DisplayCallToActionButtons()
{
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
{
string buttonDisabledReasonSuffix = "";
// Start buttons below if (!EditorApplication.isPlaying)
{ {
string buttonDisabledReasonSuffix = ""; buttonDisabledReasonSuffix = ". This can only be done in play mode";
GUI.enabled = false;
if (!EditorApplication.isPlaying) }
{
buttonDisabledReasonSuffix = ". This can only be done in play mode";
GUI.enabled = false;
}
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
{
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix))) if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
{ {
m_NetworkManager.StartHost(); m_NetworkManager.StartHost();
@@ -324,12 +321,20 @@ namespace Unity.Netcode.Editor
{ {
m_NetworkManager.StartClient(); m_NetworkManager.StartClient();
} }
}
if (!EditorApplication.isPlaying) else
{
if (GUILayout.Button(new GUIContent("Start Client", "Starts a distributed authority client instance" + buttonDisabledReasonSuffix)))
{ {
GUI.enabled = true; m_NetworkManager.StartClient();
} }
} }
if (!EditorApplication.isPlaying)
{
GUI.enabled = true;
}
} }
else else
{ {
@@ -357,6 +362,21 @@ namespace Unity.Netcode.Editor
} }
} }
/// <inheritdoc/>
public override void OnInspectorGUI()
{
var networkManager = target as NetworkManager;
Initialize();
CheckNullProperties();
#if !MULTIPLAYER_TOOLS
DrawInstallMultiplayerToolsTip();
#endif
void SetExpanded(bool expanded) { networkManager.NetworkManagerExpanded = expanded; };
DrawFoldOutGroup<NetworkManager>(networkManager.GetType(), DisplayNetworkManagerProperties, networkManager.NetworkManagerExpanded, SetExpanded);
DisplayCallToActionButtons();
base.OnInspectorGUI();
}
private static void DrawInstallMultiplayerToolsTip() private static void DrawInstallMultiplayerToolsTip()
{ {
const string getToolsText = "Access additional tools for multiplayer development by installing the Multiplayer Tools package in the Package Manager."; const string getToolsText = "Access additional tools for multiplayer development by installing the Multiplayer Tools package in the Package Manager.";

View File

@@ -61,6 +61,12 @@ namespace Unity.Netcode.Editor
{ {
s_LastKnownNetworkManagerParents.Clear(); s_LastKnownNetworkManagerParents.Clear();
ScenesInBuildActiveSceneCheck(); ScenesInBuildActiveSceneCheck();
EditorApplication.hierarchyChanged -= EditorApplication_hierarchyChanged;
break;
}
case PlayModeStateChange.EnteredEditMode:
{
EditorApplication.hierarchyChanged += EditorApplication_hierarchyChanged;
break; break;
} }
} }
@@ -110,6 +116,12 @@ namespace Unity.Netcode.Editor
/// </summary> /// </summary>
private static void EditorApplication_hierarchyChanged() private static void EditorApplication_hierarchyChanged()
{ {
if (Application.isPlaying)
{
EditorApplication.hierarchyChanged -= EditorApplication_hierarchyChanged;
return;
}
var allNetworkManagers = Resources.FindObjectsOfTypeAll<NetworkManager>(); var allNetworkManagers = Resources.FindObjectsOfTypeAll<NetworkManager>();
foreach (var networkManager in allNetworkManagers) foreach (var networkManager in allNetworkManagers)
{ {

View File

@@ -1,5 +1,5 @@
using System.Collections.Generic; using System.Collections.Generic;
#if MULTIPLAYER_SDK_INSTALLED #if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED
using System.Linq; using System.Linq;
#endif #endif
using UnityEditor; using UnityEditor;
@@ -148,7 +148,7 @@ namespace Unity.Netcode.Editor
// Keeping this here just in case, but it appears that in Unity 6 the visual bugs with // Keeping this here just in case, but it appears that in Unity 6 the visual bugs with
// enum flags is resolved // enum flags is resolved
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SDK_INSTALLED #if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED
[CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))] [CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))]
public class NetworkObjectOwnership : PropertyDrawer public class NetworkObjectOwnership : PropertyDrawer
{ {

View File

@@ -0,0 +1,42 @@
#if COM_UNITY_MODULES_PHYSICS || COM_UNITY_MODULES_PHYSICS2D
using Unity.Netcode.Components;
using UnityEditor;
namespace Unity.Netcode.Editor
{
[CustomEditor(typeof(NetworkRigidbodyBase), true)]
[CanEditMultipleObjects]
public class NetworkRigidbodyBaseEditor : NetcodeEditorBase<NetworkBehaviour>
{
private SerializedProperty m_UseRigidBodyForMotion;
private SerializedProperty m_AutoUpdateKinematicState;
private SerializedProperty m_AutoSetKinematicOnDespawn;
public override void OnEnable()
{
m_UseRigidBodyForMotion = serializedObject.FindProperty(nameof(NetworkRigidbodyBase.UseRigidBodyForMotion));
m_AutoUpdateKinematicState = serializedObject.FindProperty(nameof(NetworkRigidbodyBase.AutoUpdateKinematicState));
m_AutoSetKinematicOnDespawn = serializedObject.FindProperty(nameof(NetworkRigidbodyBase.AutoSetKinematicOnDespawn));
base.OnEnable();
}
private void DisplayNetworkRigidbodyProperties()
{
EditorGUILayout.PropertyField(m_UseRigidBodyForMotion);
EditorGUILayout.PropertyField(m_AutoUpdateKinematicState);
EditorGUILayout.PropertyField(m_AutoSetKinematicOnDespawn);
}
/// <inheritdoc/>
public override void OnInspectorGUI()
{
var networkRigidbodyBase = target as NetworkRigidbodyBase;
void SetExpanded(bool expanded) { networkRigidbodyBase.NetworkRigidbodyBaseExpanded = expanded; };
DrawFoldOutGroup<NetworkRigidbodyBase>(networkRigidbodyBase.GetType(), DisplayNetworkRigidbodyProperties, networkRigidbodyBase.NetworkRigidbodyBaseExpanded, SetExpanded);
base.OnInspectorGUI();
}
}
}
#endif

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 06561c57f81a6354f8bb16076f1de3a9

View File

@@ -8,8 +8,11 @@ namespace Unity.Netcode.Editor
/// The <see cref="CustomEditor"/> for <see cref="NetworkTransform"/> /// The <see cref="CustomEditor"/> for <see cref="NetworkTransform"/>
/// </summary> /// </summary>
[CustomEditor(typeof(NetworkTransform), true)] [CustomEditor(typeof(NetworkTransform), true)]
public class NetworkTransformEditor : UnityEditor.Editor [CanEditMultipleObjects]
public class NetworkTransformEditor : NetcodeEditorBase<NetworkTransform>
{ {
private SerializedProperty m_SwitchTransformSpaceWhenParented;
private SerializedProperty m_TickSyncChildren;
private SerializedProperty m_UseUnreliableDeltas; private SerializedProperty m_UseUnreliableDeltas;
private SerializedProperty m_SyncPositionXProperty; private SerializedProperty m_SyncPositionXProperty;
private SerializedProperty m_SyncPositionYProperty; private SerializedProperty m_SyncPositionYProperty;
@@ -30,6 +33,7 @@ namespace Unity.Netcode.Editor
private SerializedProperty m_UseQuaternionCompression; private SerializedProperty m_UseQuaternionCompression;
private SerializedProperty m_UseHalfFloatPrecision; private SerializedProperty m_UseHalfFloatPrecision;
private SerializedProperty m_SlerpPosition; private SerializedProperty m_SlerpPosition;
private SerializedProperty m_AuthorityMode;
private static int s_ToggleOffset = 45; private static int s_ToggleOffset = 45;
private static float s_MaxRowWidth = EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + 5; private static float s_MaxRowWidth = EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + 5;
@@ -38,8 +42,10 @@ namespace Unity.Netcode.Editor
private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale"); private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale");
/// <inheritdoc/> /// <inheritdoc/>
public void OnEnable() public override void OnEnable()
{ {
m_SwitchTransformSpaceWhenParented = serializedObject.FindProperty(nameof(NetworkTransform.SwitchTransformSpaceWhenParented));
m_TickSyncChildren = serializedObject.FindProperty(nameof(NetworkTransform.TickSyncChildren));
m_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas)); m_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas));
m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX)); m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX));
m_SyncPositionYProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionY)); m_SyncPositionYProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionY));
@@ -59,12 +65,14 @@ namespace Unity.Netcode.Editor
m_UseQuaternionCompression = serializedObject.FindProperty(nameof(NetworkTransform.UseQuaternionCompression)); m_UseQuaternionCompression = serializedObject.FindProperty(nameof(NetworkTransform.UseQuaternionCompression));
m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision)); m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision));
m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition)); m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition));
m_AuthorityMode = serializedObject.FindProperty(nameof(NetworkTransform.AuthorityMode));
base.OnEnable();
} }
/// <inheritdoc/> private void DisplayNetworkTransformProperties()
public override void OnInspectorGUI()
{ {
EditorGUILayout.LabelField("Syncing", EditorStyles.boldLabel); var networkTransform = target as NetworkTransform;
EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel);
{ {
GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal();
@@ -126,6 +134,11 @@ namespace Unity.Netcode.Editor
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
} }
EditorGUILayout.Space();
EditorGUILayout.LabelField("Authority", EditorStyles.boldLabel);
{
EditorGUILayout.PropertyField(m_AuthorityMode);
}
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUILayout.LabelField("Thresholds", EditorStyles.boldLabel); EditorGUILayout.LabelField("Thresholds", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_PositionThresholdProperty); EditorGUILayout.PropertyField(m_PositionThresholdProperty);
@@ -133,11 +146,20 @@ namespace Unity.Netcode.Editor
EditorGUILayout.PropertyField(m_ScaleThresholdProperty); EditorGUILayout.PropertyField(m_ScaleThresholdProperty);
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUILayout.LabelField("Delivery", EditorStyles.boldLabel); EditorGUILayout.LabelField("Delivery", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_TickSyncChildren);
EditorGUILayout.PropertyField(m_UseUnreliableDeltas); EditorGUILayout.PropertyField(m_UseUnreliableDeltas);
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel); EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_SwitchTransformSpaceWhenParented);
if (m_SwitchTransformSpaceWhenParented.boolValue)
{
m_TickSyncChildren.boolValue = true;
}
EditorGUILayout.PropertyField(m_InLocalSpaceProperty); EditorGUILayout.PropertyField(m_InLocalSpaceProperty);
EditorGUILayout.PropertyField(m_InterpolateProperty); if (!networkTransform.HideInterpolateValue)
{
EditorGUILayout.PropertyField(m_InterpolateProperty);
}
EditorGUILayout.PropertyField(m_SlerpPosition); EditorGUILayout.PropertyField(m_SlerpPosition);
EditorGUILayout.PropertyField(m_UseQuaternionSynchronization); EditorGUILayout.PropertyField(m_UseQuaternionSynchronization);
if (m_UseQuaternionSynchronization.boolValue) if (m_UseQuaternionSynchronization.boolValue)
@@ -152,8 +174,7 @@ namespace Unity.Netcode.Editor
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
// if rigidbody is present but network rigidbody is not present // if rigidbody is present but network rigidbody is not present
var go = ((NetworkTransform)target).gameObject; if (networkTransform.TryGetComponent<Rigidbody>(out _) && networkTransform.TryGetComponent<NetworkRigidbody>(out _) == false)
if (go.TryGetComponent<Rigidbody>(out _) && go.TryGetComponent<NetworkRigidbody>(out _) == false)
{ {
EditorGUILayout.HelpBox("This GameObject contains a Rigidbody but no NetworkRigidbody.\n" + EditorGUILayout.HelpBox("This GameObject contains a Rigidbody but no NetworkRigidbody.\n" +
"Add a NetworkRigidbody component to improve Rigidbody synchronization.", MessageType.Warning); "Add a NetworkRigidbody component to improve Rigidbody synchronization.", MessageType.Warning);
@@ -161,14 +182,23 @@ namespace Unity.Netcode.Editor
#endif // COM_UNITY_MODULES_PHYSICS #endif // COM_UNITY_MODULES_PHYSICS
#if COM_UNITY_MODULES_PHYSICS2D #if COM_UNITY_MODULES_PHYSICS2D
if (go.TryGetComponent<Rigidbody2D>(out _) && go.TryGetComponent<NetworkRigidbody2D>(out _) == false) if (networkTransform.TryGetComponent<Rigidbody2D>(out _) && networkTransform.TryGetComponent<NetworkRigidbody2D>(out _) == false)
{ {
EditorGUILayout.HelpBox("This GameObject contains a Rigidbody2D but no NetworkRigidbody2D.\n" + EditorGUILayout.HelpBox("This GameObject contains a Rigidbody2D but no NetworkRigidbody2D.\n" +
"Add a NetworkRigidbody2D component to improve Rigidbody2D synchronization.", MessageType.Warning); "Add a NetworkRigidbody2D component to improve Rigidbody2D synchronization.", MessageType.Warning);
} }
#endif // COM_UNITY_MODULES_PHYSICS2D #endif // COM_UNITY_MODULES_PHYSICS2D
}
serializedObject.ApplyModifiedProperties();
/// <inheritdoc/>
public override void OnInspectorGUI()
{
var networkTransform = target as NetworkTransform;
void SetExpanded(bool expanded) { networkTransform.NetworkTransformExpanded = expanded; };
DrawFoldOutGroup<NetworkTransform>(networkTransform.GetType(), DisplayNetworkTransformProperties, networkTransform.NetworkTransformExpanded, SetExpanded);
base.OnInspectorGUI();
} }
} }
} }

View File

@@ -57,7 +57,7 @@
{ {
"name": "com.unity.services.multiplayer", "name": "com.unity.services.multiplayer",
"expression": "0.2.0", "expression": "0.2.0",
"define": "MULTIPLAYER_SDK_INSTALLED" "define": "MULTIPLAYER_SERVICES_SDK_INSTALLED"
} }
], ],
"noEngineReferences": false "noEngineReferences": false

View File

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

View File

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

View File

@@ -8,7 +8,7 @@ namespace Unity.Netcode.Components
/// Half float precision <see cref="Vector3"/>. /// Half float precision <see cref="Vector3"/>.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// The Vector3T<ushort> values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each /// The Vector3T&lt;ushort&gt; values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
/// individual axis and the 16 bits of the half float are stored as <see cref="ushort"/> values since C# does not have /// individual axis and the 16 bits of the half float are stored as <see cref="ushort"/> values since C# does not have
/// a half float type. /// a half float type.
/// </remarks> /// </remarks>

View File

@@ -8,7 +8,7 @@ namespace Unity.Netcode.Components
/// Half Precision <see cref="Vector4"/> that can also be used to convert a <see cref="Quaternion"/> to half precision. /// Half Precision <see cref="Vector4"/> that can also be used to convert a <see cref="Quaternion"/> to half precision.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// The Vector4T<ushort> values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each /// The Vector4T&lt;ushort&gt; values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
/// individual axis and the 16 bits of the half float are stored as <see cref="ushort"/> values since C# does not have /// individual axis and the 16 bits of the half float are stored as <see cref="ushort"/> values since C# does not have
/// a half float type. /// a half float type.
/// </remarks> /// </remarks>

View File

@@ -5,14 +5,14 @@ using UnityEngine;
namespace Unity.Netcode namespace Unity.Netcode
{ {
/// <summary> /// <summary>
/// Solves for incoming values that are jittered /// Solves for incoming values that are jittered.
/// Partially solves for message loss. Unclamped lerping helps hide this, but not completely /// Partially solves for message loss. Unclamped lerping helps hide this, but not completely
/// </summary> /// </summary>
/// <typeparam name="T">The type of interpolated value</typeparam> /// <typeparam name="T">The type of interpolated value</typeparam>
public abstract class BufferedLinearInterpolator<T> where T : struct public abstract class BufferedLinearInterpolator<T> where T : struct
{ {
internal float MaxInterpolationBound = 3.0f; internal float MaxInterpolationBound = 3.0f;
private struct BufferedItem protected internal struct BufferedItem
{ {
public T Item; public T Item;
public double TimeSent; public double TimeSent;
@@ -31,14 +31,16 @@ namespace Unity.Netcode
private const double k_SmallValue = 9.999999439624929E-11; // copied from Vector3's equal operator private const double k_SmallValue = 9.999999439624929E-11; // copied from Vector3's equal operator
private T m_InterpStartValue; protected internal T m_InterpStartValue;
private T m_CurrentInterpValue; protected internal T m_CurrentInterpValue;
private T m_InterpEndValue; protected internal T m_InterpEndValue;
private double m_EndTimeConsumed; private double m_EndTimeConsumed;
private double m_StartTimeConsumed; private double m_StartTimeConsumed;
private readonly List<BufferedItem> m_Buffer = new List<BufferedItem>(k_BufferCountLimit); protected internal readonly List<BufferedItem> m_Buffer = new List<BufferedItem>(k_BufferCountLimit);
// Buffer consumption scenarios // Buffer consumption scenarios
// Perfect case consumption // Perfect case consumption
@@ -73,6 +75,21 @@ namespace Unity.Netcode
private bool InvalidState => m_Buffer.Count == 0 && m_LifetimeConsumedCount == 0; private bool InvalidState => m_Buffer.Count == 0 && m_LifetimeConsumedCount == 0;
internal bool EndOfBuffer => m_Buffer.Count == 0;
internal bool InLocalSpace;
protected internal virtual void OnConvertTransformSpace(Transform transform, bool inLocalSpace)
{
}
internal void ConvertTransformSpace(Transform transform, bool inLocalSpace)
{
OnConvertTransformSpace(transform, inLocalSpace);
InLocalSpace = inLocalSpace;
}
/// <summary> /// <summary>
/// Resets interpolator to initial state /// Resets interpolator to initial state
/// </summary> /// </summary>
@@ -351,6 +368,35 @@ namespace Unity.Netcode
return Quaternion.Lerp(start, end, time); return Quaternion.Lerp(start, end, time);
} }
} }
private Quaternion ConvertToNewTransformSpace(Transform transform, Quaternion rotation, bool inLocalSpace)
{
if (inLocalSpace)
{
return Quaternion.Inverse(transform.rotation) * rotation;
}
else
{
return transform.rotation * rotation;
}
}
protected internal override void OnConvertTransformSpace(Transform transform, bool inLocalSpace)
{
for (int i = 0; i < m_Buffer.Count; i++)
{
var entry = m_Buffer[i];
entry.Item = ConvertToNewTransformSpace(transform, entry.Item, inLocalSpace);
m_Buffer[i] = entry;
}
m_InterpStartValue = ConvertToNewTransformSpace(transform, m_InterpStartValue, inLocalSpace);
m_CurrentInterpValue = ConvertToNewTransformSpace(transform, m_CurrentInterpValue, inLocalSpace);
m_InterpEndValue = ConvertToNewTransformSpace(transform, m_InterpEndValue, inLocalSpace);
base.OnConvertTransformSpace(transform, inLocalSpace);
}
} }
/// <summary> /// <summary>
@@ -388,5 +434,34 @@ namespace Unity.Netcode
return Vector3.Lerp(start, end, time); return Vector3.Lerp(start, end, time);
} }
} }
private Vector3 ConvertToNewTransformSpace(Transform transform, Vector3 position, bool inLocalSpace)
{
if (inLocalSpace)
{
return transform.InverseTransformPoint(position);
}
else
{
return transform.TransformPoint(position);
}
}
protected internal override void OnConvertTransformSpace(Transform transform, bool inLocalSpace)
{
for (int i = 0; i < m_Buffer.Count; i++)
{
var entry = m_Buffer[i];
entry.Item = ConvertToNewTransformSpace(transform, entry.Item, inLocalSpace);
m_Buffer[i] = entry;
}
m_InterpStartValue = ConvertToNewTransformSpace(transform, m_InterpStartValue, inLocalSpace);
m_CurrentInterpValue = ConvertToNewTransformSpace(transform, m_CurrentInterpValue, inLocalSpace);
m_InterpEndValue = ConvertToNewTransformSpace(transform, m_InterpEndValue, inLocalSpace);
base.OnConvertTransformSpace(transform, inLocalSpace);
}
} }
} }

View File

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

View File

@@ -186,7 +186,6 @@ namespace Unity.Netcode.Components
/// NetworkAnimator enables remote synchronization of <see cref="UnityEngine.Animator"/> state for on network objects. /// NetworkAnimator enables remote synchronization of <see cref="UnityEngine.Animator"/> state for on network objects.
/// </summary> /// </summary>
[AddComponentMenu("Netcode/Network Animator")] [AddComponentMenu("Netcode/Network Animator")]
[RequireComponent(typeof(Animator))]
public class NetworkAnimator : NetworkBehaviour, ISerializationCallbackReceiver public class NetworkAnimator : NetworkBehaviour, ISerializationCallbackReceiver
{ {
[Serializable] [Serializable]
@@ -499,9 +498,13 @@ namespace Unity.Netcode.Components
/// <summary> /// <summary>
/// Override this method and return false to switch to owner authoritative mode /// Override this method and return false to switch to owner authoritative mode
/// </summary> /// </summary>
/// <remarks>
/// When using a distributed authority network topology, this will default to
/// owner authoritative.
/// </remarks>
protected virtual bool OnIsServerAuthoritative() protected virtual bool OnIsServerAuthoritative()
{ {
return true; return NetworkManager ? !NetworkManager.DistributedAuthorityMode : true;
} }
// Animators only support up to 32 parameters // Animators only support up to 32 parameters
@@ -581,7 +584,7 @@ namespace Unity.Netcode.Components
base.OnDestroy(); base.OnDestroy();
} }
private void Awake() protected virtual void Awake()
{ {
int layers = m_Animator.layerCount; int layers = m_Animator.layerCount;
// Initializing the below arrays for everyone handles an issue // Initializing the below arrays for everyone handles an issue
@@ -852,7 +855,12 @@ namespace Unity.Netcode.Components
stateChangeDetected = true; stateChangeDetected = true;
//Debug.Log($"[Cross-Fade] To-Hash: {nt.fullPathHash} | TI-Duration: ({tt.duration}) | TI-Norm: ({tt.normalizedTime}) | From-Hash: ({m_AnimationHash[layer]}) | SI-FPHash: ({st.fullPathHash}) | SI-Norm: ({st.normalizedTime})"); //Debug.Log($"[Cross-Fade] To-Hash: {nt.fullPathHash} | TI-Duration: ({tt.duration}) | TI-Norm: ({tt.normalizedTime}) | From-Hash: ({m_AnimationHash[layer]}) | SI-FPHash: ({st.fullPathHash}) | SI-Norm: ({st.normalizedTime})");
} }
else if (!tt.anyState && tt.fullPathHash != m_TransitionHash[layer]) // If we are not transitioned into the "any state" and the animator transition isn't a full path hash (layer to layer) and our pre-built destination state to transition does not contain the
// current layer (i.e. transitioning into a state from another layer) =or= we do contain the layer and the layer contains state to transition to is contained within our pre-built destination
// state then we can handle this transition as a non-cross fade state transition between layers.
// Otherwise, if we don't enter into this then this is a "trigger transition to some state that is now being transitioned back to the Idle state via trigger" or "Dual Triggers" IDLE<-->State.
else if (!tt.anyState && tt.fullPathHash != m_TransitionHash[layer] && (!m_DestinationStateToTransitioninfo.ContainsKey(layer) ||
(m_DestinationStateToTransitioninfo.ContainsKey(layer) && m_DestinationStateToTransitioninfo[layer].ContainsKey(nt.fullPathHash))))
{ {
// first time in this transition for this layer // first time in this transition for this layer
m_TransitionHash[layer] = tt.fullPathHash; m_TransitionHash[layer] = tt.fullPathHash;
@@ -861,6 +869,10 @@ namespace Unity.Netcode.Components
animState.CrossFade = false; animState.CrossFade = false;
animState.Transition = true; animState.Transition = true;
animState.NormalizedTime = tt.normalizedTime; animState.NormalizedTime = tt.normalizedTime;
if (m_DestinationStateToTransitioninfo.ContainsKey(layer) && m_DestinationStateToTransitioninfo[layer].ContainsKey(nt.fullPathHash))
{
animState.DestinationStateHash = nt.fullPathHash;
}
stateChangeDetected = true; stateChangeDetected = true;
//Debug.Log($"[Transition] TI-Duration: ({tt.duration}) | TI-Norm: ({tt.normalizedTime}) | From-Hash: ({m_AnimationHash[layer]}) |SI-FPHash: ({st.fullPathHash}) | SI-Norm: ({st.normalizedTime})"); //Debug.Log($"[Transition] TI-Duration: ({tt.duration}) | TI-Norm: ({tt.normalizedTime}) | From-Hash: ({m_AnimationHash[layer]}) |SI-FPHash: ({st.fullPathHash}) | SI-Norm: ({st.normalizedTime})");
} }
@@ -940,8 +952,14 @@ namespace Unity.Netcode.Components
{ {
// Just notify all remote clients and not the local server // Just notify all remote clients and not the local server
m_ClientSendList.Clear(); m_ClientSendList.Clear();
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds); foreach (var clientId in NetworkManager.ConnectedClientsIds)
m_ClientSendList.Remove(NetworkManager.LocalClientId); {
if (clientId == NetworkManager.LocalClientId || !NetworkObject.Observers.Contains(clientId))
{
continue;
}
m_ClientSendList.Add(clientId);
}
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList; m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
SendAnimStateClientRpc(m_AnimationMessage, m_ClientRpcParams); SendAnimStateClientRpc(m_AnimationMessage, m_ClientRpcParams);
} }
@@ -1252,9 +1270,15 @@ namespace Unity.Netcode.Components
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1)) if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
{ {
m_ClientSendList.Clear(); m_ClientSendList.Clear();
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds); foreach (var clientId in NetworkManager.ConnectedClientsIds)
m_ClientSendList.Remove(serverRpcParams.Receive.SenderClientId); {
m_ClientSendList.Remove(NetworkManager.ServerClientId); if (clientId == serverRpcParams.Receive.SenderClientId || clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
{
continue;
}
m_ClientSendList.Add(clientId);
}
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList; m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
m_NetworkAnimatorStateChangeHandler.SendParameterUpdate(parametersUpdate, m_ClientRpcParams); m_NetworkAnimatorStateChangeHandler.SendParameterUpdate(parametersUpdate, m_ClientRpcParams);
} }
@@ -1309,9 +1333,14 @@ namespace Unity.Netcode.Components
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1)) if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
{ {
m_ClientSendList.Clear(); m_ClientSendList.Clear();
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds); foreach (var clientId in NetworkManager.ConnectedClientsIds)
m_ClientSendList.Remove(serverRpcParams.Receive.SenderClientId); {
m_ClientSendList.Remove(NetworkManager.ServerClientId); if (clientId == serverRpcParams.Receive.SenderClientId || clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
{
continue;
}
m_ClientSendList.Add(clientId);
}
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList; m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
m_NetworkAnimatorStateChangeHandler.SendAnimationUpdate(animationMessage, m_ClientRpcParams); m_NetworkAnimatorStateChangeHandler.SendAnimationUpdate(animationMessage, m_ClientRpcParams);
} }
@@ -1378,9 +1407,14 @@ namespace Unity.Netcode.Components
InternalSetTrigger(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet); InternalSetTrigger(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet);
m_ClientSendList.Clear(); m_ClientSendList.Clear();
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds); foreach (var clientId in NetworkManager.ConnectedClientsIds)
m_ClientSendList.Remove(NetworkManager.ServerClientId); {
if (clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
{
continue;
}
m_ClientSendList.Add(clientId);
}
if (IsServerAuthoritative()) if (IsServerAuthoritative())
{ {
m_NetworkAnimatorStateChangeHandler.QueueTriggerUpdateToClient(animationTriggerMessage, m_ClientRpcParams); m_NetworkAnimatorStateChangeHandler.QueueTriggerUpdateToClient(animationTriggerMessage, m_ClientRpcParams);

View File

@@ -1,4 +1,4 @@
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS || COM_UNITY_MODULES_PHYSICS2D
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using UnityEngine; using UnityEngine;
@@ -14,6 +14,12 @@ namespace Unity.Netcode.Components
/// </remarks> /// </remarks>
public abstract class NetworkRigidbodyBase : NetworkBehaviour public abstract class NetworkRigidbodyBase : NetworkBehaviour
{ {
#if UNITY_EDITOR
[HideInInspector]
[SerializeField]
internal bool NetworkRigidbodyBaseExpanded;
#endif
/// <summary> /// <summary>
/// When enabled, the associated <see cref="NetworkTransform"/> will use the Rigidbody/Rigidbody2D to apply and synchronize changes in position, rotation, and /// When enabled, the associated <see cref="NetworkTransform"/> will use the Rigidbody/Rigidbody2D to apply and synchronize changes in position, rotation, and
/// allows for the use of Rigidbody interpolation/extrapolation. /// allows for the use of Rigidbody interpolation/extrapolation.
@@ -42,9 +48,14 @@ namespace Unity.Netcode.Components
private bool m_IsRigidbody2D => RigidbodyType == RigidbodyTypes.Rigidbody2D; private bool m_IsRigidbody2D => RigidbodyType == RigidbodyTypes.Rigidbody2D;
// Used to cache the authority state of this Rigidbody during the last frame // Used to cache the authority state of this Rigidbody during the last frame
private bool m_IsAuthority; private bool m_IsAuthority;
private Rigidbody m_Rigidbody;
private Rigidbody2D m_Rigidbody2D; protected internal Rigidbody m_InternalRigidbody { get; private set; }
protected internal Rigidbody2D m_InternalRigidbody2D { get; private set; }
internal NetworkTransform NetworkTransform; internal NetworkTransform NetworkTransform;
private float m_TickFrequency;
private float m_TickRate;
private enum InterpolationTypes private enum InterpolationTypes
{ {
None, None,
@@ -84,18 +95,18 @@ namespace Unity.Netcode.Components
return; return;
} }
RigidbodyType = rigidbodyType; RigidbodyType = rigidbodyType;
m_Rigidbody2D = rigidbody2D; m_InternalRigidbody2D = rigidbody2D;
m_Rigidbody = rigidbody; m_InternalRigidbody = rigidbody;
NetworkTransform = networkTransform; NetworkTransform = networkTransform;
if (m_IsRigidbody2D && m_Rigidbody2D == null) if (m_IsRigidbody2D && m_InternalRigidbody2D == null)
{ {
m_Rigidbody2D = GetComponent<Rigidbody2D>(); m_InternalRigidbody2D = GetComponent<Rigidbody2D>();
} }
else if (m_Rigidbody == null) else if (m_InternalRigidbody == null)
{ {
m_Rigidbody = GetComponent<Rigidbody>(); m_InternalRigidbody = GetComponent<Rigidbody>();
} }
SetOriginalInterpolation(); SetOriginalInterpolation();
@@ -120,6 +131,137 @@ namespace Unity.Netcode.Components
} }
} }
internal Vector3 GetAdjustedPositionThreshold()
{
// Since the threshold is a measurement of unity world space units per tick, we will allow for the maximum threshold
// to be no greater than the threshold measured in unity world space units per second
var thresholdMax = NetworkTransform.PositionThreshold * m_TickRate;
// Get the velocity in unity world space units per tick
var perTickVelocity = GetLinearVelocity() * m_TickFrequency;
// Since a rigid body can have "micro-motion" when allowed to come to rest (based on friction etc), we will allow for
// no less than 1/10th the threshold value.
var minThreshold = NetworkTransform.PositionThreshold * 0.1f;
// Finally, we adjust the threshold based on the body's current velocity
perTickVelocity.x = Mathf.Clamp(Mathf.Abs(perTickVelocity.x), minThreshold, thresholdMax);
perTickVelocity.y = Mathf.Clamp(Mathf.Abs(perTickVelocity.y), minThreshold, thresholdMax);
// 2D Rigidbody only moves on x & y axis
if (!m_IsRigidbody2D)
{
perTickVelocity.z = Mathf.Clamp(Mathf.Abs(perTickVelocity.z), minThreshold, thresholdMax);
}
return perTickVelocity;
}
internal Vector3 GetAdjustedRotationThreshold()
{
// Since the rotation threshold is a measurement pf degrees per tick, we get the maximum threshold
// by calculating the threshold in degrees per second.
var thresholdMax = NetworkTransform.RotAngleThreshold * m_TickRate;
// Angular velocity is expressed in radians per second where as the rotation being checked is in degrees.
// Convert the angular velocity to degrees per second and then convert that to degrees per tick.
var rotationPerTick = (GetAngularVelocity() * Mathf.Rad2Deg) * m_TickFrequency;
var minThreshold = NetworkTransform.RotAngleThreshold * m_TickFrequency;
// 2D Rigidbody only rotates around Z axis
if (!m_IsRigidbody2D)
{
rotationPerTick.x = Mathf.Clamp(Mathf.Abs(rotationPerTick.x), minThreshold, thresholdMax);
rotationPerTick.y = Mathf.Clamp(Mathf.Abs(rotationPerTick.y), minThreshold, thresholdMax);
}
rotationPerTick.z = Mathf.Clamp(Mathf.Abs(rotationPerTick.z), minThreshold, thresholdMax);
return rotationPerTick;
}
/// <summary>
/// Sets the linear velocity of the Rigidbody.
/// </summary>
/// <remarks>
/// For <see cref="Rigidbody2D"/>, only the x and y components of the <see cref="Vector3"/> are applied.
/// </remarks>
public void SetLinearVelocity(Vector3 linearVelocity)
{
if (m_IsRigidbody2D)
{
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
m_InternalRigidbody2D.linearVelocity = linearVelocity;
#else
m_InternalRigidbody2D.velocity = linearVelocity;
#endif
}
else
{
m_InternalRigidbody.linearVelocity = linearVelocity;
}
}
/// <summary>
/// Gets the linear velocity of the Rigidbody.
/// </summary>
/// <remarks>
/// For <see cref="Rigidbody2D"/>, the <see cref="Vector3"/> velocity returned is only applied to the x and y components.
/// </remarks>
/// <returns><see cref="Vector3"/> as the linear velocity</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector3 GetLinearVelocity()
{
if (m_IsRigidbody2D)
{
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
return m_InternalRigidbody2D.linearVelocity;
#else
return m_InternalRigidbody2D.velocity;
#endif
}
else
{
return m_InternalRigidbody.linearVelocity;
}
}
/// <summary>
/// Sets the angular velocity for the Rigidbody.
/// </summary>
/// <remarks>
/// For <see cref="Rigidbody2D"/>, the z component of <param name="angularVelocity"/> is only used to set the angular velocity.
/// A quick way to pass in a 2D angular velocity component is: <see cref="Vector3.forward"/> * angularVelocity (where angularVelocity is a float)
/// </remarks>
/// <param name="angularVelocity">the angular velocity to apply to the body</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetAngularVelocity(Vector3 angularVelocity)
{
if (m_IsRigidbody2D)
{
m_InternalRigidbody2D.angularVelocity = angularVelocity.z;
}
else
{
m_InternalRigidbody.angularVelocity = angularVelocity;
}
}
/// <summary>
/// Gets the angular velocity for the Rigidbody.
/// </summary>
/// <remarks>
/// For <see cref="Rigidbody2D"/>, the z component of the <see cref="Vector3"/> returned is the angular velocity of the object.
/// </remarks>
/// <returns>angular velocity as a <see cref="Vector3"/></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector3 GetAngularVelocity()
{
if (m_IsRigidbody2D)
{
return Vector3.forward * m_InternalRigidbody2D.angularVelocity;
}
else
{
return m_InternalRigidbody.angularVelocity;
}
}
/// <summary> /// <summary>
/// Gets the position of the Rigidbody /// Gets the position of the Rigidbody
/// </summary> /// </summary>
@@ -129,11 +271,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
return m_Rigidbody2D.position; return m_InternalRigidbody2D.position;
} }
else else
{ {
return m_Rigidbody.position; return m_InternalRigidbody.position;
} }
} }
@@ -148,13 +290,13 @@ namespace Unity.Netcode.Components
{ {
var quaternion = Quaternion.identity; var quaternion = Quaternion.identity;
var angles = quaternion.eulerAngles; var angles = quaternion.eulerAngles;
angles.z = m_Rigidbody2D.rotation; angles.z = m_InternalRigidbody2D.rotation;
quaternion.eulerAngles = angles; quaternion.eulerAngles = angles;
return quaternion; return quaternion;
} }
else else
{ {
return m_Rigidbody.rotation; return m_InternalRigidbody.rotation;
} }
} }
@@ -167,11 +309,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.MovePosition(position); m_InternalRigidbody2D.MovePosition(position);
} }
else else
{ {
m_Rigidbody.MovePosition(position); m_InternalRigidbody.MovePosition(position);
} }
} }
@@ -184,11 +326,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.position = position; m_InternalRigidbody2D.position = position;
} }
else else
{ {
m_Rigidbody.position = position; m_InternalRigidbody.position = position;
} }
} }
@@ -200,16 +342,19 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.position = transform.position; m_InternalRigidbody2D.position = transform.position;
m_Rigidbody2D.rotation = transform.eulerAngles.z; m_InternalRigidbody2D.rotation = transform.eulerAngles.z;
} }
else else
{ {
m_Rigidbody.position = transform.position; m_InternalRigidbody.position = transform.position;
m_Rigidbody.rotation = transform.rotation; m_InternalRigidbody.rotation = transform.rotation;
} }
} }
// Used for Rigidbody only (see info on normalized below)
private Vector4 m_QuaternionCheck = Vector4.zero;
/// <summary> /// <summary>
/// Rotatates the Rigidbody towards a specified rotation /// Rotatates the Rigidbody towards a specified rotation
/// </summary> /// </summary>
@@ -221,13 +366,24 @@ namespace Unity.Netcode.Components
{ {
var quaternion = Quaternion.identity; var quaternion = Quaternion.identity;
var angles = quaternion.eulerAngles; var angles = quaternion.eulerAngles;
angles.z = m_Rigidbody2D.rotation; angles.z = m_InternalRigidbody2D.rotation;
quaternion.eulerAngles = angles; quaternion.eulerAngles = angles;
m_Rigidbody2D.MoveRotation(quaternion); m_InternalRigidbody2D.MoveRotation(quaternion);
} }
else else
{ {
m_Rigidbody.MoveRotation(rotation); // Evidently we need to check to make sure the quaternion is a perfect
// magnitude of 1.0f when applying the rotation to a rigid body.
m_QuaternionCheck.x = rotation.x;
m_QuaternionCheck.y = rotation.y;
m_QuaternionCheck.z = rotation.z;
m_QuaternionCheck.w = rotation.w;
// If the magnitude is greater than 1.0f (even by a very small fractional value), then normalize the quaternion
if (m_QuaternionCheck.magnitude != 1.0f)
{
rotation.Normalize();
}
m_InternalRigidbody.MoveRotation(rotation);
} }
} }
@@ -240,11 +396,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.rotation = rotation.eulerAngles.z; m_InternalRigidbody2D.rotation = rotation.eulerAngles.z;
} }
else else
{ {
m_Rigidbody.rotation = rotation; m_InternalRigidbody.rotation = rotation;
} }
} }
@@ -256,7 +412,7 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
switch (m_Rigidbody2D.interpolation) switch (m_InternalRigidbody2D.interpolation)
{ {
case RigidbodyInterpolation2D.None: case RigidbodyInterpolation2D.None:
{ {
@@ -277,7 +433,7 @@ namespace Unity.Netcode.Components
} }
else else
{ {
switch (m_Rigidbody.interpolation) switch (m_InternalRigidbody.interpolation)
{ {
case RigidbodyInterpolation.None: case RigidbodyInterpolation.None:
{ {
@@ -306,16 +462,16 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
if (m_Rigidbody2D.IsSleeping()) if (m_InternalRigidbody2D.IsSleeping())
{ {
m_Rigidbody2D.WakeUp(); m_InternalRigidbody2D.WakeUp();
} }
} }
else else
{ {
if (m_Rigidbody.IsSleeping()) if (m_InternalRigidbody.IsSleeping())
{ {
m_Rigidbody.WakeUp(); m_InternalRigidbody.WakeUp();
} }
} }
} }
@@ -328,11 +484,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.Sleep(); m_InternalRigidbody2D.Sleep();
} }
else else
{ {
m_Rigidbody.Sleep(); m_InternalRigidbody.Sleep();
} }
} }
@@ -341,11 +497,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
return m_Rigidbody2D.isKinematic; return m_InternalRigidbody2D.bodyType == RigidbodyType2D.Kinematic;
} }
else else
{ {
return m_Rigidbody.isKinematic; return m_InternalRigidbody.isKinematic;
} }
} }
@@ -370,11 +526,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.isKinematic = isKinematic; m_InternalRigidbody2D.bodyType = isKinematic ? RigidbodyType2D.Kinematic : RigidbodyType2D.Dynamic;
} }
else else
{ {
m_Rigidbody.isKinematic = isKinematic; m_InternalRigidbody.isKinematic = isKinematic;
} }
// If we are not spawned, then exit early // If we are not spawned, then exit early
@@ -391,7 +547,7 @@ namespace Unity.Netcode.Components
if (IsKinematic()) if (IsKinematic())
{ {
// If not already set to interpolate then set the Rigidbody to interpolate // If not already set to interpolate then set the Rigidbody to interpolate
if (m_Rigidbody.interpolation == RigidbodyInterpolation.Extrapolate) if (m_InternalRigidbody.interpolation == RigidbodyInterpolation.Extrapolate)
{ {
// Sleep until the next fixed update when switching from extrapolation to interpolation // Sleep until the next fixed update when switching from extrapolation to interpolation
SleepRigidbody(); SleepRigidbody();
@@ -420,11 +576,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.None; m_InternalRigidbody2D.interpolation = RigidbodyInterpolation2D.None;
} }
else else
{ {
m_Rigidbody.interpolation = RigidbodyInterpolation.None; m_InternalRigidbody.interpolation = RigidbodyInterpolation.None;
} }
break; break;
} }
@@ -432,11 +588,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.Interpolate; m_InternalRigidbody2D.interpolation = RigidbodyInterpolation2D.Interpolate;
} }
else else
{ {
m_Rigidbody.interpolation = RigidbodyInterpolation.Interpolate; m_InternalRigidbody.interpolation = RigidbodyInterpolation.Interpolate;
} }
break; break;
} }
@@ -444,11 +600,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.Extrapolate; m_InternalRigidbody2D.interpolation = RigidbodyInterpolation2D.Extrapolate;
} }
else else
{ {
m_Rigidbody.interpolation = RigidbodyInterpolation.Extrapolate; m_InternalRigidbody.interpolation = RigidbodyInterpolation.Extrapolate;
} }
break; break;
} }
@@ -501,6 +657,8 @@ namespace Unity.Netcode.Components
/// <inheritdoc /> /// <inheritdoc />
public override void OnNetworkSpawn() public override void OnNetworkSpawn()
{ {
m_TickFrequency = 1.0f / NetworkManager.NetworkConfig.TickRate;
m_TickRate = NetworkManager.NetworkConfig.TickRate;
UpdateOwnershipAuthority(); UpdateOwnershipAuthority();
} }
@@ -561,24 +719,28 @@ namespace Unity.Netcode.Components
private void ApplyFixedJoint2D(NetworkRigidbodyBase bodyToConnect, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true) private void ApplyFixedJoint2D(NetworkRigidbodyBase bodyToConnect, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
{ {
transform.position = position; transform.position = position;
m_Rigidbody2D.position = position; m_InternalRigidbody2D.position = position;
m_OriginalGravitySetting = bodyToConnect.m_Rigidbody.useGravity; m_OriginalGravitySetting = bodyToConnect.m_InternalRigidbody.useGravity;
m_FixedJoint2DUsingGravity = useGravity; m_FixedJoint2DUsingGravity = useGravity;
if (!useGravity) if (!useGravity)
{ {
m_OriginalGravityScale = m_Rigidbody2D.gravityScale; m_OriginalGravityScale = m_InternalRigidbody2D.gravityScale;
m_Rigidbody2D.gravityScale = 0.0f; m_InternalRigidbody2D.gravityScale = 0.0f;
} }
if (zeroVelocity) if (zeroVelocity)
{ {
m_Rigidbody2D.velocity = Vector2.zero; #if COM_UNITY_MODULES_PHYSICS2D_LINEAR
m_Rigidbody2D.angularVelocity = 0.0f; m_InternalRigidbody2D.linearVelocity = Vector2.zero;
#else
m_InternalRigidbody2D.velocity = Vector2.zero;
#endif
m_InternalRigidbody2D.angularVelocity = 0.0f;
} }
FixedJoint2D = gameObject.AddComponent<FixedJoint2D>(); FixedJoint2D = gameObject.AddComponent<FixedJoint2D>();
FixedJoint2D.connectedBody = bodyToConnect.m_Rigidbody2D; FixedJoint2D.connectedBody = bodyToConnect.m_InternalRigidbody2D;
OnFixedJoint2DCreated(); OnFixedJoint2DCreated();
} }
@@ -586,16 +748,16 @@ namespace Unity.Netcode.Components
private void ApplyFixedJoint(NetworkRigidbodyBase bodyToConnectTo, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true) private void ApplyFixedJoint(NetworkRigidbodyBase bodyToConnectTo, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
{ {
transform.position = position; transform.position = position;
m_Rigidbody.position = position; m_InternalRigidbody.position = position;
if (zeroVelocity) if (zeroVelocity)
{ {
m_Rigidbody.linearVelocity = Vector3.zero; m_InternalRigidbody.linearVelocity = Vector3.zero;
m_Rigidbody.angularVelocity = Vector3.zero; m_InternalRigidbody.angularVelocity = Vector3.zero;
} }
m_OriginalGravitySetting = m_Rigidbody.useGravity; m_OriginalGravitySetting = m_InternalRigidbody.useGravity;
m_Rigidbody.useGravity = useGravity; m_InternalRigidbody.useGravity = useGravity;
FixedJoint = gameObject.AddComponent<FixedJoint>(); FixedJoint = gameObject.AddComponent<FixedJoint>();
FixedJoint.connectedBody = bodyToConnectTo.m_Rigidbody; FixedJoint.connectedBody = bodyToConnectTo.m_InternalRigidbody;
FixedJoint.connectedMassScale = connectedMassScale; FixedJoint.connectedMassScale = connectedMassScale;
FixedJoint.massScale = massScale; FixedJoint.massScale = massScale;
OnFixedJointCreated(); OnFixedJointCreated();
@@ -707,7 +869,7 @@ namespace Unity.Netcode.Components
if (FixedJoint != null) if (FixedJoint != null)
{ {
FixedJoint.connectedBody = null; FixedJoint.connectedBody = null;
m_Rigidbody.useGravity = m_OriginalGravitySetting; m_InternalRigidbody.useGravity = m_OriginalGravitySetting;
Destroy(FixedJoint); Destroy(FixedJoint);
FixedJoint = null; FixedJoint = null;
ResetInterpolation(); ResetInterpolation();

View File

@@ -12,6 +12,9 @@ namespace Unity.Netcode.Components
[AddComponentMenu("Netcode/Network Rigidbody")] [AddComponentMenu("Netcode/Network Rigidbody")]
public class NetworkRigidbody : NetworkRigidbodyBase public class NetworkRigidbody : NetworkRigidbodyBase
{ {
public Rigidbody Rigidbody => m_InternalRigidbody;
protected virtual void Awake() protected virtual void Awake()
{ {
Initialize(RigidbodyTypes.Rigidbody); Initialize(RigidbodyTypes.Rigidbody);

View File

@@ -12,6 +12,7 @@ namespace Unity.Netcode.Components
[AddComponentMenu("Netcode/Network Rigidbody 2D")] [AddComponentMenu("Netcode/Network Rigidbody 2D")]
public class NetworkRigidbody2D : NetworkRigidbodyBase public class NetworkRigidbody2D : NetworkRigidbodyBase
{ {
public Rigidbody2D Rigidbody2D => m_InternalRigidbody2D;
protected virtual void Awake() protected virtual void Awake()
{ {
Initialize(RigidbodyTypes.Rigidbody2D); Initialize(RigidbodyTypes.Rigidbody2D);

File diff suppressed because it is too large Load Diff

View File

@@ -159,9 +159,21 @@ namespace Unity.Netcode
public bool AutoSpawnPlayerPrefabClientSide = true; public bool AutoSpawnPlayerPrefabClientSide = true;
#if MULTIPLAYER_TOOLS #if MULTIPLAYER_TOOLS
/// <summary>
/// Controls whether network messaging metrics will be gathered. (defaults to true)
/// There is a slight performance cost to having this enabled, and can increase in processing time based on network message traffic.
/// </summary>
/// <remarks>
/// The Realtime Network Stats Monitoring tool requires this to be enabled.
/// </remarks>
[Tooltip("Enable (default) if you want to gather messaging metrics. Realtime Network Stats Monitor requires this to be enabled. Disabling this can improve performance in release builds.")]
public bool NetworkMessageMetrics = true; public bool NetworkMessageMetrics = true;
#endif #endif
/// <summary>
/// When enabled (default, this enables network profiling information. This does come with a per message processing cost.
/// Network profiling information is automatically disabled in release builds.
/// </summary>
[Tooltip("Enable (default) if you want to profile network messages with development builds and defaults to being disabled in release builds. When disabled, network messaging profiling will be disabled in development builds.")]
public bool NetworkProfilingMetrics = true; public bool NetworkProfilingMetrics = true;
/// <summary> /// <summary>

View File

@@ -1,15 +1,8 @@
using System.Collections.Generic;
using UnityEngine; using UnityEngine;
namespace Unity.Netcode namespace Unity.Netcode
{ {
public enum NetworkTopologyTypes
{
ClientServer,
DistributedAuthority
}
/// <summary> /// <summary>
/// A NetworkClient /// A NetworkClient
/// </summary> /// </summary>
@@ -61,9 +54,9 @@ namespace Unity.Netcode
public NetworkObject PlayerObject; public NetworkObject PlayerObject;
/// <summary> /// <summary>
/// The list of NetworkObject's owned by this client instance /// The NetworkObject's owned by this client instance
/// </summary> /// </summary>
public List<NetworkObject> OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new List<NetworkObject>(); public NetworkObject[] OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new NetworkObject[] { };
internal NetworkSpawnManager SpawnManager { get; private set; } internal NetworkSpawnManager SpawnManager { get; private set; }

View File

@@ -735,42 +735,23 @@ namespace Unity.Netcode
RemovePendingClient(ownerClientId); RemovePendingClient(ownerClientId);
var client = AddClient(ownerClientId); var client = AddClient(ownerClientId);
if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && NetworkManager.NetworkConfig.PlayerPrefab != null)
// Server-side spawning (only if there is a prefab hash or player prefab provided)
if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && (response.PlayerPrefabHash.HasValue || NetworkManager.NetworkConfig.PlayerPrefab != null))
{ {
var prefabNetworkObject = NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>(); var playerObject = response.PlayerPrefabHash.HasValue ? NetworkManager.SpawnManager.GetNetworkObjectToSpawn(response.PlayerPrefabHash.Value, ownerClientId, response.Position.GetValueOrDefault(), response.Rotation.GetValueOrDefault())
var playerPrefabHash = response.PlayerPrefabHash ?? prefabNetworkObject.GlobalObjectIdHash; : NetworkManager.SpawnManager.GetNetworkObjectToSpawn(NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash, ownerClientId, response.Position.GetValueOrDefault(), response.Rotation.GetValueOrDefault());
// Generate a SceneObject for the player object to spawn
// Note: This is only to create the local NetworkObject, many of the serialized properties of the player prefab will be set when instantiated.
var sceneObject = new NetworkObject.SceneObject
{
OwnerClientId = ownerClientId,
IsPlayerObject = true,
IsSceneObject = false,
HasTransform = prefabNetworkObject.SynchronizeTransform,
Hash = playerPrefabHash,
TargetClientId = ownerClientId,
DontDestroyWithOwner = prefabNetworkObject.DontDestroyWithOwner,
Transform = new NetworkObject.SceneObject.TransformData
{
Position = response.Position.GetValueOrDefault(),
Rotation = response.Rotation.GetValueOrDefault()
}
};
// Create the player NetworkObject locally
var networkObject = NetworkManager.SpawnManager.CreateLocalNetworkObject(sceneObject);
// Spawn the player NetworkObject locally // Spawn the player NetworkObject locally
NetworkManager.SpawnManager.SpawnNetworkObjectLocally( NetworkManager.SpawnManager.SpawnNetworkObjectLocally(
networkObject, playerObject,
NetworkManager.SpawnManager.GetNetworkObjectId(), NetworkManager.SpawnManager.GetNetworkObjectId(),
sceneObject: false, sceneObject: false,
playerObject: true, playerObject: true,
ownerClientId, ownerClientId,
destroyWithScene: false); destroyWithScene: false);
client.AssignPlayerObject(ref networkObject); client.AssignPlayerObject(ref playerObject);
} }
// Server doesn't send itself the connection approved message // Server doesn't send itself the connection approved message
@@ -871,6 +852,7 @@ namespace Unity.Netcode
} }
} }
// Exit early if no player object was spawned
if (!response.CreatePlayerObject || (response.PlayerPrefabHash == null && NetworkManager.NetworkConfig.PlayerPrefab == null)) if (!response.CreatePlayerObject || (response.PlayerPrefabHash == null && NetworkManager.NetworkConfig.PlayerPrefab == null))
{ {
return; return;
@@ -1003,10 +985,18 @@ namespace Unity.Netcode
ConnectedClientIds.Add(clientId); ConnectedClientIds.Add(clientId);
} }
var distributedAuthority = NetworkManager.DistributedAuthorityMode;
var sessionOwnerId = NetworkManager.CurrentSessionOwner;
var isSessionOwner = NetworkManager.LocalClient.IsSessionOwner;
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList) foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
{ {
if (networkObject.SpawnWithObservers) if (networkObject.SpawnWithObservers)
{ {
// Don't add the client to the observers if hidden from the session owner
if (networkObject.IsOwner && distributedAuthority && !isSessionOwner && !networkObject.Observers.Contains(sessionOwnerId))
{
continue;
}
networkObject.Observers.Add(clientId); networkObject.Observers.Add(clientId);
} }
} }
@@ -1229,6 +1219,8 @@ namespace Unity.Netcode
var message = new ClientDisconnectedMessage { ClientId = clientId }; var message = new ClientDisconnectedMessage { ClientId = clientId };
MessageManager?.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds); MessageManager?.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
// Used for testing/validation purposes only
#if ENABLE_DAHOST_AUTOPROMOTE_SESSION_OWNER
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress && NetworkManager.IsListening) if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress && NetworkManager.IsListening)
{ {
var newSessionOwner = NetworkManager.LocalClientId; var newSessionOwner = NetworkManager.LocalClientId;
@@ -1259,6 +1251,7 @@ namespace Unity.Netcode
MessageManager?.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds); MessageManager?.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
NetworkManager.SetSessionOwner(newSessionOwner); NetworkManager.SetSessionOwner(newSessionOwner);
} }
#endif
} }
// If the client ID transport map exists // If the client ID transport map exists
@@ -1306,7 +1299,15 @@ namespace Unity.Netcode
{ {
if (!LocalClient.IsServer) if (!LocalClient.IsServer)
{ {
throw new NotServerException($"Only server can disconnect remote clients. Please use `{nameof(Shutdown)}()` instead."); if (NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
{
throw new NotServerException($"Only server can disconnect remote clients. Please use `{nameof(Shutdown)}()` instead.");
}
else
{
Debug.LogWarning($"Currently, clients cannot disconnect other clients from a distributed authority session. Please use `{nameof(Shutdown)}()` instead.");
return;
}
} }
if (clientId == NetworkManager.ServerClientId) if (clientId == NetworkManager.ServerClientId)

View File

@@ -15,10 +15,16 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// The base class to override to write network code. Inherits MonoBehaviour /// The base class to override to write network code. Inherits MonoBehaviour.
/// </summary> /// </summary>
public abstract class NetworkBehaviour : MonoBehaviour public abstract class NetworkBehaviour : MonoBehaviour
{ {
#if UNITY_EDITOR
[HideInInspector]
[SerializeField]
internal bool ShowTopMostFoldoutHeaderGroup = true;
#endif
#pragma warning disable IDE1006 // disable naming rule violation check #pragma warning disable IDE1006 // disable naming rule violation check
// RuntimeAccessModifiersILPP will make this `public` // RuntimeAccessModifiersILPP will make this `public`
@@ -27,7 +33,7 @@ namespace Unity.Netcode
// RuntimeAccessModifiersILPP will make this `public` // RuntimeAccessModifiersILPP will make this `public`
internal static readonly Dictionary<Type, Dictionary<uint, RpcReceiveHandler>> __rpc_func_table = new Dictionary<Type, Dictionary<uint, RpcReceiveHandler>>(); internal static readonly Dictionary<Type, Dictionary<uint, RpcReceiveHandler>> __rpc_func_table = new Dictionary<Type, Dictionary<uint, RpcReceiveHandler>>();
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
// RuntimeAccessModifiersILPP will make this `public` // RuntimeAccessModifiersILPP will make this `public`
internal static readonly Dictionary<Type, Dictionary<uint, string>> __rpc_name_table = new Dictionary<Type, Dictionary<uint, string>>(); internal static readonly Dictionary<Type, Dictionary<uint, string>> __rpc_name_table = new Dictionary<Type, Dictionary<uint, string>>();
#endif #endif
@@ -124,7 +130,7 @@ namespace Unity.Netcode
} }
bufferWriter.Dispose(); bufferWriter.Dispose();
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName)) if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
{ {
NetworkManager.NetworkMetrics.TrackRpcSent( NetworkManager.NetworkMetrics.TrackRpcSent(
@@ -252,7 +258,7 @@ namespace Unity.Netcode
} }
bufferWriter.Dispose(); bufferWriter.Dispose();
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName)) if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
{ {
if (clientRpcParams.Send.TargetClientIds != null) if (clientRpcParams.Send.TargetClientIds != null)
@@ -410,8 +416,8 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Gets the NetworkManager that owns this NetworkBehaviour instance /// Gets the NetworkManager that owns this NetworkBehaviour instance.
/// See note around `NetworkObject` for how there is a chicken / egg problem when we are not initialized /// See `NetworkObject` note for how there is a chicken/egg problem when not initialized.
/// </summary> /// </summary>
public NetworkManager NetworkManager public NetworkManager NetworkManager
{ {
@@ -439,38 +445,40 @@ namespace Unity.Netcode
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeArray{ulong})"/>, /// <see cref="Unity.Netcode.RpcTarget.Not(NativeArray{ulong})"/>,
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeList{ulong})"/>, /// <see cref="Unity.Netcode.RpcTarget.Not(NativeList{ulong})"/>,
/// <see cref="Unity.Netcode.RpcTarget.Not(ulong[])"/>, and /// <see cref="Unity.Netcode.RpcTarget.Not(ulong[])"/>, and
/// <see cref="Unity.Netcode.RpcTarget.Not{T}(T)"/> /// <see cref="Unity.Netcode.RpcTarget.Not{T}(T)"/>.
/// </summary> /// </summary>
#pragma warning restore IDE0001 #pragma warning restore IDE0001
public RpcTarget RpcTarget => NetworkManager.RpcTarget; public RpcTarget RpcTarget => NetworkManager.RpcTarget;
/// <summary> /// <summary>
/// If a NetworkObject is assigned, it will return whether or not this NetworkObject /// If a NetworkObject is assigned, returns whether the NetworkObject
/// is the local player object. If no NetworkObject is assigned it will always return false. /// is the local player object. If no NetworkObject is assigned, returns false.
/// </summary> /// </summary>
public bool IsLocalPlayer { get; private set; } public bool IsLocalPlayer { get; private set; }
/// <summary> /// <summary>
/// Gets if the object is owned by the local player or if the object is the local player object /// Gets whether the object is owned by the local player or if the object is the local player object.
/// </summary> /// </summary>
public bool IsOwner { get; internal set; } public bool IsOwner { get; internal set; }
/// <summary> /// <summary>
/// Gets if we are executing as server /// Gets whether executing as a server.
/// </summary> /// </summary>
public bool IsServer { get; private set; } public bool IsServer { get; private set; }
/// <summary> /// <summary>
/// Determines if the local client has authority over the associated NetworkObject /// Determines if the local client has authority over the associated NetworkObject.
/// Client-Server: This will return true if IsServer or IsHost /// <list type="bullet">
/// Distributed Authority: This will return true if IsOwner /// <item>In client-server contexts: returns true if `IsServer` or `IsHost`.</item>
/// <item>In distributed authority contexts: returns true if `IsOwner`.</item>
/// </list>
/// </summary> /// </summary>
public bool HasAuthority { get; internal set; } public bool HasAuthority { get; internal set; }
internal NetworkClient LocalClient { get; private set; } internal NetworkClient LocalClient { get; private set; }
/// <summary> /// <summary>
/// Gets if the client is the distributed authority mode session owner /// Gets whether the client is the distributed authority mode session owner.
/// </summary> /// </summary>
public bool IsSessionOwner public bool IsSessionOwner
{ {
@@ -486,29 +494,29 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Gets if the server (local or remote) is a host - i.e., also a client /// Gets whether the server (local or remote) is a host.
/// </summary> /// </summary>
public bool ServerIsHost { get; private set; } public bool ServerIsHost { get; private set; }
/// <summary> /// <summary>
/// Gets if we are executing as client /// Gets whether executing as a client.
/// </summary> /// </summary>
public bool IsClient { get; private set; } public bool IsClient { get; private set; }
/// <summary> /// <summary>
/// Gets if we are executing as Host, I.E Server and Client /// Gets whether executing as a host (both server and client).
/// </summary> /// </summary>
public bool IsHost { get; private set; } public bool IsHost { get; private set; }
/// <summary> /// <summary>
/// Gets Whether or not the object has a owner /// Gets whether the object has an owner.
/// </summary> /// </summary>
public bool IsOwnedByServer { get; internal set; } public bool IsOwnedByServer { get; internal set; }
/// <summary> /// <summary>
/// Used to determine if it is safe to access NetworkObject and NetworkManager from within a NetworkBehaviour component /// Determines whether it's safe to access a NetworkObject and NetworkManager from within a NetworkBehaviour component.
/// Primarily useful when checking NetworkObject/NetworkManager properties within FixedUpate /// Primarily useful when checking NetworkObject or NetworkManager properties within FixedUpate.
/// </summary> /// </summary>
public bool IsSpawned { get; internal set; } public bool IsSpawned { get; internal set; }
@@ -528,7 +536,7 @@ namespace Unity.Netcode
/// the warning below. This is why IsBehaviourEditable had to be created. Matt was going to re-do /// the warning below. This is why IsBehaviourEditable had to be created. Matt was going to re-do
/// how NetworkObject works but it was close to the release and too risky to change /// how NetworkObject works but it was close to the release and too risky to change
/// <summary> /// <summary>
/// Gets the NetworkObject that owns this NetworkBehaviour instance /// Gets the NetworkObject that owns this NetworkBehaviour instance.
/// </summary> /// </summary>
public NetworkObject NetworkObject public NetworkObject NetworkObject
{ {
@@ -567,19 +575,19 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Gets whether or not this NetworkBehaviour instance has a NetworkObject owner. /// Gets whether this NetworkBehaviour instance has a NetworkObject owner.
/// </summary> /// </summary>
public bool HasNetworkObject => NetworkObject != null; public bool HasNetworkObject => NetworkObject != null;
private NetworkObject m_NetworkObject = null; private NetworkObject m_NetworkObject = null;
/// <summary> /// <summary>
/// Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour /// Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour instance.
/// </summary> /// </summary>
public ulong NetworkObjectId { get; internal set; } public ulong NetworkObjectId { get; internal set; }
/// <summary> /// <summary>
/// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject /// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject.
/// </summary> /// </summary>
public ushort NetworkBehaviourId { get; internal set; } public ushort NetworkBehaviourId { get; internal set; }
@@ -589,7 +597,7 @@ namespace Unity.Netcode
internal ushort NetworkBehaviourIdCache = 0; internal ushort NetworkBehaviourIdCache = 0;
/// <summary> /// <summary>
/// Returns a the NetworkBehaviour with a given BehaviourId for the current NetworkObject /// Returns the NetworkBehaviour with a given BehaviourId for the current NetworkObject.
/// </summary> /// </summary>
/// <param name="behaviourId">The behaviourId to return</param> /// <param name="behaviourId">The behaviourId to return</param>
/// <returns>Returns NetworkBehaviour with given behaviourId</returns> /// <returns>Returns NetworkBehaviour with given behaviourId</returns>
@@ -599,7 +607,7 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Gets the ClientId that owns the NetworkObject /// Gets the ClientId that owns this NetworkObject.
/// </summary> /// </summary>
public ulong OwnerClientId { get; internal set; } public ulong OwnerClientId { get; internal set; }
@@ -651,28 +659,29 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Distributed Authority Mode Only /// Only for use in distributed authority mode.
/// Invoked only on the authority instance when a <see cref="NetworkObject"/> is deferring its despawn on non-authoritative instances. /// Invoked only on the authority instance when a <see cref="NetworkObject"/> is deferring its despawn on non-authoritative instances.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// See also: <see cref="NetworkObject.DeferDespawn(int, bool)"/> /// See also: <see cref="NetworkObject.DeferDespawn(int, bool)"/>
/// </remarks> /// </remarks>
/// <param name="despawnTick">the future network tick that the <see cref="NetworkObject"/> will be despawned on non-authoritative instances</param> /// <param name="despawnTick">The future network tick that the <see cref="NetworkObject"/> will be despawned on non-authoritative instances</param>
public virtual void OnDeferringDespawn(int despawnTick) { } public virtual void OnDeferringDespawn(int despawnTick) { }
/// <summary>
/// Gets called after the <see cref="NetworkObject"/> is spawned. No NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked yet. /// Gets called after the <see cref="NetworkObject"/> is spawned. No NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked yet.
/// A reference to <see cref="NetworkManager"/> is passed in as a parameter to determine the context of execution (IsServer/IsClient) /// A reference to <see cref="NetworkManager"/> is passed in as a parameter to determine the context of execution (`IsServer` or `IsClient`).
/// </summary> /// </summary>
/// <remarks>
/// <param name="networkManager">a ref to the <see cref="NetworkManager"/> since this is not yet set on the <see cref="NetworkBehaviour"/></param> /// <param name="networkManager">a ref to the <see cref="NetworkManager"/> since this is not yet set on the <see cref="NetworkBehaviour"/></param>
/// <remarks>
/// The <see cref="NetworkBehaviour"/> will not have anything assigned to it at this point in time. /// The <see cref="NetworkBehaviour"/> 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. /// 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. /// This can be used to handle things like initializing a NetworkVariable.
/// </remarks> /// </remarks>
protected virtual void OnNetworkPreSpawn(ref NetworkManager networkManager) { } protected virtual void OnNetworkPreSpawn(ref NetworkManager networkManager) { }
/// <summary> /// <summary>
/// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup. /// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered, and the network is set up.
/// </summary> /// </summary>
public virtual void OnNetworkSpawn() { } public virtual void OnNetworkSpawn() { }
@@ -685,29 +694,33 @@ namespace Unity.Netcode
/// </remarks> /// </remarks>
protected virtual void OnNetworkPostSpawn() { } protected virtual void OnNetworkPostSpawn() { }
protected internal virtual void InternalOnNetworkPostSpawn() { }
/// <summary> /// <summary>
/// [Client-Side Only] /// This method is only available client-side.
/// 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 /// When a new client joins it's synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all
/// <see cref="NetworkObject"/>s and scenes (if scene management is enabled) have finished synchronizing, all NetworkBehaviour components associated with spawned <see cref="NetworkObject"/>s /// <see cref="NetworkObject"/>s and scenes (if scene management is enabled) have finished synchronizing, all NetworkBehaviour components associated with spawned <see cref="NetworkObject"/>s
/// will have this method invoked. /// will have this method invoked.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// 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 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. /// This is only invoked on clients during a client-server network topology session.
/// </remarks> /// </remarks>
protected virtual void OnNetworkSessionSynchronized() { } protected virtual void OnNetworkSessionSynchronized() { }
protected internal virtual void InternalOnNetworkSessionSynchronized() { }
/// <summary> /// <summary>
/// [Client & Server Side] /// When a scene is loaded and in-scene placed NetworkObjects are finished spawning, this method is invoked on all of the newly spawned in-scene placed NetworkObjects.
/// 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 method runs both client and server side.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// 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. /// This method 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.
/// </remarks> /// </remarks>
protected virtual void OnInSceneObjectsSpawned() { } protected virtual void OnInSceneObjectsSpawned() { }
/// <summary> /// <summary>
/// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients. /// Gets called when the <see cref="NetworkObject"/> gets despawned. This method runs both client and server side.
/// </summary> /// </summary>
public virtual void OnNetworkDespawn() { } public virtual void OnNetworkDespawn() { }
@@ -756,6 +769,7 @@ namespace Unity.Netcode
{ {
try try
{ {
InternalOnNetworkPostSpawn();
OnNetworkPostSpawn(); OnNetworkPostSpawn();
} }
catch (Exception e) catch (Exception e)
@@ -768,6 +782,7 @@ namespace Unity.Netcode
{ {
try try
{ {
InternalOnNetworkSessionSynchronized();
OnNetworkSessionSynchronized(); OnNetworkSessionSynchronized();
} }
catch (Exception e) catch (Exception e)
@@ -803,7 +818,8 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Gets called when the local client gains ownership of this object /// In client-server contexts, this method is invoked on both the server and the local client of the owner when <see cref="Netcode.NetworkObject"/> ownership is assigned.
/// <para>In distributed authority contexts, this method is only invoked on the local client that has been assigned ownership of the associated <see cref="Netcode.NetworkObject"/>.</para>
/// </summary> /// </summary>
public virtual void OnGainedOwnership() { } public virtual void OnGainedOwnership() { }
@@ -814,8 +830,8 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Invoked on all clients, override this method to be notified of any /// Invoked on all clients. Override this method to be notified of any
/// ownership changes (even if the instance was niether the previous or /// ownership changes (even if the instance was neither the previous or
/// newly assigned current owner). /// newly assigned current owner).
/// </summary> /// </summary>
/// <param name="previous">the previous owner</param> /// <param name="previous">the previous owner</param>
@@ -831,7 +847,9 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Gets called when we loose ownership of this object /// In client-server contexts, this method is invoked on the local client when it loses ownership of the associated <see cref="Netcode.NetworkObject"/>
/// and on the server when any client loses ownership.
/// <para>In distributed authority contexts, this method is only invoked on the local client that has lost ownership of the associated <see cref="Netcode.NetworkObject"/>.</para>
/// </summary> /// </summary>
public virtual void OnLostOwnership() { } public virtual void OnLostOwnership() { }
@@ -842,11 +860,13 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Gets called when the parent NetworkObject of this NetworkBehaviour's NetworkObject has changed /// Gets called when the parent NetworkObject of this NetworkBehaviour's NetworkObject has changed.
/// </summary> /// </summary>
/// <param name="parentNetworkObject">the new <see cref="NetworkObject"/> parent</param> /// <param name="parentNetworkObject">the new <see cref="NetworkObject"/> parent</param>
public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { } public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
internal virtual void InternalOnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
private bool m_VarInit = false; private bool m_VarInit = false;
private readonly List<HashSet<int>> m_DeliveryMappedNetworkVariableIndices = new List<HashSet<int>>(); private readonly List<HashSet<int>> m_DeliveryMappedNetworkVariableIndices = new List<HashSet<int>>();
@@ -877,7 +897,7 @@ namespace Unity.Netcode
#pragma warning restore IDE1006 // restore naming rule violation check #pragma warning restore IDE1006 // restore naming rule violation check
{ {
__rpc_func_table[GetType()][hash] = handler; __rpc_func_table[GetType()][hash] = handler;
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
__rpc_name_table[GetType()][hash] = rpcMethodName; __rpc_name_table[GetType()][hash] = rpcMethodName;
#endif #endif
} }
@@ -903,7 +923,7 @@ namespace Unity.Netcode
if (!__rpc_func_table.ContainsKey(GetType())) if (!__rpc_func_table.ContainsKey(GetType()))
{ {
__rpc_func_table[GetType()] = new Dictionary<uint, RpcReceiveHandler>(); __rpc_func_table[GetType()] = new Dictionary<uint, RpcReceiveHandler>();
#if UNITY_EDITOR || DEVELOPMENT_BUILD #if UNITY_EDITOR || DEVELOPMENT_BUILD || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
__rpc_name_table[GetType()] = new Dictionary<uint, string>(); __rpc_name_table[GetType()] = new Dictionary<uint, string>();
#endif #endif
__initializeRpcs(); __initializeRpcs();
@@ -950,7 +970,16 @@ namespace Unity.Netcode
// during OnNetworkSpawn has been sent and needs to be cleared // during OnNetworkSpawn has been sent and needs to be cleared
for (int i = 0; i < NetworkVariableFields.Count; i++) for (int i = 0; i < NetworkVariableFields.Count; i++)
{ {
NetworkVariableFields[i].ResetDirty(); var networkVariable = NetworkVariableFields[i];
if (networkVariable.IsDirty())
{
if (networkVariable.CanSend())
{
networkVariable.UpdateLastSentTime();
networkVariable.ResetDirty();
networkVariable.SetDirty(false);
}
}
} }
} }
else else
@@ -958,7 +987,16 @@ namespace Unity.Netcode
// mark any variables we wrote as no longer dirty // mark any variables we wrote as no longer dirty
for (int i = 0; i < NetworkVariableIndexesToReset.Count; i++) for (int i = 0; i < NetworkVariableIndexesToReset.Count; i++)
{ {
NetworkVariableFields[NetworkVariableIndexesToReset[i]].ResetDirty(); var networkVariable = NetworkVariableFields[NetworkVariableIndexesToReset[i]];
if (networkVariable.IsDirty())
{
if (networkVariable.CanSend())
{
networkVariable.UpdateLastSentTime();
networkVariable.ResetDirty();
networkVariable.SetDirty(false);
}
}
} }
} }
@@ -1001,7 +1039,10 @@ namespace Unity.Netcode
networkVariable = NetworkVariableFields[k]; networkVariable = NetworkVariableFields[k];
if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId)) if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId))
{ {
shouldSend = true; if (networkVariable.CanSend())
{
shouldSend = true;
}
break; break;
} }
} }
@@ -1057,9 +1098,16 @@ namespace Unity.Netcode
// TODO: There should be a better way by reading one dirty variable vs. 'n' // TODO: There should be a better way by reading one dirty variable vs. 'n'
for (int i = 0; i < NetworkVariableFields.Count; i++) for (int i = 0; i < NetworkVariableFields.Count; i++)
{ {
if (NetworkVariableFields[i].IsDirty()) var networkVariable = NetworkVariableFields[i];
if (networkVariable.IsDirty())
{ {
return true; if (networkVariable.CanSend())
{
return true;
}
// If it's dirty but can't be sent yet, we have to keep monitoring it until one of the
// conditions blocking its send changes.
NetworkManager.BehaviourUpdater.AddForUpdate(NetworkObject);
} }
} }
@@ -1084,31 +1132,38 @@ namespace Unity.Netcode
/// </remarks> /// </remarks>
internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClientId) internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClientId)
{ {
// Create any values that require accessing the NetworkManager locally (it is expensive to access it in NetworkBehaviour)
var networkManager = NetworkManager; var networkManager = NetworkManager;
if (networkManager.DistributedAuthorityMode) var distributedAuthority = networkManager.DistributedAuthorityMode;
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
// Always write the NetworkVariable count even if zero for distributed authority (used by comb server)
if (distributedAuthority)
{ {
writer.WriteValueSafe((ushort)NetworkVariableFields.Count); writer.WriteValueSafe((ushort)NetworkVariableFields.Count);
} }
// Exit early if there are no NetworkVariables
if (NetworkVariableFields.Count == 0) if (NetworkVariableFields.Count == 0)
{ {
return; return;
} }
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
// Worth either merging or more cleanly separating these codepaths.
for (int j = 0; j < NetworkVariableFields.Count; j++) for (int j = 0; j < NetworkVariableFields.Count; j++)
{ {
// Note: In distributed authority mode, all clients can read // Client-Server: Try to write values only for clients that have read permissions.
// Distributed Authority: All clients have read permissions, always try to write the value.
if (NetworkVariableFields[j].CanClientRead(targetClientId)) if (NetworkVariableFields[j].CanClientRead(targetClientId))
{ {
if (networkManager.DistributedAuthorityMode) // Write additional NetworkVariable information when length safety is enabled or when in distributed authority mode
if (ensureLengthSafety || distributedAuthority)
{ {
writer.WriteValueSafe(NetworkVariableFields[j].Type); // Write the type being serialized for distributed authority (only for comb-server)
} if (distributedAuthority)
{
writer.WriteValueSafe(NetworkVariableFields[j].Type);
}
if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
{
var writePos = writer.Position; var writePos = writer.Position;
// Note: This value can't be packed because we don't know how large it will be in advance // Note: This value can't be packed because we don't know how large it will be in advance
// we reserve space for it, then write the data, then come back and fill in the space // we reserve space for it, then write the data, then come back and fill in the space
@@ -1120,18 +1175,19 @@ namespace Unity.Netcode
NetworkVariableFields[j].WriteField(writer); NetworkVariableFields[j].WriteField(writer);
var size = writer.Position - startPos; var size = writer.Position - startPos;
writer.Seek(writePos); writer.Seek(writePos);
// Write the NetworkVariable value
writer.WriteValueSafe((ushort)size); writer.WriteValueSafe((ushort)size);
writer.Seek(startPos + size); writer.Seek(startPos + size);
} }
else else // Client-Server Only: Should only ever be invoked when using a client-server NetworkTopology
{ {
// Write the NetworkVariable value
NetworkVariableFields[j].WriteField(writer); NetworkVariableFields[j].WriteField(writer);
} }
} }
else else if (ensureLengthSafety)
{ {
// Only if EnsureNetworkVariableLengthSafety, otherwise just skip // Client-Server Only: If the client cannot read this field, then skip it but write a 0 for this NetworkVariable's position
if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
{ {
writer.WriteValueSafe((ushort)0); writer.WriteValueSafe((ushort)0);
} }
@@ -1149,75 +1205,78 @@ namespace Unity.Netcode
/// </remarks> /// </remarks>
internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId) internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId)
{ {
// Stack cache any values that requires accessing the NetworkManager (it is expensive to access it in NetworkBehaviour)
var networkManager = NetworkManager; var networkManager = NetworkManager;
if (networkManager.DistributedAuthorityMode) var distributedAuthority = networkManager.DistributedAuthorityMode;
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
// Always read the NetworkVariable count when in distributed authority (sanity check if comb-server matches what client has locally)
if (distributedAuthority)
{ {
reader.ReadValueSafe(out ushort variableCount); reader.ReadValueSafe(out ushort variableCount);
if (variableCount != NetworkVariableFields.Count) if (variableCount != NetworkVariableFields.Count)
{ {
Debug.LogError("NetworkVariable count mismatch."); Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}] NetworkVariable count mismatch! (Read: {variableCount} vs. Expected: {NetworkVariableFields.Count})");
return; return;
} }
} }
// Exit early if nothing else to read
if (NetworkVariableFields.Count == 0) if (NetworkVariableFields.Count == 0)
{ {
return; return;
} }
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
// Worth either merging or more cleanly separating these codepaths.
for (int j = 0; j < NetworkVariableFields.Count; j++) for (int j = 0; j < NetworkVariableFields.Count; j++)
{ {
var varSize = (ushort)0; var varSize = (ushort)0;
var readStartPos = 0; var readStartPos = 0;
if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) // Client-Server: Clients that only have read permissions will try to read the value
// Distributed Authority: All clients have read permissions, always try to read the value
if (NetworkVariableFields[j].CanClientRead(clientId))
{ {
reader.ReadValueSafe(out varSize); if (ensureLengthSafety || distributedAuthority)
if (varSize == 0)
{ {
continue; // Read the type being serialized and discard it (for now) when in a distributed authority network topology (only used by comb-server)
if (distributedAuthority)
{
reader.ReadValueSafe(out NetworkVariableType _);
}
reader.ReadValueSafe(out varSize);
if (varSize == 0)
{
Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] Expected non-zero size readable NetworkVariable! (Skipping)");
continue;
}
readStartPos = reader.Position;
} }
readStartPos = reader.Position;
} }
else // If the client cannot read this field, then skip it else // Client-Server Only: If the client cannot read this field, then skip it
if (!NetworkVariableFields[j].CanClientRead(clientId))
{ {
if (networkManager.DistributedAuthorityMode) // If skipping and length safety, then fill in a 0 size for this one spot
if (ensureLengthSafety)
{ {
reader.ReadValueSafe(out ushort size); reader.ReadValueSafe(out ushort size);
if (size != 0) if (size != 0)
{ {
Debug.LogError("Expected zero size"); Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] Expected zero size for non-readable NetworkVariable when EnsureNetworkVariableLengthSafety is enabled! (Skipping)");
} }
} }
continue; continue;
} }
if (networkManager.DistributedAuthorityMode) // Read the NetworkVarible value
{ NetworkVariableFields[j].ReadField(reader);
// Explicit setting of the NetworkVariableType is only needed for CMB Runtime
reader.ReadValueSafe(out NetworkVariableType _);
reader.ReadValueSafe(out ushort size);
var start_marker = reader.Position;
NetworkVariableFields[j].ReadField(reader);
if (reader.Position - start_marker != size)
{
Debug.LogError("Mismatched network variable size");
}
}
else
{
NetworkVariableFields[j].ReadField(reader);
}
if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) // When EnsureNetworkVariableLengthSafety or DistributedAuthorityMode always do a bounds check
if (ensureLengthSafety || distributedAuthority)
{ {
if (reader.Position > (readStartPos + varSize)) if (reader.Position > (readStartPos + varSize))
{ {
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{ {
NetworkLog.LogWarning($"Var data read too far. {reader.Position - (readStartPos + varSize)} bytes."); NetworkLog.LogWarning($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] NetworkVariable data read too big. {reader.Position - (readStartPos + varSize)} bytes.");
} }
reader.Seek(readStartPos + varSize); reader.Seek(readStartPos + varSize);
@@ -1226,7 +1285,7 @@ namespace Unity.Netcode
{ {
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{ {
NetworkLog.LogWarning($"Var data read too little. {(readStartPos + varSize) - reader.Position} bytes."); NetworkLog.LogWarning($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] NetworkVariable data read too small. {(readStartPos + varSize) - reader.Position} bytes.");
} }
reader.Seek(readStartPos + varSize); reader.Seek(readStartPos + varSize);
@@ -1236,7 +1295,7 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Gets the local instance of a object with a given NetworkId /// Gets the local instance of a NetworkObject with a given NetworkId.
/// </summary> /// </summary>
/// <param name="networkId"></param> /// <param name="networkId"></param>
/// <returns></returns> /// <returns></returns>
@@ -1247,14 +1306,14 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// Override this method if your derived NetworkBehaviour requires custom synchronization data. /// Override this method if your derived NetworkBehaviour requires custom synchronization data.
/// Note: Use of this method is only for the initial client synchronization of NetworkBehaviours /// Use of this method is only for the initial client synchronization of NetworkBehaviours
/// and will increase the payload size for client synchronization and dynamically spawned /// and will increase the payload size for client synchronization and dynamically spawned
/// <see cref="NetworkObject"/>s. /// <see cref="NetworkObject"/>s.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// When serializing (writing) this will be invoked during the client synchronization period and /// When serializing (writing), this method is invoked during the client synchronization period and
/// when spawning new NetworkObjects. /// when spawning new NetworkObjects.
/// When deserializing (reading), this will be invoked prior to the NetworkBehaviour's associated /// When deserializing (reading), this method is invoked prior to the NetworkBehaviour's associated
/// NetworkObject being spawned. /// NetworkObject being spawned.
/// </remarks> /// </remarks>
/// <param name="serializer">The serializer to use to read and write the data.</param> /// <param name="serializer">The serializer to use to read and write the data.</param>
@@ -1268,14 +1327,19 @@ namespace Unity.Netcode
} }
public virtual void OnReanticipate(double lastRoundTripTime)
{
}
/// <summary> /// <summary>
/// The relative client identifier targeted for the serialization of this <see cref="NetworkBehaviour"/> instance. /// The relative client identifier targeted for the serialization of this <see cref="NetworkBehaviour"/> instance.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// This value will be set prior to <see cref="OnSynchronize{T}(ref BufferSerializer{T})"/> being invoked. /// This value is set prior to <see cref="OnSynchronize{T}(ref BufferSerializer{T})"/> being invoked.
/// For writing (server-side), this is useful to know which client will receive the serialized data. /// For writing (server-side), this is useful to know which client will receive the serialized data.
/// For reading (client-side), this will be the <see cref="NetworkManager.LocalClientId"/>. /// For reading (client-side), this will be the <see cref="NetworkManager.LocalClientId"/>.
/// When synchronization of this instance is complete, this value will be reset to 0 /// When synchronization of this instance is complete, this value is reset to 0.
/// </remarks> /// </remarks>
protected ulong m_TargetIdBeingSynchronized { get; private set; } protected ulong m_TargetIdBeingSynchronized { get; private set; }
@@ -1398,9 +1462,8 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to. /// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to is destroyed.
/// NOTE: If you override this, you will want to always invoke this base class version of this /// If you override this, you must always invoke the base class version of this <see cref="OnDestroy"/> method.
/// <see cref="OnDestroy"/> method!!
/// </summary> /// </summary>
public virtual void OnDestroy() public virtual void OnDestroy()
{ {

View File

@@ -11,6 +11,7 @@ namespace Unity.Netcode
private NetworkManager m_NetworkManager; private NetworkManager m_NetworkManager;
private NetworkConnectionManager m_ConnectionManager; private NetworkConnectionManager m_ConnectionManager;
private HashSet<NetworkObject> m_DirtyNetworkObjects = new HashSet<NetworkObject>(); private HashSet<NetworkObject> m_DirtyNetworkObjects = new HashSet<NetworkObject>();
private HashSet<NetworkObject> m_PendingDirtyNetworkObjects = new HashSet<NetworkObject>();
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR
private ProfilerMarker m_NetworkBehaviourUpdate = new ProfilerMarker($"{nameof(NetworkBehaviour)}.{nameof(NetworkBehaviourUpdate)}"); private ProfilerMarker m_NetworkBehaviourUpdate = new ProfilerMarker($"{nameof(NetworkBehaviour)}.{nameof(NetworkBehaviourUpdate)}");
@@ -18,7 +19,7 @@ namespace Unity.Netcode
internal void AddForUpdate(NetworkObject networkObject) internal void AddForUpdate(NetworkObject networkObject)
{ {
m_DirtyNetworkObjects.Add(networkObject); m_PendingDirtyNetworkObjects.Add(networkObject);
} }
internal void NetworkBehaviourUpdate() internal void NetworkBehaviourUpdate()
@@ -28,6 +29,9 @@ namespace Unity.Netcode
#endif #endif
try try
{ {
m_DirtyNetworkObjects.UnionWith(m_PendingDirtyNetworkObjects);
m_PendingDirtyNetworkObjects.Clear();
// NetworkObject references can become null, when hidden or despawned. Once NUll, there is no point // NetworkObject references can become null, when hidden or despawned. Once NUll, there is no point
// trying to process them, even if they were previously marked as dirty. // trying to process them, even if they were previously marked as dirty.
m_DirtyNetworkObjects.RemoveWhere((sobj) => sobj == null); m_DirtyNetworkObjects.RemoveWhere((sobj) => sobj == null);

View File

@@ -8,7 +8,6 @@ using UnityEditor;
#endif #endif
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
using Debug = UnityEngine.Debug; using Debug = UnityEngine.Debug;
using Unity.Netcode.Components;
namespace Unity.Netcode namespace Unity.Netcode
{ {
@@ -18,6 +17,12 @@ namespace Unity.Netcode
[AddComponentMenu("Netcode/Network Manager", -100)] [AddComponentMenu("Netcode/Network Manager", -100)]
public class NetworkManager : MonoBehaviour, INetworkUpdateSystem public class NetworkManager : MonoBehaviour, INetworkUpdateSystem
{ {
#if UNITY_EDITOR
// Inspector view expand/collapse settings for this derived child class
[HideInInspector]
public bool NetworkManagerExpanded;
#endif
// TODO: Deprecate... // TODO: Deprecate...
// The following internal values are not used, but because ILPP makes them public in the assembly, they cannot // The following internal values are not used, but because ILPP makes them public in the assembly, they cannot
// be removed thanks to our semver validation. // be removed thanks to our semver validation.
@@ -29,24 +34,47 @@ namespace Unity.Netcode
// RuntimeAccessModifiersILPP will make this `public` // RuntimeAccessModifiersILPP will make this `public`
internal static readonly Dictionary<uint, RpcReceiveHandler> __rpc_func_table = new Dictionary<uint, RpcReceiveHandler>(); internal static readonly Dictionary<uint, RpcReceiveHandler> __rpc_func_table = new Dictionary<uint, RpcReceiveHandler>();
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
// RuntimeAccessModifiersILPP will make this `public` // RuntimeAccessModifiersILPP will make this `public`
internal static readonly Dictionary<uint, string> __rpc_name_table = new Dictionary<uint, string>(); internal static readonly Dictionary<uint, string> __rpc_name_table = new Dictionary<uint, string>();
#endif #endif
#pragma warning restore IDE1006 // restore naming rule violation check #pragma warning restore IDE1006 // restore naming rule violation check
#if DEVELOPMENT_BUILD || UNITY_EDITOR
private static List<Type> s_SerializedType = new List<Type>();
// This is used to control the serialized type not optimized messaging for integration test purposes
internal static bool DisableNotOptimizedSerializedType;
/// <summary>
/// Until all serialized types are optimized for the distributed authority network topology,
/// this will handle the notification to the user that the type being serialized is not yet
/// optimized but will only log the message once to prevent log spamming.
/// </summary>
internal static void LogSerializedTypeNotOptimized<T>()
{
if (DisableNotOptimizedSerializedType)
{
return;
}
var type = typeof(T);
if (!s_SerializedType.Contains(type))
{
s_SerializedType.Add(type);
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
{
Debug.LogWarning($"[{type.Name}] Serialized type has not been optimized for use with Distributed Authority!");
}
}
}
#endif
internal static bool IsDistributedAuthority;
/// <summary> /// <summary>
/// Distributed Authority Mode /// Distributed Authority Mode
/// Returns true if the current session is running in distributed authority mode. /// Returns true if the current session is running in distributed authority mode.
/// </summary> /// </summary>
public bool DistributedAuthorityMode public bool DistributedAuthorityMode { get; private set; }
{
get
{
return NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority;
}
}
/// <summary> /// <summary>
/// Distributed Authority Mode /// Distributed Authority Mode
@@ -131,6 +159,18 @@ namespace Unity.Netcode
public ulong CurrentSessionOwner { get; internal set; } public ulong CurrentSessionOwner { get; internal set; }
/// <summary>
/// Delegate declaration for <see cref="OnSessionOwnerPromoted"/>
/// </summary>
/// <param name="sessionOwnerPromoted">the new session owner client identifier</param>
public delegate void OnSessionOwnerPromotedDelegateHandler(ulong sessionOwnerPromoted);
/// <summary>
/// Network Topology: Distributed Authority
/// When a new session owner is promoted, this event is triggered on all connected clients
/// </summary>
public event OnSessionOwnerPromotedDelegateHandler OnSessionOwnerPromoted;
internal void SetSessionOwner(ulong sessionOwner) internal void SetSessionOwner(ulong sessionOwner)
{ {
var previousSessionOwner = CurrentSessionOwner; var previousSessionOwner = CurrentSessionOwner;
@@ -151,10 +191,11 @@ namespace Unity.Netcode
} }
} }
} }
OnSessionOwnerPromoted?.Invoke(sessionOwner);
} }
// TODO: Make this internal after testing internal void PromoteSessionOwner(ulong clientId)
public void PromoteSessionOwner(ulong clientId)
{ {
if (!DistributedAuthorityMode) if (!DistributedAuthorityMode)
{ {
@@ -178,25 +219,25 @@ namespace Unity.Netcode
} }
} }
internal Dictionary<ulong, NetworkTransform> NetworkTransformUpdate = new Dictionary<ulong, NetworkTransform>(); internal Dictionary<ulong, NetworkObject> NetworkTransformUpdate = new Dictionary<ulong, NetworkObject>();
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
internal Dictionary<ulong, NetworkTransform> NetworkTransformFixedUpdate = new Dictionary<ulong, NetworkTransform>(); internal Dictionary<ulong, NetworkObject> NetworkTransformFixedUpdate = new Dictionary<ulong, NetworkObject>();
#endif #endif
internal void NetworkTransformRegistration(NetworkTransform networkTransform, bool forUpdate = true, bool register = true) internal void NetworkTransformRegistration(NetworkObject networkObject, bool onUpdate = true, bool register = true)
{ {
if (forUpdate) if (onUpdate)
{ {
if (register) if (register)
{ {
if (!NetworkTransformUpdate.ContainsKey(networkTransform.NetworkObjectId)) if (!NetworkTransformUpdate.ContainsKey(networkObject.NetworkObjectId))
{ {
NetworkTransformUpdate.Add(networkTransform.NetworkObjectId, networkTransform); NetworkTransformUpdate.Add(networkObject.NetworkObjectId, networkObject);
} }
} }
else else
{ {
NetworkTransformUpdate.Remove(networkTransform.NetworkObjectId); NetworkTransformUpdate.Remove(networkObject.NetworkObjectId);
} }
} }
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
@@ -204,42 +245,69 @@ namespace Unity.Netcode
{ {
if (register) if (register)
{ {
if (!NetworkTransformFixedUpdate.ContainsKey(networkTransform.NetworkObjectId)) if (!NetworkTransformFixedUpdate.ContainsKey(networkObject.NetworkObjectId))
{ {
NetworkTransformFixedUpdate.Add(networkTransform.NetworkObjectId, networkTransform); NetworkTransformFixedUpdate.Add(networkObject.NetworkObjectId, networkObject);
} }
} }
else else
{ {
NetworkTransformFixedUpdate.Remove(networkTransform.NetworkObjectId); NetworkTransformFixedUpdate.Remove(networkObject.NetworkObjectId);
} }
} }
#endif #endif
} }
private void UpdateTopology()
{
var transportTopology = IsListening ? NetworkConfig.NetworkTransport.CurrentTopology() : NetworkConfig.NetworkTopology;
if (transportTopology != NetworkConfig.NetworkTopology)
{
NetworkLog.LogErrorServer($"[Topology Mismatch] Transport detected an issue with the topology ({transportTopology} | {NetworkConfig.NetworkTopology}) usage or setting! Disconnecting from session.");
Shutdown();
}
else
{
IsDistributedAuthority = DistributedAuthorityMode = transportTopology == NetworkTopologyTypes.DistributedAuthority;
}
}
public void NetworkUpdate(NetworkUpdateStage updateStage) public void NetworkUpdate(NetworkUpdateStage updateStage)
{ {
switch (updateStage) switch (updateStage)
{ {
case NetworkUpdateStage.EarlyUpdate: case NetworkUpdateStage.EarlyUpdate:
{ {
UpdateTopology();
ConnectionManager.ProcessPendingApprovals(); ConnectionManager.ProcessPendingApprovals();
ConnectionManager.PollAndHandleNetworkEvents(); ConnectionManager.PollAndHandleNetworkEvents();
DeferredMessageManager.ProcessTriggers(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0); DeferredMessageManager.ProcessTriggers(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0);
AnticipationSystem.SetupForUpdate();
MessageManager.ProcessIncomingMessageQueue(); MessageManager.ProcessIncomingMessageQueue();
MessageManager.CleanupDisconnectedClients(); MessageManager.CleanupDisconnectedClients();
AnticipationSystem.ProcessReanticipation();
} }
break; break;
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
case NetworkUpdateStage.FixedUpdate: case NetworkUpdateStage.FixedUpdate:
{ {
foreach (var networkTransformEntry in NetworkTransformFixedUpdate) foreach (var networkObjectEntry in NetworkTransformFixedUpdate)
{ {
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned) // if not active or not spawned then skip
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
{ {
networkTransformEntry.Value.OnFixedUpdate(); continue;
}
foreach (var networkTransformEntry in networkObjectEntry.Value.NetworkTransforms)
{
// only update if enabled
if (networkTransformEntry.enabled)
{
networkTransformEntry.OnFixedUpdate();
}
} }
} }
} }
@@ -248,20 +316,37 @@ namespace Unity.Netcode
case NetworkUpdateStage.PreUpdate: case NetworkUpdateStage.PreUpdate:
{ {
NetworkTimeSystem.UpdateTime(); NetworkTimeSystem.UpdateTime();
AnticipationSystem.Update();
} }
break; break;
case NetworkUpdateStage.PreLateUpdate: case NetworkUpdateStage.PreLateUpdate:
{ {
// Non-physics based non-authority NetworkTransforms update their states after all other components // Non-physics based non-authority NetworkTransforms update their states after all other components
foreach (var networkTransformEntry in NetworkTransformUpdate) foreach (var networkObjectEntry in NetworkTransformUpdate)
{ {
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned) // if not active or not spawned then skip
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
{ {
networkTransformEntry.Value.OnUpdate(); continue;
}
foreach (var networkTransformEntry in networkObjectEntry.Value.NetworkTransforms)
{
// only update if enabled
if (networkTransformEntry.enabled)
{
networkTransformEntry.OnUpdate();
}
} }
} }
} }
break; break;
case NetworkUpdateStage.PostScriptLateUpdate:
{
AnticipationSystem.Sync();
AnticipationSystem.SetupForRender();
}
break;
case NetworkUpdateStage.PostLateUpdate: case NetworkUpdateStage.PostLateUpdate:
{ {
// Handle deferred despawning // Handle deferred despawning
@@ -501,6 +586,25 @@ namespace Unity.Netcode
remove => ConnectionManager.OnTransportFailure -= value; remove => ConnectionManager.OnTransportFailure -= value;
} }
public delegate void ReanticipateDelegate(double lastRoundTripTime);
/// <summary>
/// This callback is called after all individual OnReanticipate calls on AnticipatedNetworkVariable
/// and AnticipatedNetworkTransform values have been invoked. The first parameter is a hash set of
/// all the variables that have been changed on this frame (you can detect a particular variable by
/// checking if the set contains it), while the second parameter is a set of all anticipated network
/// transforms that have been changed. Both are passed as their base class type.
///
/// The third parameter is the local time corresponding to the current authoritative server state
/// (i.e., to determine the amount of time that needs to be re-simulated, you will use
/// NetworkManager.LocalTime.Time - authorityTime).
/// </summary>
public event ReanticipateDelegate OnReanticipate
{
add => AnticipationSystem.OnReanticipate += value;
remove => AnticipationSystem.OnReanticipate -= value;
}
/// <summary> /// <summary>
/// The callback to invoke during connection approval. Allows client code to decide whether or not to allow incoming client connection /// The callback to invoke during connection approval. Allows client code to decide whether or not to allow incoming client connection
/// </summary> /// </summary>
@@ -745,6 +849,8 @@ namespace Unity.Netcode
/// </summary> /// </summary>
public NetworkTickSystem NetworkTickSystem { get; private set; } public NetworkTickSystem NetworkTickSystem { get; private set; }
internal AnticipationSystem AnticipationSystem { get; private set; }
/// <summary> /// <summary>
/// Used for time mocking in tests /// Used for time mocking in tests
/// </summary> /// </summary>
@@ -789,6 +895,11 @@ namespace Unity.Netcode
OnNetworkManagerReset?.Invoke(this); OnNetworkManagerReset?.Invoke(this);
} }
protected virtual void OnValidateComponent()
{
}
internal void OnValidate() internal void OnValidate()
{ {
if (NetworkConfig == null) if (NetworkConfig == null)
@@ -849,6 +960,15 @@ namespace Unity.Netcode
} }
} }
} }
try
{
OnValidateComponent();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
} }
private void ModeChanged(PlayModeStateChange change) private void ModeChanged(PlayModeStateChange change)
@@ -1007,11 +1127,20 @@ namespace Unity.Netcode
internal void Initialize(bool server) internal void Initialize(bool server)
{ {
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!DisableNotOptimizedSerializedType)
{
s_SerializedType.Clear();
}
#endif
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
NetworkTransformFixedUpdate.Clear(); NetworkTransformFixedUpdate.Clear();
#endif #endif
NetworkTransformUpdate.Clear(); NetworkTransformUpdate.Clear();
UpdateTopology();
//DANGOEXP TODO: Remove this before finalizing the experimental release //DANGOEXP TODO: Remove this before finalizing the experimental release
NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode; NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode;
@@ -1051,6 +1180,7 @@ namespace Unity.Netcode
this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate);
#endif #endif
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PostScriptLateUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate);
@@ -1090,6 +1220,7 @@ namespace Unity.Netcode
// The remaining systems can then be initialized // The remaining systems can then be initialized
NetworkTimeSystem = server ? NetworkTimeSystem.ServerTimeSystem() : new NetworkTimeSystem(1.0 / NetworkConfig.TickRate); NetworkTimeSystem = server ? NetworkTimeSystem.ServerTimeSystem() : new NetworkTimeSystem(1.0 / NetworkConfig.TickRate);
NetworkTickSystem = NetworkTimeSystem.Initialize(this); NetworkTickSystem = NetworkTimeSystem.Initialize(this);
AnticipationSystem = new AnticipationSystem(this);
// Create spawn manager instance // Create spawn manager instance
SpawnManager = new NetworkSpawnManager(this); SpawnManager = new NetworkSpawnManager(this);
@@ -1191,6 +1322,8 @@ namespace Unity.Netcode
{ {
SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
// Notify the server that everything should be synchronized/spawned at this time.
SpawnManager.NotifyNetworkObjectsSynchronized();
OnServerStarted?.Invoke(); OnServerStarted?.Invoke();
ConnectionManager.LocalClient.IsApproved = true; ConnectionManager.LocalClient.IsApproved = true;
return true; return true;
@@ -1338,6 +1471,9 @@ namespace Unity.Netcode
SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
// Notify the host that everything should be synchronized/spawned at this time.
SpawnManager.NotifyNetworkObjectsSynchronized();
OnServerStarted?.Invoke(); OnServerStarted?.Invoke();
OnClientStarted?.Invoke(); OnClientStarted?.Invoke();

View File

@@ -37,7 +37,7 @@ namespace Unity.Netcode
internal uint PrefabGlobalObjectIdHash; internal uint PrefabGlobalObjectIdHash;
/// <summary> /// <summary>
/// This is the source prefab of an in-scene placed NetworkObject. This is not set for in-scene /// This is the source prefab of an in-scene placed NetworkObject. This is not set for in-scene
/// placd NetworkObjects that are not prefab instances, dynamically spawned prefab instances, /// placd NetworkObjects that are not prefab instances, dynamically spawned prefab instances,
/// or for network prefab assets. /// or for network prefab assets.
/// </summary> /// </summary>
@@ -67,6 +67,7 @@ namespace Unity.Netcode
/// </remarks> /// </remarks>
public List<NetworkTransform> NetworkTransforms { get; private set; } public List<NetworkTransform> NetworkTransforms { get; private set; }
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
/// <summary> /// <summary>
/// All <see cref="NetworkRigidbodyBase"></see> component instances associated with a <see cref="NetworkObject"/> component instance. /// All <see cref="NetworkRigidbodyBase"></see> component instances associated with a <see cref="NetworkObject"/> component instance.
@@ -207,8 +208,8 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// This checks to see if this NetworkObject is an in-scene placed prefab instance. If so it will /// This checks to see if this NetworkObject is an in-scene placed prefab instance. If so it will
/// automatically find the source prefab asset's GlobalObjectIdHash value, assign it to /// automatically find the source prefab asset's GlobalObjectIdHash value, assign it to
/// InScenePlacedSourceGlobalObjectIdHash and mark this as being in-scene placed. /// InScenePlacedSourceGlobalObjectIdHash and mark this as being in-scene placed.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
@@ -430,7 +431,7 @@ namespace Unity.Netcode
/// Determines whether a NetworkObject can be distributed to other clients during /// Determines whether a NetworkObject can be distributed to other clients during
/// a <see cref="NetworkTopologyTypes.DistributedAuthority"/> session. /// a <see cref="NetworkTopologyTypes.DistributedAuthority"/> session.
/// </summary> /// </summary>
#if !MULTIPLAYER_SDK_INSTALLED #if !MULTIPLAYER_SERVICES_SDK_INSTALLED
[HideInInspector] [HideInInspector]
#endif #endif
[SerializeField] [SerializeField]
@@ -540,8 +541,8 @@ namespace Unity.Netcode
/// permission failure status codes will be returned via <see cref="OnOwnershipPermissionsFailure"/>. /// permission failure status codes will be returned via <see cref="OnOwnershipPermissionsFailure"/>.
/// <see cref="Locked"/>: The <see cref="NetworkObject"/> is locked and ownership cannot be acquired. /// <see cref="Locked"/>: The <see cref="NetworkObject"/> is locked and ownership cannot be acquired.
/// <see cref="RequestRequired"/>: The <see cref="NetworkObject"/> requires an ownership request via <see cref="RequestOwnership"/>. /// <see cref="RequestRequired"/>: The <see cref="NetworkObject"/> requires an ownership request via <see cref="RequestOwnership"/>.
/// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> already is processing an ownership request and ownership cannot be acquired at this time. /// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> is already processing an ownership request and ownership cannot be acquired at this time.
/// <see cref="NotTransferrable": The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired. /// <see cref="NotTransferrable"/>: The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired.
/// </summary> /// </summary>
public enum OwnershipPermissionsFailureStatus public enum OwnershipPermissionsFailureStatus
{ {
@@ -937,6 +938,7 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// If true, the object will always be replicated as root on clients and the parent will be ignored. /// If true, the object will always be replicated as root on clients and the parent will be ignored.
/// </summary> /// </summary>
[Tooltip("If enabled (default disabled), instances of this NetworkObject will ignore any parent(s) it might have and replicate on clients as the root being its parent.")]
public bool AlwaysReplicateAsRoot; public bool AlwaysReplicateAsRoot;
/// <summary> /// <summary>
@@ -954,6 +956,8 @@ namespace Unity.Netcode
/// bandwidth cost. This can also be useful for UI elements that have /// bandwidth cost. This can also be useful for UI elements that have
/// a predetermined fixed position. /// a predetermined fixed position.
/// </remarks> /// </remarks>
[Tooltip("If enabled (default enabled), newly joining clients will be synchronized with the transform of the associated GameObject this component is attached to. Typical use case" +
" scenario would be for managment objects or in-scene placed objects that don't move and already have their transform settings applied within the scene information.")]
public bool SynchronizeTransform = true; public bool SynchronizeTransform = true;
/// <summary> /// <summary>
@@ -1011,6 +1015,7 @@ namespace Unity.Netcode
/// To synchronize clients of a <see cref="NetworkObject"/>'s scene being changed via <see cref="SceneManager.MoveGameObjectToScene(GameObject, Scene)"/>, /// To synchronize clients of a <see cref="NetworkObject"/>'s scene being changed via <see cref="SceneManager.MoveGameObjectToScene(GameObject, Scene)"/>,
/// make sure <see cref="SceneMigrationSynchronization"/> is enabled (it is by default). /// make sure <see cref="SceneMigrationSynchronization"/> is enabled (it is by default).
/// </remarks> /// </remarks>
[Tooltip("When enabled (default disabled), spawned instances of this NetworkObject will automatically migrate to any newly assigned active scene.")]
public bool ActiveSceneSynchronization; public bool ActiveSceneSynchronization;
/// <summary> /// <summary>
@@ -1029,6 +1034,7 @@ namespace Unity.Netcode
/// is <see cref="true"/> and <see cref="ActiveSceneSynchronization"/> is <see cref="false"/> and the scene is not the currently /// is <see cref="true"/> and <see cref="ActiveSceneSynchronization"/> is <see cref="false"/> and the scene is not the currently
/// active scene, then the <see cref="NetworkObject"/> will be destroyed. /// active scene, then the <see cref="NetworkObject"/> will be destroyed.
/// </remarks> /// </remarks>
[Tooltip("When enabled (default enabled), dynamically spawned instances of this NetworkObject's migration to a different scene will automatically be synchonize amongst clients.")]
public bool SceneMigrationSynchronization = true; public bool SceneMigrationSynchronization = true;
/// <summary> /// <summary>
@@ -1044,7 +1050,7 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// When set to false, the NetworkObject will be spawned with no observers initially (other than the server) /// When set to false, the NetworkObject will be spawned with no observers initially (other than the server)
/// </summary> /// </summary>
[Tooltip("When false, the NetworkObject will spawn with no observers initially. (default is true)")] [Tooltip("When disabled (default enabled), the NetworkObject will spawn with no observers. You control object visibility using NetworkShow. This applies to newly joining clients as well.")]
public bool SpawnWithObservers = true; public bool SpawnWithObservers = true;
/// <summary> /// <summary>
@@ -1073,13 +1079,35 @@ namespace Unity.Netcode
/// Whether or not to destroy this object if it's owner is destroyed. /// Whether or not to destroy this object if it's owner is destroyed.
/// If true, the objects ownership will be given to the server. /// If true, the objects ownership will be given to the server.
/// </summary> /// </summary>
[Tooltip("When enabled (default disabled), instances of this NetworkObject will not be destroyed if the owning client disconnects.")]
public bool DontDestroyWithOwner; public bool DontDestroyWithOwner;
/// <summary> /// <summary>
/// Whether or not to enable automatic NetworkObject parent synchronization. /// Whether or not to enable automatic NetworkObject parent synchronization.
/// </summary> /// </summary>
[Tooltip("When disabled (default enabled), NetworkObject parenting will not be automatically synchronized. This is typically used when you want to implement your own custom parenting solution.")]
public bool AutoObjectParentSync = true; public bool AutoObjectParentSync = true;
/// <summary>
/// Determines if the owner will apply transform values sent by the parenting message.
/// </summary>
/// <remarks>
/// When enabled, the resultant parenting transform changes sent by the authority will be applied on all instances. <br />
/// When disabled, the resultant parenting transform changes sent by the authority will not be applied on the owner's instance. <br />
/// When disabled, all non-owner instances will still be synchronized by the authority's transform values when parented.
/// When using a <see cref="NetworkTopologyTypes.ClientServer"/> network topology and an owner authoritative motion model, disabling this can help smooth parenting transitions.
/// When using a <see cref="NetworkTopologyTypes.DistributedAuthority"/> network topology this will have no impact on the owner's instance since only the authority/owner can parent.
/// </remarks>
[Tooltip("When disabled (default enabled), the owner will not apply a server or host's transform properties when parenting changes. Primarily useful for client-server network topology configurations.")]
public bool SyncOwnerTransformWhenParented = true;
/// <summary>
/// Client-Server specific, when enabled an owner of a NetworkObject can parent locally as opposed to requiring the owner to notify the server it would like to be parented.
/// This behavior is always true when using a distributed authority network topology and does not require it to be set.
/// </summary>
[Tooltip("When enabled (default disabled), owner's can parent a NetworkObject locally without having to send an RPC to the server or host. Only pertinent when using client-server network topology configurations.")]
public bool AllowOwnerToParent;
internal readonly HashSet<ulong> Observers = new HashSet<ulong>(); internal readonly HashSet<ulong> Observers = new HashSet<ulong>();
#if MULTIPLAYER_TOOLS #if MULTIPLAYER_TOOLS
@@ -1547,6 +1575,11 @@ namespace Unity.Netcode
if (NetworkManager.DistributedAuthorityMode) if (NetworkManager.DistributedAuthorityMode)
{ {
if (NetworkManager.LocalClient == null || !NetworkManager.IsConnectedClient || !NetworkManager.ConnectionManager.LocalClient.IsApproved)
{
Debug.LogError($"Cannot spawn {name} until the client is fully connected to the session!");
return;
}
if (NetworkManager.NetworkConfig.EnableSceneManagement) if (NetworkManager.NetworkConfig.EnableSceneManagement)
{ {
NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[gameObject.scene.handle]; NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[gameObject.scene.handle];
@@ -1638,7 +1671,7 @@ namespace Unity.Netcode
return null; return null;
} }
ownerClientId = networkManager.DistributedAuthorityMode ? networkManager.LocalClientId : NetworkManager.ServerClientId; ownerClientId = networkManager.DistributedAuthorityMode ? networkManager.LocalClientId : ownerClientId;
// We only need to check for authority when running in client-server mode // We only need to check for authority when running in client-server mode
if (!networkManager.IsServer && !networkManager.DistributedAuthorityMode) if (!networkManager.IsServer && !networkManager.DistributedAuthorityMode)
{ {
@@ -1782,6 +1815,9 @@ namespace Unity.Netcode
{ {
for (int i = 0; i < ChildNetworkBehaviours.Count; i++) for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{ {
// Invoke internal notification
ChildNetworkBehaviours[i].InternalOnNetworkObjectParentChanged(parentNetworkObject);
// Invoke public notification
ChildNetworkBehaviours[i].OnNetworkObjectParentChanged(parentNetworkObject); ChildNetworkBehaviours[i].OnNetworkObjectParentChanged(parentNetworkObject);
} }
} }
@@ -1913,7 +1949,7 @@ namespace Unity.Netcode
// DANGO-TODO: Do we want to worry about ownership permissions here? // DANGO-TODO: Do we want to worry about ownership permissions here?
// It wouldn't make sense to not allow parenting, but keeping this note here as a reminder. // It wouldn't make sense to not allow parenting, but keeping this note here as a reminder.
var isAuthority = HasAuthority; var isAuthority = HasAuthority || (AllowOwnerToParent && IsOwner);
// If we don't have authority and we are not shutting down, then don't allow any parenting. // If we don't have authority and we are not shutting down, then don't allow any parenting.
// If we are shutting down and don't have authority then allow it. // If we are shutting down and don't have authority then allow it.
@@ -1979,7 +2015,7 @@ namespace Unity.Netcode
var isAuthority = false; var isAuthority = false;
// With distributed authority, we need to track "valid authoritative" parenting changes. // With distributed authority, we need to track "valid authoritative" parenting changes.
// So, either the authority or AuthorityAppliedParenting is considered a "valid parenting change". // So, either the authority or AuthorityAppliedParenting is considered a "valid parenting change".
isAuthority = HasAuthority || AuthorityAppliedParenting; isAuthority = HasAuthority || AuthorityAppliedParenting || (AllowOwnerToParent && IsOwner);
var distributedAuthority = NetworkManager.DistributedAuthorityMode; var distributedAuthority = NetworkManager.DistributedAuthorityMode;
// If we do not have authority and we are spawned // If we do not have authority and we are spawned
@@ -2071,7 +2107,7 @@ namespace Unity.Netcode
} }
// If we are connected to a CMB service or we are running a mock CMB service then send to the "server" identifier // If we are connected to a CMB service or we are running a mock CMB service then send to the "server" identifier
if (distributedAuthority) if (distributedAuthority || (!distributedAuthority && AllowOwnerToParent && IsOwner && !NetworkManager.IsServer))
{ {
if (!NetworkManager.DAHost) if (!NetworkManager.DAHost)
{ {
@@ -2354,13 +2390,15 @@ namespace Unity.Netcode
{ {
m_ChildNetworkBehaviours.Add(networkBehaviours[i]); m_ChildNetworkBehaviours.Add(networkBehaviours[i]);
var type = networkBehaviours[i].GetType(); var type = networkBehaviours[i].GetType();
if (type.IsInstanceOfType(typeof(NetworkTransform)) || type.IsSubclassOf(typeof(NetworkTransform))) if (type == typeof(NetworkTransform) || type.IsInstanceOfType(typeof(NetworkTransform)) || type.IsSubclassOf(typeof(NetworkTransform)))
{ {
if (NetworkTransforms == null) if (NetworkTransforms == null)
{ {
NetworkTransforms = new List<NetworkTransform>(); NetworkTransforms = new List<NetworkTransform>();
} }
NetworkTransforms.Add(networkBehaviours[i] as NetworkTransform); var networkTransform = networkBehaviours[i] as NetworkTransform;
networkTransform.IsNested = i != 0 && networkTransform.gameObject != gameObject;
NetworkTransforms.Add(networkTransform);
} }
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
else if (type.IsSubclassOf(typeof(NetworkRigidbodyBase))) else if (type.IsSubclassOf(typeof(NetworkRigidbodyBase)))
@@ -2436,10 +2474,10 @@ namespace Unity.Netcode
if (NetworkManager.DistributedAuthorityMode) if (NetworkManager.DistributedAuthorityMode)
{ {
var readerPosition = reader.Position; var readerPosition = reader.Position;
reader.ReadValueSafe(out ushort behaviorCount); reader.ReadValueSafe(out ushort behaviourCount);
if (behaviorCount != ChildNetworkBehaviours.Count) if (behaviourCount != ChildNetworkBehaviours.Count)
{ {
Debug.LogError($"Network Behavior Count Mismatch! [{readerPosition}][{reader.Position}]"); Debug.LogError($"[{name}] Network Behavior Count Mismatch! [In: {behaviourCount} vs Local: {ChildNetworkBehaviours.Count}][StartReaderPos: {readerPosition}] CurrentReaderPos: {reader.Position}]");
return false; return false;
} }
} }

View File

@@ -54,6 +54,12 @@ namespace Unity.Netcode
/// </summary> /// </summary>
PreLateUpdate = 6, PreLateUpdate = 6,
/// <summary> /// <summary>
/// Updated after Monobehaviour.LateUpdate, but BEFORE rendering
/// </summary>
// Yes, these numbers are out of order due to backward compatibility requirements.
// The enum values are listed in the order they will be called.
PostScriptLateUpdate = 8,
/// <summary>
/// Updated after the Monobehaviour.LateUpdate for all components is invoked /// Updated after the Monobehaviour.LateUpdate for all components is invoked
/// </summary> /// </summary>
PostLateUpdate = 7 PostLateUpdate = 7
@@ -258,6 +264,18 @@ namespace Unity.Netcode
} }
} }
internal struct NetworkPostScriptLateUpdate
{
public static PlayerLoopSystem CreateLoopSystem()
{
return new PlayerLoopSystem
{
type = typeof(NetworkPostScriptLateUpdate),
updateDelegate = () => RunNetworkUpdateStage(NetworkUpdateStage.PostScriptLateUpdate)
};
}
}
internal struct NetworkPostLateUpdate internal struct NetworkPostLateUpdate
{ {
public static PlayerLoopSystem CreateLoopSystem() public static PlayerLoopSystem CreateLoopSystem()
@@ -399,6 +417,7 @@ namespace Unity.Netcode
else if (currentSystem.type == typeof(PreLateUpdate)) else if (currentSystem.type == typeof(PreLateUpdate))
{ {
TryAddLoopSystem(ref currentSystem, NetworkPreLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.Before); TryAddLoopSystem(ref currentSystem, NetworkPreLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.Before);
TryAddLoopSystem(ref currentSystem, NetworkPostScriptLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.After);
} }
else if (currentSystem.type == typeof(PostLateUpdate)) else if (currentSystem.type == typeof(PostLateUpdate))
{ {
@@ -440,6 +459,7 @@ namespace Unity.Netcode
else if (currentSystem.type == typeof(PreLateUpdate)) else if (currentSystem.type == typeof(PreLateUpdate))
{ {
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPreLateUpdate)); TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPreLateUpdate));
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPostScriptLateUpdate));
} }
else if (currentSystem.type == typeof(PostLateUpdate)) else if (currentSystem.type == typeof(PostLateUpdate))
{ {

View File

@@ -95,6 +95,7 @@ namespace Unity.Netcode
return; return;
} }
ValidateMessageSize(messageBuffer, networkDelivery, isNamed: false);
if (m_NetworkManager.IsHost) if (m_NetworkManager.IsHost)
{ {
@@ -131,6 +132,8 @@ namespace Unity.Netcode
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param> /// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
public void SendUnnamedMessage(ulong clientId, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) public void SendUnnamedMessage(ulong clientId, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
{ {
ValidateMessageSize(messageBuffer, networkDelivery, isNamed: false);
if (m_NetworkManager.IsHost) if (m_NetworkManager.IsHost)
{ {
if (clientId == m_NetworkManager.LocalClientId) if (clientId == m_NetworkManager.LocalClientId)
@@ -286,6 +289,8 @@ namespace Unity.Netcode
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param> /// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
public void SendNamedMessage(string messageName, ulong clientId, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) public void SendNamedMessage(string messageName, ulong clientId, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
{ {
ValidateMessageSize(messageStream, networkDelivery, isNamed: true);
ulong hash = 0; ulong hash = 0;
switch (m_NetworkManager.NetworkConfig.RpcHashSize) switch (m_NetworkManager.NetworkConfig.RpcHashSize)
{ {
@@ -367,6 +372,8 @@ namespace Unity.Netcode
return; return;
} }
ValidateMessageSize(messageStream, networkDelivery, isNamed: true);
ulong hash = 0; ulong hash = 0;
switch (m_NetworkManager.NetworkConfig.RpcHashSize) switch (m_NetworkManager.NetworkConfig.RpcHashSize)
{ {
@@ -405,5 +412,32 @@ namespace Unity.Netcode
m_NetworkManager.NetworkMetrics.TrackNamedMessageSent(clientIds, messageName, size); m_NetworkManager.NetworkMetrics.TrackNamedMessageSent(clientIds, messageName, size);
} }
} }
/// <summary>
/// Validate the size of the message. If it's a non-fragmented delivery type the message must fit within the
/// max allowed size with headers also subtracted. Named messages also include the hash
/// of the name string. Only validates in editor and development builds.
/// </summary>
/// <param name="messageStream">The named message payload</param>
/// <param name="networkDelivery">Delivery method</param>
/// <param name="isNamed">Is the message named (or unnamed)</param>
/// <exception cref="OverflowException">Exception thrown in case validation fails</exception>
private unsafe void ValidateMessageSize(FastBufferWriter messageStream, NetworkDelivery networkDelivery, bool isNamed)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
var maxNonFragmentedSize = m_NetworkManager.MessageManager.NonFragmentedMessageMaxSize - FastBufferWriter.GetWriteSize<NetworkMessageHeader>() - sizeof(NetworkBatchHeader);
if (isNamed)
{
maxNonFragmentedSize -= sizeof(ulong); // MessageName hash
}
if (networkDelivery != NetworkDelivery.ReliableFragmentedSequenced
&& messageStream.Length > maxNonFragmentedSize)
{
throw new OverflowException($"Given message size ({messageStream.Length} bytes) is greater than " +
$"the maximum allowed for the selected delivery method ({maxNonFragmentedSize} bytes). Try using " +
$"ReliableFragmentedSequenced delivery method instead.");
}
#endif
}
} }
} }

View File

@@ -47,6 +47,8 @@ namespace Unity.Netcode
SessionOwner = 20, SessionOwner = 20,
TimeSync = 21, TimeSync = 21,
Unnamed = 22, Unnamed = 22,
AnticipationCounterSyncPingMessage = 23,
AnticipationCounterSyncPongMessage = 24,
} }
@@ -103,7 +105,9 @@ namespace Unity.Netcode
{ typeof(ServerRpcMessage), NetworkMessageTypes.ServerRpc }, { typeof(ServerRpcMessage), NetworkMessageTypes.ServerRpc },
{ typeof(TimeSyncMessage), NetworkMessageTypes.TimeSync }, { typeof(TimeSyncMessage), NetworkMessageTypes.TimeSync },
{ typeof(UnnamedMessage), NetworkMessageTypes.Unnamed }, { typeof(UnnamedMessage), NetworkMessageTypes.Unnamed },
{ typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner } { typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner },
{ typeof(AnticipationCounterSyncPingMessage), NetworkMessageTypes.AnticipationCounterSyncPingMessage},
{ typeof(AnticipationCounterSyncPongMessage), NetworkMessageTypes.AnticipationCounterSyncPongMessage},
}; };
// Assure the type to lookup table count and NetworkMessageType enum count matches (i.e. to catch human error when adding new messages) // Assure the type to lookup table count and NetworkMessageType enum count matches (i.e. to catch human error when adding new messages)

View File

@@ -0,0 +1,70 @@
namespace Unity.Netcode
{
internal struct AnticipationCounterSyncPingMessage : INetworkMessage
{
public int Version => 0;
public ulong Counter;
public double Time;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
BytePacker.WriteValuePacked(writer, Counter);
writer.WriteValueSafe(Time);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.IsServer)
{
return false;
}
ByteUnpacker.ReadValuePacked(reader, out Counter);
reader.ReadValueSafe(out Time);
return true;
}
public void Handle(ref NetworkContext context)
{
var networkManager = (NetworkManager)context.SystemOwner;
if (networkManager.IsListening && !networkManager.ShutdownInProgress && networkManager.ConnectedClients.ContainsKey(context.SenderId))
{
var message = new AnticipationCounterSyncPongMessage { Counter = Counter, Time = Time };
networkManager.MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, context.SenderId);
}
}
}
internal struct AnticipationCounterSyncPongMessage : INetworkMessage
{
public int Version => 0;
public ulong Counter;
public double Time;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
BytePacker.WriteValuePacked(writer, Counter);
writer.WriteValueSafe(Time);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.IsClient)
{
return false;
}
ByteUnpacker.ReadValuePacked(reader, out Counter);
reader.ReadValueSafe(out Time);
return true;
}
public void Handle(ref NetworkContext context)
{
var networkManager = (NetworkManager)context.SystemOwner;
networkManager.AnticipationSystem.LastAnticipationAck = Counter;
networkManager.AnticipationSystem.LastAnticipationAckTime = Time;
}
}
}

View File

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

View File

@@ -31,7 +31,7 @@ namespace Unity.Netcode
public void Handle(ref NetworkContext context) public void Handle(ref NetworkContext context)
{ {
var networkManager = (NetworkManager)context.SystemOwner; var networkManager = (NetworkManager)context.SystemOwner;
if ((ShouldSynchronize || networkManager.CMBServiceConnection) && networkManager.DistributedAuthorityMode && networkManager.LocalClient.IsSessionOwner) if (ShouldSynchronize && networkManager.NetworkConfig.EnableSceneManagement && networkManager.DistributedAuthorityMode && networkManager.LocalClient.IsSessionOwner)
{ {
networkManager.SceneManager.SynchronizeNetworkObjects(ClientId); networkManager.SceneManager.SynchronizeNetworkObjects(ClientId);
} }
@@ -55,6 +55,15 @@ namespace Unity.Netcode
// Don't redistribute for the local instance // Don't redistribute for the local instance
if (ClientId != networkManager.LocalClientId) if (ClientId != networkManager.LocalClientId)
{ {
// Show any NetworkObjects that are:
// - Hidden from the session owner
// - Owned by this client
// - Has NetworkObject.SpawnWithObservers set to true (the default)
if (!networkManager.LocalClient.IsSessionOwner)
{
networkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(ClientId);
}
// We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate // We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate
networkManager.RedistributeToClient = true; networkManager.RedistributeToClient = true;
networkManager.ClientToRedistribute = ClientId; networkManager.ClientToRedistribute = ClientId;

View File

@@ -224,10 +224,7 @@ namespace Unity.Netcode
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId); networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
// For convenience, notify all NetworkBehaviours that synchronization is complete. // For convenience, notify all NetworkBehaviours that synchronization is complete.
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList) networkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
{
networkObject.InternalNetworkSessionSynchronized();
}
} }
else else
{ {
@@ -240,6 +237,9 @@ namespace Unity.Netcode
if (!IsRestoredSession) if (!IsRestoredSession)
{ {
// Synchronize the service with the initial session owner's loaded scenes and spawned objects
networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId);
// Spawn any in-scene placed NetworkObjects // Spawn any in-scene placed NetworkObjects
networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
@@ -251,6 +251,14 @@ namespace Unity.Netcode
// Synchronize the service with the initial session owner's loaded scenes and spawned objects // Synchronize the service with the initial session owner's loaded scenes and spawned objects
networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId); networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId);
// With scene management enabled and since the session owner doesn't send a Synchronize scene event synchronize itself,
// we need to notify the session owner that everything should be synchronized/spawned at this time.
networkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
// When scene management is enabled and since the session owner is synchronizing the service (i.e. acting like host),
// we need to locallyh invoke the OnClientConnected callback at this point in time.
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(OwnerClientId);
} }
} }
} }

View File

@@ -17,6 +17,8 @@ namespace Unity.Netcode
internal NetworkTransform.NetworkTransformState State; internal NetworkTransform.NetworkTransformState State;
private FastBufferReader m_CurrentReader; private FastBufferReader m_CurrentReader;
internal int BytesWritten;
private unsafe void CopyPayload(ref FastBufferWriter writer) private unsafe void CopyPayload(ref FastBufferWriter writer)
{ {
writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position); writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position);
@@ -30,7 +32,7 @@ namespace Unity.Netcode
} }
else else
{ {
NetworkTransform.SerializeMessage(writer, targetVersion); BytesWritten = NetworkTransform.SerializeMessage(writer, targetVersion);
} }
} }
@@ -75,6 +77,7 @@ namespace Unity.Netcode
ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer; ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer;
reader.ReadNetworkSerializableInPlace(ref NetworkTransform.InboundState); reader.ReadNetworkSerializableInPlace(ref NetworkTransform.InboundState);
NetworkTransform.InboundState.LastSerializedSize = reader.Position - currentPosition;
} }
else else
{ {

View File

@@ -25,8 +25,6 @@ namespace Unity.Netcode
private const string k_Name = "NetworkVariableDeltaMessage"; 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) public void Serialize(FastBufferWriter writer, int targetVersion)
{ {
if (!writer.TryBeginWrite(FastBufferWriter.GetWriteSize(NetworkObjectId) + FastBufferWriter.GetWriteSize(NetworkBehaviourIndex))) if (!writer.TryBeginWrite(FastBufferWriter.GetWriteSize(NetworkObjectId) + FastBufferWriter.GetWriteSize(NetworkBehaviourIndex)))
@@ -69,7 +67,8 @@ namespace Unity.Netcode
var networkVariable = NetworkBehaviour.NetworkVariableFields[i]; var networkVariable = NetworkBehaviour.NetworkVariableFields[i];
var shouldWrite = networkVariable.IsDirty() && var shouldWrite = networkVariable.IsDirty() &&
networkVariable.CanClientRead(TargetClientId) && networkVariable.CanClientRead(TargetClientId) &&
(networkManager.IsServer || networkVariable.CanClientWrite(networkManager.LocalClientId)); (networkManager.IsServer || networkVariable.CanClientWrite(networkManager.LocalClientId)) &&
networkVariable.CanSend();
// Prevent the server from writing to the client that owns a given NetworkVariable // Prevent the server from writing to the client that owns a given NetworkVariable
// Allowing the write would send an old value to the client and cause jitter // Allowing the write would send an old value to the client and cause jitter
@@ -125,10 +124,6 @@ namespace Unity.Netcode
} }
else else
{ {
// DANGO-TODO:
// Complex types with custom type serialization (either registered custom types or INetworkSerializable implementations) will be problematic
// Non-complex types always provide a full state update per delta
// DANGO-TODO: Add NetworkListEvent<T>.EventType awareness to the cloud-state server
if (networkManager.DistributedAuthorityMode) if (networkManager.DistributedAuthorityMode)
{ {
var size_marker = writer.Position; var size_marker = writer.Position;
@@ -166,8 +161,6 @@ namespace Unity.Netcode
return true; return true;
} }
// 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 Handle(ref NetworkContext context) public void Handle(ref NetworkContext context)
{ {
var networkManager = (NetworkManager)context.SystemOwner; var networkManager = (NetworkManager)context.SystemOwner;

View File

@@ -117,22 +117,28 @@ namespace Unity.Netcode
networkObject.SetNetworkParenting(LatestParent, WorldPositionStays); networkObject.SetNetworkParenting(LatestParent, WorldPositionStays);
networkObject.ApplyNetworkParenting(RemoveParent); networkObject.ApplyNetworkParenting(RemoveParent);
// We set all of the transform values after parenting as they are // This check is primarily for client-server network topologies when the motion model is owner authoritative:
// the values of the server-side post-parenting transform values // When SyncOwnerTransformWhenParented is enabled, then always apply the transform values.
if (!WorldPositionStays) // When SyncOwnerTransformWhenParented is disabled, then only synchronize the transform on non-owner instances.
if (networkObject.SyncOwnerTransformWhenParented || (!networkObject.SyncOwnerTransformWhenParented && !networkObject.IsOwner))
{ {
networkObject.transform.localPosition = Position; // We set all of the transform values after parenting as they are
networkObject.transform.localRotation = Rotation; // the values of the server-side post-parenting transform values
if (!WorldPositionStays)
{
networkObject.transform.localPosition = Position;
networkObject.transform.localRotation = Rotation;
}
else
{
networkObject.transform.position = Position;
networkObject.transform.rotation = Rotation;
}
networkObject.transform.localScale = Scale;
} }
else
{
networkObject.transform.position = Position;
networkObject.transform.rotation = Rotation;
}
networkObject.transform.localScale = Scale;
// If in distributed authority mode and we are running a DAHost and this is the DAHost, then forward the parent changed message to any remaining clients // If in distributed authority mode and we are running a DAHost and this is the DAHost, then forward the parent changed message to any remaining clients
if (networkManager.DistributedAuthorityMode && !networkManager.CMBServiceConnection && networkManager.DAHost) if ((networkManager.DistributedAuthorityMode && !networkManager.CMBServiceConnection && networkManager.DAHost) || (networkObject.AllowOwnerToParent && context.SenderId == networkObject.OwnerClientId && networkManager.IsServer))
{ {
var size = 0; var size = 0;
var message = this; var message = this;

View File

@@ -1,4 +1,3 @@
using System;
using Unity.Collections; using Unity.Collections;
namespace Unity.Netcode namespace Unity.Netcode
@@ -34,21 +33,13 @@ namespace Unity.Netcode
var networkManager = (NetworkManager)context.SystemOwner; var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(WrappedMessage.Metadata.NetworkObjectId, out var networkObject)) if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(WrappedMessage.Metadata.NetworkObjectId, out var networkObject))
{ {
// With distributed authority mode, we can send Rpcs before we have been notified the NetworkObject is despawned. // If the NetworkObject no longer exists then just log a warning when developer mode logging is enabled and exit.
// DANGO-TODO: Should the CMB Service cull out any Rpcs targeting recently despawned NetworkObjects? // This can happen if NetworkObject is despawned and a client sends an RPC before receiving the despawn message.
// DANGO-TODO: This would require the service to keep track of despawned NetworkObjects since we re-use NetworkObject identifiers. if (networkManager.LogLevel == LogLevel.Developer)
if (networkManager.DistributedAuthorityMode)
{ {
if (networkManager.LogLevel == LogLevel.Developer) NetworkLog.LogWarning($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}] An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
{
NetworkLog.LogWarning($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}]An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
}
return;
}
else
{
throw new InvalidOperationException($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}]An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
} }
return;
} }
var observers = networkObject.Observers; var observers = networkObject.Observers;

View File

@@ -41,7 +41,7 @@ namespace Unity.Netcode
payload = new FastBufferReader(reader.GetUnsafePtrAtCurrentPosition(), Allocator.None, reader.Length - reader.Position); payload = new FastBufferReader(reader.GetUnsafePtrAtCurrentPosition(), Allocator.None, reader.Length - reader.Position);
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (NetworkBehaviour.__rpc_name_table[networkBehaviour.GetType()].TryGetValue(metadata.NetworkRpcMethodId, out var rpcMethodName)) if (NetworkBehaviour.__rpc_name_table[networkBehaviour.GetType()].TryGetValue(metadata.NetworkRpcMethodId, out var rpcMethodName))
{ {
networkManager.NetworkMetrics.TrackRpcReceived( networkManager.NetworkMetrics.TrackRpcReceived(
@@ -60,7 +60,13 @@ namespace Unity.Netcode
var networkManager = (NetworkManager)context.SystemOwner; var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(metadata.NetworkObjectId, out var networkObject)) if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(metadata.NetworkObjectId, out var networkObject))
{ {
throw new InvalidOperationException($"An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs."); // If the NetworkObject no longer exists then just log a warning when developer mode logging is enabled and exit.
// This can happen if NetworkObject is despawned and a client sends an RPC before receiving the despawn message.
if (networkManager.LogLevel == LogLevel.Developer)
{
NetworkLog.LogWarning($"[{metadata.NetworkObjectId}, {metadata.NetworkBehaviourId}, {metadata.NetworkRpcMethodId}] An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
}
return;
} }
var networkBehaviour = networkObject.GetNetworkBehaviourAtOrderIndex(metadata.NetworkBehaviourId); var networkBehaviour = networkObject.GetNetworkBehaviourAtOrderIndex(metadata.NetworkBehaviourId);

View File

@@ -20,7 +20,7 @@ namespace Unity.Netcode
public void Handle(ref NetworkContext context) public void Handle(ref NetworkContext context)
{ {
((NetworkManager)context.SystemOwner).CustomMessagingManager.InvokeUnnamedMessage(context.SenderId, m_ReceivedData, context.SerializedHeaderSize); ((NetworkManager)context.SystemOwner).CustomMessagingManager?.InvokeUnnamedMessage(context.SenderId, m_ReceivedData, context.SerializedHeaderSize);
} }
} }
} }

View File

@@ -34,6 +34,9 @@ namespace Unity.Netcode
internal class NetworkMessageManager : IDisposable internal class NetworkMessageManager : IDisposable
{ {
public bool StopProcessing = false; public bool StopProcessing = false;
private static Type s_ConnectionApprovedType = typeof(ConnectionApprovedMessage);
private static Type s_ConnectionRequestType = typeof(ConnectionRequestMessage);
private static Type s_DisconnectReasonType = typeof(DisconnectReasonMessage);
private struct ReceiveQueueItem private struct ReceiveQueueItem
{ {
@@ -524,6 +527,7 @@ namespace Unity.Netcode
return new T().Version; return new T().Version;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal int GetMessageVersion(Type type, ulong clientId, bool forReceive = false) internal int GetMessageVersion(Type type, ulong clientId, bool forReceive = false)
{ {
if (!m_PerClientMessageVersions.TryGetValue(clientId, out var versionMap)) if (!m_PerClientMessageVersions.TryGetValue(clientId, out var versionMap))
@@ -551,16 +555,20 @@ namespace Unity.Netcode
return messageVersion; return messageVersion;
} }
public static void ReceiveMessage<T>(FastBufferReader reader, ref NetworkContext context, NetworkMessageManager manager) where T : INetworkMessage, new() public static void ReceiveMessage<T>(FastBufferReader reader, ref NetworkContext context, NetworkMessageManager manager) where T : INetworkMessage, new()
{ {
var messageType = typeof(T);
var message = new T(); var message = new T();
var messageVersion = 0; var messageVersion = 0;
// Special cases because these are the messages that carry the version info - thus the version info isn't // Special cases because these are the messages that carry the version info - thus the version info isn't
// populated yet when we get these. The first part of these messages always has to be the version data // populated yet when we get these. The first part of these messages always has to be the version data
// and can't change. // and can't change.
if (typeof(T) != typeof(ConnectionRequestMessage) && typeof(T) != typeof(ConnectionApprovedMessage) && typeof(T) != typeof(DisconnectReasonMessage) && context.SenderId != manager.m_LocalClientId) if (messageType != s_ConnectionRequestType && messageType != s_ConnectionApprovedType && messageType != s_DisconnectReasonType && context.SenderId != manager.m_LocalClientId)
{ {
messageVersion = manager.GetMessageVersion(typeof(T), context.SenderId, true); messageVersion = manager.GetMessageVersion(messageType, context.SenderId, true);
if (messageVersion < 0) if (messageVersion < 0)
{ {
return; return;
@@ -612,7 +620,7 @@ namespace Unity.Netcode
var messageVersion = 0; var messageVersion = 0;
// Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this. // Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this.
// The first part of this message always has to be the version data and can't change. // The first part of this message always has to be the version data and can't change.
if (typeof(TMessageType) != typeof(ConnectionRequestMessage)) if (typeof(TMessageType) != s_ConnectionRequestType)
{ {
messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]); messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]);
if (messageVersion < 0) if (messageVersion < 0)
@@ -666,7 +674,7 @@ namespace Unity.Netcode
// Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this. // Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this.
// The first part of this message always has to be the version data and can't change. // The first part of this message always has to be the version data and can't change.
if (typeof(TMessageType) != typeof(ConnectionRequestMessage)) if (typeof(TMessageType) != s_ConnectionRequestType)
{ {
var messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]); var messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]);
if (messageVersion < 0) if (messageVersion < 0)
@@ -725,7 +733,11 @@ namespace Unity.Netcode
} }
ref var writeQueueItem = ref sendQueueItem.ElementAt(sendQueueItem.Length - 1); ref var writeQueueItem = ref sendQueueItem.ElementAt(sendQueueItem.Length - 1);
writeQueueItem.Writer.TryBeginWrite(tmpSerializer.Length + headerSerializer.Length); if (!writeQueueItem.Writer.TryBeginWrite(tmpSerializer.Length + headerSerializer.Length))
{
Debug.LogError($"Not enough space to write message, size={tmpSerializer.Length + headerSerializer.Length} space used={writeQueueItem.Writer.Position} total size={writeQueueItem.Writer.Capacity}");
continue;
}
writeQueueItem.Writer.WriteBytes(headerSerializer.GetUnsafePtr(), headerSerializer.Length); writeQueueItem.Writer.WriteBytes(headerSerializer.GetUnsafePtr(), headerSerializer.Length);
writeQueueItem.Writer.WriteBytes(tmpSerializer.GetUnsafePtr(), tmpSerializer.Length); writeQueueItem.Writer.WriteBytes(tmpSerializer.GetUnsafePtr(), tmpSerializer.Length);
@@ -746,7 +758,7 @@ namespace Unity.Netcode
// Special case because this is the message that carries the version info - thus the version info isn't // Special case because this is the message that carries the version info - thus the version info isn't
// populated yet when we get this. The first part of this message always has to be the version data // populated yet when we get this. The first part of this message always has to be the version data
// and can't change. // and can't change.
if (typeof(TMessageType) != typeof(ConnectionRequestMessage)) if (typeof(TMessageType) != s_ConnectionRequestType)
{ {
messageVersion = GetMessageVersion(typeof(TMessageType), clientId); messageVersion = GetMessageVersion(typeof(TMessageType), clientId);
if (messageVersion < 0) if (messageVersion < 0)

View File

@@ -36,12 +36,12 @@ namespace Unity.Netcode
private protected void SendMessageToClient(NetworkBehaviour behaviour, ulong clientId, ref RpcMessage message, NetworkDelivery delivery) private protected void SendMessageToClient(NetworkBehaviour behaviour, ulong clientId, ref RpcMessage message, NetworkDelivery delivery)
{ {
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
var size = var size =
#endif #endif
behaviour.NetworkManager.MessageManager.SendMessage(ref message, delivery, clientId); behaviour.NetworkManager.MessageManager.SendMessage(ref message, delivery, clientId);
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName)) if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
{ {
behaviour.NetworkManager.NetworkMetrics.TrackRpcSent( behaviour.NetworkManager.NetworkMetrics.TrackRpcSent(

View File

@@ -4,23 +4,37 @@ namespace Unity.Netcode
{ {
private NotServerRpcTarget m_NotServerRpcTarget; private NotServerRpcTarget m_NotServerRpcTarget;
private ServerRpcTarget m_ServerRpcTarget; private ServerRpcTarget m_ServerRpcTarget;
private NotAuthorityRpcTarget m_NotAuthorityRpcTarget;
private AuthorityRpcTarget m_AuthorityRpcTarget;
public override void Dispose() public override void Dispose()
{ {
m_NotServerRpcTarget.Dispose(); m_NotServerRpcTarget.Dispose();
m_ServerRpcTarget.Dispose(); m_ServerRpcTarget.Dispose();
m_NotAuthorityRpcTarget.Dispose();
m_AuthorityRpcTarget.Dispose();
} }
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams) internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
{ {
m_NotServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams); if (NetworkManager.IsDistributedAuthority)
m_ServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams); {
m_NotAuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
m_AuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
}
else
{
m_NotServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
m_ServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
}
} }
internal EveryoneRpcTarget(NetworkManager manager) : base(manager) internal EveryoneRpcTarget(NetworkManager manager) : base(manager)
{ {
m_NotServerRpcTarget = new NotServerRpcTarget(manager); m_NotServerRpcTarget = new NotServerRpcTarget(manager);
m_ServerRpcTarget = new ServerRpcTarget(manager); m_ServerRpcTarget = new ServerRpcTarget(manager);
m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager);
m_AuthorityRpcTarget = new AuthorityRpcTarget(manager);
} }
} }
} }

View File

@@ -46,7 +46,7 @@ namespace Unity.Netcode
message.Handle(ref context); message.Handle(ref context);
length = tempBuffer.Length; length = tempBuffer.Length;
} }
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName)) if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
{ {
networkManager.NetworkMetrics.TrackRpcSent( networkManager.NetworkMetrics.TrackRpcSent(

View File

@@ -29,6 +29,12 @@ namespace Unity.Netcode
{ {
continue; continue;
} }
// The CMB-Service holds ID 0 and should not be added to the targets
if (clientId == NetworkManager.ServerClientId && m_NetworkManager.CMBServiceConnection)
{
continue;
}
m_GroupSendTarget.Add(clientId); m_GroupSendTarget.Add(clientId);
} }
} }
@@ -41,6 +47,12 @@ namespace Unity.Netcode
continue; continue;
} }
// The CMB-Service holds ID 0 and should not be added to the targets
if (clientId == NetworkManager.ServerClientId && m_NetworkManager.CMBServiceConnection)
{
continue;
}
if (clientId == m_NetworkManager.LocalClientId) if (clientId == m_NetworkManager.LocalClientId)
{ {
m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams); m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams);

View File

@@ -17,13 +17,18 @@ namespace Unity.Netcode
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams) internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
{ {
// If there are no targets then don't attempt to send anything.
if (TargetClientIds.Length == 0 && Ids.Count == 0)
{
return;
}
var proxyMessage = new ProxyMessage { Delivery = delivery, TargetClientIds = TargetClientIds.AsArray(), WrappedMessage = message }; var proxyMessage = new ProxyMessage { Delivery = delivery, TargetClientIds = TargetClientIds.AsArray(), WrappedMessage = message };
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
var size = var size =
#endif #endif
behaviour.NetworkManager.MessageManager.SendMessage(ref proxyMessage, delivery, NetworkManager.ServerClientId); behaviour.NetworkManager.MessageManager.SendMessage(ref proxyMessage, delivery, NetworkManager.ServerClientId);
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName)) if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
{ {
foreach (var clientId in TargetClientIds) foreach (var clientId in TargetClientIds)

View File

@@ -0,0 +1,392 @@
using System;
using Unity.Mathematics;
using UnityEngine;
namespace Unity.Netcode
{
public enum StaleDataHandling
{
Ignore,
Reanticipate
}
#pragma warning disable IDE0001
/// <summary>
/// A variable that can be synchronized over the network.
/// This version supports basic client anticipation - the client can set a value on the belief that the server
/// will update it to reflect the same value in a future update (i.e., as the result of an RPC call).
/// This value can then be adjusted as new updates from the server come in, in three basic modes:
///
/// <list type="bullet">
///
/// <item><b>Snap:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and no <see cref="NetworkBehaviour.OnReanticipate"/> callback),
/// the moment a more up-to-date value is received from the authority, it will simply replace the anticipated value,
/// resulting in a "snap" to the new value if it is different from the anticipated value.</item>
///
/// <item><b>Smooth:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> callback that calls
/// <see cref="Smooth"/> from the anticipated value to the authority value with an appropriate
/// <see cref="Mathf.Lerp"/>-style smooth function), when a more up-to-date value is received from the authority,
/// it will interpolate over time from an incorrect anticipated value to the correct authoritative value.</item>
///
/// <item><b>Constant Reanticipation:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Reanticipate"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> that calculates a
/// new anticipated value based on the current authoritative value), when a more up-to-date value is received from
/// the authority, user code calculates a new anticipated value, possibly calling <see cref="Smooth"/> to interpolate
/// between the previous anticipation and the new anticipation. This is useful for values that change frequently and
/// need to constantly be re-evaluated, as opposed to values that change only in response to user action and simply
/// need a one-time anticipation when the user performs that action.</item>
///
/// </list>
///
/// Note that these three modes may be combined. For example, if an <see cref="NetworkBehaviour.OnReanticipate"/> callback
/// does not call either <see cref="Smooth"/> or <see cref="Anticipate"/>, the result will be a snap to the
/// authoritative value, enabling for a callback that may conditionally call <see cref="Smooth"/> when the
/// difference between the anticipated and authoritative values is within some threshold, but fall back to
/// snap behavior if the difference is too large.
/// </summary>
/// <typeparam name="T">the unmanaged type for <see cref="NetworkVariable{T}"/> </typeparam>
#pragma warning restore IDE0001
[Serializable]
[GenerateSerializationForGenericParameter(0)]
public class AnticipatedNetworkVariable<T> : NetworkVariableBase
{
[SerializeField]
private NetworkVariable<T> m_AuthoritativeValue;
private T m_AnticipatedValue;
private T m_PreviousAnticipatedValue;
private ulong m_LastAuthorityUpdateCounter = 0;
private ulong m_LastAnticipationCounter = 0;
private bool m_IsDisposed = false;
private bool m_SettingAuthoritativeValue = false;
private T m_SmoothFrom;
private T m_SmoothTo;
private float m_SmoothDuration;
private float m_CurrentSmoothTime;
private bool m_HasSmoothValues;
#pragma warning disable IDE0001
/// <summary>
/// Defines what the behavior should be if we receive a value from the server with an earlier associated
/// time value than the anticipation time value.
/// <br/><br/>
/// If this is <see cref="Netcode.StaleDataHandling.Ignore"/>, the stale data will be ignored and the authoritative
/// value will not replace the anticipated value until the anticipation time is reached. <see cref="OnAuthoritativeValueChanged"/>
/// and <see cref="NetworkBehaviour.OnReanticipate"/> will also not be invoked for this stale data.
/// <br/><br/>
/// If this is <see cref="Netcode.StaleDataHandling.Reanticipate"/>, the stale data will replace the anticipated data and
/// <see cref="OnAuthoritativeValueChanged"/> and <see cref="NetworkBehaviour.OnReanticipate"/> will be invoked.
/// In this case, the authoritativeTime value passed to <see cref="NetworkBehaviour.OnReanticipate"/> will be lower than
/// the anticipationTime value, and that callback can be used to calculate a new anticipated value.
/// </summary>
#pragma warning restore IDE0001
public StaleDataHandling StaleDataHandling;
public delegate void OnAuthoritativeValueChangedDelegate(AnticipatedNetworkVariable<T> variable, in T previousValue, in T newValue);
/// <summary>
/// Invoked any time the authoritative value changes, even when the data is stale or has been changed locally.
/// </summary>
public OnAuthoritativeValueChangedDelegate OnAuthoritativeValueChanged = null;
/// <summary>
/// Determines if the difference between the last serialized value and the current value is large enough
/// to serialize it again.
/// </summary>
public event NetworkVariable<T>.CheckExceedsDirtinessThresholdDelegate CheckExceedsDirtinessThreshold
{
add => m_AuthoritativeValue.CheckExceedsDirtinessThreshold += value;
remove => m_AuthoritativeValue.CheckExceedsDirtinessThreshold -= value;
}
private class AnticipatedObject : IAnticipatedObject
{
public AnticipatedNetworkVariable<T> Variable;
public void Update()
{
Variable.Update();
}
public void ResetAnticipation()
{
Variable.ShouldReanticipate = false;
}
public NetworkObject OwnerObject => Variable.m_NetworkBehaviour.NetworkObject;
}
private AnticipatedObject m_AnticipatedObject;
public override void OnInitialize()
{
m_AuthoritativeValue.Initialize(m_NetworkBehaviour);
NetworkVariableSerialization<T>.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue);
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
if (m_NetworkBehaviour != null && m_NetworkBehaviour.NetworkManager != null && m_NetworkBehaviour.NetworkManager.AnticipationSystem != null)
{
m_AnticipatedObject = new AnticipatedObject { Variable = this };
m_NetworkBehaviour.NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
}
}
public override bool ExceedsDirtinessThreshold()
{
return m_AuthoritativeValue.ExceedsDirtinessThreshold();
}
/// <summary>
/// Retrieves the current value for the variable.
/// This is the "display value" for this variable, and is affected by <see cref="Anticipate"/> and
/// <see cref="Smooth"/>, as well as by updates from the authority, depending on <see cref="StaleDataHandling"/>
/// and the behavior of any <see cref="NetworkBehaviour.OnReanticipate"/> callbacks.
/// <br /><br />
/// When a server update arrives, this value will be overwritten
/// by the new server value (unless stale data handling is set
/// to "Ignore" and the update is determined to be stale).
/// This value will be duplicated in
/// <see cref="PreviousAnticipatedValue"/>, which
/// will NOT be overwritten in server updates.
/// </summary>
public T Value => m_AnticipatedValue;
/// <summary>
/// Indicates whether this variable currently needs
/// reanticipation. If this is true, the anticipated value
/// has been overwritten by the authoritative value from the
/// server; the previous anticipated value is stored in <see cref="PreviousAnticipatedState"/>
/// </summary>
public bool ShouldReanticipate
{
get;
private set;
}
/// <summary>
/// Holds the most recent anticipated value, whatever was
/// most recently set using <see cref="Anticipate"/>. Unlike
/// <see cref="Value"/>, this does not get overwritten
/// when a server update arrives.
/// </summary>
public T PreviousAnticipatedValue => m_PreviousAnticipatedValue;
/// <summary>
/// Sets the current value of the variable on the expectation that the authority will set the variable
/// to the same value within one network round trip (i.e., in response to an RPC).
/// </summary>
/// <param name="value"></param>
public void Anticipate(T value)
{
if (m_NetworkBehaviour.NetworkManager.ShutdownInProgress || !m_NetworkBehaviour.NetworkManager.IsListening)
{
return;
}
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
m_LastAnticipationCounter = m_NetworkBehaviour.NetworkManager.AnticipationSystem.AnticipationCounter;
m_AnticipatedValue = value;
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
if (CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
{
AuthoritativeValue = value;
}
}
#pragma warning disable IDE0001
/// <summary>
/// Retrieves or sets the underlying authoritative value.
/// Note that only a client or server with write permissions to this variable may set this value.
/// When this variable has been anticipated, this value will alawys return the most recent authoritative
/// state, which is updated even if <see cref="StaleDataHandling"/> is <see cref="Netcode.StaleDataHandling.Ignore"/>.
/// </summary>
#pragma warning restore IDE0001
public T AuthoritativeValue
{
get => m_AuthoritativeValue.Value;
set
{
m_SettingAuthoritativeValue = true;
try
{
m_AuthoritativeValue.Value = value;
m_AnticipatedValue = value;
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
}
finally
{
m_SettingAuthoritativeValue = false;
}
}
}
/// <summary>
/// A function to interpolate between two values based on a percentage.
/// See <see cref="Mathf.Lerp"/>, <see cref="Vector3.Lerp"/>, <see cref="Vector3.Slerp"/>, and so on
/// for examples.
/// </summary>
public delegate T SmoothDelegate(T authoritativeValue, T anticipatedValue, float amount);
private SmoothDelegate m_SmoothDelegate = null;
public AnticipatedNetworkVariable(T value = default,
StaleDataHandling staleDataHandling = StaleDataHandling.Ignore)
: base()
{
StaleDataHandling = staleDataHandling;
m_AuthoritativeValue = new NetworkVariable<T>(value)
{
OnValueChanged = OnValueChangedInternal
};
}
public void Update()
{
if (m_CurrentSmoothTime < m_SmoothDuration)
{
m_CurrentSmoothTime += m_NetworkBehaviour.NetworkManager.RealTimeProvider.DeltaTime;
var pct = math.min(m_CurrentSmoothTime / m_SmoothDuration, 1f);
m_AnticipatedValue = m_SmoothDelegate(m_SmoothFrom, m_SmoothTo, pct);
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
}
}
public override void Dispose()
{
if (m_IsDisposed)
{
return;
}
if (m_NetworkBehaviour != null && m_NetworkBehaviour.NetworkManager != null && m_NetworkBehaviour.NetworkManager.AnticipationSystem != null)
{
if (m_AnticipatedObject != null)
{
m_NetworkBehaviour.NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject);
m_NetworkBehaviour.NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject);
m_AnticipatedObject = null;
}
}
m_IsDisposed = true;
m_AuthoritativeValue.Dispose();
if (m_AnticipatedValue is IDisposable anticipatedValueDisposable)
{
anticipatedValueDisposable.Dispose();
}
m_AnticipatedValue = default;
if (m_PreviousAnticipatedValue is IDisposable previousValueDisposable)
{
previousValueDisposable.Dispose();
m_PreviousAnticipatedValue = default;
}
if (m_HasSmoothValues)
{
if (m_SmoothFrom is IDisposable smoothFromDisposable)
{
smoothFromDisposable.Dispose();
m_SmoothFrom = default;
}
if (m_SmoothTo is IDisposable smoothToDisposable)
{
smoothToDisposable.Dispose();
m_SmoothTo = default;
}
m_HasSmoothValues = false;
}
}
~AnticipatedNetworkVariable()
{
Dispose();
}
private void OnValueChangedInternal(T previousValue, T newValue)
{
if (!m_SettingAuthoritativeValue)
{
m_LastAuthorityUpdateCounter = m_NetworkBehaviour.NetworkManager.AnticipationSystem.LastAnticipationAck;
if (StaleDataHandling == StaleDataHandling.Ignore && m_LastAnticipationCounter > m_LastAuthorityUpdateCounter)
{
// Keep the anticipated value unchanged because it is more recent than the authoritative one.
return;
}
ShouldReanticipate = true;
m_NetworkBehaviour.NetworkManager.AnticipationSystem.ObjectsToReanticipate.Add(m_AnticipatedObject);
}
NetworkVariableSerialization<T>.Duplicate(AuthoritativeValue, ref m_AnticipatedValue);
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
OnAuthoritativeValueChanged?.Invoke(this, previousValue, newValue);
}
/// <summary>
/// Interpolate this variable from <see cref="from"/> to <see cref="to"/> over <see cref="durationSeconds"/> of
/// real time. The duration uses <see cref="Time.deltaTime"/>, so it is affected by <see cref="Time.timeScale"/>.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <param name="durationSeconds"></param>
/// <param name="how"></param>
public void Smooth(in T from, in T to, float durationSeconds, SmoothDelegate how)
{
if (durationSeconds <= 0)
{
NetworkVariableSerialization<T>.Duplicate(to, ref m_AnticipatedValue);
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
m_SmoothDelegate = null;
return;
}
NetworkVariableSerialization<T>.Duplicate(from, ref m_AnticipatedValue);
NetworkVariableSerialization<T>.Duplicate(from, ref m_SmoothFrom);
NetworkVariableSerialization<T>.Duplicate(to, ref m_SmoothTo);
m_SmoothDuration = durationSeconds;
m_CurrentSmoothTime = 0;
m_SmoothDelegate = how;
m_HasSmoothValues = true;
}
public override bool IsDirty()
{
return m_AuthoritativeValue.IsDirty();
}
public override void ResetDirty()
{
m_AuthoritativeValue.ResetDirty();
}
public override void WriteDelta(FastBufferWriter writer)
{
m_AuthoritativeValue.WriteDelta(writer);
}
public override void WriteField(FastBufferWriter writer)
{
m_AuthoritativeValue.WriteField(writer);
}
public override void ReadField(FastBufferReader reader)
{
m_AuthoritativeValue.ReadField(reader);
NetworkVariableSerialization<T>.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue);
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
}
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
{
m_AuthoritativeValue.ReadDelta(reader, keepDirtyDelta);
}
}
}

View File

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

View File

@@ -94,18 +94,18 @@ namespace Unity.Netcode
{ {
case NetworkListEvent<T>.EventType.Add: case NetworkListEvent<T>.EventType.Add:
{ {
NetworkVariableSerialization<T>.Write(writer, ref element.Value); NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
} }
break; break;
case NetworkListEvent<T>.EventType.Insert: case NetworkListEvent<T>.EventType.Insert:
{ {
BytePacker.WriteValueBitPacked(writer, element.Index); BytePacker.WriteValueBitPacked(writer, element.Index);
NetworkVariableSerialization<T>.Write(writer, ref element.Value); NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
} }
break; break;
case NetworkListEvent<T>.EventType.Remove: case NetworkListEvent<T>.EventType.Remove:
{ {
NetworkVariableSerialization<T>.Write(writer, ref element.Value); NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
} }
break; break;
case NetworkListEvent<T>.EventType.RemoveAt: case NetworkListEvent<T>.EventType.RemoveAt:
@@ -116,7 +116,7 @@ namespace Unity.Netcode
case NetworkListEvent<T>.EventType.Value: case NetworkListEvent<T>.EventType.Value:
{ {
BytePacker.WriteValueBitPacked(writer, element.Index); BytePacker.WriteValueBitPacked(writer, element.Index);
NetworkVariableSerialization<T>.Write(writer, ref element.Value); NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
} }
break; break;
case NetworkListEvent<T>.EventType.Clear: case NetworkListEvent<T>.EventType.Clear:
@@ -133,13 +133,13 @@ namespace Unity.Netcode
{ {
if (m_NetworkManager.DistributedAuthorityMode) if (m_NetworkManager.DistributedAuthorityMode)
{ {
writer.WriteValueSafe(NetworkVariableSerialization<T>.Type); writer.WriteValueSafe(NetworkVariableSerialization<T>.Serializer.Type);
if (NetworkVariableSerialization<T>.Type == CollectionItemType.Unmanaged) if (NetworkVariableSerialization<T>.Serializer.Type == NetworkVariableType.Unmanaged)
{ {
// Write the size of the unmanaged serialized type as it has a fixed size. This allows the CMB runtime to correctly read the unmanged type. // Write the size of the unmanaged serialized type as it has a fixed size. This allows the CMB runtime to correctly read the unmanged type.
var placeholder = new T(); var placeholder = new T();
var startPos = writer.Position; var startPos = writer.Position;
NetworkVariableSerialization<T>.Write(writer, ref placeholder); NetworkVariableSerialization<T>.Serializer.Write(writer, ref placeholder);
var size = writer.Position - startPos; var size = writer.Position - startPos;
writer.Seek(startPos); writer.Seek(startPos);
BytePacker.WriteValueBitPacked(writer, size); BytePacker.WriteValueBitPacked(writer, size);
@@ -148,7 +148,7 @@ namespace Unity.Netcode
writer.WriteValueSafe((ushort)m_List.Length); writer.WriteValueSafe((ushort)m_List.Length);
for (int i = 0; i < m_List.Length; i++) for (int i = 0; i < m_List.Length; i++)
{ {
NetworkVariableSerialization<T>.Write(writer, ref m_List.ElementAt(i)); NetworkVariableSerialization<T>.Serializer.Write(writer, ref m_List.ElementAt(i));
} }
} }
@@ -158,9 +158,9 @@ namespace Unity.Netcode
m_List.Clear(); m_List.Clear();
if (m_NetworkManager.DistributedAuthorityMode) if (m_NetworkManager.DistributedAuthorityMode)
{ {
// Collection item type is used by the CMB rust service, drop value here. SerializationTools.ReadType(reader, NetworkVariableSerialization<T>.Serializer);
reader.ReadValueSafe(out CollectionItemType type); // Collection item type is used by the DA server, drop value here.
if (type == CollectionItemType.Unmanaged) if (NetworkVariableSerialization<T>.Serializer.Type == NetworkVariableType.Unmanaged)
{ {
ByteUnpacker.ReadValueBitPacked(reader, out int _); ByteUnpacker.ReadValueBitPacked(reader, out int _);
} }
@@ -169,7 +169,7 @@ namespace Unity.Netcode
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++)
{ {
var value = new T(); var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value); NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
m_List.Add(value); m_List.Add(value);
} }
} }
@@ -186,7 +186,7 @@ namespace Unity.Netcode
case NetworkListEvent<T>.EventType.Add: case NetworkListEvent<T>.EventType.Add:
{ {
var value = new T(); var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value); NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
m_List.Add(value); m_List.Add(value);
if (OnListChanged != null) if (OnListChanged != null)
@@ -215,7 +215,7 @@ namespace Unity.Netcode
{ {
ByteUnpacker.ReadValueBitPacked(reader, out int index); ByteUnpacker.ReadValueBitPacked(reader, out int index);
var value = new T(); var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value); NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
if (index < m_List.Length) if (index < m_List.Length)
{ {
@@ -252,7 +252,7 @@ namespace Unity.Netcode
case NetworkListEvent<T>.EventType.Remove: case NetworkListEvent<T>.EventType.Remove:
{ {
var value = new T(); var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value); NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
int index = m_List.IndexOf(value); int index = m_List.IndexOf(value);
if (index == -1) if (index == -1)
{ {
@@ -315,7 +315,7 @@ namespace Unity.Netcode
{ {
ByteUnpacker.ReadValueBitPacked(reader, out int index); ByteUnpacker.ReadValueBitPacked(reader, out int index);
var value = new T(); var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value); NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
if (index >= m_List.Length) if (index >= m_List.Length)
{ {
throw new Exception("Shouldn't be here, index is higher than list length"); throw new Exception("Shouldn't be here, index is higher than list length");
@@ -393,7 +393,8 @@ namespace Unity.Netcode
// check write permissions // check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId)) if (!CanClientWrite(m_NetworkManager.LocalClientId))
{ {
throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); LogWritePermissionError();
return;
} }
m_List.Add(item); m_List.Add(item);
@@ -414,7 +415,8 @@ namespace Unity.Netcode
// check write permissions // check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId)) if (!CanClientWrite(m_NetworkManager.LocalClientId))
{ {
throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); LogWritePermissionError();
return;
} }
m_List.Clear(); m_List.Clear();
@@ -440,7 +442,8 @@ namespace Unity.Netcode
// check write permissions // check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId)) if (!CanClientWrite(m_NetworkManager.LocalClientId))
{ {
throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); LogWritePermissionError();
return false;
} }
int index = m_List.IndexOf(item); int index = m_List.IndexOf(item);
@@ -475,7 +478,8 @@ namespace Unity.Netcode
// check write permissions // check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId)) if (!CanClientWrite(m_NetworkManager.LocalClientId))
{ {
throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); LogWritePermissionError();
return;
} }
if (index < m_List.Length) if (index < m_List.Length)
@@ -520,6 +524,8 @@ namespace Unity.Netcode
HandleAddListEvent(listEvent); HandleAddListEvent(listEvent);
} }
/// <inheritdoc /> /// <inheritdoc />
public T this[int index] public T this[int index]
{ {
@@ -529,7 +535,8 @@ namespace Unity.Netcode
// check write permissions // check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId)) if (!CanClientWrite(m_NetworkManager.LocalClientId))
{ {
throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); LogWritePermissionError();
return;
} }
var previousValue = m_List[index]; var previousValue = m_List[index];

View File

@@ -21,6 +21,29 @@ namespace Unity.Netcode
/// The callback to be invoked when the value gets changed /// The callback to be invoked when the value gets changed
/// </summary> /// </summary>
public OnValueChangedDelegate OnValueChanged; public OnValueChangedDelegate OnValueChanged;
public delegate bool CheckExceedsDirtinessThresholdDelegate(in T previousValue, in T newValue);
public CheckExceedsDirtinessThresholdDelegate CheckExceedsDirtinessThreshold;
public override bool ExceedsDirtinessThreshold()
{
if (CheckExceedsDirtinessThreshold != null && m_HasPreviousValue)
{
return CheckExceedsDirtinessThreshold(m_PreviousValue, m_InternalValue);
}
return true;
}
public override void OnInitialize()
{
base.OnInitialize();
m_HasPreviousValue = true;
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
}
internal override NetworkVariableType Type => NetworkVariableType.Value; internal override NetworkVariableType Type => NetworkVariableType.Value;
/// <summary> /// <summary>
@@ -71,27 +94,59 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// The value of the NetworkVariable container /// The value of the NetworkVariable container
/// </summary> /// </summary>
/// <remarks>
/// When assigning collections to <see cref="Value"/>, unless it is a completely new collection this will not
/// detect any deltas with most managed collection classes since assignment of one collection value to another
/// is actually just a reference to the collection itself. <br />
/// To detect deltas in a collection, you should invoke <see cref="CheckDirtyState"/> after making modifications to the collection.
/// </remarks>
public virtual T Value public virtual T Value
{ {
get => m_InternalValue; get => m_InternalValue;
set set
{ {
// Compare bitwise if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId))
if (NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref value))
{ {
LogWritePermissionError();
return; return;
} }
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId)) // Compare the Value being applied to the current value
if (!NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref value))
{ {
throw new InvalidOperationException($"[Client-{m_NetworkManager.LocalClientId}][{m_NetworkBehaviour.name}][{Name}] Write permissions ({WritePerm}) for this client instance is not allowed!"); T previousValue = m_InternalValue;
m_InternalValue = value;
SetDirty(true);
m_IsDisposed = false;
OnValueChanged?.Invoke(previousValue, m_InternalValue);
} }
Set(value);
m_IsDisposed = false;
} }
} }
/// <summary>
/// Invoke this method to check if a collection's items are dirty.
/// The default behavior is to exit early if the <see cref="NetworkVariable{T}"/> is already dirty.
/// </summary>
/// <param name="forceCheck"> when true, this check will force a full item collection check even if the NetworkVariable is already dirty</param>
/// <remarks>
/// This is to be used as a way to check if a <see cref="NetworkVariable{T}"/> containing a managed collection has any changees to the collection items.<br />
/// If you invoked this when a collection is dirty, it will not trigger the <see cref="OnValueChanged"/> unless you set <param name="forceCheck"/> to true. <br />
/// </remarks>
public bool CheckDirtyState(bool forceCheck = false)
{
var isDirty = base.IsDirty();
// Compare the previous with the current if not dirty or forcing a check.
if ((!isDirty || forceCheck) && !NetworkVariableSerialization<T>.AreEqual(ref m_PreviousValue, ref m_InternalValue))
{
SetDirty(true);
OnValueChanged?.Invoke(m_PreviousValue, m_InternalValue);
m_IsDisposed = false;
isDirty = true;
}
return isDirty;
}
internal ref T RefValue() internal ref T RefValue()
{ {
return ref m_InternalValue; return ref m_InternalValue;
@@ -170,19 +225,6 @@ namespace Unity.Netcode
base.ResetDirty(); base.ResetDirty();
} }
/// <summary>
/// Sets the <see cref="Value"/>, marks the <see cref="NetworkVariable{T}"/> dirty, and invokes the <see cref="OnValueChanged"/> callback
/// if there are subscribers to that event.
/// </summary>
/// <param name="value">the new value of type `T` to be set/></param>
private protected void Set(T value)
{
SetDirty(true);
T previousValue = m_InternalValue;
m_InternalValue = value;
OnValueChanged?.Invoke(previousValue, m_InternalValue);
}
/// <summary> /// <summary>
/// Writes the variable to the writer /// Writes the variable to the writer
/// </summary> /// </summary>
@@ -199,20 +241,22 @@ namespace Unity.Netcode
/// <param name="keepDirtyDelta">Whether or not the container should keep the dirty delta, or mark the delta as consumed</param> /// <param name="keepDirtyDelta">Whether or not the container should keep the dirty delta, or mark the delta as consumed</param>
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta) public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
{ {
// In order to get managed collections to properly have a previous and current value, we have to
// duplicate the collection at this point before making any modifications to the current.
m_HasPreviousValue = true;
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
NetworkVariableSerialization<T>.ReadDelta(reader, ref m_InternalValue);
// todo: // todo:
// keepDirtyDelta marks a variable received as dirty and causes the server to send the value to clients // keepDirtyDelta marks a variable received as dirty and causes the server to send the value to clients
// In a prefect world, whether a variable was A) modified locally or B) received and needs retransmit // In a prefect world, whether a variable was A) modified locally or B) received and needs retransmit
// would be stored in different fields // would be stored in different fields
T previousValue = m_InternalValue;
NetworkVariableSerialization<T>.ReadDelta(reader, ref m_InternalValue);
if (keepDirtyDelta) if (keepDirtyDelta)
{ {
SetDirty(true); SetDirty(true);
} }
OnValueChanged?.Invoke(previousValue, m_InternalValue); OnValueChanged?.Invoke(m_PreviousValue, m_InternalValue);
} }
/// <inheritdoc /> /// <inheritdoc />

View File

@@ -3,11 +3,26 @@ using UnityEngine;
namespace Unity.Netcode namespace Unity.Netcode
{ {
public struct NetworkVariableUpdateTraits
{
[Tooltip("The minimum amount of time that must pass between sending updates. If this amount of time has not passed since the last update, dirtiness will be ignored.")]
public float MinSecondsBetweenUpdates;
[Tooltip("The maximum amount of time that a variable can be dirty without sending an update. If this amount of time has passed since the last update, an update will be sent even if the dirtiness threshold has not been met.")]
public float MaxSecondsBetweenUpdates;
}
/// <summary> /// <summary>
/// Interface for network value containers /// Interface for network value containers
/// </summary> /// </summary>
public abstract class NetworkVariableBase : IDisposable public abstract class NetworkVariableBase : IDisposable
{ {
[SerializeField]
internal NetworkVariableUpdateTraits UpdateTraits = default;
[NonSerialized]
internal double LastUpdateSent;
/// <summary> /// <summary>
/// The delivery type (QoS) to send data with /// The delivery type (QoS) to send data with
/// </summary> /// </summary>
@@ -20,7 +35,17 @@ namespace Unity.Netcode
private NetworkManager m_InternalNetworkManager; private NetworkManager m_InternalNetworkManager;
internal virtual NetworkVariableType Type => NetworkVariableType.Custom; internal virtual NetworkVariableType Type => NetworkVariableType.Unknown;
internal string GetWritePermissionError()
{
return $"|Client-{m_NetworkManager.LocalClientId}|{m_NetworkBehaviour.name}|{Name}| Write permissions ({WritePerm}) for this client instance is not allowed!";
}
internal void LogWritePermissionError()
{
Debug.LogError(GetWritePermissionError());
}
private protected NetworkManager m_NetworkManager private protected NetworkManager m_NetworkManager
{ {
@@ -52,7 +77,42 @@ namespace Unity.Netcode
m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager; m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager;
// When in distributed authority mode, there is no such thing as server write permissions // When in distributed authority mode, there is no such thing as server write permissions
InternalWritePerm = m_InternalNetworkManager.DistributedAuthorityMode ? NetworkVariableWritePermission.Owner : InternalWritePerm; InternalWritePerm = m_InternalNetworkManager.DistributedAuthorityMode ? NetworkVariableWritePermission.Owner : InternalWritePerm;
if (m_NetworkBehaviour.NetworkManager.NetworkTimeSystem != null)
{
UpdateLastSentTime();
}
} }
OnInitialize();
}
/// <summary>
/// Called on initialization
/// </summary>
public virtual void OnInitialize()
{
}
/// <summary>
/// Sets the update traits for this network variable to determine how frequently it will send updates.
/// </summary>
/// <param name="traits"></param>
public void SetUpdateTraits(NetworkVariableUpdateTraits traits)
{
UpdateTraits = traits;
}
/// <summary>
/// Check whether or not this variable has changed significantly enough to send an update.
/// If not, no update will be sent even if the variable is dirty, unless the time since last update exceeds
/// the <see cref="UpdateTraits"/>' <see cref="NetworkVariableUpdateTraits.MaxSecondsBetweenUpdates"/>.
/// </summary>
/// <returns></returns>
public virtual bool ExceedsDirtinessThreshold()
{
return true;
} }
/// <summary> /// <summary>
@@ -125,6 +185,28 @@ namespace Unity.Netcode
} }
} }
internal bool CanSend()
{
// When connected to a service or not the server, always use the synchronized server time as opposed to the local time
var time = m_InternalNetworkManager.CMBServiceConnection || !m_InternalNetworkManager.IsServer ? m_NetworkBehaviour.NetworkManager.ServerTime.Time : m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime;
var timeSinceLastUpdate = time - LastUpdateSent;
return
(
UpdateTraits.MaxSecondsBetweenUpdates > 0 &&
timeSinceLastUpdate >= UpdateTraits.MaxSecondsBetweenUpdates
) ||
(
timeSinceLastUpdate >= UpdateTraits.MinSecondsBetweenUpdates &&
ExceedsDirtinessThreshold()
);
}
internal void UpdateLastSentTime()
{
// When connected to a service or not the server, always use the synchronized server time as opposed to the local time
LastUpdateSent = m_InternalNetworkManager.CMBServiceConnection || !m_InternalNetworkManager.IsServer ? m_NetworkBehaviour.NetworkManager.ServerTime.Time : m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime;
}
internal static bool IgnoreInitializeWarning; internal static bool IgnoreInitializeWarning;
protected void MarkNetworkBehaviourDirty() protected void MarkNetworkBehaviourDirty()
@@ -147,6 +229,17 @@ namespace Unity.Netcode
} }
return; return;
} }
if (!m_NetworkBehaviour.NetworkManager.IsListening)
{
if (m_NetworkBehaviour.NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogWarning($"NetworkVariable is written to after the NetworkManager has already shutdown! " +
"Are you modifying a NetworkVariable within a NetworkBehaviour.OnDestroy or NetworkBehaviour.OnDespawn method?");
}
return;
}
m_NetworkBehaviour.NetworkManager.BehaviourUpdater?.AddForUpdate(m_NetworkBehaviour.NetworkObject); m_NetworkBehaviour.NetworkManager.BehaviourUpdater?.AddForUpdate(m_NetworkBehaviour.NetworkObject);
} }
@@ -174,6 +267,11 @@ namespace Unity.Netcode
/// <returns>Whether or not the client has permission to read</returns> /// <returns>Whether or not the client has permission to read</returns>
public bool CanClientRead(ulong clientId) public bool CanClientRead(ulong clientId)
{ {
if (!m_NetworkBehaviour)
{
return false;
}
// When in distributed authority mode, everyone can read (but only the owner can write) // When in distributed authority mode, everyone can read (but only the owner can write)
if (m_NetworkManager != null && m_NetworkManager.DistributedAuthorityMode) if (m_NetworkManager != null && m_NetworkManager.DistributedAuthorityMode)
{ {
@@ -196,6 +294,11 @@ namespace Unity.Netcode
/// <returns>Whether or not the client has permission to write</returns> /// <returns>Whether or not the client has permission to write</returns>
public bool CanClientWrite(ulong clientId) public bool CanClientWrite(ulong clientId)
{ {
if (!m_NetworkBehaviour)
{
return false;
}
switch (WritePerm) switch (WritePerm)
{ {
default: default:
@@ -231,7 +334,6 @@ namespace Unity.Netcode
/// </summary> /// </summary>
/// <param name="reader">The stream to read the state from</param> /// <param name="reader">The stream to read the state from</param>
public abstract void ReadField(FastBufferReader reader); public abstract void ReadField(FastBufferReader reader);
/// <summary> /// <summary>
/// Reads delta from the reader and applies them to the internal value /// Reads delta from the reader and applies them to the internal value
/// </summary> /// </summary>
@@ -247,47 +349,4 @@ namespace Unity.Netcode
m_InternalNetworkManager = null; m_InternalNetworkManager = null;
} }
} }
/// <summary>
/// Enum representing the different types of Network Variables.
/// </summary>
public enum NetworkVariableType : byte
{
/// <summary>
/// Value
/// Used for all of the basic NetworkVariables that contain a single value
/// </summary>
Value = 0,
/// <summary>
/// Custom
/// For any custom implemented extension of the NetworkVariableBase
/// </summary>
Custom = 1,
/// <summary>
/// NetworkList
/// </summary>
NetworkList = 2
}
public enum CollectionItemType : byte
{
/// <summary>
/// For any type that is not valid inside a NetworkVariable collection
/// </summary>
Unknown = 0,
/// <summary>
/// The following types are valid types inside of NetworkVariable collections
/// </summary>
Short = 1,
UShort = 2,
Int = 3,
UInt = 4,
Long = 5,
ULong = 6,
Unmanaged = 7,
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 2c6ef5fdf2e94ec3b4ce8086d52700b3
timeCreated: 1650985453

View File

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

View File

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

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d960ae6c5b8241aa9e2906b709095ea1
timeCreated: 1718215841

View File

@@ -0,0 +1,107 @@
using System;
using Unity.Collections;
namespace Unity.Netcode
{
/// <summary>
/// This class is instantiated for types that we can't determine ahead of time are serializable - types
/// that don't meet any of the constraints for methods that are available on FastBufferReader and
/// FastBufferWriter. These types may or may not be serializable through extension methods. To ensure
/// the user has time to pass in the delegates to UserNetworkVariableSerialization, the existence
/// of user serialization isn't checked until it's used, so if no serialization is provided, this
/// will throw an exception when an object containing the relevant NetworkVariable is spawned.
/// </summary>
/// <typeparam name="T"></typeparam>
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
{
public NetworkVariableType Type => NetworkVariableType.Unknown;
public bool IsDistributedAuthorityOptimized => true;
private void ThrowArgumentError()
{
throw new ArgumentException($"Serialization has not been generated for type {typeof(T).FullName}. This can be addressed by adding a [{nameof(GenerateSerializationForGenericParameterAttribute)}] to your generic class that serializes this value (if you are using one), adding [{nameof(GenerateSerializationForTypeAttribute)}(typeof({typeof(T).FullName})] to the class or method that is attempting to serialize it, or creating a field on a {nameof(NetworkBehaviour)} of type {nameof(NetworkVariable<T>)}. If this error continues to appear after doing one of those things and this is a type you can change, then either implement {nameof(INetworkSerializable)} or mark it as serializable by memcpy by adding {nameof(INetworkSerializeByMemcpy)} to its interface list to enable automatic serialization generation. If not, assign serialization code to {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.WriteValue)}, {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.ReadValue)}, and {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.DuplicateValue)}, or if it's serializable by memcpy (contains no pointers), wrap it in {typeof(ForceNetworkSerializeByMemcpy<>).Name}.");
}
public void Write(FastBufferWriter writer, ref T value)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
UserNetworkVariableSerialization<T>.WriteValue(writer, value);
}
public void Read(FastBufferReader reader, ref T value)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
UserNetworkVariableSerialization<T>.ReadValue(reader, out value);
}
public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
if (UserNetworkVariableSerialization<T>.WriteDelta == null || UserNetworkVariableSerialization<T>.ReadDelta == null)
{
UserNetworkVariableSerialization<T>.WriteValue(writer, value);
return;
}
UserNetworkVariableSerialization<T>.WriteDelta(writer, value, previousValue);
}
public void ReadDelta(FastBufferReader reader, ref T value)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
if (UserNetworkVariableSerialization<T>.WriteDelta == null || UserNetworkVariableSerialization<T>.ReadDelta == null)
{
UserNetworkVariableSerialization<T>.ReadValue(reader, out value);
return;
}
UserNetworkVariableSerialization<T>.ReadDelta(reader, ref value);
}
void INetworkVariableSerializer<T>.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator)
{
throw new NotImplementedException();
}
public void Duplicate(in T value, ref T duplicatedValue)
{
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
{
ThrowArgumentError();
}
UserNetworkVariableSerialization<T>.DuplicateValue(value, ref duplicatedValue);
}
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value) => ThrowArgumentError();
public void ReadDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError();
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => ThrowArgumentError();
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError();
}
// RuntimeAccessModifiersILPP will make this `public`
// This is just pass-through to NetworkVariableSerialization<T> but is here because I could not get ILPP
// to generate code that would successfully call Type<T>.Method(T), but it has no problem calling Type.Method<T>(T)
internal class RpcFallbackSerialization
{
public static void Write<T>(FastBufferWriter writer, ref T value)
{
NetworkVariableSerialization<T>.Write(writer, ref value);
}
public static void Read<T>(FastBufferReader reader, ref T value)
{
NetworkVariableSerialization<T>.Read(reader, ref value);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 288dbe7d1ff74860ae3552c034485538
timeCreated: 1718219109

View File

@@ -0,0 +1,42 @@
using Unity.Collections;
namespace Unity.Netcode
{
/// <summary>
/// Interface used by NetworkVariables to serialize them with additional information for the DA runtime
/// </summary>
///
/// <typeparam name="T"></typeparam>
internal interface IDistributedAuthoritySerializer<T>
{
/// <summary>
/// The Type tells the DA server how to parse this type.
/// The user should never be able to override this value, as it is meaningful for the DA server
/// </summary>
public NetworkVariableType Type { get; }
public bool IsDistributedAuthorityOptimized { get; }
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value);
public void ReadDistributedAuthority(FastBufferReader reader, ref T value);
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value);
}
/// <typeparam name="T"></typeparam>
internal interface INetworkVariableSerializer<T> : IDistributedAuthoritySerializer<T>
{
// Write has to be taken by ref here because of INetworkSerializable
// Open Instance Delegates (pointers to methods without an instance attached to them)
// require the first parameter passed to them (the instance) to be passed by ref.
// So foo.Bar() becomes BarDelegate(ref foo);
// Taking T as an in parameter like we do in other places would require making a copy
// of it to pass it as a ref parameter.,
public void Write(FastBufferWriter writer, ref T value);
public void Read(FastBufferReader reader, ref T value);
public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue);
public void ReadDelta(FastBufferReader reader, ref T value);
internal void ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator);
public void Duplicate(in T value, ref T duplicatedValue);
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f78e258ef55f4ee89bc3f24d67b8d242
timeCreated: 1718218205

View File

@@ -0,0 +1,357 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Netcode;
namespace Unity.Netcode
{
internal static class NetworkVariableEquality<T>
{
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool ValueEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : unmanaged
{
// get unmanaged pointers
var aptr = UnsafeUtility.AddressOf(ref a);
var bptr = UnsafeUtility.AddressOf(ref b);
// compare addresses
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType)) == 0;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool ValueEqualsList<TValueType>(ref NativeList<TValueType> a, ref NativeList<TValueType> b) where TValueType : unmanaged
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
if (a.Length != b.Length)
{
return false;
}
#if UTP_TRANSPORT_2_0_ABOVE
var aptr = a.GetUnsafePtr();
var bptr = b.GetUnsafePtr();
#else
var aptr = (TValueType*)a.GetUnsafePtr();
var bptr = (TValueType*)b.GetUnsafePtr();
#endif
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType) * a.Length) == 0;
}
#endif
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool ValueEqualsArray<TValueType>(ref NativeArray<TValueType> a, ref NativeArray<TValueType> b) where TValueType : unmanaged
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
if (a.Length != b.Length)
{
return false;
}
var aptr = (TValueType*)a.GetUnsafePtr();
var bptr = (TValueType*)b.GetUnsafePtr();
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType) * a.Length) == 0;
}
internal static bool EqualityEqualsObject<TValueType>(ref TValueType a, ref TValueType b) where TValueType : class, IEquatable<TValueType>
{
if (a == null)
{
return b == null;
}
if (b == null)
{
return false;
}
return a.Equals(b);
}
internal static bool EqualityEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : unmanaged, IEquatable<TValueType>
{
return a.Equals(b);
}
internal static bool EqualityEqualsList<TValueType>(ref List<TValueType> a, ref List<TValueType> b)
{
if (a == null != (b == null))
{
return false;
}
if (a == null)
{
return true;
}
if (a.Count != b.Count)
{
return false;
}
for (var i = 0; i < a.Count; ++i)
{
var aItem = a[i];
var bItem = b[i];
if (!NetworkVariableSerialization<TValueType>.AreEqual(ref aItem, ref bItem))
{
return false;
}
}
return true;
}
internal static bool EqualityEqualsHashSet<TValueType>(ref HashSet<TValueType> a, ref HashSet<TValueType> b) where TValueType : IEquatable<TValueType>
{
if (a == null != (b == null))
{
return false;
}
if (a == null)
{
return true;
}
if (a.Count != b.Count)
{
return false;
}
foreach (var item in a)
{
if (!b.Contains(item))
{
return false;
}
}
return true;
}
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool EqualityEqualsArray<TValueType>(ref NativeArray<TValueType> a, ref NativeArray<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
if (a.Length != b.Length)
{
return false;
}
var aptr = (TValueType*)a.GetUnsafePtr();
var bptr = (TValueType*)b.GetUnsafePtr();
for (var i = 0; i < a.Length; ++i)
{
if (!EqualityEquals(ref aptr[i], ref bptr[i]))
{
return false;
}
}
return true;
}
internal static bool ClassEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : class
{
return a == b;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
// Compares two values of the same unmanaged type by underlying memory
// Ignoring any overridden value checks
// Size is fixed
internal static unsafe bool EqualityEqualsNativeList<TValueType>(ref NativeList<TValueType> a, ref NativeList<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
if (a.Length != b.Length)
{
return false;
}
#if UTP_TRANSPORT_2_0_ABOVE
var aptr = a.GetUnsafePtr();
var bptr = b.GetUnsafePtr();
#else
var aptr = (TValueType*)a.GetUnsafePtr();
var bptr = (TValueType*)b.GetUnsafePtr();
#endif
for (var i = 0; i < a.Length; ++i)
{
if (!EqualityEquals(ref aptr[i], ref bptr[i]))
{
return false;
}
}
return true;
}
internal static bool EqualityEqualsNativeHashSet<TValueType>(ref NativeHashSet<TValueType> a, ref NativeHashSet<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
#if UTP_TRANSPORT_2_0_ABOVE
if (a.Count != b.Count)
#else
if (a.Count() != b.Count())
#endif
{
return false;
}
foreach (var item in a)
{
if (!b.Contains(item))
{
return false;
}
}
return true;
}
#endif
}
}
/// <summary>
/// Support methods for equality of NetworkVariable collection types.
/// Because there are multiple overloads of WriteValue/ReadValue based on different generic constraints,
/// but there's no way to achieve the same thing with a class, this sets up various read/write schemes
/// based on which constraints are met by `T` using reflection, which is done at module load time.
/// </summary>
/// <typeparam name="TKey">The type the associated NetworkVariable dictionary collection key templated on</typeparam>
/// <typeparam name="TVal">The type the associated NetworkVariable dictionary collection value templated on</typeparam>
internal class NetworkVariableDictionarySerialization<TKey, TVal>
where TKey : IEquatable<TKey>
{
internal static bool GenericEqualsDictionary(ref Dictionary<TKey, TVal> a, ref Dictionary<TKey, TVal> b)
{
if (a == null != (b == null))
{
return false;
}
if (a == null)
{
return true;
}
if (a.Count != b.Count)
{
return false;
}
foreach (var item in a)
{
var hasKey = b.TryGetValue(item.Key, out var val);
if (!hasKey)
{
return false;
}
var bVal = item.Value;
if (!NetworkVariableSerialization<TVal>.AreEqual(ref bVal, ref val))
{
return false;
}
}
return true;
}
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
internal class NetworkVariableMapSerialization<TKey, TVal>
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
internal static bool GenericEqualsNativeHashMap(ref NativeHashMap<TKey, TVal> a, ref NativeHashMap<TKey, TVal> b)
{
if (a.IsCreated != b.IsCreated)
{
return false;
}
if (!a.IsCreated)
{
return true;
}
#if UTP_TRANSPORT_2_0_ABOVE
if (a.Count != b.Count)
#else
if (a.Count() != b.Count())
#endif
{
return false;
}
foreach (var item in a)
{
var hasKey = b.TryGetValue(item.Key, out var val);
if (!hasKey || !NetworkVariableSerialization<TVal>.AreEqual(ref item.Value, ref val))
{
return false;
}
}
return true;
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 24b8352a975044509931bf684ccfdb82
timeCreated: 1718219366

View File

@@ -0,0 +1,195 @@
using System;
namespace Unity.Netcode
{
/// <summary>
/// Support methods for reading/writing NetworkVariables
/// Because there are multiple overloads of WriteValue/ReadValue based on different generic constraints,
/// but there's no way to achieve the same thing with a class, this sets up various read/write schemes
/// based on which constraints are met by `T` using reflection, which is done at module load time.
/// </summary>
/// <typeparam name="T">The type the associated NetworkVariable is templated on</typeparam>
[Serializable]
public static class NetworkVariableSerialization<T>
{
internal static INetworkVariableSerializer<T> Serializer = new FallbackSerializer<T>();
internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority;
/// <summary>
/// A callback to check if two values are equal.
/// </summary>
public delegate bool EqualsDelegate(ref T a, ref T b);
/// <summary>
/// Uses the most efficient mechanism for a given type to determine if two values are equal.
/// For types that implement <see cref="IEquatable{T}"/>, it will call the Equals() method.
/// For unmanaged types, it will do a bytewise memory comparison.
/// For other types, it will call the == operator.
/// <br/>
/// <br/>
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute"/> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to check their equality yourself.
/// </summary>
public static EqualsDelegate AreEqual { get; internal set; }
/// <summary>
/// Serialize a value using the best-known serialization method for a generic value.
/// Will reliably serialize any value that is passed to it correctly with no boxing.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to use FastBufferWriter directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.WriteValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user serialization callback to it at runtime.
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
public static void Write(FastBufferWriter writer, ref T value)
{
if (IsDistributedAuthority)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized)
{
NetworkManager.LogSerializedTypeNotOptimized<T>();
}
#endif
Serializer.WriteDistributedAuthority(writer, ref value);
}
else
{
Serializer.Write(writer, ref value);
}
}
/// <summary>
/// Deserialize a value using the best-known serialization method for a generic value.
/// Will reliably deserialize any value that is passed to it correctly with no boxing.
/// For types whose deserialization can be determined by codegen (which is most types),
/// GC will only be incurred if the type is a managed type and the ref value passed in is `null`,
/// in which case a new value is created; otherwise, it will be deserialized in-place.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to use FastBufferReader directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.ReadValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user deserialization callback to it at runtime.
/// </summary>
/// <param name="reader"></param>
/// <param name="value"></param>
public static void Read(FastBufferReader reader, ref T value)
{
if (IsDistributedAuthority)
{
Serializer.ReadDistributedAuthority(reader, ref value);
}
else
{
Serializer.Read(reader, ref value);
}
}
/// <summary>
/// Serialize a value using the best-known serialization method for a generic value.
/// Will reliably serialize any value that is passed to it correctly with no boxing.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to use FastBufferWriter directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.WriteValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user serialization callback to it at runtime.
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
{
if (IsDistributedAuthority)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized)
{
NetworkManager.LogSerializedTypeNotOptimized<T>();
}
#endif
Serializer.WriteDeltaDistributedAuthority(writer, ref value, ref previousValue);
}
else
{
Serializer.WriteDelta(writer, ref value, ref previousValue);
}
}
/// <summary>
/// Deserialize a value using the best-known serialization method for a generic value.
/// Will reliably deserialize any value that is passed to it correctly with no boxing.
/// For types whose deserialization can be determined by codegen (which is most types),
/// GC will only be incurred if the type is a managed type and the ref value passed in is `null`,
/// in which case a new value is created; otherwise, it will be deserialized in-place.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to use FastBufferReader directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.ReadValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user deserialization callback to it at runtime.
/// </summary>
/// <param name="reader"></param>
/// <param name="value"></param>
public static void ReadDelta(FastBufferReader reader, ref T value)
{
if (IsDistributedAuthority)
{
Serializer.ReadDeltaDistributedAuthority(reader, ref value);
}
else
{
Serializer.ReadDelta(reader, ref value);
}
}
/// <summary>
/// Duplicates a value using the most efficient means of creating a complete copy.
/// For most types this is a simple assignment or memcpy.
/// For managed types, this is will serialize and then deserialize the value to ensure
/// a correct copy.
/// <br />
/// <br />
/// Note: If you are using this in a custom generic class, please make sure your class is
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
/// initialize the serialization mechanisms correctly. If your class is NOT
/// generic, it is better to duplicate it directly.
/// <br />
/// <br />
/// If the codegen is unable to determine a serializer for a type,
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.DuplicateValue" /> is called, which, by default,
/// will throw an exception, unless you have assigned a user duplication callback to it at runtime.
/// </summary>
/// <param name="value"></param>
/// <param name="duplicatedValue"></param>
public static void Duplicate(in T value, ref T duplicatedValue)
{
Serializer.Duplicate(value, ref duplicatedValue);
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7a943170e35746e8913dd494d79bb63d
timeCreated: 1718215899

View File

@@ -0,0 +1,315 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
using UnityEditor;
using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// This class contains initialization functions for various different types used in NetworkVariables.
/// Generally speaking, these methods are called by a module initializer created by codegen (NetworkBehaviourILPP)
/// and do not need to be called manually.
///
/// There are two types of initializers: Serializers and EqualityCheckers. Every type must have an EqualityChecker
/// registered to it in order to be used in NetworkVariable; however, not all types need a Serializer. Types without
/// a serializer registered will fall back to using the delegates in <see cref="UserNetworkVariableSerialization{T}"/>.
/// If no such delegate has been registered, a type without a serializer will throw an exception on the first attempt
/// to serialize or deserialize it. (Again, however, codegen handles this automatically and this registration doesn't
/// typically need to be performed manually.)
/// </summary>
public static class NetworkVariableSerializationTypedInitializers
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
#if UNITY_EDITOR
[InitializeOnLoadMethod]
#endif
internal static void InitializeIntegerSerialization()
{
NetworkVariableSerialization<short>.Serializer = new ShortSerializer();
NetworkVariableSerialization<short>.AreEqual = NetworkVariableEquality<short>.ValueEquals;
NetworkVariableSerialization<ushort>.Serializer = new UshortSerializer();
NetworkVariableSerialization<ushort>.AreEqual = NetworkVariableEquality<ushort>.ValueEquals;
NetworkVariableSerialization<int>.Serializer = new IntSerializer();
NetworkVariableSerialization<int>.AreEqual = NetworkVariableEquality<int>.ValueEquals;
NetworkVariableSerialization<uint>.Serializer = new UintSerializer();
NetworkVariableSerialization<uint>.AreEqual = NetworkVariableEquality<uint>.ValueEquals;
NetworkVariableSerialization<long>.Serializer = new LongSerializer();
NetworkVariableSerialization<long>.AreEqual = NetworkVariableEquality<long>.ValueEquals;
NetworkVariableSerialization<ulong>.Serializer = new UlongSerializer();
NetworkVariableSerialization<ulong>.AreEqual = NetworkVariableEquality<ulong>.ValueEquals;
}
/// <summary>
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedByMemcpy<T>() where T : unmanaged
{
NetworkVariableSerialization<T>.Serializer = new UnmanagedTypeSerializer<T>();
}
/// <summary>
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedByMemcpyArray<T>() where T : unmanaged
{
NetworkVariableSerialization<NativeArray<T>>.Serializer = new UnmanagedArraySerializer<T>();
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedByMemcpyList<T>() where T : unmanaged
{
NetworkVariableSerialization<NativeList<T>>.Serializer = new UnmanagedListSerializer<T>();
}
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_NativeHashSet<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<NativeHashSet<T>>.Serializer = new NativeHashSetSerializer<T>();
}
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_NativeHashMap<TKey, TVal>()
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
NetworkVariableSerialization<NativeHashMap<TKey, TVal>>.Serializer = new NativeHashMapSerializer<TKey, TVal>();
}
#endif
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_List<T>()
{
NetworkVariableSerialization<List<T>>.Serializer = new ListSerializer<T>();
}
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_HashSet<T>() where T : IEquatable<T>
{
NetworkVariableSerialization<HashSet<T>>.Serializer = new HashSetSerializer<T>();
}
/// <summary>
/// Registeres a native hash set (this generic implementation works with all types)
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_Dictionary<TKey, TVal>() where TKey : IEquatable<TKey>
{
NetworkVariableSerialization<Dictionary<TKey, TVal>>.Serializer = new DictionarySerializer<TKey, TVal>();
}
/// <summary>
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
/// NetworkSerialize
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedINetworkSerializable<T>() where T : unmanaged, INetworkSerializable
{
NetworkVariableSerialization<T>.Serializer = new UnmanagedNetworkSerializableSerializer<T>();
}
/// <summary>
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
/// NetworkSerialize
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedINetworkSerializableArray<T>() where T : unmanaged, INetworkSerializable
{
NetworkVariableSerialization<NativeArray<T>>.Serializer = new UnmanagedNetworkSerializableArraySerializer<T>();
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
/// NetworkSerialize
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_UnmanagedINetworkSerializableList<T>() where T : unmanaged, INetworkSerializable
{
NetworkVariableSerialization<NativeList<T>>.Serializer = new UnmanagedNetworkSerializableListSerializer<T>();
}
#endif
/// <summary>
/// Registers a managed type that implements INetworkSerializable and will be serialized through a call to
/// NetworkSerialize
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_ManagedINetworkSerializable<T>() where T : class, INetworkSerializable, new()
{
NetworkVariableSerialization<T>.Serializer = new ManagedNetworkSerializableSerializer<T>();
}
/// <summary>
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
/// serializers
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_FixedString<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
NetworkVariableSerialization<T>.Serializer = new FixedStringSerializer<T>();
}
/// <summary>
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
/// serializers
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_FixedStringArray<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
NetworkVariableSerialization<NativeArray<T>>.Serializer = new FixedStringArraySerializer<T>();
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
/// serializers
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeSerializer_FixedStringList<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
NetworkVariableSerialization<NativeList<T>>.Serializer = new FixedStringListSerializer<T>();
}
#endif
/// <summary>
/// Registers a managed type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_ManagedIEquatable<T>() where T : class, IEquatable<T>
{
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsObject;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedIEquatable<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.EqualityEquals;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedIEquatableArray<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<NativeArray<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsArray;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_List<T>()
{
NetworkVariableSerialization<List<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsList;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_HashSet<T>() where T : IEquatable<T>
{
NetworkVariableSerialization<HashSet<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsHashSet;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_Dictionary<TKey, TVal>()
where TKey : IEquatable<TKey>
{
NetworkVariableSerialization<Dictionary<TKey, TVal>>.AreEqual = NetworkVariableDictionarySerialization<TKey, TVal>.GenericEqualsDictionary;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedIEquatableList<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<NativeList<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsNativeList;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_NativeHashSet<T>() where T : unmanaged, IEquatable<T>
{
NetworkVariableSerialization<NativeHashSet<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsNativeHashSet;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using T.Equals()
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_NativeHashMap<TKey, TVal>()
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
NetworkVariableSerialization<NativeHashMap<TKey, TVal>>.AreEqual = NetworkVariableMapSerialization<TKey, TVal>.GenericEqualsNativeHashMap;
}
#endif
/// <summary>
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
/// equal if they are bitwise equivalent in memory
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedValueEquals<T>() where T : unmanaged
{
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.ValueEquals;
}
/// <summary>
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
/// equal if they are bitwise equivalent in memory
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedValueEqualsArray<T>() where T : unmanaged
{
NetworkVariableSerialization<NativeArray<T>>.AreEqual = NetworkVariableEquality<T>.ValueEqualsArray;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
/// equal if they are bitwise equivalent in memory
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_UnmanagedValueEqualsList<T>() where T : unmanaged
{
NetworkVariableSerialization<NativeList<T>>.AreEqual = NetworkVariableEquality<T>.ValueEqualsList;
}
#endif
/// <summary>
/// Registers a managed type that will be checked for equality using the == operator
/// </summary>
/// <typeparam name="T"></typeparam>
public static void InitializeEqualityChecker_ManagedClassEquals<T>() where T : class
{
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.ClassEquals;
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 65bdb3e11a9a412ab5e936a9c96a3da0
timeCreated: 1718216842

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: bbfa170e9dd448bbbe381ce38d5c139d
timeCreated: 1718216671

View File

@@ -0,0 +1,73 @@
namespace Unity.Netcode
{
/// <summary>
/// This class is used to register user serialization with NetworkVariables for types
/// that are serialized via user serialization, such as with FastBufferReader and FastBufferWriter
/// extension methods. Finding those methods isn't achievable efficiently at runtime, so this allows
/// users to tell NetworkVariable about those extension methods (or simply pass in a lambda)
/// </summary>
/// <typeparam name="T"></typeparam>
public class UserNetworkVariableSerialization<T>
{
/// <summary>
/// The write value delegate handler definition
/// </summary>
/// <param name="writer">The <see cref="FastBufferWriter"/> to write the value of type `T`</param>
/// <param name="value">The value of type `T` to be written</param>
public delegate void WriteValueDelegate(FastBufferWriter writer, in T value);
/// <summary>
/// The write value delegate handler definition
/// </summary>
/// <param name="writer">The <see cref="FastBufferWriter"/> to write the value of type `T`</param>
/// <param name="value">The value of type `T` to be written</param>
public delegate void WriteDeltaDelegate(FastBufferWriter writer, in T value, in T previousValue);
/// <summary>
/// The read value delegate handler definition
/// </summary>
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
/// <param name="value">The value of type `T` to be read</param>
public delegate void ReadValueDelegate(FastBufferReader reader, out T value);
/// <summary>
/// The read value delegate handler definition
/// </summary>
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
/// <param name="value">The value of type `T` to be read</param>
public delegate void ReadDeltaDelegate(FastBufferReader reader, ref T value);
/// <summary>
/// The read value delegate handler definition
/// </summary>
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
/// <param name="value">The value of type `T` to be read</param>
public delegate void DuplicateValueDelegate(in T value, ref T duplicatedValue);
/// <summary>
/// Callback to write a value
/// </summary>
public static WriteValueDelegate WriteValue;
/// <summary>
/// Callback to read a value
/// </summary>
public static ReadValueDelegate ReadValue;
/// <summary>
/// Callback to write a delta between two values, based on computing the difference between the previous and
/// current values.
/// </summary>
public static WriteDeltaDelegate WriteDelta;
/// <summary>
/// Callback to read a delta, applying only select changes to the current value.
/// </summary>
public static ReadDeltaDelegate ReadDelta;
/// <summary>
/// Callback to create a duplicate of a value, used to check for dirty status.
/// </summary>
public static DuplicateValueDelegate DuplicateValue;
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b295a6756640488b9824d2ec6e26ddae
timeCreated: 1718218272

View File

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

View File

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

View File

@@ -227,6 +227,11 @@ namespace Unity.Netcode
foreach (var sceneToUnload in m_ScenesToUnload) foreach (var sceneToUnload in m_ScenesToUnload)
{ {
SceneManager.UnloadSceneAsync(sceneToUnload); SceneManager.UnloadSceneAsync(sceneToUnload);
// Update the ScenesLoaded when we unload scenes
if (sceneManager.ScenesLoaded.ContainsKey(sceneToUnload.handle))
{
sceneManager.ScenesLoaded.Remove(sceneToUnload.handle);
}
} }
} }
@@ -328,8 +333,9 @@ namespace Unity.Netcode
public void SetClientSynchronizationMode(ref NetworkManager networkManager, LoadSceneMode mode) public void SetClientSynchronizationMode(ref NetworkManager networkManager, LoadSceneMode mode)
{ {
var sceneManager = networkManager.SceneManager; var sceneManager = networkManager.SceneManager;
// Don't let non-authority set this value // In client-server, we don't let client's set this value.
if ((!networkManager.DistributedAuthorityMode && !networkManager.IsServer) || (networkManager.DistributedAuthorityMode && !networkManager.LocalClient.IsSessionOwner)) // In distributed authority, since session owner can be promoted clients can set this value
if (!networkManager.DistributedAuthorityMode && !networkManager.IsServer)
{ {
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{ {
@@ -338,7 +344,7 @@ namespace Unity.Netcode
return; return;
} }
else // Warn users if they are changing this after there are clients already connected and synchronized else // Warn users if they are changing this after there are clients already connected and synchronized
if (networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode) if (!networkManager.DistributedAuthorityMode && networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode)
{ {
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{ {

View File

@@ -774,6 +774,7 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// This setting changes how clients handle scene loading when initially synchronizing with the server.<br /> /// This setting changes how clients handle scene loading when initially synchronizing with the server.<br />
/// The server or host should set this value as clients will automatically be synchronized with the server (or host) side. /// The server or host should set this value as clients will automatically be synchronized with the server (or host) side.
/// </summary>
/// <remarks> /// <remarks>
/// <b>LoadSceneMode.Single:</b> All currently loaded scenes on the client will be unloaded and the /// <b>LoadSceneMode.Single:</b> All currently loaded scenes on the client will be unloaded and the
/// server's currently active scene will be loaded in single mode on the client unless it was already /// server's currently active scene will be loaded in single mode on the client unless it was already
@@ -2406,16 +2407,6 @@ namespace Unity.Netcode
NetworkManager.ConnectionManager.CreateAndSpawnPlayer(NetworkManager.LocalClientId); NetworkManager.ConnectionManager.CreateAndSpawnPlayer(NetworkManager.LocalClientId);
} }
// Client is now synchronized and fully "connected". This also means the client can send "RPCs" at this time
NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(NetworkManager.LocalClientId);
// Notify the client that they have finished synchronizing
OnSceneEvent?.Invoke(new SceneEvent()
{
SceneEventType = sceneEventData.SceneEventType,
ClientId = NetworkManager.LocalClientId, // Client sent this to the server
});
// Process any SceneEventType.ObjectSceneChanged messages that // Process any SceneEventType.ObjectSceneChanged messages that
// were deferred while synchronizing and migrate the associated // were deferred while synchronizing and migrate the associated
// NetworkObjects to their newly assigned scenes. // NetworkObjects to their newly assigned scenes.
@@ -2429,6 +2420,16 @@ namespace Unity.Netcode
SceneManagerHandler.UnloadUnassignedScenes(NetworkManager); SceneManagerHandler.UnloadUnassignedScenes(NetworkManager);
} }
// Client is now synchronized and fully "connected". This also means the client can send "RPCs" at this time
NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(NetworkManager.LocalClientId);
// Notify the client that they have finished synchronizing
OnSceneEvent?.Invoke(new SceneEvent()
{
SceneEventType = sceneEventData.SceneEventType,
ClientId = NetworkManager.LocalClientId, // Client sent this to the server
});
OnSynchronizeComplete?.Invoke(NetworkManager.LocalClientId); OnSynchronizeComplete?.Invoke(NetworkManager.LocalClientId);
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
@@ -2436,10 +2437,7 @@ namespace Unity.Netcode
NetworkLog.LogInfo($"[Client-{NetworkManager.LocalClientId}][Scene Management Enabled] Synchronization complete!"); NetworkLog.LogInfo($"[Client-{NetworkManager.LocalClientId}][Scene Management Enabled] Synchronization complete!");
} }
// For convenience, notify all NetworkBehaviours that synchronization is complete. // For convenience, notify all NetworkBehaviours that synchronization is complete.
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList) NetworkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
{
networkObject.InternalNetworkSessionSynchronized();
}
if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority() && IsRestoringSession) if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority() && IsRestoringSession)
{ {
@@ -2552,17 +2550,6 @@ namespace Unity.Netcode
// At this point the client is considered fully "connected" // At this point the client is considered fully "connected"
if ((NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClient.IsSessionOwner) || !NetworkManager.DistributedAuthorityMode) if ((NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClient.IsSessionOwner) || !NetworkManager.DistributedAuthorityMode)
{ {
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost)
{
// DANGO-EXP TODO: Remove this once service is sending the synchronization message to all clients
if (NetworkManager.ConnectedClients.ContainsKey(clientId) && NetworkManager.ConnectionManager.ConnectedClientIds.Contains(clientId) && NetworkManager.ConnectedClientsList.Contains(NetworkManager.ConnectedClients[clientId]))
{
EndSceneEvent(sceneEventId);
return;
}
NetworkManager.ConnectionManager.AddClient(clientId);
}
// Notify the local server that a client has finished synchronizing // Notify the local server that a client has finished synchronizing
OnSceneEvent?.Invoke(new SceneEvent() OnSceneEvent?.Invoke(new SceneEvent()
{ {
@@ -2577,6 +2564,20 @@ namespace Unity.Netcode
} }
else else
{ {
// Notify the local server that a client has finished synchronizing
OnSceneEvent?.Invoke(new SceneEvent()
{
SceneEventType = sceneEventData.SceneEventType,
SceneName = string.Empty,
ClientId = clientId
});
// Show any NetworkObjects that are:
// - Hidden from the session owner
// - Owned by this client
// - Has NetworkObject.SpawnWithObservers set to true (the default)
NetworkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(clientId);
// DANGO-EXP TODO: Remove this once service distributes objects // DANGO-EXP TODO: Remove this once service distributes objects
// Non-session owners receive this notification from newly connected clients and upon receiving // Non-session owners receive this notification from newly connected clients and upon receiving
// the event they will redistribute their NetworkObjects // the event they will redistribute their NetworkObjects
@@ -2591,9 +2592,6 @@ namespace Unity.Netcode
// At this time the client is fully synchronized with all loaded scenes and // At this time the client is fully synchronized with all loaded scenes and
// NetworkObjects and should be considered "fully connected". Send the // NetworkObjects and should be considered "fully connected". Send the
// notification that the client is connected. // notification that the client is connected.
// TODO 2023: We should have a better name for this or have multiple states the
// client progresses through (the name and associated legacy behavior/expected state
// of the client was persisted since MLAPI)
NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(clientId); NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(clientId);
if (NetworkManager.IsHost) if (NetworkManager.IsHost)
@@ -2666,9 +2664,14 @@ namespace Unity.Netcode
EventData = sceneEventData, EventData = sceneEventData,
}; };
// Forward synchronization to client then exit early because DAHost is not the current session owner // Forward synchronization to client then exit early because DAHost is not the current session owner
NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, NetworkManager.CurrentSessionOwner); foreach (var client in NetworkManager.ConnectedClientsIds)
EndSceneEvent(sceneEventData.SceneEventId); {
return; if (client == NetworkManager.LocalClientId)
{
continue;
}
NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, client);
}
} }
} }
else else

View File

@@ -523,8 +523,8 @@ namespace Unity.Netcode
/// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param> /// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param>
public unsafe void ReadValue(out string s, bool oneByteChars = false) public unsafe void ReadValue(out string s, bool oneByteChars = false)
{ {
ReadValue(out uint length); ReadLength(out int length);
s = "".PadRight((int)length); s = "".PadRight(length);
int target = s.Length; int target = s.Length;
fixed (char* native = s) fixed (char* native = s)
{ {
@@ -562,18 +562,18 @@ namespace Unity.Netcode
} }
#endif #endif
if (!TryBeginReadInternal(sizeof(uint))) if (!TryBeginReadInternal(SizeOfLengthField()))
{ {
throw new OverflowException("Reading past the end of the buffer"); throw new OverflowException("Reading past the end of the buffer");
} }
ReadValue(out uint length); ReadLength(out int length);
if (!TryBeginReadInternal((int)length * (oneByteChars ? 1 : sizeof(char)))) if (!TryBeginReadInternal(length * (oneByteChars ? 1 : sizeof(char))))
{ {
throw new OverflowException("Reading past the end of the buffer"); throw new OverflowException("Reading past the end of the buffer");
} }
s = "".PadRight((int)length); s = "".PadRight(length);
int target = s.Length; int target = s.Length;
fixed (char* native = s) fixed (char* native = s)
{ {
@@ -592,6 +592,33 @@ namespace Unity.Netcode
} }
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int SizeOfLengthField() => sizeof(uint);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ReadLengthSafe(out uint length) => ReadUnmanagedSafe(out length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ReadLength(out uint length) => ReadUnmanaged(out length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ReadLengthSafe(out int length)
{
ReadLengthSafe(out uint temp);
if (temp > int.MaxValue)
{
throw new InvalidCastException("length value outside of int32 range");
}
length = (int)temp;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ReadLength(out int length)
{
ReadLength(out uint temp);
length = (int)temp;
}
/// <summary> /// <summary>
/// Read a partial value. The value is zero-initialized and then the specified number of bytes is read into it. /// Read a partial value. The value is zero-initialized and then the specified number of bytes is read into it.
/// </summary> /// </summary>
@@ -777,7 +804,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void ReadUnmanaged<T>(out T[] value) where T : unmanaged internal unsafe void ReadUnmanaged<T>(out T[] value) where T : unmanaged
{ {
ReadUnmanaged(out int sizeInTs); ReadLength(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T); int sizeInBytes = sizeInTs * sizeof(T);
value = new T[sizeInTs]; value = new T[sizeInTs];
fixed (T* ptr = value) fixed (T* ptr = value)
@@ -789,7 +816,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void ReadUnmanagedSafe<T>(out T[] value) where T : unmanaged internal unsafe void ReadUnmanagedSafe<T>(out T[] value) where T : unmanaged
{ {
ReadUnmanagedSafe(out int sizeInTs); ReadLengthSafe(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T); int sizeInBytes = sizeInTs * sizeof(T);
value = new T[sizeInTs]; value = new T[sizeInTs];
fixed (T* ptr = value) fixed (T* ptr = value)
@@ -801,7 +828,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void ReadUnmanaged<T>(out NativeArray<T> value, Allocator allocator) where T : unmanaged internal unsafe void ReadUnmanaged<T>(out NativeArray<T> value, Allocator allocator) where T : unmanaged
{ {
ReadUnmanaged(out int sizeInTs); ReadLength(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T); int sizeInBytes = sizeInTs * sizeof(T);
value = new NativeArray<T>(sizeInTs, allocator); value = new NativeArray<T>(sizeInTs, allocator);
byte* bytes = (byte*)value.GetUnsafePtr(); byte* bytes = (byte*)value.GetUnsafePtr();
@@ -810,7 +837,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void ReadUnmanagedSafe<T>(out NativeArray<T> value, Allocator allocator) where T : unmanaged internal unsafe void ReadUnmanagedSafe<T>(out NativeArray<T> value, Allocator allocator) where T : unmanaged
{ {
ReadUnmanagedSafe(out int sizeInTs); ReadLengthSafe(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T); int sizeInBytes = sizeInTs * sizeof(T);
value = new NativeArray<T>(sizeInTs, allocator); value = new NativeArray<T>(sizeInTs, allocator);
byte* bytes = (byte*)value.GetUnsafePtr(); byte* bytes = (byte*)value.GetUnsafePtr();
@@ -820,7 +847,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void ReadUnmanagedInPlace<T>(ref NativeList<T> value) where T : unmanaged internal unsafe void ReadUnmanagedInPlace<T>(ref NativeList<T> value) where T : unmanaged
{ {
ReadUnmanaged(out int sizeInTs); ReadLength(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T); int sizeInBytes = sizeInTs * sizeof(T);
value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory); value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory);
byte* bytes = (byte*)value.GetUnsafePtr(); byte* bytes = (byte*)value.GetUnsafePtr();
@@ -829,7 +856,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void ReadUnmanagedSafeInPlace<T>(ref NativeList<T> value) where T : unmanaged internal unsafe void ReadUnmanagedSafeInPlace<T>(ref NativeList<T> value) where T : unmanaged
{ {
ReadUnmanagedSafe(out int sizeInTs); ReadLengthSafe(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T); int sizeInBytes = sizeInTs * sizeof(T);
value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory); value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory);
byte* bytes = (byte*)value.GetUnsafePtr(); byte* bytes = (byte*)value.GetUnsafePtr();
@@ -1078,7 +1105,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ReadValueSafeInPlace<T>(ref NativeHashSet<T> value) where T : unmanaged, IEquatable<T> internal void ReadValueSafeInPlace<T>(ref NativeHashSet<T> value) where T : unmanaged, IEquatable<T>
{ {
ReadUnmanagedSafe(out int length); ReadLengthSafe(out int length);
value.Clear(); value.Clear();
for (var i = 0; i < length; ++i) for (var i = 0; i < length; ++i)
{ {
@@ -1093,7 +1120,7 @@ namespace Unity.Netcode
where TKey : unmanaged, IEquatable<TKey> where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged where TVal : unmanaged
{ {
ReadUnmanagedSafe(out int length); ReadLengthSafe(out int length);
value.Clear(); value.Clear();
for (var i = 0; i < length; ++i) for (var i = 0; i < length; ++i)
{ {
@@ -1553,7 +1580,7 @@ namespace Unity.Netcode
/// This method is a little difficult to use, since you have to know the size of the string before /// This method is a little difficult to use, since you have to know the size of the string before
/// reading it, but is useful when the string is a known, fixed size. Note that the size of the /// reading it, but is useful when the string is a known, fixed size. Note that the size of the
/// string is also encoded, so the size to call TryBeginRead on is actually the fixed size (in bytes) /// string is also encoded, so the size to call TryBeginRead on is actually the fixed size (in bytes)
/// plus sizeof(int) /// plus sizeof(uint)
/// </summary> /// </summary>
/// <param name="value">the value to read</param> /// <param name="value">the value to read</param>
/// <param name="unused">An unused parameter used for enabling overload resolution based on generic constraints</param> /// <param name="unused">An unused parameter used for enabling overload resolution based on generic constraints</param>
@@ -1562,7 +1589,7 @@ namespace Unity.Netcode
public unsafe void ReadValue<T>(out T value, FastBufferWriter.ForFixedStrings unused = default) public unsafe void ReadValue<T>(out T value, FastBufferWriter.ForFixedStrings unused = default)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
ReadUnmanaged(out int length); ReadLength(out int length);
value = new T value = new T
{ {
Length = length Length = length
@@ -1584,7 +1611,7 @@ namespace Unity.Netcode
public unsafe void ReadValueSafe<T>(out T value, FastBufferWriter.ForFixedStrings unused = default) public unsafe void ReadValueSafe<T>(out T value, FastBufferWriter.ForFixedStrings unused = default)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
ReadUnmanagedSafe(out int length); ReadLengthSafe(out int length);
value = new T value = new T
{ {
Length = length Length = length
@@ -1606,7 +1633,7 @@ namespace Unity.Netcode
public unsafe void ReadValueSafeInPlace<T>(ref T value, FastBufferWriter.ForFixedStrings unused = default) public unsafe void ReadValueSafeInPlace<T>(ref T value, FastBufferWriter.ForFixedStrings unused = default)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
ReadUnmanagedSafe(out int length); ReadLengthSafe(out int length);
value.Length = length; value.Length = length;
ReadBytesSafe(value.GetUnsafePtr(), length); ReadBytesSafe(value.GetUnsafePtr(), length);
} }
@@ -1625,7 +1652,7 @@ namespace Unity.Netcode
public unsafe void ReadValueSafe<T>(out NativeArray<T> value, Allocator allocator) public unsafe void ReadValueSafe<T>(out NativeArray<T> value, Allocator allocator)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
ReadUnmanagedSafe(out int length); ReadLengthSafe(out int length);
value = new NativeArray<T>(length, allocator); value = new NativeArray<T>(length, allocator);
var ptr = (T*)value.GetUnsafePtr(); var ptr = (T*)value.GetUnsafePtr();
for (var i = 0; i < length; ++i) for (var i = 0; i < length; ++i)
@@ -1647,7 +1674,7 @@ namespace Unity.Netcode
public unsafe void ReadValueSafeTemp<T>(out NativeArray<T> value) public unsafe void ReadValueSafeTemp<T>(out NativeArray<T> value)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
ReadUnmanagedSafe(out int length); ReadLengthSafe(out int length);
value = new NativeArray<T>(length, Allocator.Temp); value = new NativeArray<T>(length, Allocator.Temp);
var ptr = (T*)value.GetUnsafePtr(); var ptr = (T*)value.GetUnsafePtr();
for (var i = 0; i < length; ++i) for (var i = 0; i < length; ++i)
@@ -1669,7 +1696,7 @@ namespace Unity.Netcode
public void ReadValueSafe<T>(out T[] value, FastBufferWriter.ForFixedStrings unused = default) public void ReadValueSafe<T>(out T[] value, FastBufferWriter.ForFixedStrings unused = default)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
ReadUnmanagedSafe(out int length); ReadLengthSafe(out int length);
value = new T[length]; value = new T[length];
for (var i = 0; i < length; ++i) for (var i = 0; i < length; ++i)
{ {
@@ -1691,7 +1718,7 @@ namespace Unity.Netcode
public void ReadValueSafeInPlace<T>(ref NativeList<T> value) public void ReadValueSafeInPlace<T>(ref NativeList<T> value)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
ReadUnmanagedSafe(out int length); ReadLengthSafe(out int length);
value.Resize(length, NativeArrayOptions.UninitializedMemory); value.Resize(length, NativeArrayOptions.UninitializedMemory);
for (var i = 0; i < length; ++i) for (var i = 0; i < length; ++i)
{ {

View File

@@ -421,7 +421,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetWriteSize(string s, bool oneByteChars = false) public static int GetWriteSize(string s, bool oneByteChars = false)
{ {
return sizeof(int) + s.Length * (oneByteChars ? sizeof(byte) : sizeof(char)); return SizeOfLengthField() + s.Length * (oneByteChars ? sizeof(byte) : sizeof(char));
} }
/// <summary> /// <summary>
@@ -445,7 +445,7 @@ namespace Unity.Netcode
public void WriteNetworkSerializable<T>(T[] array, int count = -1, int offset = 0) where T : INetworkSerializable public void WriteNetworkSerializable<T>(T[] array, int count = -1, int offset = 0) where T : INetworkSerializable
{ {
int sizeInTs = count != -1 ? count : array.Length - offset; int sizeInTs = count != -1 ? count : array.Length - offset;
WriteValueSafe(sizeInTs); WriteLengthSafe(sizeInTs);
foreach (var item in array) foreach (var item in array)
{ {
WriteNetworkSerializable(item); WriteNetworkSerializable(item);
@@ -462,7 +462,7 @@ namespace Unity.Netcode
public void WriteNetworkSerializable<T>(NativeArray<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable public void WriteNetworkSerializable<T>(NativeArray<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable
{ {
int sizeInTs = count != -1 ? count : array.Length - offset; int sizeInTs = count != -1 ? count : array.Length - offset;
WriteValueSafe(sizeInTs); WriteLengthSafe(sizeInTs);
foreach (var item in array) foreach (var item in array)
{ {
WriteNetworkSerializable(item); WriteNetworkSerializable(item);
@@ -480,7 +480,7 @@ namespace Unity.Netcode
public void WriteNetworkSerializable<T>(NativeList<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable public void WriteNetworkSerializable<T>(NativeList<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable
{ {
int sizeInTs = count != -1 ? count : array.Length - offset; int sizeInTs = count != -1 ? count : array.Length - offset;
WriteValueSafe(sizeInTs); WriteLengthSafe(sizeInTs);
foreach (var item in array) foreach (var item in array)
{ {
WriteNetworkSerializable(item); WriteNetworkSerializable(item);
@@ -495,7 +495,7 @@ namespace Unity.Netcode
/// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param> /// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param>
public unsafe void WriteValue(string s, bool oneByteChars = false) public unsafe void WriteValue(string s, bool oneByteChars = false)
{ {
WriteValue((uint)s.Length); WriteLength((uint)s.Length);
int target = s.Length; int target = s.Length;
if (oneByteChars) if (oneByteChars)
{ {
@@ -538,7 +538,7 @@ namespace Unity.Netcode
throw new OverflowException("Writing past the end of the buffer"); throw new OverflowException("Writing past the end of the buffer");
} }
WriteValue((uint)s.Length); WriteLength((uint)s.Length);
int target = s.Length; int target = s.Length;
if (oneByteChars) if (oneByteChars)
{ {
@@ -569,7 +569,7 @@ namespace Unity.Netcode
{ {
int sizeInTs = count != -1 ? count : array.Length - offset; int sizeInTs = count != -1 ? count : array.Length - offset;
int sizeInBytes = sizeInTs * sizeof(T); int sizeInBytes = sizeInTs * sizeof(T);
return sizeof(int) + sizeInBytes; return SizeOfLengthField() + sizeInBytes;
} }
/// <summary> /// <summary>
@@ -585,7 +585,7 @@ namespace Unity.Netcode
{ {
int sizeInTs = count != -1 ? count : array.Length - offset; int sizeInTs = count != -1 ? count : array.Length - offset;
int sizeInBytes = sizeInTs * sizeof(T); int sizeInBytes = sizeInTs * sizeof(T);
return sizeof(int) + sizeInBytes; return SizeOfLengthField() + sizeInBytes;
} }
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
@@ -602,7 +602,7 @@ namespace Unity.Netcode
{ {
int sizeInTs = count != -1 ? count : array.Length - offset; int sizeInTs = count != -1 ? count : array.Length - offset;
int sizeInBytes = sizeInTs * sizeof(T); int sizeInBytes = sizeInTs * sizeof(T);
return sizeof(int) + sizeInBytes; return SizeOfLengthField() + sizeInBytes;
} }
#endif #endif
@@ -700,7 +700,7 @@ namespace Unity.Netcode
} }
if (Handle->Position + size > Handle->AllowedWriteMark) if (Handle->Position + size > Handle->AllowedWriteMark)
{ {
throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}()"); throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}(), Position+Size={Handle->Position + size} > AllowedWriteMark={Handle->AllowedWriteMark}");
} }
#endif #endif
UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size); UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size);
@@ -729,7 +729,7 @@ namespace Unity.Netcode
if (!TryBeginWriteInternal(size)) if (!TryBeginWriteInternal(size))
{ {
throw new OverflowException("Writing past the end of the buffer"); throw new OverflowException($"Writing past the end of the buffer, size is {size} bytes but remaining capacity is {Handle->Capacity - Handle->Position} bytes");
} }
UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size); UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size);
Handle->Position += size; Handle->Position += size;
@@ -876,7 +876,7 @@ namespace Unity.Netcode
public static int GetWriteSize<T>(in T value) public static int GetWriteSize<T>(in T value)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
return value.Length + sizeof(int); return SizeOfLengthField() + value.Length;
} }
/// <summary> /// <summary>
@@ -888,10 +888,10 @@ namespace Unity.Netcode
public static int GetWriteSize<T>(in NativeArray<T> value) public static int GetWriteSize<T>(in NativeArray<T> value)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
var size = sizeof(int); var size = SizeOfLengthField();
foreach (var item in value) foreach (var item in value)
{ {
size += sizeof(int) + item.Length; size += SizeOfLengthField() + item.Length;
} }
return size; return size;
@@ -907,10 +907,10 @@ namespace Unity.Netcode
public static int GetWriteSize<T>(in NativeList<T> value) public static int GetWriteSize<T>(in NativeList<T> value)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
var size = sizeof(int); var size = SizeOfLengthField();
foreach (var item in value) foreach (var item in value)
{ {
size += sizeof(int) + item.Length; size += SizeOfLengthField() + item.Length;
} }
return size; return size;
@@ -946,10 +946,32 @@ namespace Unity.Netcode
} }
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int SizeOfLengthField() => sizeof(uint);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteLengthSafe(uint length) => WriteUnmanagedSafe(length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteLength(uint length) => WriteUnmanaged(length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteLengthSafe(int length)
{
if (length < 0)
{
throw new InvalidCastException("Cannot write negative length");
}
WriteLengthSafe((uint)length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteLength(int length) => WriteLength((uint)length);
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanaged<T>(T[] value) where T : unmanaged internal unsafe void WriteUnmanaged<T>(T[] value) where T : unmanaged
{ {
WriteUnmanaged(value.Length); WriteLength(value.Length);
fixed (T* ptr = value) fixed (T* ptr = value)
{ {
byte* bytes = (byte*)ptr; byte* bytes = (byte*)ptr;
@@ -959,7 +981,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanagedSafe<T>(T[] value) where T : unmanaged internal unsafe void WriteUnmanagedSafe<T>(T[] value) where T : unmanaged
{ {
WriteUnmanagedSafe(value.Length); WriteLengthSafe(value.Length);
fixed (T* ptr = value) fixed (T* ptr = value)
{ {
byte* bytes = (byte*)ptr; byte* bytes = (byte*)ptr;
@@ -970,7 +992,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanaged<T>(NativeArray<T> value) where T : unmanaged internal unsafe void WriteUnmanaged<T>(NativeArray<T> value) where T : unmanaged
{ {
WriteUnmanaged(value.Length); WriteLength(value.Length);
var ptr = (T*)value.GetUnsafePtr(); var ptr = (T*)value.GetUnsafePtr();
{ {
byte* bytes = (byte*)ptr; byte* bytes = (byte*)ptr;
@@ -980,7 +1002,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanagedSafe<T>(NativeArray<T> value) where T : unmanaged internal unsafe void WriteUnmanagedSafe<T>(NativeArray<T> value) where T : unmanaged
{ {
WriteUnmanagedSafe(value.Length); WriteLengthSafe(value.Length);
var ptr = (T*)value.GetUnsafePtr(); var ptr = (T*)value.GetUnsafePtr();
{ {
byte* bytes = (byte*)ptr; byte* bytes = (byte*)ptr;
@@ -992,7 +1014,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanaged<T>(NativeList<T> value) where T : unmanaged internal unsafe void WriteUnmanaged<T>(NativeList<T> value) where T : unmanaged
{ {
WriteUnmanaged(value.Length); WriteLength(value.Length);
#if UTP_TRANSPORT_2_0_ABOVE #if UTP_TRANSPORT_2_0_ABOVE
var ptr = value.GetUnsafePtr(); var ptr = value.GetUnsafePtr();
#else #else
@@ -1006,7 +1028,7 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanagedSafe<T>(NativeList<T> value) where T : unmanaged internal unsafe void WriteUnmanagedSafe<T>(NativeList<T> value) where T : unmanaged
{ {
WriteUnmanagedSafe(value.Length); WriteLengthSafe(value.Length);
#if UTP_TRANSPORT_2_0_ABOVE #if UTP_TRANSPORT_2_0_ABOVE
var ptr = value.GetUnsafePtr(); var ptr = value.GetUnsafePtr();
#else #else
@@ -1210,9 +1232,9 @@ namespace Unity.Netcode
internal void WriteValueSafe<T>(NativeHashSet<T> value) where T : unmanaged, IEquatable<T> internal void WriteValueSafe<T>(NativeHashSet<T> value) where T : unmanaged, IEquatable<T>
{ {
#if UTP_TRANSPORT_2_0_ABOVE #if UTP_TRANSPORT_2_0_ABOVE
WriteUnmanagedSafe(value.Count); WriteLengthSafe(value.Count);
#else #else
WriteUnmanagedSafe(value.Count()); WriteLengthSafe(value.Count());
#endif #endif
foreach (var item in value) foreach (var item in value)
{ {
@@ -1227,9 +1249,9 @@ namespace Unity.Netcode
where TVal : unmanaged where TVal : unmanaged
{ {
#if UTP_TRANSPORT_2_0_ABOVE #if UTP_TRANSPORT_2_0_ABOVE
WriteUnmanagedSafe(value.Count); WriteLengthSafe(value.Count);
#else #else
WriteUnmanagedSafe(value.Count()); WriteLengthSafe(value.Count());
#endif #endif
foreach (var item in value) foreach (var item in value)
{ {
@@ -1765,7 +1787,8 @@ namespace Unity.Netcode
public unsafe void WriteValue<T>(in T value, ForFixedStrings unused = default) public unsafe void WriteValue<T>(in T value, ForFixedStrings unused = default)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
WriteUnmanaged(value.Length); // BytePacker.WriteValuePacked(this, value.Length);
WriteLength(value.Length);
// This avoids a copy on the string, which could be costly for FixedString4096Bytes // This avoids a copy on the string, which could be costly for FixedString4096Bytes
// Otherwise, GetUnsafePtr() is an impure function call and will result in a copy // Otherwise, GetUnsafePtr() is an impure function call and will result in a copy
// for `in` parameters. // for `in` parameters.
@@ -1787,7 +1810,7 @@ namespace Unity.Netcode
public void WriteValue<T>(T[] value, ForFixedStrings unused = default) public void WriteValue<T>(T[] value, ForFixedStrings unused = default)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
WriteUnmanaged(value.Length); WriteLength(value.Length);
foreach (var str in value) foreach (var str in value)
{ {
WriteValue(str); WriteValue(str);
@@ -1806,7 +1829,7 @@ namespace Unity.Netcode
public void WriteValue<T>(in NativeArray<T> value, ForFixedStrings unused = default) public void WriteValue<T>(in NativeArray<T> value, ForFixedStrings unused = default)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
WriteUnmanaged(value.Length); WriteLength(value.Length);
foreach (var str in value) foreach (var str in value)
{ {
WriteValue(str); WriteValue(str);
@@ -1826,7 +1849,7 @@ namespace Unity.Netcode
public void WriteValue<T>(in NativeList<T> value, ForFixedStrings unused = default) public void WriteValue<T>(in NativeList<T> value, ForFixedStrings unused = default)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
WriteUnmanaged(value.Length); WriteLength(value.Length);
foreach (var str in value) foreach (var str in value)
{ {
WriteValue(str); WriteValue(str);
@@ -1848,7 +1871,7 @@ namespace Unity.Netcode
public void WriteValueSafe<T>(in T value, ForFixedStrings unused = default) public void WriteValueSafe<T>(in T value, ForFixedStrings unused = default)
where T : unmanaged, INativeList<byte>, IUTF8Bytes where T : unmanaged, INativeList<byte>, IUTF8Bytes
{ {
if (!TryBeginWriteInternal(sizeof(int) + value.Length)) if (!TryBeginWriteInternal(SizeOfLengthField() + value.Length))
{ {
throw new OverflowException("Writing past the end of the buffer"); throw new OverflowException("Writing past the end of the buffer");
} }
@@ -1871,7 +1894,7 @@ namespace Unity.Netcode
{ {
throw new OverflowException("Writing past the end of the buffer"); throw new OverflowException("Writing past the end of the buffer");
} }
WriteUnmanaged(value.Length); WriteLength(value.Length);
foreach (var str in value) foreach (var str in value)
{ {
WriteValue(str); WriteValue(str);
@@ -1894,7 +1917,7 @@ namespace Unity.Netcode
{ {
throw new OverflowException("Writing past the end of the buffer"); throw new OverflowException("Writing past the end of the buffer");
} }
WriteUnmanaged(value.Length); WriteLength(value.Length);
foreach (var str in value) foreach (var str in value)
{ {
WriteValue(str); WriteValue(str);
@@ -1918,7 +1941,7 @@ namespace Unity.Netcode
{ {
throw new OverflowException("Writing past the end of the buffer"); throw new OverflowException("Writing past the end of the buffer");
} }
WriteUnmanaged(value.Length); WriteLength(value.Length);
foreach (var str in value) foreach (var str in value)
{ {
WriteValue(str); WriteValue(str);

View File

@@ -11,6 +11,8 @@ namespace Unity.Netcode
{ {
private NetworkObjectReference m_NetworkObjectReference; private NetworkObjectReference m_NetworkObjectReference;
private ushort m_NetworkBehaviourId; private ushort m_NetworkBehaviourId;
private static ushort s_NullId = ushort.MaxValue;
/// <summary> /// <summary>
/// Creates a new instance of the <see cref="NetworkBehaviourReference{T}"/> struct. /// Creates a new instance of the <see cref="NetworkBehaviourReference{T}"/> struct.
@@ -21,7 +23,9 @@ namespace Unity.Netcode
{ {
if (networkBehaviour == null) if (networkBehaviour == null)
{ {
throw new ArgumentNullException(nameof(networkBehaviour)); m_NetworkObjectReference = new NetworkObjectReference((NetworkObject)null);
m_NetworkBehaviourId = s_NullId;
return;
} }
if (networkBehaviour.NetworkObject == null) if (networkBehaviour.NetworkObject == null)
{ {
@@ -60,6 +64,11 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static NetworkBehaviour GetInternal(NetworkBehaviourReference networkBehaviourRef, NetworkManager networkManager = null) private static NetworkBehaviour GetInternal(NetworkBehaviourReference networkBehaviourRef, NetworkManager networkManager = null)
{ {
if (networkBehaviourRef.m_NetworkBehaviourId == s_NullId)
{
return null;
}
if (networkBehaviourRef.m_NetworkObjectReference.TryGet(out NetworkObject networkObject, networkManager)) if (networkBehaviourRef.m_NetworkObjectReference.TryGet(out NetworkObject networkObject, networkManager))
{ {
return networkObject.GetNetworkBehaviourAtOrderIndex(networkBehaviourRef.m_NetworkBehaviourId); return networkObject.GetNetworkBehaviourAtOrderIndex(networkBehaviourRef.m_NetworkBehaviourId);

View File

@@ -10,6 +10,7 @@ namespace Unity.Netcode
public struct NetworkObjectReference : INetworkSerializable, IEquatable<NetworkObjectReference> public struct NetworkObjectReference : INetworkSerializable, IEquatable<NetworkObjectReference>
{ {
private ulong m_NetworkObjectId; private ulong m_NetworkObjectId;
private static ulong s_NullId = ulong.MaxValue;
/// <summary> /// <summary>
/// The <see cref="NetworkObject.NetworkObjectId"/> of the referenced <see cref="NetworkObject"/>. /// The <see cref="NetworkObject.NetworkObjectId"/> of the referenced <see cref="NetworkObject"/>.
@@ -30,7 +31,8 @@ namespace Unity.Netcode
{ {
if (networkObject == null) if (networkObject == null)
{ {
throw new ArgumentNullException(nameof(networkObject)); m_NetworkObjectId = s_NullId;
return;
} }
if (networkObject.IsSpawned == false) if (networkObject.IsSpawned == false)
@@ -51,10 +53,16 @@ namespace Unity.Netcode
{ {
if (gameObject == null) if (gameObject == null)
{ {
throw new ArgumentNullException(nameof(gameObject)); m_NetworkObjectId = s_NullId;
return;
}
var networkObject = gameObject.GetComponent<NetworkObject>();
if (!networkObject)
{
throw new ArgumentException($"Cannot create {nameof(NetworkObjectReference)} from {nameof(GameObject)} without a {nameof(NetworkObject)} component.");
} }
var networkObject = gameObject.GetComponent<NetworkObject>() ?? throw new ArgumentException($"Cannot create {nameof(NetworkObjectReference)} from {nameof(GameObject)} without a {nameof(NetworkObject)} component.");
if (networkObject.IsSpawned == false) if (networkObject.IsSpawned == false)
{ {
throw new ArgumentException($"{nameof(NetworkObjectReference)} can only be created from spawned {nameof(NetworkObject)}s."); throw new ArgumentException($"{nameof(NetworkObjectReference)} can only be created from spawned {nameof(NetworkObject)}s.");
@@ -80,10 +88,14 @@ namespace Unity.Netcode
/// </summary> /// </summary>
/// <param name="networkObjectRef">The reference.</param> /// <param name="networkObjectRef">The reference.</param>
/// <param name="networkManager">The networkmanager. Uses <see cref="NetworkManager.Singleton"/> to resolve if null.</param> /// <param name="networkManager">The networkmanager. Uses <see cref="NetworkManager.Singleton"/> to resolve if null.</param>
/// <returns>The resolves <see cref="NetworkObject"/>. Returns null if the networkobject was not found</returns> /// <returns>The resolved <see cref="NetworkObject"/>. Returns null if the networkobject was not found</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static NetworkObject Resolve(NetworkObjectReference networkObjectRef, NetworkManager networkManager = null) private static NetworkObject Resolve(NetworkObjectReference networkObjectRef, NetworkManager networkManager = null)
{ {
if (networkObjectRef.m_NetworkObjectId == s_NullId)
{
return null;
}
networkManager = networkManager ?? NetworkManager.Singleton; networkManager = networkManager ?? NetworkManager.Singleton;
networkManager.SpawnManager.SpawnedObjects.TryGetValue(networkObjectRef.m_NetworkObjectId, out NetworkObject networkObject); networkManager.SpawnManager.SpawnedObjects.TryGetValue(networkObjectRef.m_NetworkObjectId, out NetworkObject networkObject);

View File

@@ -275,17 +275,17 @@ namespace Unity.Netcode
} }
/// <summary> /// <summary>
/// Returns a list of all NetworkObjects that belong to a client. /// Returns an array of all NetworkObjects that belong to a client.
/// </summary> /// </summary>
/// <param name="clientId">the client's id <see cref="NetworkManager.LocalClientId"/></param> /// <param name="clientId">the client's id <see cref="NetworkManager.LocalClientId"/></param>
/// <returns>returns the list of <see cref="NetworkObject"/>s owned by the client</returns> /// <returns>returns an array of the <see cref="NetworkObject"/>s owned by the client</returns>
public List<NetworkObject> GetClientOwnedObjects(ulong clientId) public NetworkObject[] GetClientOwnedObjects(ulong clientId)
{ {
if (!OwnershipToObjectsTable.ContainsKey(clientId)) if (!OwnershipToObjectsTable.ContainsKey(clientId))
{ {
OwnershipToObjectsTable.Add(clientId, new Dictionary<ulong, NetworkObject>()); OwnershipToObjectsTable.Add(clientId, new Dictionary<ulong, NetworkObject>());
} }
return OwnershipToObjectsTable[clientId].Values.ToList(); return OwnershipToObjectsTable[clientId].Values.ToArray();
} }
/// <summary> /// <summary>
@@ -643,7 +643,7 @@ namespace Unity.Netcode
return null; return null;
} }
ownerClientId = NetworkManager.DistributedAuthorityMode ? NetworkManager.LocalClientId : NetworkManager.ServerClientId; ownerClientId = NetworkManager.DistributedAuthorityMode ? NetworkManager.LocalClientId : ownerClientId;
// We only need to check for authority when running in client-server mode // We only need to check for authority when running in client-server mode
if (!NetworkManager.IsServer && !NetworkManager.DistributedAuthorityMode) if (!NetworkManager.IsServer && !NetworkManager.DistributedAuthorityMode)
{ {
@@ -1581,20 +1581,46 @@ namespace Unity.Netcode
{ {
foreach (var entry in ClientsToShowObject) foreach (var entry in ClientsToShowObject)
{ {
SendSpawnCallForObserverUpdate(entry.Value.ToArray(), entry.Key); if (entry.Key != null && entry.Key.IsSpawned)
{
try
{
SendSpawnCallForObserverUpdate(entry.Value.ToArray(), entry.Key);
}
catch (Exception ex)
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogException(ex);
}
}
}
} }
ClientsToShowObject.Clear(); ClientsToShowObject.Clear();
ObjectsToShowToClient.Clear(); ObjectsToShowToClient.Clear();
return; return;
} }
// Handle NetworkObjects to show // Server or Host handling of NetworkObjects to show
foreach (var client in ObjectsToShowToClient) foreach (var client in ObjectsToShowToClient)
{ {
ulong clientId = client.Key; ulong clientId = client.Key;
foreach (var networkObject in client.Value) foreach (var networkObject in client.Value)
{ {
SendSpawnCallForObject(clientId, networkObject); if (networkObject != null && networkObject.IsSpawned)
{
try
{
SendSpawnCallForObject(clientId, networkObject);
}
catch (Exception ex)
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogException(ex);
}
}
}
} }
} }
ObjectsToShowToClient.Clear(); ObjectsToShowToClient.Clear();
@@ -1820,11 +1846,14 @@ namespace Unity.Netcode
return; return;
} }
var currentTick = serverTime.Tick; var currentTick = serverTime.Tick;
var deferredCallbackObjects = DeferredDespawnObjects.Where((c) => c.HasDeferredDespawnCheck); var deferredCallbackCount = DeferredDespawnObjects.Count();
var deferredCallbackCount = deferredCallbackObjects.Count(); for (int i = 0; i < deferredCallbackCount; i++)
for (int i = 0; i < deferredCallbackCount - 1; i++)
{ {
var deferredObjectEntry = deferredCallbackObjects.ElementAt(i); var deferredObjectEntry = DeferredDespawnObjects[i];
if (!deferredObjectEntry.HasDeferredDespawnCheck)
{
continue;
}
var networkObject = SpawnedObjects[deferredObjectEntry.NetworkObjectId]; var networkObject = SpawnedObjects[deferredObjectEntry.NetworkObjectId];
// Double check to make sure user did not remove the callback // Double check to make sure user did not remove the callback
if (networkObject.OnDeferredDespawnComplete != null) if (networkObject.OnDeferredDespawnComplete != null)
@@ -1849,9 +1878,15 @@ namespace Unity.Netcode
} }
} }
var despawnObjects = DeferredDespawnObjects.Where((c) => c.TickToDespawn < currentTick).ToList(); // Parse backwards so we can remove objects as we parse through them
foreach (var deferredObjectEntry in despawnObjects) for (int i = DeferredDespawnObjects.Count - 1; i >= 0; i--)
{ {
var deferredObjectEntry = DeferredDespawnObjects[i];
if (deferredObjectEntry.TickToDespawn >= currentTick)
{
continue;
}
if (!SpawnedObjects.ContainsKey(deferredObjectEntry.NetworkObjectId)) if (!SpawnedObjects.ContainsKey(deferredObjectEntry.NetworkObjectId))
{ {
DeferredDespawnObjects.Remove(deferredObjectEntry); DeferredDespawnObjects.Remove(deferredObjectEntry);
@@ -1863,5 +1898,66 @@ namespace Unity.Netcode
DeferredDespawnObjects.Remove(deferredObjectEntry); DeferredDespawnObjects.Remove(deferredObjectEntry);
} }
} }
internal void NotifyNetworkObjectsSynchronized()
{
// Users could spawn NetworkObjects during these notifications.
// Create a separate list from the hashset to avoid list modification errors.
var spawnedObjects = SpawnedObjectsList.ToList();
foreach (var networkObject in spawnedObjects)
{
networkObject.InternalNetworkSessionSynchronized();
}
}
/// <summary>
/// Distributed Authority Only
/// Should be invoked on non-session owner clients when a newly joined client is finished
/// synchronizing in order to "show" (spawn) anything that might be currently hidden from
/// the session owner.
/// </summary>
internal void ShowHiddenObjectsToNewlyJoinedClient(ulong newClientId)
{
if (!NetworkManager.DistributedAuthorityMode)
{
if (NetworkManager == null || !NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogWarning($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} invoked while !");
}
return;
}
if (!NetworkManager.DistributedAuthorityMode)
{
Debug.LogError($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} should only be invoked when using a distributed authority network topology!");
return;
}
if (NetworkManager.LocalClient.IsSessionOwner)
{
Debug.LogError($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} should only be invoked on a non-session owner client!");
return;
}
var localClientId = NetworkManager.LocalClient.ClientId;
var sessionOwnerId = NetworkManager.CurrentSessionOwner;
foreach (var networkObject in SpawnedObjectsList)
{
if (networkObject.SpawnWithObservers && networkObject.OwnerClientId == localClientId && !networkObject.Observers.Contains(sessionOwnerId))
{
if (networkObject.Observers.Contains(newClientId))
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
// Track if there is some other location where the client is being added to the observers list when the object is hidden from the session owner
Debug.LogWarning($"[{networkObject.name}] Has new client as an observer but it is hidden from the session owner!");
}
// For now, remove the client (impossible for the new client to have an instance since the session owner doesn't) to make sure newly added
// code to handle this edge case works.
networkObject.Observers.Remove(newClientId);
}
networkObject.NetworkShow(newClientId);
}
}
}
} }
} }

View File

@@ -0,0 +1,100 @@
using System.Collections.Generic;
namespace Unity.Netcode
{
internal interface IAnticipationEventReceiver
{
public void SetupForUpdate();
public void SetupForRender();
}
internal interface IAnticipatedObject
{
public void Update();
public void ResetAnticipation();
public NetworkObject OwnerObject { get; }
}
internal class AnticipationSystem
{
internal ulong LastAnticipationAck;
internal double LastAnticipationAckTime;
internal HashSet<IAnticipatedObject> AllAnticipatedObjects = new HashSet<IAnticipatedObject>();
internal ulong AnticipationCounter;
private NetworkManager m_NetworkManager;
public HashSet<IAnticipatedObject> ObjectsToReanticipate = new HashSet<IAnticipatedObject>();
public AnticipationSystem(NetworkManager manager)
{
m_NetworkManager = manager;
}
public event NetworkManager.ReanticipateDelegate OnReanticipate;
private HashSet<IAnticipationEventReceiver> m_AnticipationEventReceivers = new HashSet<IAnticipationEventReceiver>();
public void RegisterForAnticipationEvents(IAnticipationEventReceiver receiver)
{
m_AnticipationEventReceivers.Add(receiver);
}
public void DeregisterForAnticipationEvents(IAnticipationEventReceiver receiver)
{
m_AnticipationEventReceivers.Remove(receiver);
}
public void SetupForUpdate()
{
foreach (var receiver in m_AnticipationEventReceivers)
{
receiver.SetupForUpdate();
}
}
public void SetupForRender()
{
foreach (var receiver in m_AnticipationEventReceivers)
{
receiver.SetupForRender();
}
}
public void ProcessReanticipation()
{
var lastRoundTripTime = m_NetworkManager.LocalTime.Time - LastAnticipationAckTime;
foreach (var item in ObjectsToReanticipate)
{
foreach (var behaviour in item.OwnerObject.ChildNetworkBehaviours)
{
behaviour.OnReanticipate(lastRoundTripTime);
}
item.ResetAnticipation();
}
ObjectsToReanticipate.Clear();
OnReanticipate?.Invoke(lastRoundTripTime);
}
public void Update()
{
foreach (var item in AllAnticipatedObjects)
{
item.Update();
}
}
public void Sync()
{
if (AllAnticipatedObjects.Count != 0 && !m_NetworkManager.ShutdownInProgress && !m_NetworkManager.ConnectionManager.LocalClient.IsServer && m_NetworkManager.ConnectionManager.LocalClient.IsConnected)
{
var message = new AnticipationCounterSyncPingMessage { Counter = AnticipationCounter, Time = m_NetworkManager.LocalTime.Time };
m_NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, NetworkManager.ServerClientId);
}
++AnticipationCounter;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4a75eccede7ecf1408f61dd55c338e06

View File

@@ -24,6 +24,11 @@ namespace Unity.Netcode
/// </summary> /// </summary>
public double TickOffset => m_CachedTickOffset; public double TickOffset => m_CachedTickOffset;
/// <summary>
/// Gets the tick, including partial tick value passed since it started.
/// </summary>
public double TickWithPartial => Tick + (TickOffset / m_TickInterval);
/// <summary> /// <summary>
/// Gets the current time. This is a non fixed time value and similar to <see cref="Time.time"/>. /// Gets the current time. This is a non fixed time value and similar to <see cref="Time.time"/>.
/// </summary> /// </summary>

View File

@@ -5,7 +5,9 @@ namespace Unity.Netcode
{ {
/// <summary> /// <summary>
/// <see cref="NetworkTimeSystem"/> is a standalone system which can be used to run a network time simulation. /// <see cref="NetworkTimeSystem"/> is a standalone system which can be used to run a network time simulation.
/// The network time system maintains both a local and a server time. The local time is based on /// The network time system maintains both a local and a server time. The local time is based on the server time
/// as last received from the server plus an offset based on the current RTT - in other words, it is a best-guess
/// effort at predicting what the server tick will be when a given network action is processed on the server.
/// </summary> /// </summary>
public class NetworkTimeSystem public class NetworkTimeSystem
{ {

View File

@@ -106,6 +106,22 @@ namespace Unity.Netcode
/// </summary> /// </summary>
/// /// <param name="networkManager">optionally pass in NetworkManager</param> /// /// <param name="networkManager">optionally pass in NetworkManager</param>
public abstract void Initialize(NetworkManager networkManager = null); public abstract void Initialize(NetworkManager networkManager = null);
protected virtual NetworkTopologyTypes OnCurrentTopology()
{
return NetworkTopologyTypes.ClientServer;
}
internal NetworkTopologyTypes CurrentTopology()
{
return OnCurrentTopology();
}
}
public enum NetworkTopologyTypes
{
ClientServer,
DistributedAuthority
} }
#if UNITY_INCLUDE_TESTS #if UNITY_INCLUDE_TESTS

View File

@@ -428,6 +428,31 @@ namespace Unity.Netcode.Transports.UTP
protected NetworkDriver m_Driver; protected NetworkDriver m_Driver;
/// <summary>
/// Gets a reference to the <see cref="Networking.Transport.NetworkDriver"/>.
/// </summary>
/// <returns>ref <see cref="Networking.Transport.NetworkDriver"/></returns>
public ref NetworkDriver GetNetworkDriver()
{
return ref m_Driver;
}
/// <summary>
/// Gets the local sytem's <see cref="NetworkEndpoint"/> that is assigned for the current network session.
/// </summary>
/// <remarks>
/// If the driver is not created it will return an invalid <see cref="NetworkEndpoint"/>.
/// </remarks>
/// <returns><see cref="NetworkEndpoint"/></returns>
public NetworkEndpoint GetLocalEndpoint()
{
if (m_Driver.IsCreated)
{
return m_Driver.GetLocalEndpoint();
}
return new NetworkEndpoint();
}
private PacketLossCache m_PacketLossCache = new PacketLossCache(); private PacketLossCache m_PacketLossCache = new PacketLossCache();
private State m_State = State.Disconnected; private State m_State = State.Disconnected;
@@ -450,7 +475,10 @@ namespace Unity.Netcode.Transports.UTP
private RelayServerData m_RelayServerData; private RelayServerData m_RelayServerData;
internal NetworkManager NetworkManager; /// <summary>
/// NetworkManager associated to this transport instance
/// </summary>
protected NetworkManager m_NetworkManager;
private IRealTimeProvider m_RealTimeProvider; private IRealTimeProvider m_RealTimeProvider;
@@ -795,10 +823,10 @@ namespace Unity.Netcode.Transports.UTP
} }
var mtu = 0; var mtu = 0;
if (NetworkManager) if (m_NetworkManager)
{ {
var ngoClientId = NetworkManager.ConnectionManager.TransportIdToClientId(sendTarget.ClientId); var ngoClientId = m_NetworkManager.ConnectionManager.TransportIdToClientId(sendTarget.ClientId);
mtu = NetworkManager.GetPeerMTU(ngoClientId); mtu = m_NetworkManager.GetPeerMTU(ngoClientId);
} }
new SendBatchedMessagesJob new SendBatchedMessagesJob
@@ -947,7 +975,7 @@ namespace Unity.Netcode.Transports.UTP
} }
#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 #if MULTIPLAYER_TOOLS_1_0_0_PRE_7
if (NetworkManager) if (m_NetworkManager)
{ {
ExtractNetworkMetrics(); ExtractNetworkMetrics();
} }
@@ -963,16 +991,16 @@ namespace Unity.Netcode.Transports.UTP
#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 #if MULTIPLAYER_TOOLS_1_0_0_PRE_7
private void ExtractNetworkMetrics() private void ExtractNetworkMetrics()
{ {
if (NetworkManager.IsServer) if (m_NetworkManager.IsServer)
{ {
var ngoConnectionIds = NetworkManager.ConnectedClients.Keys; var ngoConnectionIds = m_NetworkManager.ConnectedClients.Keys;
foreach (var ngoConnectionId in ngoConnectionIds) foreach (var ngoConnectionId in ngoConnectionIds)
{ {
if (ngoConnectionId == 0 && NetworkManager.IsHost) if (ngoConnectionId == 0 && m_NetworkManager.IsHost)
{ {
continue; continue;
} }
var transportClientId = NetworkManager.ConnectionManager.ClientIdToTransportId(ngoConnectionId); var transportClientId = m_NetworkManager.ConnectionManager.ClientIdToTransportId(ngoConnectionId);
ExtractNetworkMetricsForClient(transportClientId); ExtractNetworkMetricsForClient(transportClientId);
} }
} }
@@ -992,10 +1020,10 @@ namespace Unity.Netcode.Transports.UTP
ExtractNetworkMetricsFromPipeline(m_UnreliableSequencedFragmentedPipeline, networkConnection); ExtractNetworkMetricsFromPipeline(m_UnreliableSequencedFragmentedPipeline, networkConnection);
ExtractNetworkMetricsFromPipeline(m_ReliableSequencedPipeline, networkConnection); ExtractNetworkMetricsFromPipeline(m_ReliableSequencedPipeline, networkConnection);
var rttValue = NetworkManager.IsServer ? 0 : ExtractRtt(networkConnection); var rttValue = m_NetworkManager.IsServer ? 0 : ExtractRtt(networkConnection);
NetworkMetrics.UpdateRttToServer(rttValue); NetworkMetrics.UpdateRttToServer(rttValue);
var packetLoss = NetworkManager.IsServer ? 0 : ExtractPacketLoss(networkConnection); var packetLoss = m_NetworkManager.IsServer ? 0 : ExtractPacketLoss(networkConnection);
NetworkMetrics.UpdatePacketLoss(packetLoss); NetworkMetrics.UpdatePacketLoss(packetLoss);
} }
@@ -1199,9 +1227,9 @@ namespace Unity.Netcode.Transports.UTP
// use the transport client ID) or from a user (which will be using the NGO client ID). // use the transport client ID) or from a user (which will be using the NGO client ID).
// So we just try both cases (ExtractRtt returns 0 for invalid connections). // So we just try both cases (ExtractRtt returns 0 for invalid connections).
if (NetworkManager != null) if (m_NetworkManager != null)
{ {
var transportId = NetworkManager.ConnectionManager.ClientIdToTransportId(clientId); var transportId = m_NetworkManager.ConnectionManager.ClientIdToTransportId(clientId);
var rtt = ExtractRtt(ParseClientId(transportId)); var rtt = ExtractRtt(ParseClientId(transportId));
if (rtt > 0) if (rtt > 0)
@@ -1221,14 +1249,14 @@ namespace Unity.Netcode.Transports.UTP
{ {
Debug.Assert(sizeof(ulong) == UnsafeUtility.SizeOf<NetworkConnection>(), "Netcode connection id size does not match UTP connection id size"); Debug.Assert(sizeof(ulong) == UnsafeUtility.SizeOf<NetworkConnection>(), "Netcode connection id size does not match UTP connection id size");
NetworkManager = networkManager; m_NetworkManager = networkManager;
if (NetworkManager && NetworkManager.PortOverride.Overidden) if (m_NetworkManager && m_NetworkManager.PortOverride.Overidden)
{ {
ConnectionData.Port = NetworkManager.PortOverride.Value; ConnectionData.Port = m_NetworkManager.PortOverride.Value;
} }
m_RealTimeProvider = NetworkManager ? NetworkManager.RealTimeProvider : new RealTimeProvider(); m_RealTimeProvider = m_NetworkManager ? m_NetworkManager.RealTimeProvider : new RealTimeProvider();
m_NetworkSettings = new NetworkSettings(Allocator.Persistent); m_NetworkSettings = new NetworkSettings(Allocator.Persistent);
@@ -1322,7 +1350,7 @@ namespace Unity.Netcode.Transports.UTP
// provide any reliability guarantees anymore. Disconnect the client since at // provide any reliability guarantees anymore. Disconnect the client since at
// this point they're bound to become desynchronized. // this point they're bound to become desynchronized.
var ngoClientId = NetworkManager?.ConnectionManager.TransportIdToClientId(clientId) ?? clientId; var ngoClientId = m_NetworkManager?.ConnectionManager.TransportIdToClientId(clientId) ?? clientId;
Debug.LogError($"Couldn't add payload of size {payload.Count} to reliable send queue. " + Debug.LogError($"Couldn't add payload of size {payload.Count} to reliable send queue. " +
$"Closing connection {ngoClientId} as reliability guarantees can't be maintained."); $"Closing connection {ngoClientId} as reliability guarantees can't be maintained.");
@@ -1477,6 +1505,11 @@ namespace Unity.Netcode.Transports.UTP
} }
#endif #endif
protected override NetworkTopologyTypes OnCurrentTopology()
{
return m_NetworkManager != null ? m_NetworkManager.NetworkConfig.NetworkTopology : NetworkTopologyTypes.ClientServer;
}
private string m_ServerPrivateKey; private string m_ServerPrivateKey;
private string m_ServerCertificate; private string m_ServerCertificate;
@@ -1550,7 +1583,7 @@ namespace Unity.Netcode.Transports.UTP
heartbeatTimeoutMS: transport.m_HeartbeatTimeoutMS); heartbeatTimeoutMS: transport.m_HeartbeatTimeoutMS);
#if UNITY_WEBGL && !UNITY_EDITOR #if UNITY_WEBGL && !UNITY_EDITOR
if (NetworkManager.IsServer && m_ProtocolType != ProtocolType.RelayUnityTransport) if (m_NetworkManager.IsServer && m_ProtocolType != ProtocolType.RelayUnityTransport)
{ {
throw new Exception("WebGL as a server is not supported by Unity Transport, outside the Editor."); throw new Exception("WebGL as a server is not supported by Unity Transport, outside the Editor.");
} }
@@ -1572,7 +1605,7 @@ namespace Unity.Netcode.Transports.UTP
} }
else else
{ {
if (NetworkManager.IsServer) if (m_NetworkManager.IsServer)
{ {
if (string.IsNullOrEmpty(m_ServerCertificate) || string.IsNullOrEmpty(m_ServerPrivateKey)) if (string.IsNullOrEmpty(m_ServerCertificate) || string.IsNullOrEmpty(m_ServerPrivateKey))
{ {

View File

@@ -15,7 +15,13 @@
"Unity.Burst", "Unity.Burst",
"Unity.Mathematics" "Unity.Mathematics"
], ],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true, "allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [ "versionDefines": [
{ {
"name": "com.unity.multiplayer.tools", "name": "com.unity.multiplayer.tools",
@@ -61,6 +67,17 @@
"name": "com.unity.modules.physics2d", "name": "com.unity.modules.physics2d",
"expression": "", "expression": "",
"define": "COM_UNITY_MODULES_PHYSICS2D" "define": "COM_UNITY_MODULES_PHYSICS2D"
},
{
"name": "com.unity.services.multiplayer",
"expression": "0.2.0",
"define": "MULTIPLAYER_SERVICES_SDK_INSTALLED"
},
{
"name": "Unity",
"expression": "6000.0.11f1",
"define": "COM_UNITY_MODULES_PHYSICS2D_LINEAR"
} }
] ],
} "noEngineReferences": false
}

View File

@@ -677,6 +677,11 @@ namespace Unity.Netcode.TestHelpers.Runtime
foreach (var sceneToUnload in m_ScenesToUnload) foreach (var sceneToUnload in m_ScenesToUnload)
{ {
SceneManager.UnloadSceneAsync(sceneToUnload.Key); SceneManager.UnloadSceneAsync(sceneToUnload.Key);
// Update the ScenesLoaded when we unload scenes
if (sceneManager.ScenesLoaded.ContainsKey(sceneToUnload.Key.handle))
{
sceneManager.ScenesLoaded.Remove(sceneToUnload.Key.handle);
}
} }
} }
@@ -795,8 +800,9 @@ namespace Unity.Netcode.TestHelpers.Runtime
var sceneManager = networkManager.SceneManager; var sceneManager = networkManager.SceneManager;
// Don't let client's set this value // In client-server, we don't let client's set this value.
if (!networkManager.IsServer) // In dsitributed authority, since session owner can be promoted clients can set this value
if (!networkManager.DistributedAuthorityMode && !networkManager.IsServer)
{ {
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{ {
@@ -804,7 +810,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
} }
return; return;
} }
else if (networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode) else if (!networkManager.DistributedAuthorityMode && networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode)
{ {
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{ {

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Random = UnityEngine.Random;
namespace Unity.Netcode.TestHelpers.Runtime namespace Unity.Netcode.TestHelpers.Runtime
{ {
@@ -10,6 +11,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
public ulong FromClientId; public ulong FromClientId;
public ArraySegment<byte> Payload; public ArraySegment<byte> Payload;
public NetworkEvent Event; public NetworkEvent Event;
public float AvailableTime;
} }
private static Dictionary<ulong, Queue<MessageData>> s_MessageQueue = new Dictionary<ulong, Queue<MessageData>>(); private static Dictionary<ulong, Queue<MessageData>> s_MessageQueue = new Dictionary<ulong, Queue<MessageData>>();
@@ -18,21 +20,44 @@ namespace Unity.Netcode.TestHelpers.Runtime
public static ulong HighTransportId = 0; public static ulong HighTransportId = 0;
public ulong TransportId = 0; public ulong TransportId = 0;
public float SimulatedLatencySeconds;
public float PacketDropRate;
public float LatencyJitter;
public NetworkManager NetworkManager; public NetworkManager NetworkManager;
public override void Send(ulong clientId, ArraySegment<byte> payload, NetworkDelivery networkDelivery) public override void Send(ulong clientId, ArraySegment<byte> payload, NetworkDelivery networkDelivery)
{ {
if (Random.Range(0, 1) < PacketDropRate)
{
return;
}
var copy = new byte[payload.Array.Length]; var copy = new byte[payload.Array.Length];
Array.Copy(payload.Array, copy, payload.Array.Length); Array.Copy(payload.Array, copy, payload.Array.Length);
s_MessageQueue[clientId].Enqueue(new MessageData { FromClientId = TransportId, Payload = new ArraySegment<byte>(copy, payload.Offset, payload.Count), Event = NetworkEvent.Data }); s_MessageQueue[clientId].Enqueue(new MessageData
{
FromClientId = TransportId,
Payload = new ArraySegment<byte>(copy, payload.Offset, payload.Count),
Event = NetworkEvent.Data,
AvailableTime =
NetworkManager.RealTimeProvider.UnscaledTime + SimulatedLatencySeconds + Random.Range(-LatencyJitter, LatencyJitter)
});
} }
public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment<byte> payload, out float receiveTime) public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment<byte> payload, out float receiveTime)
{ {
if (s_MessageQueue[TransportId].Count > 0) if (s_MessageQueue[TransportId].Count > 0)
{ {
var data = s_MessageQueue[TransportId].Dequeue(); var data = s_MessageQueue[TransportId].Peek();
if (data.AvailableTime > NetworkManager.RealTimeProvider.UnscaledTime)
{
clientId = 0;
payload = new ArraySegment<byte>();
receiveTime = 0;
return NetworkEvent.Nothing;
}
s_MessageQueue[TransportId].Dequeue();
clientId = data.FromClientId; clientId = data.FromClientId;
payload = data.Payload; payload = data.Payload;
receiveTime = NetworkManager.RealTimeProvider.RealTimeSinceStartup; receiveTime = NetworkManager.RealTimeProvider.RealTimeSinceStartup;
@@ -81,9 +106,28 @@ namespace Unity.Netcode.TestHelpers.Runtime
{ {
} }
protected override NetworkTopologyTypes OnCurrentTopology()
{
return NetworkManager != null ? NetworkManager.NetworkConfig.NetworkTopology : NetworkTopologyTypes.ClientServer;
}
public override void Initialize(NetworkManager networkManager = null) public override void Initialize(NetworkManager networkManager = null)
{ {
NetworkManager = networkManager; NetworkManager = networkManager;
} }
public static void Reset()
{
s_MessageQueue.Clear();
HighTransportId = 0;
}
public static void ClearQueues()
{
foreach (var kvp in s_MessageQueue)
{
kvp.Value.Clear();
}
}
} }
} }

View File

@@ -303,6 +303,11 @@ namespace Unity.Netcode.TestHelpers.Runtime
OnOneTimeSetup(); OnOneTimeSetup();
VerboseDebug($"Exiting {nameof(OneTimeSetup)}"); VerboseDebug($"Exiting {nameof(OneTimeSetup)}");
#if DEVELOPMENT_BUILD || UNITY_EDITOR
// Default to not log the serialized type not optimized warning message when testing.
NetworkManager.DisableNotOptimizedSerializedType = true;
#endif
} }
/// <summary> /// <summary>
@@ -337,6 +342,15 @@ namespace Unity.Netcode.TestHelpers.Runtime
NetcodeLogAssert = new NetcodeLogAssert(); NetcodeLogAssert = new NetcodeLogAssert();
if (m_EnableTimeTravel) if (m_EnableTimeTravel)
{ {
if (m_NetworkManagerInstatiationMode == NetworkManagerInstatiationMode.AllTests)
{
MockTransport.ClearQueues();
}
else
{
MockTransport.Reset();
}
// Setup the frames per tick for time travel advance to next tick // Setup the frames per tick for time travel advance to next tick
ConfigureFramesPerTick(); ConfigureFramesPerTick();
} }
@@ -636,6 +650,33 @@ namespace Unity.Netcode.TestHelpers.Runtime
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(() => !networkManager.IsConnectedClient)); Assert.True(WaitForConditionOrTimeOutWithTimeTravel(() => !networkManager.IsConnectedClient));
} }
protected void SetTimeTravelSimulatedLatency(float latencySeconds)
{
((MockTransport)m_ServerNetworkManager.NetworkConfig.NetworkTransport).SimulatedLatencySeconds = latencySeconds;
foreach (var client in m_ClientNetworkManagers)
{
((MockTransport)client.NetworkConfig.NetworkTransport).SimulatedLatencySeconds = latencySeconds;
}
}
protected void SetTimeTravelSimulatedDropRate(float dropRatePercent)
{
((MockTransport)m_ServerNetworkManager.NetworkConfig.NetworkTransport).PacketDropRate = dropRatePercent;
foreach (var client in m_ClientNetworkManagers)
{
((MockTransport)client.NetworkConfig.NetworkTransport).PacketDropRate = dropRatePercent;
}
}
protected void SetTimeTravelSimulatedLatencyJitter(float jitterSeconds)
{
((MockTransport)m_ServerNetworkManager.NetworkConfig.NetworkTransport).LatencyJitter = jitterSeconds;
foreach (var client in m_ClientNetworkManagers)
{
((MockTransport)client.NetworkConfig.NetworkTransport).LatencyJitter = jitterSeconds;
}
}
/// <summary> /// <summary>
/// Creates the server and clients /// Creates the server and clients
/// </summary> /// </summary>
@@ -809,6 +850,12 @@ namespace Unity.Netcode.TestHelpers.Runtime
protected virtual bool LogAllMessages => false; protected virtual bool LogAllMessages => false;
protected virtual bool ShouldCheckForSpawnedPlayers()
{
return true;
}
/// <summary> /// <summary>
/// This starts the server and clients as long as <see cref="CanStartServerAndClients"/> /// This starts the server and clients as long as <see cref="CanStartServerAndClients"/>
/// returns true. /// returns true.
@@ -897,7 +944,12 @@ namespace Unity.Netcode.TestHelpers.Runtime
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{m_ServerNetworkManager.LocalClientId}'s player object!\n {m_InternalErrorLog}"); AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{m_ServerNetworkManager.LocalClientId}'s player object!\n {m_InternalErrorLog}");
} }
} }
ClientNetworkManagerPostStartInit();
if (ShouldCheckForSpawnedPlayers())
{
ClientNetworkManagerPostStartInit();
}
// Notification that at this time the server and client(s) are instantiated, // Notification that at this time the server and client(s) are instantiated,
// started, and connected on both sides. // started, and connected on both sides.
yield return OnServerAndClientsConnected(); yield return OnServerAndClientsConnected();
@@ -989,7 +1041,10 @@ namespace Unity.Netcode.TestHelpers.Runtime
} }
} }
ClientNetworkManagerPostStartInit(); if (ShouldCheckForSpawnedPlayers())
{
ClientNetworkManagerPostStartInit();
}
// Notification that at this time the server and client(s) are instantiated, // Notification that at this time the server and client(s) are instantiated,
// started, and connected on both sides. // started, and connected on both sides.
@@ -1880,8 +1935,21 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary> /// </summary>
public static void SimulateOneFrame() public static void SimulateOneFrame()
{ {
foreach (NetworkUpdateStage stage in Enum.GetValues(typeof(NetworkUpdateStage))) foreach (NetworkUpdateStage updateStage in Enum.GetValues(typeof(NetworkUpdateStage)))
{ {
var stage = updateStage;
// These two are out of order numerically due to backward compatibility
// requirements. We have to swap them to maintain correct execution
// order.
if (stage == NetworkUpdateStage.PostScriptLateUpdate)
{
stage = NetworkUpdateStage.PostLateUpdate;
}
else if (stage == NetworkUpdateStage.PostLateUpdate)
{
stage = NetworkUpdateStage.PostScriptLateUpdate;
}
NetworkUpdateLoop.RunNetworkUpdateStage(stage); NetworkUpdateLoop.RunNetworkUpdateStage(stage);
string methodName = string.Empty; string methodName = string.Empty;
switch (stage) switch (stage)
@@ -1900,13 +1968,18 @@ namespace Unity.Netcode.TestHelpers.Runtime
if (!string.IsNullOrEmpty(methodName)) if (!string.IsNullOrEmpty(methodName))
{ {
#if UNITY_2023_1_OR_NEWER #if UNITY_2023_1_OR_NEWER
foreach (var behaviour in Object.FindObjectsByType<NetworkBehaviour>(FindObjectsSortMode.InstanceID)) foreach (var obj in Object.FindObjectsByType<NetworkObject>(FindObjectsSortMode.InstanceID))
#else #else
foreach (var behaviour in Object.FindObjectsOfType<NetworkBehaviour>()) foreach (var obj in Object.FindObjectsOfType<NetworkObject>())
#endif #endif
{ {
var method = behaviour.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var method = obj.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
method?.Invoke(behaviour, new object[] { }); method?.Invoke(obj, new object[] { });
foreach (var behaviour in obj.ChildNetworkBehaviours)
{
var behaviourMethod = behaviour.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
behaviourMethod?.Invoke(behaviour, new object[] { });
}
} }
} }
} }

View File

@@ -326,20 +326,30 @@ namespace Unity.Netcode.TestHelpers.Runtime
s_IsStarted = false; s_IsStarted = false;
// Shutdown the server which forces clients to disconnect try
foreach (var networkManager in NetworkManagerInstances)
{ {
networkManager.Shutdown(); // Shutdown the server which forces clients to disconnect
s_Hooks.Remove(networkManager); foreach (var networkManager in NetworkManagerInstances)
}
// Destroy the network manager instances
foreach (var networkManager in NetworkManagerInstances)
{
if (networkManager.gameObject != null)
{ {
Object.DestroyImmediate(networkManager.gameObject); if (networkManager != null && networkManager.IsListening)
{
networkManager?.Shutdown();
s_Hooks.Remove(networkManager);
}
} }
// Destroy the network manager instances
foreach (var networkManager in NetworkManagerInstances)
{
if (networkManager != null && networkManager.gameObject)
{
Object.DestroyImmediate(networkManager.gameObject);
}
}
}
catch (Exception ex)
{
Debug.LogException(ex);
} }
NetworkManagerInstances.Clear(); NetworkManagerInstances.Clear();
@@ -620,7 +630,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// Similar to WaitForClientConnected, this waits for multiple clients to be connected. /// Similar to WaitForClientConnected, this waits for multiple clients to be connected.
/// </summary> /// </summary>
/// <param name="clients">The clients to be connected</param> /// <param name="clients">The clients to be connected</param>
/// <param name="result">The result. If null, it will automatically assert<</param> /// <param name="result">The result. If null, it will automatically assert</param>
/// <param name="maxFrames">The max frames to wait for</param> /// <param name="maxFrames">The max frames to wait for</param>
/// <returns></returns> /// <returns></returns>
public static IEnumerator WaitForClientsConnected(NetworkManager[] clients, ResultWrapper<bool> result = null, float timeout = DefaultTimeout) public static IEnumerator WaitForClientsConnected(NetworkManager[] clients, ResultWrapper<bool> result = null, float timeout = DefaultTimeout)

View File

@@ -5,11 +5,13 @@ namespace Unity.Netcode.TestHelpers.Runtime
{ {
/// <summary> /// <summary>
/// Will automatically register for the NetworkVariable OnValueChanged /// Will automatically register for the NetworkVariable OnValueChanged
/// delegate handler. It then will expose that single delegate invocation /// delegate handler. It then will expose that single delegate invocation
/// to anything that registers for this NetworkVariableHelper's instance's OnValueChanged event. /// to anything that registers for this NetworkVariableHelper's instance's OnValueChanged event.
/// This allows us to register any NetworkVariable type as well as there are basically two "types of types": /// This allows us to register any NetworkVariable type as well as there are basically two "types of types":
/// IEquatable<T> /// <list type="bullet">
/// ValueType /// <item>IEquatable&lt;T&gt;</item>
/// <item>ValueType</item>
/// </list>
/// From both we can then at least determine if the value indeed changed /// From both we can then at least determine if the value indeed changed
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
@@ -20,7 +22,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
public event OnMyValueChangedDelegateHandler OnValueChanged; public event OnMyValueChangedDelegateHandler OnValueChanged;
/// <summary> /// <summary>
/// IEquatable<T> Equals Check /// IEquatable&lt;T&gt; Equals Check
/// </summary> /// </summary>
private void CheckVariableChanged(IEquatable<T> previous, IEquatable<T> next) private void CheckVariableChanged(IEquatable<T> previous, IEquatable<T> next)
{ {

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