From 2fd3011d31d6936104e1f86d7498e5548eeeeb81 Mon Sep 17 00:00:00 2001 From: Stedd Date: Sat, 2 Sep 2023 11:14:39 +0200 Subject: [PATCH] Added Mirror --- Assets/Mirror.meta | 8 + Assets/Mirror/Authenticators.meta | 8 + .../Authenticators/BasicAuthenticator.cs | 192 ++ .../Authenticators/BasicAuthenticator.cs.meta | 11 + .../Authenticators/DeviceAuthenticator.cs | 129 ++ .../DeviceAuthenticator.cs.meta | 11 + .../Mirror.Authenticators.asmdef | 16 + .../Mirror.Authenticators.asmdef.meta | 7 + .../Authenticators/TimeoutAuthenticator.cs | 70 + .../TimeoutAuthenticator.cs.meta | 11 + Assets/Mirror/CompilerSymbols.meta | 8 + .../Mirror.CompilerSymbols.asmdef | 14 + .../Mirror.CompilerSymbols.asmdef.meta | 7 + .../CompilerSymbols/PreprocessorDefine.cs | 43 + .../PreprocessorDefine.cs.meta | 11 + Assets/Mirror/Components.meta | 8 + Assets/Mirror/Components/AssemblyInfo.cs | 12 + Assets/Mirror/Components/AssemblyInfo.cs.meta | 11 + Assets/Mirror/Components/Discovery.meta | 8 + .../Components/Discovery/NetworkDiscovery.cs | 93 + .../Discovery/NetworkDiscovery.cs.meta | 11 + .../Discovery/NetworkDiscoveryBase.cs | 469 +++++ .../Discovery/NetworkDiscoveryBase.cs.meta | 11 + .../Discovery/NetworkDiscoveryHUD.cs | 132 ++ .../Discovery/NetworkDiscoveryHUD.cs.meta | 11 + .../Components/Discovery/ServerRequest.cs | 4 + .../Discovery/ServerRequest.cs.meta | 11 + .../Components/Discovery/ServerResponse.cs | 18 + .../Discovery/ServerResponse.cs.meta | 11 + Assets/Mirror/Components/Experimental.meta | 8 + .../Experimental/NetworkLerpRigidbody.cs | 90 + .../Experimental/NetworkLerpRigidbody.cs.meta | 11 + .../Experimental/NetworkRigidbody.cs | 347 +++ .../Experimental/NetworkRigidbody.cs.meta | 11 + .../Experimental/NetworkRigidbody2D.cs | 342 +++ .../Experimental/NetworkRigidbody2D.cs.meta | 11 + Assets/Mirror/Components/GUIConsole.cs | 115 + Assets/Mirror/Components/GUIConsole.cs.meta | 11 + .../Mirror/Components/InterestManagement.meta | 8 + .../InterestManagement/Distance.meta | 3 + .../Distance/DistanceInterestManagement.cs | 90 + .../DistanceInterestManagement.cs.meta | 11 + .../DistanceInterestManagementCustomRange.cs | 15 + ...tanceInterestManagementCustomRange.cs.meta | 11 + .../Components/InterestManagement/Match.meta | 3 + .../Match/MatchInterestManagement.cs | 174 ++ .../Match/MatchInterestManagement.cs.meta | 11 + .../InterestManagement/Match/NetworkMatch.cs | 15 + .../Match/NetworkMatch.cs.meta | 11 + .../Components/InterestManagement/Scene.meta | 3 + .../Scene/SceneInterestManagement.cs | 118 ++ .../Scene/SceneInterestManagement.cs.meta | 11 + .../InterestManagement/SpatialHashing.meta | 3 + .../SpatialHashing/Grid2D.cs | 104 + .../SpatialHashing/Grid2D.cs.meta | 11 + .../SpatialHashingInterestManagement.cs | 154 ++ .../SpatialHashingInterestManagement.cs.meta | 11 + .../Components/InterestManagement/Team.meta | 8 + .../InterestManagement/Team/NetworkTeam.cs | 17 + .../Team/NetworkTeam.cs.meta | 11 + .../Team/TeamInterestManagement.cs | 196 ++ .../Team/TeamInterestManagement.cs.meta | 11 + Assets/Mirror/Components/LagCompensation.meta | 8 + .../LagCompensation/HistoryCollider.cs | 107 + .../LagCompensation/HistoryCollider.cs.meta | 11 + .../Components/Mirror.Components.asmdef | 16 + .../Components/Mirror.Components.asmdef.meta | 7 + Assets/Mirror/Components/NetworkAnimator.cs | 619 ++++++ .../Mirror/Components/NetworkAnimator.cs.meta | 11 + .../Mirror/Components/NetworkLobbyManager.cs | 18 + .../Components/NetworkLobbyManager.cs.meta | 11 + .../Mirror/Components/NetworkLobbyPlayer.cs | 15 + .../Components/NetworkLobbyPlayer.cs.meta | 11 + .../Mirror/Components/NetworkPingDisplay.cs | 39 + .../Components/NetworkPingDisplay.cs.meta | 11 + .../Mirror/Components/NetworkRigidbody.meta | 3 + .../NetworkRigidbodyReliable.cs | 97 + .../NetworkRigidbodyReliable.cs.meta | 11 + .../NetworkRigidbodyReliable2D.cs | 97 + .../NetworkRigidbodyReliable2D.cs.meta | 11 + .../NetworkRigidbodyUnreliable.cs | 97 + .../NetworkRigidbodyUnreliable.cs.meta | 11 + .../NetworkRigidbodyUnreliable2D.cs | 97 + .../NetworkRigidbodyUnreliable2D.cs.meta | 11 + .../Mirror/Components/NetworkRoomManager.cs | 684 ++++++ .../Components/NetworkRoomManager.cs.meta | 11 + Assets/Mirror/Components/NetworkRoomPlayer.cs | 195 ++ .../Components/NetworkRoomPlayer.cs.meta | 11 + Assets/Mirror/Components/NetworkStatistics.cs | 194 ++ .../Components/NetworkStatistics.cs.meta | 11 + .../Mirror/Components/NetworkTransform.meta | 3 + .../NetworkTransform/NetworkTransform.cs | 8 + .../NetworkTransform/NetworkTransform.cs.meta | 11 + .../NetworkTransform/NetworkTransformBase.cs | 475 +++++ .../NetworkTransformBase.cs.meta | 11 + .../NetworkTransform/NetworkTransformChild.cs | 12 + .../NetworkTransformChild.cs.meta | 11 + .../NetworkTransformReliable.cs | 423 ++++ .../NetworkTransformReliable.cs.meta | 11 + .../NetworkTransformUnreliable.cs | 382 ++++ .../NetworkTransformUnreliable.cs.meta | 11 + .../NetworkTransform/TransformSnapshot.cs | 65 + .../TransformSnapshot.cs.meta | 11 + Assets/Mirror/Components/RemoteStatistics.cs | 441 ++++ .../Components/RemoteStatistics.cs.meta | 11 + Assets/Mirror/Core.meta | 8 + Assets/Mirror/Core/AssemblyInfo.cs | 12 + Assets/Mirror/Core/AssemblyInfo.cs.meta | 11 + Assets/Mirror/Core/Attributes.cs | 85 + Assets/Mirror/Core/Attributes.cs.meta | 11 + Assets/Mirror/Core/Batching.meta | 8 + Assets/Mirror/Core/Batching/Batcher.cs | 150 ++ Assets/Mirror/Core/Batching/Batcher.cs.meta | 11 + Assets/Mirror/Core/Batching/Unbatcher.cs | 129 ++ Assets/Mirror/Core/Batching/Unbatcher.cs.meta | 11 + Assets/Mirror/Core/ConnectionQuality.cs | 68 + Assets/Mirror/Core/ConnectionQuality.cs.meta | 11 + Assets/Mirror/Core/Empty.meta | 3 + Assets/Mirror/Core/Empty/ClientScene.cs | 1 + Assets/Mirror/Core/Empty/ClientScene.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud.meta | 8 + .../Mirror/Core/Empty/Cloud/ApiConnector.cs | 1 + .../Core/Empty/Cloud/ApiConnector.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/ApiUpdater.cs | 1 + .../Core/Empty/Cloud/ApiUpdater.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/Ball.cs | 1 + Assets/Mirror/Core/Empty/Cloud/Ball.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/BallManager.cs | 1 + .../Core/Empty/Cloud/BallManager.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/BaseApi.cs | 1 + .../Mirror/Core/Empty/Cloud/BaseApi.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/Events.cs | 1 + Assets/Mirror/Core/Empty/Cloud/Events.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/Extensions.cs | 1 + .../Core/Empty/Cloud/Extensions.cs.meta | 11 + .../Core/Empty/Cloud/ICoroutineRunner.cs | 1 + .../Core/Empty/Cloud/ICoroutineRunner.cs.meta | 11 + .../Core/Empty/Cloud/IRequestCreator.cs | 1 + .../Core/Empty/Cloud/IRequestCreator.cs.meta | 11 + .../Core/Empty/Cloud/IUnityEqualCheck.cs | 1 + .../Core/Empty/Cloud/IUnityEqualCheck.cs.meta | 11 + .../Empty/Cloud/InstantiateNetworkManager.cs | 1 + .../Cloud/InstantiateNetworkManager.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/JsonStructs.cs | 1 + .../Core/Empty/Cloud/JsonStructs.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/ListServer.cs | 1 + .../Core/Empty/Cloud/ListServer.cs.meta | 11 + .../Core/Empty/Cloud/ListServerBaseApi.cs | 1 + .../Empty/Cloud/ListServerBaseApi.cs.meta | 11 + .../Core/Empty/Cloud/ListServerClientApi.cs | 1 + .../Empty/Cloud/ListServerClientApi.cs.meta | 11 + .../Mirror/Core/Empty/Cloud/ListServerJson.cs | 1 + .../Core/Empty/Cloud/ListServerJson.cs.meta | 11 + .../Core/Empty/Cloud/ListServerServerApi.cs | 1 + .../Empty/Cloud/ListServerServerApi.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/Logger.cs | 1 + Assets/Mirror/Core/Empty/Cloud/Logger.cs.meta | 11 + .../Empty/Cloud/NetworkManagerListServer.cs | 1 + .../Cloud/NetworkManagerListServer.cs.meta | 11 + .../Cloud/NetworkManagerListServerPong.cs | 1 + .../NetworkManagerListServerPong.cs.meta | 11 + Assets/Mirror/Core/Empty/Cloud/Player.cs | 1 + Assets/Mirror/Core/Empty/Cloud/Player.cs.meta | 11 + .../Core/Empty/Cloud/QuickListServerDebug.cs | 1 + .../Empty/Cloud/QuickListServerDebug.cs.meta | 11 + .../Mirror/Core/Empty/Cloud/QuitButtonHUD.cs | 1 + .../Core/Empty/Cloud/QuitButtonHUD.cs.meta | 11 + .../Mirror/Core/Empty/Cloud/RequestCreator.cs | 1 + .../Core/Empty/Cloud/RequestCreator.cs.meta | 11 + .../Core/Empty/Cloud/ServerListManager.cs | 1 + .../Empty/Cloud/ServerListManager.cs.meta | 11 + .../Mirror/Core/Empty/Cloud/ServerListUI.cs | 1 + .../Core/Empty/Cloud/ServerListUI.cs.meta | 11 + .../Core/Empty/Cloud/ServerListUIItem.cs | 1 + .../Core/Empty/Cloud/ServerListUIItem.cs.meta | 11 + .../Mirror/Core/Empty/DotNetCompatibility.cs | 1 + .../Core/Empty/DotNetCompatibility.cs.meta | 11 + Assets/Mirror/Core/Empty/FallbackTransport.cs | 1 + .../Core/Empty/FallbackTransport.cs.meta | 11 + Assets/Mirror/Core/Empty/LogFactory.cs | 1 + Assets/Mirror/Core/Empty/LogFactory.cs.meta | 11 + Assets/Mirror/Core/Empty/LogFilter.cs | 1 + Assets/Mirror/Core/Empty/LogFilter.cs.meta | 11 + Assets/Mirror/Core/Empty/Logging.meta | 8 + .../Empty/Logging/ConsoleColorLogHandler.cs | 1 + .../Logging/ConsoleColorLogHandler.cs.meta | 11 + .../Empty/Logging/EditorLogSettingsLoader.cs | 1 + .../Logging/EditorLogSettingsLoader.cs.meta | 11 + .../Mirror/Core/Empty/Logging/LogFactory.cs | 1 + .../Core/Empty/Logging/LogFactory.cs.meta | 11 + .../Mirror/Core/Empty/Logging/LogSettings.cs | 2 + .../Core/Empty/Logging/LogSettings.cs.meta | 11 + .../Empty/Logging/NetworkHeadlessLogger.cs | 1 + .../Logging/NetworkHeadlessLogger.cs.meta | 11 + .../Core/Empty/Logging/NetworkLogSettings.cs | 1 + .../Empty/Logging/NetworkLogSettings.cs.meta | 11 + .../Mirror/Core/Empty/NetworkMatchChecker.cs | 1 + .../Core/Empty/NetworkMatchChecker.cs.meta | 11 + .../Mirror/Core/Empty/NetworkOwnerChecker.cs | 1 + .../Core/Empty/NetworkOwnerChecker.cs.meta | 11 + .../Core/Empty/NetworkProximityChecker.cs | 1 + .../Empty/NetworkProximityChecker.cs.meta | 11 + .../Mirror/Core/Empty/NetworkSceneChecker.cs | 1 + .../Core/Empty/NetworkSceneChecker.cs.meta | 11 + .../Mirror/Core/Empty/NetworkTransformBase.cs | 1 + .../Core/Empty/NetworkTransformBase.cs.meta | 11 + Assets/Mirror/Core/Empty/NetworkVisibility.cs | 1 + .../Core/Empty/NetworkVisibility.cs.meta | 11 + Assets/Mirror/Core/Empty/StringHash.cs | 1 + Assets/Mirror/Core/Empty/StringHash.cs.meta | 11 + Assets/Mirror/Core/Empty/SyncVar.cs | 1 + Assets/Mirror/Core/Empty/SyncVar.cs.meta | 11 + Assets/Mirror/Core/Empty/SyncVarGameObject.cs | 1 + .../Core/Empty/SyncVarGameObject.cs.meta | 11 + .../Core/Empty/SyncVarNetworkBehaviour.cs | 1 + .../Empty/SyncVarNetworkBehaviour.cs.meta | 11 + .../Core/Empty/SyncVarNetworkIdentity.cs | 1 + .../Core/Empty/SyncVarNetworkIdentity.cs.meta | 11 + Assets/Mirror/Core/HostMode.cs | 48 + Assets/Mirror/Core/HostMode.cs.meta | 11 + Assets/Mirror/Core/InterestManagement.cs | 146 ++ Assets/Mirror/Core/InterestManagement.cs.meta | 11 + Assets/Mirror/Core/InterestManagementBase.cs | 84 + .../Core/InterestManagementBase.cs.meta | 11 + Assets/Mirror/Core/LagCompensation.meta | 3 + Assets/Mirror/Core/LagCompensation/Capture.cs | 13 + .../Core/LagCompensation/Capture.cs.meta | 3 + .../Core/LagCompensation/HistoryBounds.cs | 139 ++ .../LagCompensation/HistoryBounds.cs.meta | 3 + .../Core/LagCompensation/LagCompensation.cs | 144 ++ .../LagCompensation/LagCompensation.cs.meta | 3 + .../LagCompensationSettings.cs | 19 + .../LagCompensationSettings.cs.meta | 3 + .../Core/LagCompensation/MinMaxBounds.cs | 61 + .../Core/LagCompensation/MinMaxBounds.cs.meta | 3 + Assets/Mirror/Core/LocalConnectionToClient.cs | 50 + .../Core/LocalConnectionToClient.cs.meta | 11 + Assets/Mirror/Core/LocalConnectionToServer.cs | 128 ++ .../Core/LocalConnectionToServer.cs.meta | 11 + Assets/Mirror/Core/Messages.cs | 122 ++ Assets/Mirror/Core/Messages.cs.meta | 11 + Assets/Mirror/Core/Mirror.asmdef | 16 + Assets/Mirror/Core/Mirror.asmdef.meta | 7 + Assets/Mirror/Core/NetworkAuthenticator.cs | 84 + .../Mirror/Core/NetworkAuthenticator.cs.meta | 11 + Assets/Mirror/Core/NetworkBehaviour.cs | 1361 ++++++++++++ Assets/Mirror/Core/NetworkBehaviour.cs.meta | 11 + Assets/Mirror/Core/NetworkBehaviourSyncVar.cs | 33 + .../Core/NetworkBehaviourSyncVar.cs.meta | 11 + Assets/Mirror/Core/NetworkClient.cs | 1725 +++++++++++++++ Assets/Mirror/Core/NetworkClient.cs.meta | 11 + .../Core/NetworkClient_TimeInterpolation.cs | 183 ++ .../NetworkClient_TimeInterpolation.cs.meta | 11 + Assets/Mirror/Core/NetworkConnection.cs | 206 ++ Assets/Mirror/Core/NetworkConnection.cs.meta | 11 + .../Mirror/Core/NetworkConnectionToClient.cs | 223 ++ .../Core/NetworkConnectionToClient.cs.meta | 11 + .../Mirror/Core/NetworkConnectionToServer.cs | 24 + .../Core/NetworkConnectionToServer.cs.meta | 11 + Assets/Mirror/Core/NetworkDiagnostics.cs | 63 + Assets/Mirror/Core/NetworkDiagnostics.cs.meta | 11 + Assets/Mirror/Core/NetworkIdentity.cs | 1384 ++++++++++++ Assets/Mirror/Core/NetworkIdentity.cs.meta | 11 + Assets/Mirror/Core/NetworkLoop.cs | 210 ++ Assets/Mirror/Core/NetworkLoop.cs.meta | 11 + Assets/Mirror/Core/NetworkManager.cs | 1467 +++++++++++++ Assets/Mirror/Core/NetworkManager.cs.meta | 11 + Assets/Mirror/Core/NetworkManagerHUD.cs | 155 ++ Assets/Mirror/Core/NetworkManagerHUD.cs.meta | 11 + Assets/Mirror/Core/NetworkMessage.cs | 4 + Assets/Mirror/Core/NetworkMessage.cs.meta | 11 + Assets/Mirror/Core/NetworkMessages.cs | 185 ++ Assets/Mirror/Core/NetworkMessages.cs.meta | 11 + Assets/Mirror/Core/NetworkReader.cs | 249 +++ Assets/Mirror/Core/NetworkReader.cs.meta | 11 + Assets/Mirror/Core/NetworkReaderExtensions.cs | 376 ++++ .../Core/NetworkReaderExtensions.cs.meta | 11 + Assets/Mirror/Core/NetworkReaderPool.cs | 45 + Assets/Mirror/Core/NetworkReaderPool.cs.meta | 11 + Assets/Mirror/Core/NetworkReaderPooled.cs | 15 + .../Mirror/Core/NetworkReaderPooled.cs.meta | 11 + Assets/Mirror/Core/NetworkServer.cs | 1864 +++++++++++++++++ Assets/Mirror/Core/NetworkServer.cs.meta | 11 + Assets/Mirror/Core/NetworkStartPosition.cs | 21 + .../Mirror/Core/NetworkStartPosition.cs.meta | 11 + Assets/Mirror/Core/NetworkTime.cs | 166 ++ Assets/Mirror/Core/NetworkTime.cs.meta | 11 + Assets/Mirror/Core/NetworkWriter.cs | 249 +++ Assets/Mirror/Core/NetworkWriter.cs.meta | 11 + Assets/Mirror/Core/NetworkWriterExtensions.cs | 415 ++++ .../Core/NetworkWriterExtensions.cs.meta | 11 + Assets/Mirror/Core/NetworkWriterPool.cs | 37 + Assets/Mirror/Core/NetworkWriterPool.cs.meta | 11 + Assets/Mirror/Core/NetworkWriterPooled.cs | 13 + .../Mirror/Core/NetworkWriterPooled.cs.meta | 11 + Assets/Mirror/Core/PortTransport.cs | 13 + Assets/Mirror/Core/PortTransport.cs.meta | 11 + Assets/Mirror/Core/RemoteCalls.cs | 138 ++ Assets/Mirror/Core/RemoteCalls.cs.meta | 11 + Assets/Mirror/Core/SnapshotInterpolation.meta | 8 + .../Core/SnapshotInterpolation/Snapshot.cs | 17 + .../SnapshotInterpolation/Snapshot.cs.meta | 11 + .../SnapshotInterpolation.cs | 390 ++++ .../SnapshotInterpolation.cs.meta | 11 + .../SnapshotInterpolationSettings.cs | 70 + .../SnapshotInterpolationSettings.cs.meta | 3 + .../SnapshotInterpolation/TimeSnapshot.cs | 15 + .../TimeSnapshot.cs.meta | 11 + Assets/Mirror/Core/SyncDictionary.cs | 326 +++ Assets/Mirror/Core/SyncDictionary.cs.meta | 11 + Assets/Mirror/Core/SyncList.cs | 420 ++++ Assets/Mirror/Core/SyncList.cs.meta | 11 + Assets/Mirror/Core/SyncObject.cs | 53 + Assets/Mirror/Core/SyncObject.cs.meta | 11 + Assets/Mirror/Core/SyncSet.cs | 352 ++++ Assets/Mirror/Core/SyncSet.cs.meta | 11 + Assets/Mirror/Core/Tools.meta | 3 + Assets/Mirror/Core/Tools/AccurateInterval.cs | 86 + .../Core/Tools/AccurateInterval.cs.meta | 11 + Assets/Mirror/Core/Tools/Compression.cs | 556 +++++ Assets/Mirror/Core/Tools/Compression.cs.meta | 11 + Assets/Mirror/Core/Tools/DeltaCompression.cs | 38 + .../Core/Tools/DeltaCompression.cs.meta | 11 + .../Core/Tools/ExponentialMovingAverage.cs | 53 + .../Tools/ExponentialMovingAverage.cs.meta | 11 + Assets/Mirror/Core/Tools/Extensions.cs | 64 + Assets/Mirror/Core/Tools/Extensions.cs.meta | 11 + Assets/Mirror/Core/Tools/Mathd.cs | 32 + Assets/Mirror/Core/Tools/Mathd.cs.meta | 11 + Assets/Mirror/Core/Tools/Pool.cs | 40 + Assets/Mirror/Core/Tools/Pool.cs.meta | 11 + Assets/Mirror/Core/Tools/Readme.txt | 1 + Assets/Mirror/Core/Tools/Readme.txt.meta | 3 + Assets/Mirror/Core/Tools/TimeSample.cs | 61 + Assets/Mirror/Core/Tools/TimeSample.cs.meta | 11 + Assets/Mirror/Core/Tools/Utils.cs | 188 ++ Assets/Mirror/Core/Tools/Utils.cs.meta | 11 + Assets/Mirror/Core/Tools/Vector3Long.cs | 125 ++ Assets/Mirror/Core/Tools/Vector3Long.cs.meta | 11 + Assets/Mirror/Core/Transport.cs | 191 ++ Assets/Mirror/Core/Transport.cs.meta | 11 + Assets/Mirror/Core/TransportError.cs | 17 + Assets/Mirror/Core/TransportError.cs.meta | 11 + Assets/Mirror/Core/WeaverFuse.cs | 22 + Assets/Mirror/Core/WeaverFuse.cs.meta | 3 + Assets/Mirror/Editor.meta | 8 + Assets/Mirror/Editor/AndroidManifestHelper.cs | 113 + .../Editor/AndroidManifestHelper.cs.meta | 11 + Assets/Mirror/Editor/EditorHelper.cs | 31 + Assets/Mirror/Editor/EditorHelper.cs.meta | 11 + Assets/Mirror/Editor/Empty.meta | 8 + .../Empty/EnterPlayModeSettingsCheck.cs | 1 + .../Empty/EnterPlayModeSettingsCheck.cs.meta | 11 + Assets/Mirror/Editor/Empty/LogLevelWindow.cs | 1 + .../Editor/Empty/LogLevelWindow.cs.meta | 11 + Assets/Mirror/Editor/Empty/Logging.meta | 8 + .../Editor/Empty/Logging/LogLevelWindow.cs | 1 + .../Empty/Logging/LogLevelWindow.cs.meta | 11 + .../Editor/Empty/Logging/LogLevelsGUI.cs | 1 + .../Editor/Empty/Logging/LogLevelsGUI.cs.meta | 11 + .../Editor/Empty/Logging/LogSettingsEditor.cs | 1 + .../Empty/Logging/LogSettingsEditor.cs.meta | 11 + .../Empty/Logging/NetworkLogSettingsEditor.cs | 1 + .../Logging/NetworkLogSettingsEditor.cs.meta | 11 + .../Editor/Empty/ScriptableObjectUtility.cs | 1 + .../Empty/ScriptableObjectUtility.cs.meta | 11 + Assets/Mirror/Editor/Empty/SyncVarDrawer.cs | 1 + .../Mirror/Editor/Empty/SyncVarDrawer.cs.meta | 3 + Assets/Mirror/Editor/Icon.meta | 8 + Assets/Mirror/Editor/Icon/MirrorIcon.png | Bin 0 -> 138247 bytes Assets/Mirror/Editor/Icon/MirrorIcon.png.meta | 110 + Assets/Mirror/Editor/InspectorHelper.cs | 77 + Assets/Mirror/Editor/InspectorHelper.cs.meta | 11 + Assets/Mirror/Editor/Mirror.Editor.asmdef | 19 + .../Mirror/Editor/Mirror.Editor.asmdef.meta | 7 + .../Editor/NetworkBehaviourInspector.cs | 104 + .../Editor/NetworkBehaviourInspector.cs.meta | 11 + .../Editor/NetworkInformationPreview.cs | 305 +++ .../Editor/NetworkInformationPreview.cs.meta | 11 + Assets/Mirror/Editor/NetworkManagerEditor.cs | 108 + .../Editor/NetworkManagerEditor.cs.meta | 11 + .../Mirror/Editor/NetworkScenePostProcess.cs | 98 + .../Editor/NetworkScenePostProcess.cs.meta | 11 + Assets/Mirror/Editor/SceneDrawer.cs | 47 + Assets/Mirror/Editor/SceneDrawer.cs.meta | 11 + .../Editor/SyncObjectCollectionsDrawer.cs | 83 + .../SyncObjectCollectionsDrawer.cs.meta | 3 + .../Mirror/Editor/SyncVarAttributeDrawer.cs | 28 + .../Editor/SyncVarAttributeDrawer.cs.meta | 11 + Assets/Mirror/Editor/Weaver.meta | 8 + Assets/Mirror/Editor/Weaver/AssemblyInfo.cs | 3 + .../Mirror/Editor/Weaver/AssemblyInfo.cs.meta | 11 + Assets/Mirror/Editor/Weaver/Empty.meta | 8 + .../Weaver/Empty/GenericArgumentResolver.cs | 1 + .../Empty/GenericArgumentResolver.cs.meta | 11 + .../Weaver/Empty/MessageClassProcessor.cs | 1 + .../Empty/MessageClassProcessor.cs.meta | 11 + Assets/Mirror/Editor/Weaver/Empty/Program.cs | 1 + .../Editor/Weaver/Empty/Program.cs.meta | 11 + .../Weaver/Empty/SyncDictionaryProcessor.cs | 1 + .../Empty/SyncDictionaryProcessor.cs.meta | 11 + .../Editor/Weaver/Empty/SyncEventProcessor.cs | 1 + .../Weaver/Empty/SyncEventProcessor.cs.meta | 11 + .../Editor/Weaver/Empty/SyncListProcessor.cs | 1 + .../Weaver/Empty/SyncListProcessor.cs.meta | 11 + Assets/Mirror/Editor/Weaver/EntryPoint.meta | 3 + .../EntryPoint/CompilationFinishedHook.cs | 188 ++ .../CompilationFinishedHook.cs.meta | 11 + .../EntryPoint/CompilationFinishedLogger.cs | 31 + .../CompilationFinishedLogger.cs.meta | 3 + .../Weaver/EntryPoint/EnterPlayModeHook.cs | 44 + .../EntryPoint/EnterPlayModeHook.cs.meta | 3 + .../Weaver/EntryPointILPostProcessor.meta | 3 + .../CompiledAssemblyFromFile.cs | 31 + .../CompiledAssemblyFromFile.cs.meta | 3 + .../ILPostProcessorAssemblyResolver.cs | 199 ++ .../ILPostProcessorAssemblyResolver.cs.meta | 3 + .../ILPostProcessorFromFile.cs | 53 + .../ILPostProcessorFromFile.cs.meta | 3 + .../ILPostProcessorHook.cs | 143 ++ .../ILPostProcessorHook.cs.meta | 3 + .../ILPostProcessorLogger.cs | 67 + .../ILPostProcessorLogger.cs.meta | 3 + .../ILPostProcessorReflectionImporter.cs | 36 + .../ILPostProcessorReflectionImporter.cs.meta | 3 + ...PostProcessorReflectionImporterProvider.cs | 16 + ...rocessorReflectionImporterProvider.cs.meta | 3 + Assets/Mirror/Editor/Weaver/Extensions.cs | 359 ++++ .../Mirror/Editor/Weaver/Extensions.cs.meta | 11 + Assets/Mirror/Editor/Weaver/Helpers.cs | 26 + Assets/Mirror/Editor/Weaver/Helpers.cs.meta | 11 + Assets/Mirror/Editor/Weaver/Logger.cs | 13 + Assets/Mirror/Editor/Weaver/Logger.cs.meta | 11 + Assets/Mirror/Editor/Weaver/Processors.meta | 8 + .../Weaver/Processors/CommandProcessor.cs | 130 ++ .../Processors/CommandProcessor.cs.meta | 11 + .../Weaver/Processors/MethodProcessor.cs | 139 ++ .../Weaver/Processors/MethodProcessor.cs.meta | 11 + .../Processors/MonoBehaviourProcessor.cs | 56 + .../Processors/MonoBehaviourProcessor.cs.meta | 11 + .../Processors/NetworkBehaviourProcessor.cs | 1041 +++++++++ .../NetworkBehaviourProcessor.cs.meta | 11 + .../Processors/ReaderWriterProcessor.cs | 216 ++ .../Processors/ReaderWriterProcessor.cs.meta | 11 + .../Editor/Weaver/Processors/RpcProcessor.cs | 104 + .../Weaver/Processors/RpcProcessor.cs.meta | 11 + .../ServerClientAttributeProcessor.cs | 163 ++ .../ServerClientAttributeProcessor.cs.meta | 11 + .../Processors/SyncObjectInitializer.cs | 39 + .../Processors/SyncObjectInitializer.cs.meta | 11 + .../Weaver/Processors/SyncObjectProcessor.cs | 90 + .../Processors/SyncObjectProcessor.cs.meta | 11 + .../SyncVarAttributeAccessReplacer.cs | 206 ++ .../SyncVarAttributeAccessReplacer.cs.meta | 11 + .../Processors/SyncVarAttributeProcessor.cs | 490 +++++ .../SyncVarAttributeProcessor.cs.meta | 11 + .../Weaver/Processors/TargetRpcProcessor.cs | 159 ++ .../Processors/TargetRpcProcessor.cs.meta | 11 + Assets/Mirror/Editor/Weaver/Readers.cs | 385 ++++ Assets/Mirror/Editor/Weaver/Readers.cs.meta | 11 + Assets/Mirror/Editor/Weaver/Resolvers.cs | 94 + Assets/Mirror/Editor/Weaver/Resolvers.cs.meta | 11 + .../Editor/Weaver/SyncVarAccessLists.cs | 32 + .../Editor/Weaver/SyncVarAccessLists.cs.meta | 3 + .../Editor/Weaver/TypeReferenceComparer.cs | 15 + .../Weaver/TypeReferenceComparer.cs.meta | 11 + .../Editor/Weaver/Unity.Mirror.CodeGen.asmdef | 21 + .../Weaver/Unity.Mirror.CodeGen.asmdef.meta | 7 + Assets/Mirror/Editor/Weaver/Weaver.cs | 269 +++ Assets/Mirror/Editor/Weaver/Weaver.cs.meta | 11 + .../Mirror/Editor/Weaver/WeaverExceptions.cs | 26 + .../Editor/Weaver/WeaverExceptions.cs.meta | 11 + Assets/Mirror/Editor/Weaver/WeaverTypes.cs | 171 ++ .../Mirror/Editor/Weaver/WeaverTypes.cs.meta | 3 + Assets/Mirror/Editor/Weaver/Writers.cs | 341 +++ Assets/Mirror/Editor/Weaver/Writers.cs.meta | 11 + Assets/Mirror/Editor/Welcome.cs | 23 + Assets/Mirror/Editor/Welcome.cs.meta | 11 + Assets/Mirror/Notice.txt | 123 ++ Assets/Mirror/Notice.txt.meta | 7 + Assets/Mirror/Plugins.meta | 8 + Assets/Mirror/Plugins/Mono.Cecil.meta | 8 + Assets/Mirror/Plugins/Mono.Cecil/License.txt | 25 + .../Plugins/Mono.Cecil/License.txt.meta | 7 + .../Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll | Bin 0 -> 43520 bytes .../Mono.Cecil/Mono.CecilX.Mdb.dll.meta | 92 + .../Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll | Bin 0 -> 87552 bytes .../Mono.Cecil/Mono.CecilX.Pdb.dll.meta | 92 + .../Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll | Bin 0 -> 27648 bytes .../Mono.Cecil/Mono.CecilX.Rocks.dll.meta | 92 + .../Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll | Bin 0 -> 340992 bytes .../Plugins/Mono.Cecil/Mono.CecilX.dll.meta | 94 + Assets/Mirror/Presets.meta | 8 + Assets/Mirror/Presets/NetworkTransform.meta | 8 + .../ClientAuth-Balanced.preset | 124 ++ .../ClientAuth-Balanced.preset.meta | 8 + .../ClientAuth-FastPaced.preset | 124 ++ .../ClientAuth-FastPaced.preset.meta | 8 + .../ClientAuth-VeryCasual.preset | 124 ++ .../ClientAuth-VeryCasual.preset.meta | 8 + Assets/Mirror/Readme.txt | 15 + Assets/Mirror/Readme.txt.meta | 7 + Assets/Mirror/Transports.meta | 8 + Assets/Mirror/Transports/KCP.meta | 8 + Assets/Mirror/Transports/KCP/KcpTransport.cs | 366 ++++ .../Transports/KCP/KcpTransport.cs.meta | 11 + Assets/Mirror/Transports/KCP/kcp2k.meta | 8 + Assets/Mirror/Transports/KCP/kcp2k/KCP.asmdef | 16 + .../Transports/KCP/kcp2k/KCP.asmdef.meta | 7 + .../Mirror/Transports/KCP/kcp2k/LICENSE.txt | 24 + .../Transports/KCP/kcp2k/LICENSE.txt.meta | 7 + .../Mirror/Transports/KCP/kcp2k/VERSION.txt | 238 +++ .../Transports/KCP/kcp2k/VERSION.txt.meta | 7 + Assets/Mirror/Transports/KCP/kcp2k/empty.meta | 3 + .../KCP/kcp2k/empty/KcpClientConnection.cs | 1 + .../kcp2k/empty/KcpClientConnection.cs.meta | 3 + .../empty/KcpClientConnectionNonAlloc.cs | 1 + .../empty/KcpClientConnectionNonAlloc.cs.meta | 3 + .../KCP/kcp2k/empty/KcpClientNonAlloc.cs | 1 + .../KCP/kcp2k/empty/KcpClientNonAlloc.cs.meta | 3 + .../empty/KcpServerConnectionNonAlloc.cs | 1 + .../empty/KcpServerConnectionNonAlloc.cs.meta | 3 + .../KCP/kcp2k/empty/KcpServerNonAlloc.cs | 1 + .../KCP/kcp2k/empty/KcpServerNonAlloc.cs.meta | 3 + .../Transports/KCP/kcp2k/highlevel.meta | 8 + .../Transports/KCP/kcp2k/highlevel/Common.cs | 75 + .../KCP/kcp2k/highlevel/Common.cs.meta | 3 + .../KCP/kcp2k/highlevel/ErrorCode.cs | 15 + .../KCP/kcp2k/highlevel/ErrorCode.cs.meta | 3 + .../KCP/kcp2k/highlevel/Extensions.cs | 166 ++ .../KCP/kcp2k/highlevel/Extensions.cs.meta | 3 + .../KCP/kcp2k/highlevel/KcpChannel.cs | 10 + .../KCP/kcp2k/highlevel/KcpChannel.cs.meta | 3 + .../KCP/kcp2k/highlevel/KcpClient.cs | 226 ++ .../KCP/kcp2k/highlevel/KcpClient.cs.meta | 3 + .../KCP/kcp2k/highlevel/KcpConfig.cs | 97 + .../KCP/kcp2k/highlevel/KcpConfig.cs.meta | 3 + .../KCP/kcp2k/highlevel/KcpHeader.cs | 19 + .../KCP/kcp2k/highlevel/KcpHeader.cs.meta | 3 + .../Transports/KCP/kcp2k/highlevel/KcpPeer.cs | 819 ++++++++ .../KCP/kcp2k/highlevel/KcpPeer.cs.meta | 3 + .../KCP/kcp2k/highlevel/KcpServer.cs | 377 ++++ .../KCP/kcp2k/highlevel/KcpServer.cs.meta | 3 + .../kcp2k/highlevel/KcpServerConnection.cs | 22 + .../highlevel/KcpServerConnection.cs.meta | 3 + .../Transports/KCP/kcp2k/highlevel/Log.cs | 14 + .../KCP/kcp2k/highlevel/Log.cs.meta | 11 + Assets/Mirror/Transports/KCP/kcp2k/kcp.meta | 8 + .../Transports/KCP/kcp2k/kcp/AckItem.cs | 8 + .../Transports/KCP/kcp2k/kcp/AckItem.cs.meta | 11 + .../Transports/KCP/kcp2k/kcp/AssemblyInfo.cs | 3 + .../KCP/kcp2k/kcp/AssemblyInfo.cs.meta | 3 + Assets/Mirror/Transports/KCP/kcp2k/kcp/Kcp.cs | 1118 ++++++++++ .../Transports/KCP/kcp2k/kcp/Kcp.cs.meta | 11 + .../Mirror/Transports/KCP/kcp2k/kcp/Pool.cs | 46 + .../Transports/KCP/kcp2k/kcp/Pool.cs.meta | 11 + .../Transports/KCP/kcp2k/kcp/Segment.cs | 78 + .../Transports/KCP/kcp2k/kcp/Segment.cs.meta | 11 + .../Mirror/Transports/KCP/kcp2k/kcp/Utils.cs | 76 + .../Transports/KCP/kcp2k/kcp/Utils.cs.meta | 11 + Assets/Mirror/Transports/Latency.meta | 8 + .../Transports/Latency/LatencySimulation.cs | 319 +++ .../Latency/LatencySimulation.cs.meta | 11 + Assets/Mirror/Transports/Middleware.meta | 8 + .../Middleware/MiddlewareTransport.cs | 61 + .../Middleware/MiddlewareTransport.cs.meta | 11 + .../Transports/Mirror.Transports.asmdef | 19 + .../Transports/Mirror.Transports.asmdef.meta | 7 + Assets/Mirror/Transports/Multiplex.meta | 8 + .../Multiplex/MultiplexTransport.cs | 331 +++ .../Multiplex/MultiplexTransport.cs.meta | 11 + Assets/Mirror/Transports/SimpleWeb.meta | 8 + .../Transports/SimpleWeb/SimpleWeb.meta | 8 + .../SimpleWeb/SimpleWeb/AssemblyInfo.cs | 7 + .../SimpleWeb/SimpleWeb/AssemblyInfo.cs.meta | 11 + .../SimpleWeb/SimpleWeb/CHANGELOG.md | 48 + .../SimpleWeb/SimpleWeb/CHANGELOG.md.meta | 7 + .../SimpleWeb/SimpleWeb/Client.meta | 8 + .../SimpleWeb/Client/SimpleWebClient.cs | 102 + .../SimpleWeb/Client/SimpleWebClient.cs.meta | 11 + .../SimpleWeb/Client/StandAlone.meta | 8 + .../Client/StandAlone/ClientHandshake.cs | 88 + .../Client/StandAlone/ClientHandshake.cs.meta | 11 + .../Client/StandAlone/ClientSslHelper.cs | 47 + .../Client/StandAlone/ClientSslHelper.cs.meta | 11 + .../StandAlone/WebSocketClientStandAlone.cs | 140 ++ .../WebSocketClientStandAlone.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Client/Webgl.meta | 8 + .../SimpleWeb/Client/Webgl/SimpleWebJSLib.cs | 34 + .../Client/Webgl/SimpleWebJSLib.cs.meta | 11 + .../Client/Webgl/WebSocketClientWebGl.cs | 144 ++ .../Client/Webgl/WebSocketClientWebGl.cs.meta | 11 + .../SimpleWeb/Client/Webgl/plugin.meta | 8 + .../Client/Webgl/plugin/SimpleWeb.jslib | 114 + .../Client/Webgl/plugin/SimpleWeb.jslib.meta | 37 + .../SimpleWeb/SimpleWeb/Common.meta | 8 + .../SimpleWeb/SimpleWeb/Common/BufferPool.cs | 249 +++ .../SimpleWeb/Common/BufferPool.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/Connection.cs | 133 ++ .../SimpleWeb/Common/Connection.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/Constants.cs | 77 + .../SimpleWeb/Common/Constants.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/EventType.cs | 10 + .../SimpleWeb/Common/EventType.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/Log.cs | 108 + .../SimpleWeb/SimpleWeb/Common/Log.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/Message.cs | 49 + .../SimpleWeb/Common/Message.cs.meta | 11 + .../SimpleWeb/Common/MessageProcessor.cs | 175 ++ .../SimpleWeb/Common/MessageProcessor.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/ReadHelper.cs | 123 ++ .../SimpleWeb/Common/ReadHelper.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/ReceiveLoop.cs | 254 +++ .../SimpleWeb/Common/ReceiveLoop.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/Request.cs | 26 + .../SimpleWeb/Common/Request.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/SendLoop.cs | 225 ++ .../SimpleWeb/Common/SendLoop.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/TcpConfig.cs | 26 + .../SimpleWeb/Common/TcpConfig.cs.meta | 11 + .../SimpleWeb/SimpleWeb/Common/Utils.cs | 13 + .../SimpleWeb/SimpleWeb/Common/Utils.cs.meta | 11 + .../Transports/SimpleWeb/SimpleWeb/LICENSE | 21 + .../SimpleWeb/SimpleWeb/LICENSE.meta | 7 + .../Transports/SimpleWeb/SimpleWeb/README.txt | 19 + .../SimpleWeb/SimpleWeb/README.txt.meta | 7 + .../SimpleWeb/SimpleWeb/Server.meta | 8 + .../SimpleWeb/Server/ServerHandshake.cs | 156 ++ .../SimpleWeb/Server/ServerHandshake.cs.meta | 11 + .../SimpleWeb/Server/ServerSslHelper.cs | 82 + .../SimpleWeb/Server/ServerSslHelper.cs.meta | 11 + .../SimpleWeb/Server/SimpleWebServer.cs | 117 ++ .../SimpleWeb/Server/SimpleWebServer.cs.meta | 11 + .../SimpleWeb/Server/WebSocketServer.cs | 264 +++ .../SimpleWeb/Server/WebSocketServer.cs.meta | 11 + .../SimpleWeb/SimpleWebTransport.asmdef | 14 + .../SimpleWeb/SimpleWebTransport.asmdef.meta | 7 + .../SimpleWeb/SimpleWeb/SslConfigLoader.cs | 49 + .../SimpleWeb/SslConfigLoader.cs.meta | 11 + .../SimpleWeb/SimpleWebTransport.cs | 304 +++ .../SimpleWeb/SimpleWebTransport.cs.meta | 11 + Assets/Mirror/Transports/Telepathy.meta | 8 + .../Transports/Telepathy/Telepathy.meta | 8 + .../Transports/Telepathy/Telepathy/Client.cs | 361 ++++ .../Telepathy/Telepathy/Client.cs.meta | 11 + .../Transports/Telepathy/Telepathy/Common.cs | 39 + .../Telepathy/Telepathy/Common.cs.meta | 11 + .../Telepathy/Telepathy/ConnectionState.cs | 35 + .../Telepathy/ConnectionState.cs.meta | 11 + .../Transports/Telepathy/Telepathy/Empty.meta | 8 + .../Telepathy/Telepathy/Empty/Logger.cs | 1 + .../Telepathy/Telepathy/Empty/Logger.cs.meta | 11 + .../Telepathy/Telepathy/Empty/Message.cs | 1 + .../Telepathy/Telepathy/Empty/Message.cs.meta | 11 + .../Telepathy/Telepathy/Empty/SafeQueue.cs | 1 + .../Telepathy/Empty/SafeQueue.cs.meta | 11 + .../Telepathy/Empty/ThreadExtensions.cs | 1 + .../Telepathy/Empty/ThreadExtensions.cs.meta | 11 + .../Telepathy/Telepathy/EventType.cs | 9 + .../Telepathy/Telepathy/EventType.cs.meta | 11 + .../Transports/Telepathy/Telepathy/LICENSE | 21 + .../Telepathy/Telepathy/LICENSE.meta | 7 + .../Transports/Telepathy/Telepathy/Log.cs | 15 + .../Telepathy/Telepathy/Log.cs.meta | 11 + .../Telepathy/MagnificentReceivePipe.cs | 222 ++ .../Telepathy/MagnificentReceivePipe.cs.meta | 11 + .../Telepathy/MagnificentSendPipe.cs | 165 ++ .../Telepathy/MagnificentSendPipe.cs.meta | 11 + .../Telepathy/NetworkStreamExtensions.cs | 67 + .../Telepathy/NetworkStreamExtensions.cs.meta | 11 + .../Transports/Telepathy/Telepathy/Pool.cs | 34 + .../Telepathy/Telepathy/Pool.cs.meta | 11 + .../Transports/Telepathy/Telepathy/Server.cs | 402 ++++ .../Telepathy/Telepathy/Server.cs.meta | 11 + .../Telepathy/Telepathy/Telepathy.asmdef | 12 + .../Telepathy/Telepathy/Telepathy.asmdef.meta | 7 + .../Telepathy/Telepathy/ThreadFunctions.cs | 244 +++ .../Telepathy/ThreadFunctions.cs.meta | 11 + .../Transports/Telepathy/Telepathy/Utils.cs | 23 + .../Telepathy/Telepathy/Utils.cs.meta | 11 + .../Transports/Telepathy/Telepathy/VERSION | 62 + .../Telepathy/Telepathy/VERSION.meta | 7 + .../Telepathy/TelepathyTransport.cs | 274 +++ .../Telepathy/TelepathyTransport.cs.meta | 11 + Assets/Mirror/Version.txt | 1 + Assets/Mirror/Version.txt.meta | 7 + 686 files changed, 43191 insertions(+) create mode 100644 Assets/Mirror.meta create mode 100644 Assets/Mirror/Authenticators.meta create mode 100644 Assets/Mirror/Authenticators/BasicAuthenticator.cs create mode 100644 Assets/Mirror/Authenticators/BasicAuthenticator.cs.meta create mode 100644 Assets/Mirror/Authenticators/DeviceAuthenticator.cs create mode 100644 Assets/Mirror/Authenticators/DeviceAuthenticator.cs.meta create mode 100644 Assets/Mirror/Authenticators/Mirror.Authenticators.asmdef create mode 100644 Assets/Mirror/Authenticators/Mirror.Authenticators.asmdef.meta create mode 100644 Assets/Mirror/Authenticators/TimeoutAuthenticator.cs create mode 100644 Assets/Mirror/Authenticators/TimeoutAuthenticator.cs.meta create mode 100644 Assets/Mirror/CompilerSymbols.meta create mode 100644 Assets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef create mode 100644 Assets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef.meta create mode 100644 Assets/Mirror/CompilerSymbols/PreprocessorDefine.cs create mode 100644 Assets/Mirror/CompilerSymbols/PreprocessorDefine.cs.meta create mode 100644 Assets/Mirror/Components.meta create mode 100644 Assets/Mirror/Components/AssemblyInfo.cs create mode 100644 Assets/Mirror/Components/AssemblyInfo.cs.meta create mode 100644 Assets/Mirror/Components/Discovery.meta create mode 100644 Assets/Mirror/Components/Discovery/NetworkDiscovery.cs create mode 100644 Assets/Mirror/Components/Discovery/NetworkDiscovery.cs.meta create mode 100644 Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs create mode 100644 Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs.meta create mode 100644 Assets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs create mode 100644 Assets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs.meta create mode 100644 Assets/Mirror/Components/Discovery/ServerRequest.cs create mode 100644 Assets/Mirror/Components/Discovery/ServerRequest.cs.meta create mode 100644 Assets/Mirror/Components/Discovery/ServerResponse.cs create mode 100644 Assets/Mirror/Components/Discovery/ServerResponse.cs.meta create mode 100644 Assets/Mirror/Components/Experimental.meta create mode 100644 Assets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs create mode 100644 Assets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs.meta create mode 100644 Assets/Mirror/Components/Experimental/NetworkRigidbody.cs create mode 100644 Assets/Mirror/Components/Experimental/NetworkRigidbody.cs.meta create mode 100644 Assets/Mirror/Components/Experimental/NetworkRigidbody2D.cs create mode 100644 Assets/Mirror/Components/Experimental/NetworkRigidbody2D.cs.meta create mode 100644 Assets/Mirror/Components/GUIConsole.cs create mode 100644 Assets/Mirror/Components/GUIConsole.cs.meta create mode 100644 Assets/Mirror/Components/InterestManagement.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Distance.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs create mode 100644 Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs create mode 100644 Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Match.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs create mode 100644 Assets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs create mode 100644 Assets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Scene.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs create mode 100644 Assets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs.meta create mode 100644 Assets/Mirror/Components/InterestManagement/SpatialHashing.meta create mode 100644 Assets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs create mode 100644 Assets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs.meta create mode 100644 Assets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs create mode 100644 Assets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Team.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs create mode 100644 Assets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs.meta create mode 100644 Assets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs create mode 100644 Assets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs.meta create mode 100644 Assets/Mirror/Components/LagCompensation.meta create mode 100644 Assets/Mirror/Components/LagCompensation/HistoryCollider.cs create mode 100644 Assets/Mirror/Components/LagCompensation/HistoryCollider.cs.meta create mode 100644 Assets/Mirror/Components/Mirror.Components.asmdef create mode 100644 Assets/Mirror/Components/Mirror.Components.asmdef.meta create mode 100644 Assets/Mirror/Components/NetworkAnimator.cs create mode 100644 Assets/Mirror/Components/NetworkAnimator.cs.meta create mode 100644 Assets/Mirror/Components/NetworkLobbyManager.cs create mode 100644 Assets/Mirror/Components/NetworkLobbyManager.cs.meta create mode 100644 Assets/Mirror/Components/NetworkLobbyPlayer.cs create mode 100644 Assets/Mirror/Components/NetworkLobbyPlayer.cs.meta create mode 100644 Assets/Mirror/Components/NetworkPingDisplay.cs create mode 100644 Assets/Mirror/Components/NetworkPingDisplay.cs.meta create mode 100644 Assets/Mirror/Components/NetworkRigidbody.meta create mode 100644 Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs create mode 100644 Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs.meta create mode 100644 Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs create mode 100644 Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs.meta create mode 100644 Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs create mode 100644 Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs.meta create mode 100644 Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs create mode 100644 Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs.meta create mode 100644 Assets/Mirror/Components/NetworkRoomManager.cs create mode 100644 Assets/Mirror/Components/NetworkRoomManager.cs.meta create mode 100644 Assets/Mirror/Components/NetworkRoomPlayer.cs create mode 100644 Assets/Mirror/Components/NetworkRoomPlayer.cs.meta create mode 100644 Assets/Mirror/Components/NetworkStatistics.cs create mode 100644 Assets/Mirror/Components/NetworkStatistics.cs.meta create mode 100644 Assets/Mirror/Components/NetworkTransform.meta create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransform.cs create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransform.cs.meta create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs.meta create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs.meta create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs.meta create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs create mode 100644 Assets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs.meta create mode 100644 Assets/Mirror/Components/NetworkTransform/TransformSnapshot.cs create mode 100644 Assets/Mirror/Components/NetworkTransform/TransformSnapshot.cs.meta create mode 100644 Assets/Mirror/Components/RemoteStatistics.cs create mode 100644 Assets/Mirror/Components/RemoteStatistics.cs.meta create mode 100644 Assets/Mirror/Core.meta create mode 100644 Assets/Mirror/Core/AssemblyInfo.cs create mode 100644 Assets/Mirror/Core/AssemblyInfo.cs.meta create mode 100644 Assets/Mirror/Core/Attributes.cs create mode 100644 Assets/Mirror/Core/Attributes.cs.meta create mode 100644 Assets/Mirror/Core/Batching.meta create mode 100644 Assets/Mirror/Core/Batching/Batcher.cs create mode 100644 Assets/Mirror/Core/Batching/Batcher.cs.meta create mode 100644 Assets/Mirror/Core/Batching/Unbatcher.cs create mode 100644 Assets/Mirror/Core/Batching/Unbatcher.cs.meta create mode 100644 Assets/Mirror/Core/ConnectionQuality.cs create mode 100644 Assets/Mirror/Core/ConnectionQuality.cs.meta create mode 100644 Assets/Mirror/Core/Empty.meta create mode 100644 Assets/Mirror/Core/Empty/ClientScene.cs create mode 100644 Assets/Mirror/Core/Empty/ClientScene.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ApiConnector.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ApiConnector.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ApiUpdater.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ApiUpdater.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/Ball.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/Ball.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/BallManager.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/BallManager.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/BaseApi.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/BaseApi.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/Events.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/Events.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/Extensions.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/Extensions.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/IRequestCreator.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/IRequestCreator.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/JsonStructs.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/JsonStructs.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServer.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServer.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServerJson.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServerJson.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/Logger.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/Logger.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/Player.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/Player.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/RequestCreator.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/RequestCreator.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ServerListManager.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ServerListManager.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ServerListUI.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ServerListUI.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs create mode 100644 Assets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs.meta create mode 100644 Assets/Mirror/Core/Empty/DotNetCompatibility.cs create mode 100644 Assets/Mirror/Core/Empty/DotNetCompatibility.cs.meta create mode 100644 Assets/Mirror/Core/Empty/FallbackTransport.cs create mode 100644 Assets/Mirror/Core/Empty/FallbackTransport.cs.meta create mode 100644 Assets/Mirror/Core/Empty/LogFactory.cs create mode 100644 Assets/Mirror/Core/Empty/LogFactory.cs.meta create mode 100644 Assets/Mirror/Core/Empty/LogFilter.cs create mode 100644 Assets/Mirror/Core/Empty/LogFilter.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Logging.meta create mode 100644 Assets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs create mode 100644 Assets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs create mode 100644 Assets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Logging/LogFactory.cs create mode 100644 Assets/Mirror/Core/Empty/Logging/LogFactory.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Logging/LogSettings.cs create mode 100644 Assets/Mirror/Core/Empty/Logging/LogSettings.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs create mode 100644 Assets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs.meta create mode 100644 Assets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs create mode 100644 Assets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs.meta create mode 100644 Assets/Mirror/Core/Empty/NetworkMatchChecker.cs create mode 100644 Assets/Mirror/Core/Empty/NetworkMatchChecker.cs.meta create mode 100644 Assets/Mirror/Core/Empty/NetworkOwnerChecker.cs create mode 100644 Assets/Mirror/Core/Empty/NetworkOwnerChecker.cs.meta create mode 100644 Assets/Mirror/Core/Empty/NetworkProximityChecker.cs create mode 100644 Assets/Mirror/Core/Empty/NetworkProximityChecker.cs.meta create mode 100644 Assets/Mirror/Core/Empty/NetworkSceneChecker.cs create mode 100644 Assets/Mirror/Core/Empty/NetworkSceneChecker.cs.meta create mode 100644 Assets/Mirror/Core/Empty/NetworkTransformBase.cs create mode 100644 Assets/Mirror/Core/Empty/NetworkTransformBase.cs.meta create mode 100644 Assets/Mirror/Core/Empty/NetworkVisibility.cs create mode 100644 Assets/Mirror/Core/Empty/NetworkVisibility.cs.meta create mode 100644 Assets/Mirror/Core/Empty/StringHash.cs create mode 100644 Assets/Mirror/Core/Empty/StringHash.cs.meta create mode 100644 Assets/Mirror/Core/Empty/SyncVar.cs create mode 100644 Assets/Mirror/Core/Empty/SyncVar.cs.meta create mode 100644 Assets/Mirror/Core/Empty/SyncVarGameObject.cs create mode 100644 Assets/Mirror/Core/Empty/SyncVarGameObject.cs.meta create mode 100644 Assets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs create mode 100644 Assets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs.meta create mode 100644 Assets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs create mode 100644 Assets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs.meta create mode 100644 Assets/Mirror/Core/HostMode.cs create mode 100644 Assets/Mirror/Core/HostMode.cs.meta create mode 100644 Assets/Mirror/Core/InterestManagement.cs create mode 100644 Assets/Mirror/Core/InterestManagement.cs.meta create mode 100644 Assets/Mirror/Core/InterestManagementBase.cs create mode 100644 Assets/Mirror/Core/InterestManagementBase.cs.meta create mode 100644 Assets/Mirror/Core/LagCompensation.meta create mode 100644 Assets/Mirror/Core/LagCompensation/Capture.cs create mode 100644 Assets/Mirror/Core/LagCompensation/Capture.cs.meta create mode 100644 Assets/Mirror/Core/LagCompensation/HistoryBounds.cs create mode 100644 Assets/Mirror/Core/LagCompensation/HistoryBounds.cs.meta create mode 100644 Assets/Mirror/Core/LagCompensation/LagCompensation.cs create mode 100644 Assets/Mirror/Core/LagCompensation/LagCompensation.cs.meta create mode 100644 Assets/Mirror/Core/LagCompensation/LagCompensationSettings.cs create mode 100644 Assets/Mirror/Core/LagCompensation/LagCompensationSettings.cs.meta create mode 100644 Assets/Mirror/Core/LagCompensation/MinMaxBounds.cs create mode 100644 Assets/Mirror/Core/LagCompensation/MinMaxBounds.cs.meta create mode 100644 Assets/Mirror/Core/LocalConnectionToClient.cs create mode 100644 Assets/Mirror/Core/LocalConnectionToClient.cs.meta create mode 100644 Assets/Mirror/Core/LocalConnectionToServer.cs create mode 100644 Assets/Mirror/Core/LocalConnectionToServer.cs.meta create mode 100644 Assets/Mirror/Core/Messages.cs create mode 100644 Assets/Mirror/Core/Messages.cs.meta create mode 100644 Assets/Mirror/Core/Mirror.asmdef create mode 100644 Assets/Mirror/Core/Mirror.asmdef.meta create mode 100644 Assets/Mirror/Core/NetworkAuthenticator.cs create mode 100644 Assets/Mirror/Core/NetworkAuthenticator.cs.meta create mode 100644 Assets/Mirror/Core/NetworkBehaviour.cs create mode 100644 Assets/Mirror/Core/NetworkBehaviour.cs.meta create mode 100644 Assets/Mirror/Core/NetworkBehaviourSyncVar.cs create mode 100644 Assets/Mirror/Core/NetworkBehaviourSyncVar.cs.meta create mode 100644 Assets/Mirror/Core/NetworkClient.cs create mode 100644 Assets/Mirror/Core/NetworkClient.cs.meta create mode 100644 Assets/Mirror/Core/NetworkClient_TimeInterpolation.cs create mode 100644 Assets/Mirror/Core/NetworkClient_TimeInterpolation.cs.meta create mode 100644 Assets/Mirror/Core/NetworkConnection.cs create mode 100644 Assets/Mirror/Core/NetworkConnection.cs.meta create mode 100644 Assets/Mirror/Core/NetworkConnectionToClient.cs create mode 100644 Assets/Mirror/Core/NetworkConnectionToClient.cs.meta create mode 100644 Assets/Mirror/Core/NetworkConnectionToServer.cs create mode 100644 Assets/Mirror/Core/NetworkConnectionToServer.cs.meta create mode 100644 Assets/Mirror/Core/NetworkDiagnostics.cs create mode 100644 Assets/Mirror/Core/NetworkDiagnostics.cs.meta create mode 100644 Assets/Mirror/Core/NetworkIdentity.cs create mode 100644 Assets/Mirror/Core/NetworkIdentity.cs.meta create mode 100644 Assets/Mirror/Core/NetworkLoop.cs create mode 100644 Assets/Mirror/Core/NetworkLoop.cs.meta create mode 100644 Assets/Mirror/Core/NetworkManager.cs create mode 100644 Assets/Mirror/Core/NetworkManager.cs.meta create mode 100644 Assets/Mirror/Core/NetworkManagerHUD.cs create mode 100644 Assets/Mirror/Core/NetworkManagerHUD.cs.meta create mode 100644 Assets/Mirror/Core/NetworkMessage.cs create mode 100644 Assets/Mirror/Core/NetworkMessage.cs.meta create mode 100644 Assets/Mirror/Core/NetworkMessages.cs create mode 100644 Assets/Mirror/Core/NetworkMessages.cs.meta create mode 100644 Assets/Mirror/Core/NetworkReader.cs create mode 100644 Assets/Mirror/Core/NetworkReader.cs.meta create mode 100644 Assets/Mirror/Core/NetworkReaderExtensions.cs create mode 100644 Assets/Mirror/Core/NetworkReaderExtensions.cs.meta create mode 100644 Assets/Mirror/Core/NetworkReaderPool.cs create mode 100644 Assets/Mirror/Core/NetworkReaderPool.cs.meta create mode 100644 Assets/Mirror/Core/NetworkReaderPooled.cs create mode 100644 Assets/Mirror/Core/NetworkReaderPooled.cs.meta create mode 100644 Assets/Mirror/Core/NetworkServer.cs create mode 100644 Assets/Mirror/Core/NetworkServer.cs.meta create mode 100644 Assets/Mirror/Core/NetworkStartPosition.cs create mode 100644 Assets/Mirror/Core/NetworkStartPosition.cs.meta create mode 100644 Assets/Mirror/Core/NetworkTime.cs create mode 100644 Assets/Mirror/Core/NetworkTime.cs.meta create mode 100644 Assets/Mirror/Core/NetworkWriter.cs create mode 100644 Assets/Mirror/Core/NetworkWriter.cs.meta create mode 100644 Assets/Mirror/Core/NetworkWriterExtensions.cs create mode 100644 Assets/Mirror/Core/NetworkWriterExtensions.cs.meta create mode 100644 Assets/Mirror/Core/NetworkWriterPool.cs create mode 100644 Assets/Mirror/Core/NetworkWriterPool.cs.meta create mode 100644 Assets/Mirror/Core/NetworkWriterPooled.cs create mode 100644 Assets/Mirror/Core/NetworkWriterPooled.cs.meta create mode 100644 Assets/Mirror/Core/PortTransport.cs create mode 100644 Assets/Mirror/Core/PortTransport.cs.meta create mode 100644 Assets/Mirror/Core/RemoteCalls.cs create mode 100644 Assets/Mirror/Core/RemoteCalls.cs.meta create mode 100644 Assets/Mirror/Core/SnapshotInterpolation.meta create mode 100644 Assets/Mirror/Core/SnapshotInterpolation/Snapshot.cs create mode 100644 Assets/Mirror/Core/SnapshotInterpolation/Snapshot.cs.meta create mode 100644 Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs create mode 100644 Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs.meta create mode 100644 Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs create mode 100644 Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs.meta create mode 100644 Assets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs create mode 100644 Assets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs.meta create mode 100644 Assets/Mirror/Core/SyncDictionary.cs create mode 100644 Assets/Mirror/Core/SyncDictionary.cs.meta create mode 100644 Assets/Mirror/Core/SyncList.cs create mode 100644 Assets/Mirror/Core/SyncList.cs.meta create mode 100644 Assets/Mirror/Core/SyncObject.cs create mode 100644 Assets/Mirror/Core/SyncObject.cs.meta create mode 100644 Assets/Mirror/Core/SyncSet.cs create mode 100644 Assets/Mirror/Core/SyncSet.cs.meta create mode 100644 Assets/Mirror/Core/Tools.meta create mode 100644 Assets/Mirror/Core/Tools/AccurateInterval.cs create mode 100644 Assets/Mirror/Core/Tools/AccurateInterval.cs.meta create mode 100644 Assets/Mirror/Core/Tools/Compression.cs create mode 100644 Assets/Mirror/Core/Tools/Compression.cs.meta create mode 100644 Assets/Mirror/Core/Tools/DeltaCompression.cs create mode 100644 Assets/Mirror/Core/Tools/DeltaCompression.cs.meta create mode 100644 Assets/Mirror/Core/Tools/ExponentialMovingAverage.cs create mode 100644 Assets/Mirror/Core/Tools/ExponentialMovingAverage.cs.meta create mode 100644 Assets/Mirror/Core/Tools/Extensions.cs create mode 100644 Assets/Mirror/Core/Tools/Extensions.cs.meta create mode 100644 Assets/Mirror/Core/Tools/Mathd.cs create mode 100644 Assets/Mirror/Core/Tools/Mathd.cs.meta create mode 100644 Assets/Mirror/Core/Tools/Pool.cs create mode 100644 Assets/Mirror/Core/Tools/Pool.cs.meta create mode 100644 Assets/Mirror/Core/Tools/Readme.txt create mode 100644 Assets/Mirror/Core/Tools/Readme.txt.meta create mode 100644 Assets/Mirror/Core/Tools/TimeSample.cs create mode 100644 Assets/Mirror/Core/Tools/TimeSample.cs.meta create mode 100644 Assets/Mirror/Core/Tools/Utils.cs create mode 100644 Assets/Mirror/Core/Tools/Utils.cs.meta create mode 100644 Assets/Mirror/Core/Tools/Vector3Long.cs create mode 100644 Assets/Mirror/Core/Tools/Vector3Long.cs.meta create mode 100644 Assets/Mirror/Core/Transport.cs create mode 100644 Assets/Mirror/Core/Transport.cs.meta create mode 100644 Assets/Mirror/Core/TransportError.cs create mode 100644 Assets/Mirror/Core/TransportError.cs.meta create mode 100644 Assets/Mirror/Core/WeaverFuse.cs create mode 100644 Assets/Mirror/Core/WeaverFuse.cs.meta create mode 100644 Assets/Mirror/Editor.meta create mode 100644 Assets/Mirror/Editor/AndroidManifestHelper.cs create mode 100644 Assets/Mirror/Editor/AndroidManifestHelper.cs.meta create mode 100644 Assets/Mirror/Editor/EditorHelper.cs create mode 100644 Assets/Mirror/Editor/EditorHelper.cs.meta create mode 100644 Assets/Mirror/Editor/Empty.meta create mode 100644 Assets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs create mode 100644 Assets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs.meta create mode 100644 Assets/Mirror/Editor/Empty/LogLevelWindow.cs create mode 100644 Assets/Mirror/Editor/Empty/LogLevelWindow.cs.meta create mode 100644 Assets/Mirror/Editor/Empty/Logging.meta create mode 100644 Assets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs create mode 100644 Assets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs.meta create mode 100644 Assets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs create mode 100644 Assets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs.meta create mode 100644 Assets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs create mode 100644 Assets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs.meta create mode 100644 Assets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs create mode 100644 Assets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs.meta create mode 100644 Assets/Mirror/Editor/Empty/ScriptableObjectUtility.cs create mode 100644 Assets/Mirror/Editor/Empty/ScriptableObjectUtility.cs.meta create mode 100644 Assets/Mirror/Editor/Empty/SyncVarDrawer.cs create mode 100644 Assets/Mirror/Editor/Empty/SyncVarDrawer.cs.meta create mode 100644 Assets/Mirror/Editor/Icon.meta create mode 100644 Assets/Mirror/Editor/Icon/MirrorIcon.png create mode 100644 Assets/Mirror/Editor/Icon/MirrorIcon.png.meta create mode 100644 Assets/Mirror/Editor/InspectorHelper.cs create mode 100644 Assets/Mirror/Editor/InspectorHelper.cs.meta create mode 100644 Assets/Mirror/Editor/Mirror.Editor.asmdef create mode 100644 Assets/Mirror/Editor/Mirror.Editor.asmdef.meta create mode 100644 Assets/Mirror/Editor/NetworkBehaviourInspector.cs create mode 100644 Assets/Mirror/Editor/NetworkBehaviourInspector.cs.meta create mode 100644 Assets/Mirror/Editor/NetworkInformationPreview.cs create mode 100644 Assets/Mirror/Editor/NetworkInformationPreview.cs.meta create mode 100644 Assets/Mirror/Editor/NetworkManagerEditor.cs create mode 100644 Assets/Mirror/Editor/NetworkManagerEditor.cs.meta create mode 100644 Assets/Mirror/Editor/NetworkScenePostProcess.cs create mode 100644 Assets/Mirror/Editor/NetworkScenePostProcess.cs.meta create mode 100644 Assets/Mirror/Editor/SceneDrawer.cs create mode 100644 Assets/Mirror/Editor/SceneDrawer.cs.meta create mode 100644 Assets/Mirror/Editor/SyncObjectCollectionsDrawer.cs create mode 100644 Assets/Mirror/Editor/SyncObjectCollectionsDrawer.cs.meta create mode 100644 Assets/Mirror/Editor/SyncVarAttributeDrawer.cs create mode 100644 Assets/Mirror/Editor/SyncVarAttributeDrawer.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver.meta create mode 100644 Assets/Mirror/Editor/Weaver/AssemblyInfo.cs create mode 100644 Assets/Mirror/Editor/Weaver/AssemblyInfo.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Empty.meta create mode 100644 Assets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs create mode 100644 Assets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Empty/Program.cs create mode 100644 Assets/Mirror/Editor/Weaver/Empty/Program.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPoint.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs create mode 100644 Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Extensions.cs create mode 100644 Assets/Mirror/Editor/Weaver/Extensions.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Helpers.cs create mode 100644 Assets/Mirror/Editor/Weaver/Helpers.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Logger.cs create mode 100644 Assets/Mirror/Editor/Weaver/Logger.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs create mode 100644 Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Readers.cs create mode 100644 Assets/Mirror/Editor/Weaver/Readers.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Resolvers.cs create mode 100644 Assets/Mirror/Editor/Weaver/Resolvers.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/SyncVarAccessLists.cs create mode 100644 Assets/Mirror/Editor/Weaver/SyncVarAccessLists.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/TypeReferenceComparer.cs create mode 100644 Assets/Mirror/Editor/Weaver/TypeReferenceComparer.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef create mode 100644 Assets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef.meta create mode 100644 Assets/Mirror/Editor/Weaver/Weaver.cs create mode 100644 Assets/Mirror/Editor/Weaver/Weaver.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/WeaverExceptions.cs create mode 100644 Assets/Mirror/Editor/Weaver/WeaverExceptions.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/WeaverTypes.cs create mode 100644 Assets/Mirror/Editor/Weaver/WeaverTypes.cs.meta create mode 100644 Assets/Mirror/Editor/Weaver/Writers.cs create mode 100644 Assets/Mirror/Editor/Weaver/Writers.cs.meta create mode 100644 Assets/Mirror/Editor/Welcome.cs create mode 100644 Assets/Mirror/Editor/Welcome.cs.meta create mode 100644 Assets/Mirror/Notice.txt create mode 100644 Assets/Mirror/Notice.txt.meta create mode 100644 Assets/Mirror/Plugins.meta create mode 100644 Assets/Mirror/Plugins/Mono.Cecil.meta create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/License.txt create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/License.txt.meta create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll.meta create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll.meta create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll.meta create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll create mode 100644 Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll.meta create mode 100644 Assets/Mirror/Presets.meta create mode 100644 Assets/Mirror/Presets/NetworkTransform.meta create mode 100644 Assets/Mirror/Presets/NetworkTransform/ClientAuth-Balanced.preset create mode 100644 Assets/Mirror/Presets/NetworkTransform/ClientAuth-Balanced.preset.meta create mode 100644 Assets/Mirror/Presets/NetworkTransform/ClientAuth-FastPaced.preset create mode 100644 Assets/Mirror/Presets/NetworkTransform/ClientAuth-FastPaced.preset.meta create mode 100644 Assets/Mirror/Presets/NetworkTransform/ClientAuth-VeryCasual.preset create mode 100644 Assets/Mirror/Presets/NetworkTransform/ClientAuth-VeryCasual.preset.meta create mode 100644 Assets/Mirror/Readme.txt create mode 100644 Assets/Mirror/Readme.txt.meta create mode 100644 Assets/Mirror/Transports.meta create mode 100644 Assets/Mirror/Transports/KCP.meta create mode 100644 Assets/Mirror/Transports/KCP/KcpTransport.cs create mode 100644 Assets/Mirror/Transports/KCP/KcpTransport.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/KCP.asmdef create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/KCP.asmdef.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/LICENSE.txt create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/LICENSE.txt.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/VERSION.txt create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/VERSION.txt.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnection.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnection.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnectionNonAlloc.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnectionNonAlloc.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientNonAlloc.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientNonAlloc.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerConnectionNonAlloc.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerConnectionNonAlloc.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerNonAlloc.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerNonAlloc.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/Common.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/Common.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/ErrorCode.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/ErrorCode.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/Extensions.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/Extensions.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpChannel.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpChannel.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConfig.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConfig.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpHeader.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpHeader.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpPeer.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpPeer.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServer.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServer.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServerConnection.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServerConnection.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/Log.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/highlevel/Log.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/AckItem.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/AckItem.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/AssemblyInfo.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/AssemblyInfo.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/Kcp.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/Kcp.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/Pool.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/Pool.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/Segment.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/Segment.cs.meta create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/Utils.cs create mode 100644 Assets/Mirror/Transports/KCP/kcp2k/kcp/Utils.cs.meta create mode 100644 Assets/Mirror/Transports/Latency.meta create mode 100644 Assets/Mirror/Transports/Latency/LatencySimulation.cs create mode 100644 Assets/Mirror/Transports/Latency/LatencySimulation.cs.meta create mode 100644 Assets/Mirror/Transports/Middleware.meta create mode 100644 Assets/Mirror/Transports/Middleware/MiddlewareTransport.cs create mode 100644 Assets/Mirror/Transports/Middleware/MiddlewareTransport.cs.meta create mode 100644 Assets/Mirror/Transports/Mirror.Transports.asmdef create mode 100644 Assets/Mirror/Transports/Mirror.Transports.asmdef.meta create mode 100644 Assets/Mirror/Transports/Multiplex.meta create mode 100644 Assets/Mirror/Transports/Multiplex/MultiplexTransport.cs create mode 100644 Assets/Mirror/Transports/Multiplex/MultiplexTransport.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/AssemblyInfo.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/AssemblyInfo.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/CHANGELOG.md create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/CHANGELOG.md.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/SimpleWebClient.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/SimpleWebClient.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientHandshake.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientHandshake.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientSslHelper.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientSslHelper.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/WebSocketClientStandAlone.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/WebSocketClientStandAlone.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/SimpleWebJSLib.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/SimpleWebJSLib.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/WebSocketClientWebGl.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/WebSocketClientWebGl.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin/SimpleWeb.jslib create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin/SimpleWeb.jslib.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/BufferPool.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/BufferPool.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Connection.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Connection.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Constants.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Constants.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/EventType.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/EventType.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Log.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Log.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Message.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Message.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/MessageProcessor.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/MessageProcessor.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReadHelper.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReadHelper.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReceiveLoop.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReceiveLoop.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Request.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Request.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/SendLoop.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/SendLoop.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/TcpConfig.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/TcpConfig.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Utils.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Utils.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/LICENSE create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/LICENSE.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/README.txt create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/README.txt.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerHandshake.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerHandshake.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerSslHelper.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerSslHelper.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/SimpleWebServer.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/SimpleWebServer.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/WebSocketServer.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/WebSocketServer.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SimpleWebTransport.asmdef create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SimpleWebTransport.asmdef.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SslConfigLoader.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SslConfigLoader.cs.meta create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWebTransport.cs create mode 100644 Assets/Mirror/Transports/SimpleWeb/SimpleWebTransport.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Client.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Client.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Common.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Common.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/ConnectionState.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/ConnectionState.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Empty.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Logger.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Logger.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Message.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Message.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Empty/SafeQueue.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Empty/SafeQueue.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Empty/ThreadExtensions.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Empty/ThreadExtensions.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/EventType.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/EventType.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/LICENSE create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/LICENSE.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Log.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Log.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentReceivePipe.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentReceivePipe.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentSendPipe.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentSendPipe.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/NetworkStreamExtensions.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/NetworkStreamExtensions.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Pool.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Pool.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Server.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Server.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Telepathy.asmdef create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Telepathy.asmdef.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/ThreadFunctions.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/ThreadFunctions.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Utils.cs create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/Utils.cs.meta create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/VERSION create mode 100644 Assets/Mirror/Transports/Telepathy/Telepathy/VERSION.meta create mode 100644 Assets/Mirror/Transports/Telepathy/TelepathyTransport.cs create mode 100644 Assets/Mirror/Transports/Telepathy/TelepathyTransport.cs.meta create mode 100644 Assets/Mirror/Version.txt create mode 100644 Assets/Mirror/Version.txt.meta diff --git a/Assets/Mirror.meta b/Assets/Mirror.meta new file mode 100644 index 0000000..a7a3dd0 --- /dev/null +++ b/Assets/Mirror.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5cf8eb36be0834b3da408c694a41cb88 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Authenticators.meta b/Assets/Mirror/Authenticators.meta new file mode 100644 index 0000000..644f4ec --- /dev/null +++ b/Assets/Mirror/Authenticators.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1b2f9d254154cd942ba40b06b869b8f3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Authenticators/BasicAuthenticator.cs b/Assets/Mirror/Authenticators/BasicAuthenticator.cs new file mode 100644 index 0000000..3c077c7 --- /dev/null +++ b/Assets/Mirror/Authenticators/BasicAuthenticator.cs @@ -0,0 +1,192 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror.Authenticators +{ + [AddComponentMenu("Network/ Authenticators/Basic Authenticator")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-authenticators/basic-authenticator")] + public class BasicAuthenticator : NetworkAuthenticator + { + [Header("Server Credentials")] + public string serverUsername; + public string serverPassword; + + [Header("Client Credentials")] + public string username; + public string password; + + readonly HashSet connectionsPendingDisconnect = new HashSet(); + + #region Messages + + public struct AuthRequestMessage : NetworkMessage + { + // use whatever credentials make sense for your game + // for example, you might want to pass the accessToken if using oauth + public string authUsername; + public string authPassword; + } + + public struct AuthResponseMessage : NetworkMessage + { + public byte code; + public string message; + } + + #endregion + + #region Server + + /// + /// Called on server from StartServer to initialize the Authenticator + /// Server message handlers should be registered in this method. + /// + public override void OnStartServer() + { + // register a handler for the authentication request we expect from client + NetworkServer.RegisterHandler(OnAuthRequestMessage, false); + } + + /// + /// Called on server from StopServer to reset the Authenticator + /// Server message handlers should be unregistered in this method. + /// + public override void OnStopServer() + { + // unregister the handler for the authentication request + NetworkServer.UnregisterHandler(); + } + + /// + /// Called on server from OnServerConnectInternal when a client needs to authenticate + /// + /// Connection to client. + public override void OnServerAuthenticate(NetworkConnectionToClient conn) + { + // do nothing...wait for AuthRequestMessage from client + } + + /// + /// Called on server when the client's AuthRequestMessage arrives + /// + /// Connection to client. + /// The message payload + public void OnAuthRequestMessage(NetworkConnectionToClient conn, AuthRequestMessage msg) + { + //Debug.Log($"Authentication Request: {msg.authUsername} {msg.authPassword}"); + + if (connectionsPendingDisconnect.Contains(conn)) return; + + // check the credentials by calling your web server, database table, playfab api, or any method appropriate. + if (msg.authUsername == serverUsername && msg.authPassword == serverPassword) + { + // create and send msg to client so it knows to proceed + AuthResponseMessage authResponseMessage = new AuthResponseMessage + { + code = 100, + message = "Success" + }; + + conn.Send(authResponseMessage); + + // Accept the successful authentication + ServerAccept(conn); + } + else + { + connectionsPendingDisconnect.Add(conn); + + // create and send msg to client so it knows to disconnect + AuthResponseMessage authResponseMessage = new AuthResponseMessage + { + code = 200, + message = "Invalid Credentials" + }; + + conn.Send(authResponseMessage); + + // must set NetworkConnection isAuthenticated = false + conn.isAuthenticated = false; + + // disconnect the client after 1 second so that response message gets delivered + StartCoroutine(DelayedDisconnect(conn, 1f)); + } + } + + IEnumerator DelayedDisconnect(NetworkConnectionToClient conn, float waitTime) + { + yield return new WaitForSeconds(waitTime); + + // Reject the unsuccessful authentication + ServerReject(conn); + + yield return null; + + // remove conn from pending connections + connectionsPendingDisconnect.Remove(conn); + } + + #endregion + + #region Client + + /// + /// Called on client from StartClient to initialize the Authenticator + /// Client message handlers should be registered in this method. + /// + public override void OnStartClient() + { + // register a handler for the authentication response we expect from server + NetworkClient.RegisterHandler(OnAuthResponseMessage, false); + } + + /// + /// Called on client from StopClient to reset the Authenticator + /// Client message handlers should be unregistered in this method. + /// + public override void OnStopClient() + { + // unregister the handler for the authentication response + NetworkClient.UnregisterHandler(); + } + + /// + /// Called on client from OnClientConnectInternal when a client needs to authenticate + /// + public override void OnClientAuthenticate() + { + AuthRequestMessage authRequestMessage = new AuthRequestMessage + { + authUsername = username, + authPassword = password + }; + + NetworkClient.Send(authRequestMessage); + } + + /// + /// Called on client when the server's AuthResponseMessage arrives + /// + /// The message payload + public void OnAuthResponseMessage(AuthResponseMessage msg) + { + if (msg.code == 100) + { + //Debug.Log($"Authentication Response: {msg.message}"); + + // Authentication has been accepted + ClientAccept(); + } + else + { + Debug.LogError($"Authentication Response: {msg.message}"); + + // Authentication has been rejected + ClientReject(); + } + } + + #endregion + } +} diff --git a/Assets/Mirror/Authenticators/BasicAuthenticator.cs.meta b/Assets/Mirror/Authenticators/BasicAuthenticator.cs.meta new file mode 100644 index 0000000..4765013 --- /dev/null +++ b/Assets/Mirror/Authenticators/BasicAuthenticator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28496b776660156428f00cf78289c1ec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Authenticators/DeviceAuthenticator.cs b/Assets/Mirror/Authenticators/DeviceAuthenticator.cs new file mode 100644 index 0000000..5e0ea56 --- /dev/null +++ b/Assets/Mirror/Authenticators/DeviceAuthenticator.cs @@ -0,0 +1,129 @@ +using System; +using UnityEngine; + +namespace Mirror.Authenticators +{ + /// + /// An authenticator that identifies the user by their device. + /// A GUID is used as a fallback when the platform doesn't support SystemInfo.deviceUniqueIdentifier. + /// Note: deviceUniqueIdentifier can be spoofed, so security is not guaranteed. + /// See https://docs.unity3d.com/ScriptReference/SystemInfo-deviceUniqueIdentifier.html for details. + /// + [AddComponentMenu("Network/ Authenticators/Device Authenticator")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-authenticators/device-authenticator")] + public class DeviceAuthenticator : NetworkAuthenticator + { + #region Messages + + public struct AuthRequestMessage : NetworkMessage + { + public string clientDeviceID; + } + + public struct AuthResponseMessage : NetworkMessage { } + + #endregion + + #region Server + + /// + /// Called on server from StartServer to initialize the Authenticator + /// Server message handlers should be registered in this method. + /// + public override void OnStartServer() + { + // register a handler for the authentication request we expect from client + NetworkServer.RegisterHandler(OnAuthRequestMessage, false); + } + + /// + /// Called on server from StopServer to reset the Authenticator + /// Server message handlers should be registered in this method. + /// + public override void OnStopServer() + { + // unregister the handler for the authentication request + NetworkServer.UnregisterHandler(); + } + + /// + /// Called on server from OnServerConnectInternal when a client needs to authenticate + /// + /// Connection to client. + public override void OnServerAuthenticate(NetworkConnectionToClient conn) + { + // do nothing, wait for client to send his id + } + + void OnAuthRequestMessage(NetworkConnectionToClient conn, AuthRequestMessage msg) + { + Debug.Log($"connection {conn.connectionId} authenticated with id {msg.clientDeviceID}"); + + // Store the device id for later reference, e.g. when spawning the player + conn.authenticationData = msg.clientDeviceID; + + // Send a response to client telling it to proceed as authenticated + conn.Send(new AuthResponseMessage()); + + // Accept the successful authentication + ServerAccept(conn); + } + + #endregion + + #region Client + + /// + /// Called on client from StartClient to initialize the Authenticator + /// Client message handlers should be registered in this method. + /// + public override void OnStartClient() + { + // register a handler for the authentication response we expect from server + NetworkClient.RegisterHandler(OnAuthResponseMessage, false); + } + + /// + /// Called on client from StopClient to reset the Authenticator + /// Client message handlers should be unregistered in this method. + /// + public override void OnStopClient() + { + // unregister the handler for the authentication response + NetworkClient.UnregisterHandler(); + } + + /// + /// Called on client from OnClientConnectInternal when a client needs to authenticate + /// + public override void OnClientAuthenticate() + { + string deviceUniqueIdentifier = SystemInfo.deviceUniqueIdentifier; + + // Not all platforms support this, so we use a GUID instead + if (deviceUniqueIdentifier == SystemInfo.unsupportedIdentifier) + { + // Get the value from PlayerPrefs if it exists, new GUID if it doesn't + deviceUniqueIdentifier = PlayerPrefs.GetString("deviceUniqueIdentifier", Guid.NewGuid().ToString()); + + // Store the deviceUniqueIdentifier to PlayerPrefs (in case we just made a new GUID) + PlayerPrefs.SetString("deviceUniqueIdentifier", deviceUniqueIdentifier); + } + + // send the deviceUniqueIdentifier to the server + NetworkClient.Send(new AuthRequestMessage { clientDeviceID = deviceUniqueIdentifier } ); + } + + /// + /// Called on client when the server's AuthResponseMessage arrives + /// + /// The message payload + public void OnAuthResponseMessage(AuthResponseMessage msg) + { + Debug.Log("Authentication Success"); + ClientAccept(); + } + + #endregion + } +} diff --git a/Assets/Mirror/Authenticators/DeviceAuthenticator.cs.meta b/Assets/Mirror/Authenticators/DeviceAuthenticator.cs.meta new file mode 100644 index 0000000..9ca9f64 --- /dev/null +++ b/Assets/Mirror/Authenticators/DeviceAuthenticator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 60960a6ba81a842deb2fdcdc93788242 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Authenticators/Mirror.Authenticators.asmdef b/Assets/Mirror/Authenticators/Mirror.Authenticators.asmdef new file mode 100644 index 0000000..70eacf3 --- /dev/null +++ b/Assets/Mirror/Authenticators/Mirror.Authenticators.asmdef @@ -0,0 +1,16 @@ +{ + "name": "Mirror.Authenticators", + "rootNamespace": "", + "references": [ + "GUID:30817c1a0e6d646d99c048fc403f5979" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Mirror/Authenticators/Mirror.Authenticators.asmdef.meta b/Assets/Mirror/Authenticators/Mirror.Authenticators.asmdef.meta new file mode 100644 index 0000000..2731701 --- /dev/null +++ b/Assets/Mirror/Authenticators/Mirror.Authenticators.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: e720aa64e3f58fb4880566a322584340 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Authenticators/TimeoutAuthenticator.cs b/Assets/Mirror/Authenticators/TimeoutAuthenticator.cs new file mode 100644 index 0000000..711ee6e --- /dev/null +++ b/Assets/Mirror/Authenticators/TimeoutAuthenticator.cs @@ -0,0 +1,70 @@ +using System.Collections; +using UnityEngine; + +namespace Mirror.Authenticators +{ + /// + /// An authenticator that disconnects connections if they don't + /// authenticate within a specified time limit. + /// + [AddComponentMenu("Network/ Authenticators/Timeout Authenticator")] + public class TimeoutAuthenticator : NetworkAuthenticator + { + public NetworkAuthenticator authenticator; + + [Range(0, 600), Tooltip("Timeout to auto-disconnect in seconds. Set to 0 for no timeout.")] + public float timeout = 60; + + public void Awake() + { + authenticator.OnServerAuthenticated.AddListener(connection => OnServerAuthenticated.Invoke(connection)); + authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated.Invoke); + } + + public override void OnStartServer() + { + authenticator.OnStartServer(); + } + + public override void OnStopServer() + { + authenticator.OnStopServer(); + } + + public override void OnStartClient() + { + authenticator.OnStartClient(); + } + + public override void OnStopClient() + { + authenticator.OnStopClient(); + } + + public override void OnServerAuthenticate(NetworkConnectionToClient conn) + { + authenticator.OnServerAuthenticate(conn); + if (timeout > 0) + StartCoroutine(BeginAuthentication(conn)); + } + + public override void OnClientAuthenticate() + { + authenticator.OnClientAuthenticate(); + if (timeout > 0) + StartCoroutine(BeginAuthentication(NetworkClient.connection)); + } + + IEnumerator BeginAuthentication(NetworkConnection conn) + { + //Debug.Log($"Authentication countdown started {conn} {timeout}"); + yield return new WaitForSecondsRealtime(timeout); + + if (!conn.isAuthenticated) + { + Debug.LogError($"Authentication Timeout - Disconnecting {conn}"); + conn.Disconnect(); + } + } + } +} diff --git a/Assets/Mirror/Authenticators/TimeoutAuthenticator.cs.meta b/Assets/Mirror/Authenticators/TimeoutAuthenticator.cs.meta new file mode 100644 index 0000000..b19ddec --- /dev/null +++ b/Assets/Mirror/Authenticators/TimeoutAuthenticator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 24d8269a07b8e4edfa374753a91c946e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/CompilerSymbols.meta b/Assets/Mirror/CompilerSymbols.meta new file mode 100644 index 0000000..4652ae1 --- /dev/null +++ b/Assets/Mirror/CompilerSymbols.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1f8b918bcd89f5c488b06f5574f34760 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef b/Assets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef new file mode 100644 index 0000000..af25622 --- /dev/null +++ b/Assets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef @@ -0,0 +1,14 @@ +{ + "name": "Mirror.CompilerSymbols", + "references": [], + "optionalUnityReferences": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [] +} \ No newline at end of file diff --git a/Assets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef.meta b/Assets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef.meta new file mode 100644 index 0000000..8b23823 --- /dev/null +++ b/Assets/Mirror/CompilerSymbols/Mirror.CompilerSymbols.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 325984b52e4128546bc7558552f8b1d2 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/CompilerSymbols/PreprocessorDefine.cs b/Assets/Mirror/CompilerSymbols/PreprocessorDefine.cs new file mode 100644 index 0000000..b553d40 --- /dev/null +++ b/Assets/Mirror/CompilerSymbols/PreprocessorDefine.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using UnityEditor; + +namespace Mirror +{ + static class PreprocessorDefine + { + /// + /// Add define symbols as soon as Unity gets done compiling. + /// + [InitializeOnLoadMethod] + public static void AddDefineSymbols() + { + string currentDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); + HashSet defines = new HashSet(currentDefines.Split(';')) + { + "MIRROR", + "MIRROR_57_0_OR_NEWER", + "MIRROR_58_0_OR_NEWER", + "MIRROR_65_0_OR_NEWER", + "MIRROR_66_0_OR_NEWER", + "MIRROR_2022_9_OR_NEWER", + "MIRROR_2022_10_OR_NEWER", + "MIRROR_70_0_OR_NEWER", + "MIRROR_71_0_OR_NEWER", + "MIRROR_73_OR_NEWER", + "MIRROR_78_OR_NEWER", + "MIRROR_79_OR_NEWER", + "MIRROR_81_OR_NEWER" + // Remove oldest when adding next month's symbol. + // Keep a rolling 12 months of symbols. + }; + + // only touch PlayerSettings if we actually modified it, + // otherwise it shows up as changed in git each time. + string newDefines = string.Join(";", defines); + if (newDefines != currentDefines) + { + PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, newDefines); + } + } + } +} diff --git a/Assets/Mirror/CompilerSymbols/PreprocessorDefine.cs.meta b/Assets/Mirror/CompilerSymbols/PreprocessorDefine.cs.meta new file mode 100644 index 0000000..6306c16 --- /dev/null +++ b/Assets/Mirror/CompilerSymbols/PreprocessorDefine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1d66fe74ec6f42dd974cba37d25d453 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components.meta b/Assets/Mirror/Components.meta new file mode 100644 index 0000000..c2771d9 --- /dev/null +++ b/Assets/Mirror/Components.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9bee879fbc8ef4b1a9a9f7088bfbf726 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/AssemblyInfo.cs b/Assets/Mirror/Components/AssemblyInfo.cs new file mode 100644 index 0000000..f342716 --- /dev/null +++ b/Assets/Mirror/Components/AssemblyInfo.cs @@ -0,0 +1,12 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Mirror.Tests.Common")] +[assembly: InternalsVisibleTo("Mirror.Tests")] +// need to use Unity.*.CodeGen assembly name to import Unity.CompilationPipeline +// for ILPostProcessor tests. +[assembly: InternalsVisibleTo("Unity.Mirror.Tests.CodeGen")] +[assembly: InternalsVisibleTo("Mirror.Tests.Generated")] +[assembly: InternalsVisibleTo("Mirror.Tests.Runtime")] +[assembly: InternalsVisibleTo("Mirror.Tests.Performance.Editor")] +[assembly: InternalsVisibleTo("Mirror.Tests.Performance.Runtime")] +[assembly: InternalsVisibleTo("Mirror.Editor")] diff --git a/Assets/Mirror/Components/AssemblyInfo.cs.meta b/Assets/Mirror/Components/AssemblyInfo.cs.meta new file mode 100644 index 0000000..f9af1fa --- /dev/null +++ b/Assets/Mirror/Components/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a65b9283f7a724e70b8e17cb277f4c1e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Discovery.meta b/Assets/Mirror/Components/Discovery.meta new file mode 100644 index 0000000..d5bb0cb --- /dev/null +++ b/Assets/Mirror/Components/Discovery.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b5dcf9618f5e14a4eb60bff5480284a6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Discovery/NetworkDiscovery.cs b/Assets/Mirror/Components/Discovery/NetworkDiscovery.cs new file mode 100644 index 0000000..5fa9397 --- /dev/null +++ b/Assets/Mirror/Components/Discovery/NetworkDiscovery.cs @@ -0,0 +1,93 @@ +using System; +using System.Net; +using UnityEngine; +using UnityEngine.Events; + +namespace Mirror.Discovery +{ + [Serializable] + public class ServerFoundUnityEvent : UnityEvent {}; + + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Discovery")] + public class NetworkDiscovery : NetworkDiscoveryBase + { + #region Server + + /// + /// Process the request from a client + /// + /// + /// Override if you wish to provide more information to the clients + /// such as the name of the host player + /// + /// Request coming from client + /// Address of the client that sent the request + /// The message to be sent back to the client or null + protected override ServerResponse ProcessRequest(ServerRequest request, IPEndPoint endpoint) + { + // In this case we don't do anything with the request + // but other discovery implementations might want to use the data + // in there, This way the client can ask for + // specific game mode or something + + try + { + // this is an example reply message, return your own + // to include whatever is relevant for your game + return new ServerResponse + { + serverId = ServerId, + uri = transport.ServerUri() + }; + } + catch (NotImplementedException) + { + Debug.LogError($"Transport {transport} does not support network discovery"); + throw; + } + } + + #endregion + + #region Client + + /// + /// Create a message that will be broadcasted on the network to discover servers + /// + /// + /// Override if you wish to include additional data in the discovery message + /// such as desired game mode, language, difficulty, etc... + /// An instance of ServerRequest with data to be broadcasted + protected override ServerRequest GetRequest() => new ServerRequest(); + + /// + /// Process the answer from a server + /// + /// + /// A client receives a reply from a server, this method processes the + /// reply and raises an event + /// + /// Response that came from the server + /// Address of the server that replied + protected override void ProcessResponse(ServerResponse response, IPEndPoint endpoint) + { + // we received a message from the remote endpoint + response.EndPoint = endpoint; + + // although we got a supposedly valid url, we may not be able to resolve + // the provided host + // However we know the real ip address of the server because we just + // received a packet from it, so use that as host. + UriBuilder realUri = new UriBuilder(response.uri) + { + Host = response.EndPoint.Address.ToString() + }; + response.uri = realUri.Uri; + + OnServerFound.Invoke(response); + } + + #endregion + } +} diff --git a/Assets/Mirror/Components/Discovery/NetworkDiscovery.cs.meta b/Assets/Mirror/Components/Discovery/NetworkDiscovery.cs.meta new file mode 100644 index 0000000..c691a61 --- /dev/null +++ b/Assets/Mirror/Components/Discovery/NetworkDiscovery.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c761308e733c51245b2e8bb4201f46dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs b/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs new file mode 100644 index 0000000..8e13f01 --- /dev/null +++ b/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs @@ -0,0 +1,469 @@ +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading.Tasks; +using UnityEngine; + +// Based on https://github.com/EnlightenedOne/MirrorNetworkDiscovery +// forked from https://github.com/in0finite/MirrorNetworkDiscovery +// Both are MIT Licensed + +namespace Mirror.Discovery +{ + /// + /// Base implementation for Network Discovery. Extend this component + /// to provide custom discovery with game specific data + /// NetworkDiscovery for a sample implementation + /// + [DisallowMultipleComponent] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-discovery")] + public abstract class NetworkDiscoveryBase : MonoBehaviour + where Request : NetworkMessage + where Response : NetworkMessage + { + public static bool SupportedOnThisPlatform { get { return Application.platform != RuntimePlatform.WebGLPlayer; } } + + [SerializeField] + [Tooltip("If true, broadcasts a discovery request every ActiveDiscoveryInterval seconds")] + public bool enableActiveDiscovery = true; + + // broadcast address needs to be configurable on iOS: + // https://github.com/vis2k/Mirror/pull/3255 + [Tooltip("iOS may require LAN IP address here (e.g. 192.168.x.x), otherwise leave blank.")] + public string BroadcastAddress = ""; + + [SerializeField] + [Tooltip("The UDP port the server will listen for multi-cast messages")] + protected int serverBroadcastListenPort = 47777; + + [SerializeField] + [Tooltip("Time in seconds between multi-cast messages")] + [Range(1, 60)] + float ActiveDiscoveryInterval = 3; + + [Tooltip("Transport to be advertised during discovery")] + public Transport transport; + + [Tooltip("Invoked when a server is found")] + public ServerFoundUnityEvent OnServerFound; + + // Each game should have a random unique handshake, + // this way you can tell if this is the same game or not + [HideInInspector] + public long secretHandshake; + + public long ServerId { get; private set; } + + protected UdpClient serverUdpClient; + protected UdpClient clientUdpClient; + +#if UNITY_EDITOR + public virtual void OnValidate() + { + if (transport == null) + transport = GetComponent(); + + if (secretHandshake == 0) + { + secretHandshake = RandomLong(); + UnityEditor.Undo.RecordObject(this, "Set secret handshake"); + } + } +#endif + + /// + /// virtual so that inheriting classes' Start() can call base.Start() too + /// + public virtual void Start() + { + ServerId = RandomLong(); + + // active transport gets initialized in Awake + // so make sure we set it here in Start() after Awake + // Or just let the user assign it in the inspector + if (transport == null) + transport = Transport.active; + + // Server mode? then start advertising +#if UNITY_SERVER + AdvertiseServer(); +#endif + } + + public static long RandomLong() + { + int value1 = UnityEngine.Random.Range(int.MinValue, int.MaxValue); + int value2 = UnityEngine.Random.Range(int.MinValue, int.MaxValue); + return value1 + ((long)value2 << 32); + } + + // Ensure the ports are cleared no matter when Game/Unity UI exits + void OnApplicationQuit() + { + //Debug.Log("NetworkDiscoveryBase OnApplicationQuit"); + Shutdown(); + } + + void OnDisable() + { + //Debug.Log("NetworkDiscoveryBase OnDisable"); + Shutdown(); + } + + void OnDestroy() + { + //Debug.Log("NetworkDiscoveryBase OnDestroy"); + Shutdown(); + } + + void Shutdown() + { + EndpMulticastLock(); + if (serverUdpClient != null) + { + try + { + serverUdpClient.Close(); + } + catch (Exception) + { + // it is just close, swallow the error + } + + serverUdpClient = null; + } + + if (clientUdpClient != null) + { + try + { + clientUdpClient.Close(); + } + catch (Exception) + { + // it is just close, swallow the error + } + + clientUdpClient = null; + } + + CancelInvoke(); + } + + #region Server + + /// + /// Advertise this server in the local network + /// + public void AdvertiseServer() + { + if (!SupportedOnThisPlatform) + throw new PlatformNotSupportedException("Network discovery not supported in this platform"); + + StopDiscovery(); + + // Setup port -- may throw exception + serverUdpClient = new UdpClient(serverBroadcastListenPort) + { + EnableBroadcast = true, + MulticastLoopback = false + }; + + // listen for client pings + _ = ServerListenAsync(); + } + + public async Task ServerListenAsync() + { + BeginMulticastLock(); + while (true) + { + try + { + await ReceiveRequestAsync(serverUdpClient); + } + catch (ObjectDisposedException) + { + // socket has been closed + break; + } + catch (Exception) {} + } + } + + async Task ReceiveRequestAsync(UdpClient udpClient) + { + // only proceed if there is available data in network buffer, or otherwise Receive() will block + // average time for UdpClient.Available : 10 us + + UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); + + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(udpReceiveResult.Buffer)) + { + long handshake = networkReader.ReadLong(); + if (handshake != secretHandshake) + { + // message is not for us + throw new ProtocolViolationException("Invalid handshake"); + } + + Request request = networkReader.Read(); + + ProcessClientRequest(request, udpReceiveResult.RemoteEndPoint); + } + } + + /// + /// Reply to the client to inform it of this server + /// + /// + /// Override if you wish to ignore server requests based on + /// custom criteria such as language, full server game mode or difficulty + /// + /// Request coming from client + /// Address of the client that sent the request + protected virtual void ProcessClientRequest(Request request, IPEndPoint endpoint) + { + Response info = ProcessRequest(request, endpoint); + + if (info == null) + return; + + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + try + { + writer.WriteLong(secretHandshake); + + writer.Write(info); + + ArraySegment data = writer.ToArraySegment(); + // signature matches + // send response + serverUdpClient.Send(data.Array, data.Count, endpoint); + } + catch (Exception ex) + { + Debug.LogException(ex, this); + } + } + } + + /// + /// Process the request from a client + /// + /// + /// Override if you wish to provide more information to the clients + /// such as the name of the host player + /// + /// Request coming from client + /// Address of the client that sent the request + /// The message to be sent back to the client or null + protected abstract Response ProcessRequest(Request request, IPEndPoint endpoint); + + // Android Multicast fix: https://github.com/vis2k/Mirror/pull/2887 +#if UNITY_ANDROID + AndroidJavaObject multicastLock; + bool hasMulticastLock; +#endif + + void BeginMulticastLock() + { +#if UNITY_ANDROID + if (hasMulticastLock) return; + + if (Application.platform == RuntimePlatform.Android) + { + using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic("currentActivity")) + { + using (var wifiManager = activity.Call("getSystemService", "wifi")) + { + multicastLock = wifiManager.Call("createMulticastLock", "lock"); + multicastLock.Call("acquire"); + hasMulticastLock = true; + } + } + } +#endif + } + + void EndpMulticastLock() + { +#if UNITY_ANDROID + if (!hasMulticastLock) return; + + multicastLock?.Call("release"); + hasMulticastLock = false; +#endif + } + +#endregion + + #region Client + + /// + /// Start Active Discovery + /// + public void StartDiscovery() + { + if (!SupportedOnThisPlatform) + throw new PlatformNotSupportedException("Network discovery not supported in this platform"); + + StopDiscovery(); + + try + { + // Setup port + clientUdpClient = new UdpClient(0) + { + EnableBroadcast = true, + MulticastLoopback = false + }; + } + catch (Exception) + { + // Free the port if we took it + //Debug.LogError("NetworkDiscoveryBase StartDiscovery Exception"); + Shutdown(); + throw; + } + + _ = ClientListenAsync(); + + if (enableActiveDiscovery) InvokeRepeating(nameof(BroadcastDiscoveryRequest), 0, ActiveDiscoveryInterval); + } + + /// + /// Stop Active Discovery + /// + public void StopDiscovery() + { + //Debug.Log("NetworkDiscoveryBase StopDiscovery"); + Shutdown(); + } + + /// + /// Awaits for server response + /// + /// ClientListenAsync Task + public async Task ClientListenAsync() + { + // while clientUpdClient to fix: + // https://github.com/vis2k/Mirror/pull/2908 + // + // If, you cancel discovery the clientUdpClient is set to null. + // However, nothing cancels ClientListenAsync. If we change the if(true) + // to check if the client is null. You can properly cancel the discovery, + // and kill the listen thread. + // + // Prior to this fix, if you cancel the discovery search. It crashes the + // thread, and is super noisy in the output. As well as causes issues on + // the quest. + while (clientUdpClient != null) + { + try + { + await ReceiveGameBroadcastAsync(clientUdpClient); + } + catch (ObjectDisposedException) + { + // socket was closed, no problem + return; + } + catch (Exception ex) + { + Debug.LogException(ex); + } + } + } + + /// + /// Sends discovery request from client + /// + public void BroadcastDiscoveryRequest() + { + if (clientUdpClient == null) + return; + + if (NetworkClient.isConnected) + { + StopDiscovery(); + return; + } + + IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, serverBroadcastListenPort); + + if (!string.IsNullOrWhiteSpace(BroadcastAddress)) + { + try + { + endPoint = new IPEndPoint(IPAddress.Parse(BroadcastAddress), serverBroadcastListenPort); + } + catch (Exception ex) + { + Debug.LogException(ex); + } + } + + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + writer.WriteLong(secretHandshake); + + try + { + Request request = GetRequest(); + + writer.Write(request); + + ArraySegment data = writer.ToArraySegment(); + + clientUdpClient.SendAsync(data.Array, data.Count, endPoint); + } + catch (Exception) + { + // It is ok if we can't broadcast to one of the addresses + } + } + } + + /// + /// Create a message that will be broadcasted on the network to discover servers + /// + /// + /// Override if you wish to include additional data in the discovery message + /// such as desired game mode, language, difficulty, etc... + /// An instance of ServerRequest with data to be broadcasted + protected virtual Request GetRequest() => default; + + async Task ReceiveGameBroadcastAsync(UdpClient udpClient) + { + // only proceed if there is available data in network buffer, or otherwise Receive() will block + // average time for UdpClient.Available : 10 us + + UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); + + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(udpReceiveResult.Buffer)) + { + if (networkReader.ReadLong() != secretHandshake) + return; + + Response response = networkReader.Read(); + + ProcessResponse(response, udpReceiveResult.RemoteEndPoint); + } + } + + /// + /// Process the answer from a server + /// + /// + /// A client receives a reply from a server, this method processes the + /// reply and raises an event + /// + /// Response that came from the server + /// Address of the server that replied + protected abstract void ProcessResponse(Response response, IPEndPoint endpoint); + + #endregion + } +} diff --git a/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs.meta b/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs.meta new file mode 100644 index 0000000..fecf845 --- /dev/null +++ b/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b9971d60ce61f4e39b07cd9e7e0c68fa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs b/Assets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs new file mode 100644 index 0000000..e43c3d7 --- /dev/null +++ b/Assets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs @@ -0,0 +1,132 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror.Discovery +{ + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Discovery HUD")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-discovery")] + [RequireComponent(typeof(NetworkDiscovery))] + public class NetworkDiscoveryHUD : MonoBehaviour + { + readonly Dictionary discoveredServers = new Dictionary(); + Vector2 scrollViewPos = Vector2.zero; + + public NetworkDiscovery networkDiscovery; + +#if UNITY_EDITOR + void OnValidate() + { + if (networkDiscovery == null) + { + networkDiscovery = GetComponent(); + UnityEditor.Events.UnityEventTools.AddPersistentListener(networkDiscovery.OnServerFound, OnDiscoveredServer); + UnityEditor.Undo.RecordObjects(new Object[] { this, networkDiscovery }, "Set NetworkDiscovery"); + } + } +#endif + + void OnGUI() + { + if (NetworkManager.singleton == null) + return; + + if (!NetworkClient.isConnected && !NetworkServer.active && !NetworkClient.active) + DrawGUI(); + + if (NetworkServer.active || NetworkClient.active) + StopButtons(); + } + + void DrawGUI() + { + GUILayout.BeginArea(new Rect(10, 10, 300, 500)); + GUILayout.BeginHorizontal(); + + if (GUILayout.Button("Find Servers")) + { + discoveredServers.Clear(); + networkDiscovery.StartDiscovery(); + } + + // LAN Host + if (GUILayout.Button("Start Host")) + { + discoveredServers.Clear(); + NetworkManager.singleton.StartHost(); + networkDiscovery.AdvertiseServer(); + } + + // Dedicated server + if (GUILayout.Button("Start Server")) + { + discoveredServers.Clear(); + NetworkManager.singleton.StartServer(); + networkDiscovery.AdvertiseServer(); + } + + GUILayout.EndHorizontal(); + + // show list of found server + + GUILayout.Label($"Discovered Servers [{discoveredServers.Count}]:"); + + // servers + scrollViewPos = GUILayout.BeginScrollView(scrollViewPos); + + foreach (ServerResponse info in discoveredServers.Values) + if (GUILayout.Button(info.EndPoint.Address.ToString())) + Connect(info); + + GUILayout.EndScrollView(); + GUILayout.EndArea(); + } + + void StopButtons() + { + GUILayout.BeginArea(new Rect(10, 40, 100, 25)); + + // stop host if host mode + if (NetworkServer.active && NetworkClient.isConnected) + { + if (GUILayout.Button("Stop Host")) + { + NetworkManager.singleton.StopHost(); + networkDiscovery.StopDiscovery(); + } + } + // stop client if client-only + else if (NetworkClient.isConnected) + { + if (GUILayout.Button("Stop Client")) + { + NetworkManager.singleton.StopClient(); + networkDiscovery.StopDiscovery(); + } + } + // stop server if server-only + else if (NetworkServer.active) + { + if (GUILayout.Button("Stop Server")) + { + NetworkManager.singleton.StopServer(); + networkDiscovery.StopDiscovery(); + } + } + + GUILayout.EndArea(); + } + + void Connect(ServerResponse info) + { + networkDiscovery.StopDiscovery(); + NetworkManager.singleton.StartClient(info.uri); + } + + public void OnDiscoveredServer(ServerResponse info) + { + // Note that you can check the versioning to decide if you can connect to the server or not using this method + discoveredServers[info.serverId] = info; + } + } +} diff --git a/Assets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs.meta b/Assets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs.meta new file mode 100644 index 0000000..f93b275 --- /dev/null +++ b/Assets/Mirror/Components/Discovery/NetworkDiscoveryHUD.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 88c37d3deca7a834d80cfd8d3cfcc510 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Discovery/ServerRequest.cs b/Assets/Mirror/Components/Discovery/ServerRequest.cs new file mode 100644 index 0000000..647b619 --- /dev/null +++ b/Assets/Mirror/Components/Discovery/ServerRequest.cs @@ -0,0 +1,4 @@ +namespace Mirror.Discovery +{ + public struct ServerRequest : NetworkMessage {} +} diff --git a/Assets/Mirror/Components/Discovery/ServerRequest.cs.meta b/Assets/Mirror/Components/Discovery/ServerRequest.cs.meta new file mode 100644 index 0000000..a7e246c --- /dev/null +++ b/Assets/Mirror/Components/Discovery/ServerRequest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ea7254bf7b9454da4adad881d94cd141 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Discovery/ServerResponse.cs b/Assets/Mirror/Components/Discovery/ServerResponse.cs new file mode 100644 index 0000000..7465783 --- /dev/null +++ b/Assets/Mirror/Components/Discovery/ServerResponse.cs @@ -0,0 +1,18 @@ +using System; +using System.Net; + +namespace Mirror.Discovery +{ + public struct ServerResponse : NetworkMessage + { + // The server that sent this + // this is a property so that it is not serialized, but the + // client fills this up after we receive it + public IPEndPoint EndPoint { get; set; } + + public Uri uri; + + // Prevent duplicate server appearance when a connection can be made via LAN on multiple NICs + public long serverId; + } +} \ No newline at end of file diff --git a/Assets/Mirror/Components/Discovery/ServerResponse.cs.meta b/Assets/Mirror/Components/Discovery/ServerResponse.cs.meta new file mode 100644 index 0000000..239b218 --- /dev/null +++ b/Assets/Mirror/Components/Discovery/ServerResponse.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 36f97227fdf2d7a4e902db5bfc43039c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Experimental.meta b/Assets/Mirror/Components/Experimental.meta new file mode 100644 index 0000000..57cce38 --- /dev/null +++ b/Assets/Mirror/Components/Experimental.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bfbf2a1f2b300c5489dcab219ef2846e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs b/Assets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs new file mode 100644 index 0000000..1b19ab7 --- /dev/null +++ b/Assets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs @@ -0,0 +1,90 @@ +using System; +using UnityEngine; + +namespace Mirror.Experimental +{ + [AddComponentMenu("Network/ Experimental/Network Lerp Rigidbody")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-lerp-rigidbody")] + [Obsolete("Use the new NetworkRigidbodyReliable/Unreliable component with Snapshot Interpolation instead.")] + public class NetworkLerpRigidbody : NetworkBehaviour + { + [Header("Settings")] + [SerializeField] internal Rigidbody target = null; + + [Tooltip("How quickly current velocity approaches target velocity")] + [SerializeField] float lerpVelocityAmount = 0.5f; + + [Tooltip("How quickly current position approaches target position")] + [SerializeField] float lerpPositionAmount = 0.5f; + + [Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")] + [SerializeField] bool clientAuthority = false; + + double nextSyncTime; + + [SyncVar()] + Vector3 targetVelocity; + + [SyncVar()] + Vector3 targetPosition; + + /// + /// Ignore value if is host or client with Authority + /// + bool IgnoreSync => isServer || ClientWithAuthority; + + bool ClientWithAuthority => clientAuthority && isOwned; + + protected override void OnValidate() + { + base.OnValidate(); + if (target == null) + target = GetComponent(); + } + + void Update() + { + if (isServer) + SyncToClients(); + else if (ClientWithAuthority) + SendToServer(); + } + + void SyncToClients() + { + targetVelocity = target.velocity; + targetPosition = target.position; + } + + void SendToServer() + { + double now = NetworkTime.localTime; // Unity 2019 doesn't have Time.timeAsDouble yet + if (now > nextSyncTime) + { + nextSyncTime = now + syncInterval; + CmdSendState(target.velocity, target.position); + } + } + + [Command] + void CmdSendState(Vector3 velocity, Vector3 position) + { + target.velocity = velocity; + target.position = position; + targetVelocity = velocity; + targetPosition = position; + } + + void FixedUpdate() + { + if (IgnoreSync) { return; } + + target.velocity = Vector3.Lerp(target.velocity, targetVelocity, lerpVelocityAmount); + target.position = Vector3.Lerp(target.position, targetPosition, lerpPositionAmount); + // add velocity to position as position would have moved on server at that velocity + target.position += target.velocity * Time.fixedDeltaTime; + + // TODO does this also need to sync acceleration so and update velocity? + } + } +} diff --git a/Assets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs.meta b/Assets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs.meta new file mode 100644 index 0000000..35ef1fe --- /dev/null +++ b/Assets/Mirror/Components/Experimental/NetworkLerpRigidbody.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f032128052c95a46afb0ddd97d994cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Experimental/NetworkRigidbody.cs b/Assets/Mirror/Components/Experimental/NetworkRigidbody.cs new file mode 100644 index 0000000..0c2498d --- /dev/null +++ b/Assets/Mirror/Components/Experimental/NetworkRigidbody.cs @@ -0,0 +1,347 @@ +using System; +using UnityEngine; + +namespace Mirror.Experimental +{ + [AddComponentMenu("Network/ Experimental/Network Rigidbody")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-rigidbody")] + [Obsolete("Use the new NetworkRigidbodyReliable/Unreliable component with Snapshot Interpolation instead.")] + public class NetworkRigidbody : NetworkBehaviour + { + [Header("Settings")] + [SerializeField] internal Rigidbody target = null; + + [Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")] + public bool clientAuthority = false; + + [Header("Velocity")] + [Tooltip("Syncs Velocity every SyncInterval")] + [SerializeField] bool syncVelocity = true; + + [Tooltip("Set velocity to 0 each frame (only works if syncVelocity is false")] + [SerializeField] bool clearVelocity = false; + + [Tooltip("Only Syncs Value if distance between previous and current is great than sensitivity")] + [SerializeField] float velocitySensitivity = 0.1f; + + [Header("Angular Velocity")] + [Tooltip("Syncs AngularVelocity every SyncInterval")] + [SerializeField] bool syncAngularVelocity = true; + + [Tooltip("Set angularVelocity to 0 each frame (only works if syncAngularVelocity is false")] + [SerializeField] bool clearAngularVelocity = false; + + [Tooltip("Only Syncs Value if distance between previous and current is great than sensitivity")] + [SerializeField] float angularVelocitySensitivity = 0.1f; + + /// + /// Values sent on client with authority after they are sent to the server + /// + readonly ClientSyncState previousValue = new ClientSyncState(); + + protected override void OnValidate() + { + base.OnValidate(); + if (target == null) + target = GetComponent(); + } + + #region Sync vars + + [SyncVar(hook = nameof(OnVelocityChanged))] + Vector3 velocity; + + [SyncVar(hook = nameof(OnAngularVelocityChanged))] + Vector3 angularVelocity; + + [SyncVar(hook = nameof(OnIsKinematicChanged))] + bool isKinematic; + + [SyncVar(hook = nameof(OnUseGravityChanged))] + bool useGravity; + + [SyncVar(hook = nameof(OnuDragChanged))] + float drag; + + [SyncVar(hook = nameof(OnAngularDragChanged))] + float angularDrag; + + /// + /// Ignore value if is host or client with Authority + /// + /// + bool IgnoreSync => isServer || ClientWithAuthority; + + bool ClientWithAuthority => clientAuthority && isOwned; + + void OnVelocityChanged(Vector3 _, Vector3 newValue) + { + if (IgnoreSync) + return; + + target.velocity = newValue; + } + + void OnAngularVelocityChanged(Vector3 _, Vector3 newValue) + { + if (IgnoreSync) + return; + + target.angularVelocity = newValue; + } + + void OnIsKinematicChanged(bool _, bool newValue) + { + if (IgnoreSync) + return; + + target.isKinematic = newValue; + } + + void OnUseGravityChanged(bool _, bool newValue) + { + if (IgnoreSync) + return; + + target.useGravity = newValue; + } + + void OnuDragChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.drag = newValue; + } + + void OnAngularDragChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.angularDrag = newValue; + } + + #endregion + + internal void Update() + { + if (isServer) + SyncToClients(); + else if (ClientWithAuthority) + SendToServer(); + } + + internal void FixedUpdate() + { + if (clearAngularVelocity && !syncAngularVelocity) + target.angularVelocity = Vector3.zero; + + if (clearVelocity && !syncVelocity) + target.velocity = Vector3.zero; + } + + /// + /// Updates sync var values on server so that they sync to the client + /// + [Server] + void SyncToClients() + { + // only update if they have changed more than Sensitivity + + Vector3 currentVelocity = syncVelocity ? target.velocity : default; + Vector3 currentAngularVelocity = syncAngularVelocity ? target.angularVelocity : default; + + bool velocityChanged = syncVelocity && ((previousValue.velocity - currentVelocity).sqrMagnitude > velocitySensitivity * velocitySensitivity); + bool angularVelocityChanged = syncAngularVelocity && ((previousValue.angularVelocity - currentAngularVelocity).sqrMagnitude > angularVelocitySensitivity * angularVelocitySensitivity); + + if (velocityChanged) + { + velocity = currentVelocity; + previousValue.velocity = currentVelocity; + } + + if (angularVelocityChanged) + { + angularVelocity = currentAngularVelocity; + previousValue.angularVelocity = currentAngularVelocity; + } + + // other rigidbody settings + isKinematic = target.isKinematic; + useGravity = target.useGravity; + drag = target.drag; + angularDrag = target.angularDrag; + } + + /// + /// Uses Command to send values to server + /// + [Client] + void SendToServer() + { + if (!isOwned) + { + Debug.LogWarning("SendToServer called without authority"); + return; + } + + SendVelocity(); + SendRigidBodySettings(); + } + + [Client] + void SendVelocity() + { + double now = NetworkTime.localTime; // Unity 2019 doesn't have Time.timeAsDouble yet + if (now < previousValue.nextSyncTime) + return; + + Vector3 currentVelocity = syncVelocity ? target.velocity : default; + Vector3 currentAngularVelocity = syncAngularVelocity ? target.angularVelocity : default; + + bool velocityChanged = syncVelocity && ((previousValue.velocity - currentVelocity).sqrMagnitude > velocitySensitivity * velocitySensitivity); + bool angularVelocityChanged = syncAngularVelocity && ((previousValue.angularVelocity - currentAngularVelocity).sqrMagnitude > angularVelocitySensitivity * angularVelocitySensitivity); + + // if angularVelocity has changed it is likely that velocity has also changed so just sync both values + // however if only velocity has changed just send velocity + if (angularVelocityChanged) + { + CmdSendVelocityAndAngular(currentVelocity, currentAngularVelocity); + previousValue.velocity = currentVelocity; + previousValue.angularVelocity = currentAngularVelocity; + } + else if (velocityChanged) + { + CmdSendVelocity(currentVelocity); + previousValue.velocity = currentVelocity; + } + + + // only update syncTime if either has changed + if (angularVelocityChanged || velocityChanged) + previousValue.nextSyncTime = now + syncInterval; + } + + [Client] + void SendRigidBodySettings() + { + // These shouldn't change often so it is ok to send in their own Command + if (previousValue.isKinematic != target.isKinematic) + { + CmdSendIsKinematic(target.isKinematic); + previousValue.isKinematic = target.isKinematic; + } + if (previousValue.useGravity != target.useGravity) + { + CmdSendUseGravity(target.useGravity); + previousValue.useGravity = target.useGravity; + } + if (previousValue.drag != target.drag) + { + CmdSendDrag(target.drag); + previousValue.drag = target.drag; + } + if (previousValue.angularDrag != target.angularDrag) + { + CmdSendAngularDrag(target.angularDrag); + previousValue.angularDrag = target.angularDrag; + } + } + + /// + /// Called when only Velocity has changed on the client + /// + [Command] + void CmdSendVelocity(Vector3 velocity) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.velocity = velocity; + target.velocity = velocity; + } + + /// + /// Called when angularVelocity has changed on the client + /// + [Command] + void CmdSendVelocityAndAngular(Vector3 velocity, Vector3 angularVelocity) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + if (syncVelocity) + { + this.velocity = velocity; + target.velocity = velocity; + } + + this.angularVelocity = angularVelocity; + target.angularVelocity = angularVelocity; + } + + [Command] + void CmdSendIsKinematic(bool isKinematic) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.isKinematic = isKinematic; + target.isKinematic = isKinematic; + } + + [Command] + void CmdSendUseGravity(bool useGravity) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.useGravity = useGravity; + target.useGravity = useGravity; + } + + [Command] + void CmdSendDrag(float drag) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.drag = drag; + target.drag = drag; + } + + [Command] + void CmdSendAngularDrag(float angularDrag) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.angularDrag = angularDrag; + target.angularDrag = angularDrag; + } + + /// + /// holds previously synced values + /// + public class ClientSyncState + { + /// + /// Next sync time that velocity will be synced, based on syncInterval. + /// + public double nextSyncTime; + public Vector3 velocity; + public Vector3 angularVelocity; + public bool isKinematic; + public bool useGravity; + public float drag; + public float angularDrag; + } + } +} diff --git a/Assets/Mirror/Components/Experimental/NetworkRigidbody.cs.meta b/Assets/Mirror/Components/Experimental/NetworkRigidbody.cs.meta new file mode 100644 index 0000000..1610f0a --- /dev/null +++ b/Assets/Mirror/Components/Experimental/NetworkRigidbody.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83392ae5c1b731446909f252fd494ae4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Experimental/NetworkRigidbody2D.cs b/Assets/Mirror/Components/Experimental/NetworkRigidbody2D.cs new file mode 100644 index 0000000..e3bdd29 --- /dev/null +++ b/Assets/Mirror/Components/Experimental/NetworkRigidbody2D.cs @@ -0,0 +1,342 @@ +using UnityEngine; + +namespace Mirror.Experimental +{ + [AddComponentMenu("Network/ Experimental/Network Rigidbody 2D")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-rigidbody")] + public class NetworkRigidbody2D : NetworkBehaviour + { + [Header("Settings")] + [SerializeField] internal Rigidbody2D target = null; + + [Tooltip("Set to true if moves come from owner client, set to false if moves always come from server")] + public bool clientAuthority = false; + + [Header("Velocity")] + [Tooltip("Syncs Velocity every SyncInterval")] + [SerializeField] bool syncVelocity = true; + + [Tooltip("Set velocity to 0 each frame (only works if syncVelocity is false")] + [SerializeField] bool clearVelocity = false; + + [Tooltip("Only Syncs Value if distance between previous and current is great than sensitivity")] + [SerializeField] float velocitySensitivity = 0.1f; + + [Header("Angular Velocity")] + [Tooltip("Syncs AngularVelocity every SyncInterval")] + [SerializeField] bool syncAngularVelocity = true; + + [Tooltip("Set angularVelocity to 0 each frame (only works if syncAngularVelocity is false")] + [SerializeField] bool clearAngularVelocity = false; + + [Tooltip("Only Syncs Value if distance between previous and current is great than sensitivity")] + [SerializeField] float angularVelocitySensitivity = 0.1f; + + /// + /// Values sent on client with authority after they are sent to the server + /// + readonly ClientSyncState previousValue = new ClientSyncState(); + + protected override void OnValidate() + { + base.OnValidate(); + if (target == null) + target = GetComponent(); + } + + #region Sync vars + + [SyncVar(hook = nameof(OnVelocityChanged))] + Vector2 velocity; + + [SyncVar(hook = nameof(OnAngularVelocityChanged))] + float angularVelocity; + + [SyncVar(hook = nameof(OnIsKinematicChanged))] + bool isKinematic; + + [SyncVar(hook = nameof(OnGravityScaleChanged))] + float gravityScale; + + [SyncVar(hook = nameof(OnuDragChanged))] + float drag; + + [SyncVar(hook = nameof(OnAngularDragChanged))] + float angularDrag; + + /// + /// Ignore value if is host or client with Authority + /// + bool IgnoreSync => isServer || ClientWithAuthority; + + bool ClientWithAuthority => clientAuthority && isOwned; + + void OnVelocityChanged(Vector2 _, Vector2 newValue) + { + if (IgnoreSync) + return; + + target.velocity = newValue; + } + + void OnAngularVelocityChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.angularVelocity = newValue; + } + + void OnIsKinematicChanged(bool _, bool newValue) + { + if (IgnoreSync) + return; + + target.isKinematic = newValue; + } + + void OnGravityScaleChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.gravityScale = newValue; + } + + void OnuDragChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.drag = newValue; + } + + void OnAngularDragChanged(float _, float newValue) + { + if (IgnoreSync) + return; + + target.angularDrag = newValue; + } + + #endregion + + internal void Update() + { + if (isServer) + SyncToClients(); + else if (ClientWithAuthority) + SendToServer(); + } + + internal void FixedUpdate() + { + if (clearAngularVelocity && !syncAngularVelocity) + target.angularVelocity = 0f; + + if (clearVelocity && !syncVelocity) + target.velocity = Vector2.zero; + } + + /// + /// Updates sync var values on server so that they sync to the client + /// + [Server] + void SyncToClients() + { + // only update if they have changed more than Sensitivity + + Vector2 currentVelocity = syncVelocity ? target.velocity : default; + float currentAngularVelocity = syncAngularVelocity ? target.angularVelocity : default; + + bool velocityChanged = syncVelocity && ((previousValue.velocity - currentVelocity).sqrMagnitude > velocitySensitivity * velocitySensitivity); + bool angularVelocityChanged = syncAngularVelocity && ((previousValue.angularVelocity - currentAngularVelocity) > angularVelocitySensitivity); + + if (velocityChanged) + { + velocity = currentVelocity; + previousValue.velocity = currentVelocity; + } + + if (angularVelocityChanged) + { + angularVelocity = currentAngularVelocity; + previousValue.angularVelocity = currentAngularVelocity; + } + + // other rigidbody settings + isKinematic = target.isKinematic; + gravityScale = target.gravityScale; + drag = target.drag; + angularDrag = target.angularDrag; + } + + /// + /// Uses Command to send values to server + /// + [Client] + void SendToServer() + { + if (!isOwned) + { + Debug.LogWarning("SendToServer called without authority"); + return; + } + + SendVelocity(); + SendRigidBodySettings(); + } + + [Client] + void SendVelocity() + { + float now = Time.time; + if (now < previousValue.nextSyncTime) + return; + + Vector2 currentVelocity = syncVelocity ? target.velocity : default; + float currentAngularVelocity = syncAngularVelocity ? target.angularVelocity : default; + + bool velocityChanged = syncVelocity && ((previousValue.velocity - currentVelocity).sqrMagnitude > velocitySensitivity * velocitySensitivity); + bool angularVelocityChanged = syncAngularVelocity && previousValue.angularVelocity != currentAngularVelocity;//((previousValue.angularVelocity - currentAngularVelocity).sqrMagnitude > angularVelocitySensitivity * angularVelocitySensitivity); + + // if angularVelocity has changed it is likely that velocity has also changed so just sync both values + // however if only velocity has changed just send velocity + if (angularVelocityChanged) + { + CmdSendVelocityAndAngular(currentVelocity, currentAngularVelocity); + previousValue.velocity = currentVelocity; + previousValue.angularVelocity = currentAngularVelocity; + } + else if (velocityChanged) + { + CmdSendVelocity(currentVelocity); + previousValue.velocity = currentVelocity; + } + + // only update syncTime if either has changed + if (angularVelocityChanged || velocityChanged) + previousValue.nextSyncTime = now + syncInterval; + } + + [Client] + void SendRigidBodySettings() + { + // These shouldn't change often so it is ok to send in their own Command + if (previousValue.isKinematic != target.isKinematic) + { + CmdSendIsKinematic(target.isKinematic); + previousValue.isKinematic = target.isKinematic; + } + if (previousValue.gravityScale != target.gravityScale) + { + CmdChangeGravityScale(target.gravityScale); + previousValue.gravityScale = target.gravityScale; + } + if (previousValue.drag != target.drag) + { + CmdSendDrag(target.drag); + previousValue.drag = target.drag; + } + if (previousValue.angularDrag != target.angularDrag) + { + CmdSendAngularDrag(target.angularDrag); + previousValue.angularDrag = target.angularDrag; + } + } + + /// + /// Called when only Velocity has changed on the client + /// + [Command] + void CmdSendVelocity(Vector2 velocity) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.velocity = velocity; + target.velocity = velocity; + } + + /// + /// Called when angularVelocity has changed on the client + /// + [Command] + void CmdSendVelocityAndAngular(Vector2 velocity, float angularVelocity) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + if (syncVelocity) + { + this.velocity = velocity; + target.velocity = velocity; + } + this.angularVelocity = angularVelocity; + target.angularVelocity = angularVelocity; + } + + [Command] + void CmdSendIsKinematic(bool isKinematic) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.isKinematic = isKinematic; + target.isKinematic = isKinematic; + } + + [Command] + void CmdChangeGravityScale(float gravityScale) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.gravityScale = gravityScale; + target.gravityScale = gravityScale; + } + + [Command] + void CmdSendDrag(float drag) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.drag = drag; + target.drag = drag; + } + + [Command] + void CmdSendAngularDrag(float angularDrag) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + this.angularDrag = angularDrag; + target.angularDrag = angularDrag; + } + + /// + /// holds previously synced values + /// + public class ClientSyncState + { + /// + /// Next sync time that velocity will be synced, based on syncInterval. + /// + public float nextSyncTime; + public Vector2 velocity; + public float angularVelocity; + public bool isKinematic; + public float gravityScale; + public float drag; + public float angularDrag; + } + } +} diff --git a/Assets/Mirror/Components/Experimental/NetworkRigidbody2D.cs.meta b/Assets/Mirror/Components/Experimental/NetworkRigidbody2D.cs.meta new file mode 100644 index 0000000..df466bd --- /dev/null +++ b/Assets/Mirror/Components/Experimental/NetworkRigidbody2D.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ab2cbc52526ea384ba280d13cd1a57b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/GUIConsole.cs b/Assets/Mirror/Components/GUIConsole.cs new file mode 100644 index 0000000..c6acbb8 --- /dev/null +++ b/Assets/Mirror/Components/GUIConsole.cs @@ -0,0 +1,115 @@ +// People should be able to see and report errors to the developer very easily. +// +// Unity's Developer Console only works in development builds and it only shows +// errors. This class provides a console that works in all builds and also shows +// log and warnings in development builds. +// +// Note: we don't include the stack trace, because that can also be grabbed from +// the log files if needed. +// +// Note: there is no 'hide' button because we DO want people to see those errors +// and report them back to us. +// +// Note: normal Debug.Log messages can be shown by building in Debug/Development +// mode. +using UnityEngine; +using System.Collections.Generic; + +namespace Mirror +{ + struct LogEntry + { + public string message; + public LogType type; + + public LogEntry(string message, LogType type) + { + this.message = message; + this.type = type; + } + } + + public class GUIConsole : MonoBehaviour + { + public int height = 150; + + // only keep the recent 'n' entries. otherwise memory would grow forever + // and drawing would get slower and slower. + public int maxLogCount = 50; + + // log as queue so we can remove the first entry easily + Queue log = new Queue(); + + // hotkey to show/hide at runtime for easier debugging + // (sometimes we need to temporarily hide/show it) + // => F12 makes sense. nobody can find ^ in other games. + public KeyCode hotKey = KeyCode.F12; + + // GUI + bool visible; + Vector2 scroll = Vector2.zero; + + void Awake() + { + Application.logMessageReceived += OnLog; + } + + // OnLog logs everything, even Debug.Log messages in release builds + // => this makes a lot of things easier. e.g. addon initialization logs. + // => it's really better to have than not to have those + void OnLog(string message, string stackTrace, LogType type) + { + // is this important? + // => always show exceptions & errors + // => usually a good idea to show warnings too, otherwise it's too + // easy to miss OnDeserialize warnings etc. in builds + bool isImportant = type == LogType.Error || type == LogType.Exception || type == LogType.Warning; + + // use stack trace only if important + // (otherwise users would have to find and search the log file. + // seeing it in the console directly is way easier to deal with.) + // => only add \n if stack trace is available (only in debug builds) + if (isImportant && !string.IsNullOrWhiteSpace(stackTrace)) + message += $"\n{stackTrace}"; + + // add to queue + log.Enqueue(new LogEntry(message, type)); + + // respect max entries + if (log.Count > maxLogCount) + log.Dequeue(); + + // become visible if it was important + // (no need to become visible for regular log. let the user decide.) + if (isImportant) + visible = true; + + // auto scroll + scroll.y = float.MaxValue; + } + + void Update() + { + if (Input.GetKeyDown(hotKey)) + visible = !visible; + } + + void OnGUI() + { + if (!visible) return; + + scroll = GUILayout.BeginScrollView(scroll, "Box", GUILayout.Width(Screen.width), GUILayout.Height(height)); + foreach (LogEntry entry in log) + { + if (entry.type == LogType.Error || entry.type == LogType.Exception) + GUI.color = Color.red; + else if (entry.type == LogType.Warning) + GUI.color = Color.yellow; + + GUILayout.Label(entry.message); + GUI.color = Color.white; + } + GUILayout.EndScrollView(); + } + } +} diff --git a/Assets/Mirror/Components/GUIConsole.cs.meta b/Assets/Mirror/Components/GUIConsole.cs.meta new file mode 100644 index 0000000..5664216 --- /dev/null +++ b/Assets/Mirror/Components/GUIConsole.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9021b6cc314944290986ab6feb48db79 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement.meta b/Assets/Mirror/Components/InterestManagement.meta new file mode 100644 index 0000000..9b1f746 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c66f27e006ab94253b39a55a3b213651 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/Distance.meta b/Assets/Mirror/Components/InterestManagement/Distance.meta new file mode 100644 index 0000000..9847902 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Distance.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fa4cbc6b9c584db4971985cb9f369077 +timeCreated: 1613110605 \ No newline at end of file diff --git a/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs new file mode 100644 index 0000000..0441558 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs @@ -0,0 +1,90 @@ +// straight forward Vector3.Distance based interest management. +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Distance/Distance Interest Management")] + public class DistanceInterestManagement : InterestManagement + { + [Tooltip("The maximum range that objects will be visible at. Add DistanceInterestManagementCustomRange onto NetworkIdentities for custom ranges.")] + public int visRange = 500; + + [Tooltip("Rebuild all every 'rebuildInterval' seconds.")] + public float rebuildInterval = 1; + double lastRebuildTime; + + // cache custom ranges to avoid runtime TryGetComponent lookups + readonly Dictionary CustomRanges = new Dictionary(); + + // helper function to get vis range for a given object, or default. + [ServerCallback] + int GetVisRange(NetworkIdentity identity) + { + return CustomRanges.TryGetValue(identity, out DistanceInterestManagementCustomRange custom) ? custom.visRange : visRange; + } + + [ServerCallback] + public override void Reset() + { + lastRebuildTime = 0D; + CustomRanges.Clear(); + } + + public override void OnSpawned(NetworkIdentity identity) + { + if (identity.TryGetComponent(out DistanceInterestManagementCustomRange custom)) + CustomRanges[identity] = custom; + } + + public override void OnDestroyed(NetworkIdentity identity) + { + CustomRanges.Remove(identity); + } + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + int range = GetVisRange(identity); + return Vector3.Distance(identity.transform.position, newObserver.identity.transform.position) < range; + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + // cache range and .transform because both call GetComponent. + int range = GetVisRange(identity); + Vector3 position = identity.transform.position; + + // brute force distance check + // -> only player connections can be observers, so it's enough if we + // go through all connections instead of all spawned identities. + // -> compared to UNET's sphere cast checking, this one is orders of + // magnitude faster. if we have 10k monsters and run a sphere + // cast 10k times, we will see a noticeable lag even with physics + // layers. but checking to every connection is fast. + foreach (NetworkConnectionToClient conn in NetworkServer.connections.Values) + { + // authenticated and joined world with a player? + if (conn != null && conn.isAuthenticated && conn.identity != null) + { + // check distance + if (Vector3.Distance(conn.identity.transform.position, position) < range) + { + newObservers.Add(conn); + } + } + } + } + + // internal so we can update from tests + [ServerCallback] + internal void Update() + { + // rebuild all spawned NetworkIdentity's observers every interval + if (NetworkTime.localTime >= lastRebuildTime + rebuildInterval) + { + RebuildAll(); + lastRebuildTime = NetworkTime.localTime; + } + } + } +} diff --git a/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs.meta b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs.meta new file mode 100644 index 0000000..1a575af --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f60becab051427fbdd3c8ac9ab4712b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs new file mode 100644 index 0000000..12556e5 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs @@ -0,0 +1,15 @@ +// add this to NetworkIdentities for custom range if needed. +// only works with DistanceInterestManagement. +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [AddComponentMenu("Network/ Interest Management/ Distance/Distance Custom Range")] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public class DistanceInterestManagementCustomRange : NetworkBehaviour + { + [Tooltip("The maximum range that objects will be visible at.")] + public int visRange = 100; + } +} diff --git a/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs.meta b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs.meta new file mode 100644 index 0000000..406ca78 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagementCustomRange.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2e242ee38a14076a39934172a19079b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/Match.meta b/Assets/Mirror/Components/InterestManagement/Match.meta new file mode 100644 index 0000000..e429883 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Match.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5eca5245ae6bb460e9a92f7e14d5493a +timeCreated: 1622649517 \ No newline at end of file diff --git a/Assets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs b/Assets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs new file mode 100644 index 0000000..516cf55 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Match/Match Interest Management")] + public class MatchInterestManagement : InterestManagement + { + readonly Dictionary> matchObjects = + new Dictionary>(); + + readonly Dictionary lastObjectMatch = + new Dictionary(); + + readonly HashSet dirtyMatches = new HashSet(); + + [ServerCallback] + public override void OnSpawned(NetworkIdentity identity) + { + if (!identity.TryGetComponent(out NetworkMatch networkMatch)) + return; + + Guid networkMatchId = networkMatch.matchId; + lastObjectMatch[identity] = networkMatchId; + + // Guid.Empty is never a valid matchId...do not add to matchObjects collection + if (networkMatchId == Guid.Empty) + return; + + // Debug.Log($"MatchInterestManagement.OnSpawned({identity.name}) currentMatch: {currentMatch}"); + if (!matchObjects.TryGetValue(networkMatchId, out HashSet objects)) + { + objects = new HashSet(); + matchObjects.Add(networkMatchId, objects); + } + + objects.Add(identity); + + // Match ID could have been set in NetworkBehaviour::OnStartServer on this object. + // Since that's after OnCheckObserver is called it would be missed, so force Rebuild here. + // Add the current match to dirtyMatches for Update to rebuild it. + dirtyMatches.Add(networkMatchId); + } + + [ServerCallback] + public override void OnDestroyed(NetworkIdentity identity) + { + // Don't RebuildSceneObservers here - that will happen in Update. + // Multiple objects could be destroyed in same frame and we don't + // want to rebuild for each one...let Update do it once. + // We must add the current match to dirtyMatches for Update to rebuild it. + if (lastObjectMatch.TryGetValue(identity, out Guid currentMatch)) + { + lastObjectMatch.Remove(identity); + if (currentMatch != Guid.Empty && matchObjects.TryGetValue(currentMatch, out HashSet objects) && objects.Remove(identity)) + dirtyMatches.Add(currentMatch); + } + } + + // internal so we can update from tests + [ServerCallback] + internal void Update() + { + // for each spawned: + // if match changed: + // add previous to dirty + // add new to dirty + foreach (NetworkIdentity identity in NetworkServer.spawned.Values) + { + // Ignore objects that don't have a NetworkMatch component + if (!identity.TryGetComponent(out NetworkMatch networkMatch)) + continue; + + Guid newMatch = networkMatch.matchId; + if (!lastObjectMatch.TryGetValue(identity, out Guid currentMatch)) + continue; + + // Guid.Empty is never a valid matchId + // Nothing to do if matchId hasn't changed + if (newMatch == Guid.Empty || newMatch == currentMatch) + continue; + + // Mark new/old matches as dirty so they get rebuilt + UpdateDirtyMatches(newMatch, currentMatch); + + // This object is in a new match so observers in the prior match + // and the new match need to rebuild their respective observers lists. + UpdateMatchObjects(identity, newMatch, currentMatch); + } + + // rebuild all dirty matches + foreach (Guid dirtyMatch in dirtyMatches) + RebuildMatchObservers(dirtyMatch); + + dirtyMatches.Clear(); + } + + void UpdateDirtyMatches(Guid newMatch, Guid currentMatch) + { + // Guid.Empty is never a valid matchId + if (currentMatch != Guid.Empty) + dirtyMatches.Add(currentMatch); + + dirtyMatches.Add(newMatch); + } + + void UpdateMatchObjects(NetworkIdentity netIdentity, Guid newMatch, Guid currentMatch) + { + // Remove this object from the hashset of the match it just left + // Guid.Empty is never a valid matchId + if (currentMatch != Guid.Empty) + matchObjects[currentMatch].Remove(netIdentity); + + // Set this to the new match this object just entered + lastObjectMatch[netIdentity] = newMatch; + + // Make sure this new match is in the dictionary + if (!matchObjects.ContainsKey(newMatch)) + matchObjects.Add(newMatch, new HashSet()); + + // Add this object to the hashset of the new match + matchObjects[newMatch].Add(netIdentity); + } + + void RebuildMatchObservers(Guid matchId) + { + foreach (NetworkIdentity netIdentity in matchObjects[matchId]) + if (netIdentity != null) + NetworkServer.RebuildObservers(netIdentity, false); + } + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + // Never observed if no NetworkMatch component + if (!identity.TryGetComponent(out NetworkMatch identityNetworkMatch)) + return false; + + // Guid.Empty is never a valid matchId + if (identityNetworkMatch.matchId == Guid.Empty) + return false; + + // Never observed if no NetworkMatch component + if (!newObserver.identity.TryGetComponent(out NetworkMatch newObserverNetworkMatch)) + return false; + + // Guid.Empty is never a valid matchId + if (newObserverNetworkMatch.matchId == Guid.Empty) + return false; + + return identityNetworkMatch.matchId == newObserverNetworkMatch.matchId; + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + if (!identity.TryGetComponent(out NetworkMatch networkMatch)) + return; + + Guid matchId = networkMatch.matchId; + + // Guid.Empty is never a valid matchId + if (matchId == Guid.Empty) + return; + + if (!matchObjects.TryGetValue(matchId, out HashSet objects)) + return; + + // Add everything in the hashset for this object's current match + foreach (NetworkIdentity networkIdentity in objects) + if (networkIdentity != null && networkIdentity.connectionToClient != null) + newObservers.Add(networkIdentity.connectionToClient); + } + } +} diff --git a/Assets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs.meta b/Assets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs.meta new file mode 100644 index 0000000..605d215 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Match/MatchInterestManagement.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d09f5c8bf2f4747b7a9284ef5d9ce2a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs b/Assets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs new file mode 100644 index 0000000..f6689f2 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs @@ -0,0 +1,15 @@ +// simple component that holds match information +using System; +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [AddComponentMenu("Network/ Interest Management/ Match/Network Match")] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public class NetworkMatch : NetworkBehaviour + { + ///Set this to the same value on all networked objects that belong to a given match + public Guid matchId; + } +} diff --git a/Assets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs.meta b/Assets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs.meta new file mode 100644 index 0000000..47fc70a --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Match/NetworkMatch.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5d17e718851449a6879986e45c458fb7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/Scene.meta b/Assets/Mirror/Components/InterestManagement/Scene.meta new file mode 100644 index 0000000..28b469f --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Scene.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7655d309a46a4bd4860edf964228b3f6 +timeCreated: 1622649517 \ No newline at end of file diff --git a/Assets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs b/Assets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs new file mode 100644 index 0000000..28e5eba --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Scene/Scene Interest Management")] + public class SceneInterestManagement : InterestManagement + { + // Use Scene instead of string scene.name because when additively + // loading multiples of a subscene the name won't be unique + readonly Dictionary> sceneObjects = + new Dictionary>(); + + readonly Dictionary lastObjectScene = + new Dictionary(); + + HashSet dirtyScenes = new HashSet(); + + [ServerCallback] + public override void OnSpawned(NetworkIdentity identity) + { + Scene currentScene = identity.gameObject.scene; + lastObjectScene[identity] = currentScene; + // Debug.Log($"SceneInterestManagement.OnSpawned({identity.name}) currentScene: {currentScene}"); + if (!sceneObjects.TryGetValue(currentScene, out HashSet objects)) + { + objects = new HashSet(); + sceneObjects.Add(currentScene, objects); + } + + objects.Add(identity); + } + + [ServerCallback] + public override void OnDestroyed(NetworkIdentity identity) + { + // Don't RebuildSceneObservers here - that will happen in Update. + // Multiple objects could be destroyed in same frame and we don't + // want to rebuild for each one...let Update do it once. + // We must add the current scene to dirtyScenes for Update to rebuild it. + if (lastObjectScene.TryGetValue(identity, out Scene currentScene)) + { + lastObjectScene.Remove(identity); + if (sceneObjects.TryGetValue(currentScene, out HashSet objects) && objects.Remove(identity)) + dirtyScenes.Add(currentScene); + } + } + + // internal so we can update from tests + [ServerCallback] + internal void Update() + { + // for each spawned: + // if scene changed: + // add previous to dirty + // add new to dirty + foreach (NetworkIdentity identity in NetworkServer.spawned.Values) + { + if (!lastObjectScene.TryGetValue(identity, out Scene currentScene)) + continue; + + Scene newScene = identity.gameObject.scene; + if (newScene == currentScene) + continue; + + // Mark new/old scenes as dirty so they get rebuilt + dirtyScenes.Add(currentScene); + dirtyScenes.Add(newScene); + + // This object is in a new scene so observers in the prior scene + // and the new scene need to rebuild their respective observers lists. + + // Remove this object from the hashset of the scene it just left + sceneObjects[currentScene].Remove(identity); + + // Set this to the new scene this object just entered + lastObjectScene[identity] = newScene; + + // Make sure this new scene is in the dictionary + if (!sceneObjects.ContainsKey(newScene)) + sceneObjects.Add(newScene, new HashSet()); + + // Add this object to the hashset of the new scene + sceneObjects[newScene].Add(identity); + } + + // rebuild all dirty scenes + foreach (Scene dirtyScene in dirtyScenes) + RebuildSceneObservers(dirtyScene); + + dirtyScenes.Clear(); + } + + void RebuildSceneObservers(Scene scene) + { + foreach (NetworkIdentity netIdentity in sceneObjects[scene]) + if (netIdentity != null) + NetworkServer.RebuildObservers(netIdentity, false); + } + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + return identity.gameObject.scene == newObserver.identity.gameObject.scene; + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + if (!sceneObjects.TryGetValue(identity.gameObject.scene, out HashSet objects)) + return; + + // Add everything in the hashset for this object's current scene + foreach (NetworkIdentity networkIdentity in objects) + if (networkIdentity != null && networkIdentity.connectionToClient != null) + newObservers.Add(networkIdentity.connectionToClient); + } + } +} diff --git a/Assets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs.meta b/Assets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs.meta new file mode 100644 index 0000000..9cc1ff5 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Scene/SceneInterestManagement.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b979f26c95d34324ba005bfacfa9c4fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/SpatialHashing.meta b/Assets/Mirror/Components/InterestManagement/SpatialHashing.meta new file mode 100644 index 0000000..00f5cd6 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/SpatialHashing.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cfa12b73503344d49b398b01bcb07967 +timeCreated: 1613110634 \ No newline at end of file diff --git a/Assets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs b/Assets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs new file mode 100644 index 0000000..d557713 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs @@ -0,0 +1,104 @@ +// Grid2D from uMMORPG: get/set values of type T at any point +// -> not named 'Grid' because Unity already has a Grid type. causes warnings. +// -> struct to avoid memory indirection. it's accessed a lot. +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // struct to avoid memory indirection. it's accessed a lot. + public struct Grid2D + { + // the grid + // note that we never remove old keys. + // => over time, HashSets will be allocated for every possible + // grid position in the world + // => Clear() doesn't clear them so we don't constantly reallocate the + // entries when populating the grid in every Update() call + // => makes the code a lot easier too + // => this is FINE because in the worst case, every grid position in the + // game world is filled with a player anyway! + readonly Dictionary> grid; + + // cache a 9 neighbor grid of vector2 offsets so we can use them more easily + readonly Vector2Int[] neighbourOffsets; + + public Grid2D(int initialCapacity) + { + grid = new Dictionary>(initialCapacity); + + neighbourOffsets = new[] { + Vector2Int.up, + Vector2Int.up + Vector2Int.left, + Vector2Int.up + Vector2Int.right, + Vector2Int.left, + Vector2Int.zero, + Vector2Int.right, + Vector2Int.down, + Vector2Int.down + Vector2Int.left, + Vector2Int.down + Vector2Int.right + }; + } + + // helper function so we can add an entry without worrying + public void Add(Vector2Int position, T value) + { + // initialize set in grid if it's not in there yet + if (!grid.TryGetValue(position, out HashSet hashSet)) + { + // each grid entry may hold hundreds of entities. + // let's create the HashSet with a large initial capacity + // in order to avoid resizing & allocations. +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have "new HashSet(capacity)" yet + hashSet = new HashSet(); +#else + hashSet = new HashSet(128); +#endif + grid[position] = hashSet; + } + + // add to it + hashSet.Add(value); + } + + // helper function to get set at position without worrying + // -> result is passed as parameter to avoid allocations + // -> result is not cleared before. this allows us to pass the HashSet from + // GetWithNeighbours and avoid .UnionWith which is very expensive. + void GetAt(Vector2Int position, HashSet result) + { + // return the set at position + if (grid.TryGetValue(position, out HashSet hashSet)) + { + foreach (T entry in hashSet) + result.Add(entry); + } + } + + // helper function to get at position and it's 8 neighbors without worrying + // -> result is passed as parameter to avoid allocations + public void GetWithNeighbours(Vector2Int position, HashSet result) + { + // clear result first + result.Clear(); + + // add neighbours + foreach (Vector2Int offset in neighbourOffsets) + GetAt(position + offset, result); + } + + // clear: clears the whole grid + // IMPORTANT: we already allocated HashSets and don't want to do + // reallocate every single update when we rebuild the grid. + // => so simply remove each position's entries, but keep + // every position in there + // => see 'grid' comments above! + // => named ClearNonAlloc to make it more obvious! + public void ClearNonAlloc() + { + foreach (HashSet hashSet in grid.Values) + hashSet.Clear(); + } + } +} diff --git a/Assets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs.meta b/Assets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs.meta new file mode 100644 index 0000000..f1d3cf0 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c5232a4d2854116a35d52b80ec07752 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs b/Assets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs new file mode 100644 index 0000000..2986034 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs @@ -0,0 +1,154 @@ +// extremely fast spatial hashing interest management based on uMMORPG GridChecker. +// => 30x faster in initial tests +// => scales way higher +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Spatial Hash/Spatial Hashing Interest Management")] + public class SpatialHashingInterestManagement : InterestManagement + { + [Tooltip("The maximum range that objects will be visible at.")] + public int visRange = 30; + + // we use a 9 neighbour grid. + // so we always see in a distance of 2 grids. + // for example, our own grid and then one on top / below / left / right. + // + // this means that grid resolution needs to be distance / 2. + // so for example, for distance = 30 we see 2 cells = 15 * 2 distance. + // + // on first sight, it seems we need distance / 3 (we see left/us/right). + // but that's not the case. + // resolution would be 10, and we only see 1 cell far, so 10+10=20. + public int resolution => visRange / 2; + + [Tooltip("Rebuild all every 'rebuildInterval' seconds.")] + public float rebuildInterval = 1; + double lastRebuildTime; + + public enum CheckMethod + { + XZ_FOR_3D, + XY_FOR_2D + } + [Tooltip("Spatial Hashing supports 3D (XZ) and 2D (XY) games.")] + public CheckMethod checkMethod = CheckMethod.XZ_FOR_3D; + + // debugging + public bool showSlider; + + // the grid + // begin with a large capacity to avoid resizing & allocations. + Grid2D grid = new Grid2D(1024); + + // project 3d world position to grid position + Vector2Int ProjectToGrid(Vector3 position) => + checkMethod == CheckMethod.XZ_FOR_3D + ? Vector2Int.RoundToInt(new Vector2(position.x, position.z) / resolution) + : Vector2Int.RoundToInt(new Vector2(position.x, position.y) / resolution); + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + // calculate projected positions + Vector2Int projected = ProjectToGrid(identity.transform.position); + Vector2Int observerProjected = ProjectToGrid(newObserver.identity.transform.position); + + // distance needs to be at max one of the 8 neighbors, which is + // 1 for the direct neighbors + // 1.41 for the diagonal neighbors (= sqrt(2)) + // => use sqrMagnitude and '2' to avoid computations. same result. + return (projected - observerProjected).sqrMagnitude <= 2; + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + // add everyone in 9 neighbour grid + // -> pass observers to GetWithNeighbours directly to avoid allocations + // and expensive .UnionWith computations. + Vector2Int current = ProjectToGrid(identity.transform.position); + grid.GetWithNeighbours(current, newObservers); + } + + [ServerCallback] + public override void Reset() + { + lastRebuildTime = 0D; + } + + // update everyone's position in the grid + // (internal so we can update from tests) + [ServerCallback] + internal void Update() + { + // NOTE: unlike Scene/MatchInterestManagement, this rebuilds ALL + // entities every INTERVAL. consider the other approach later. + + // IMPORTANT: refresh grid every update! + // => newly spawned entities get observers assigned via + // OnCheckObservers. this can happen any time and we don't want + // them broadcast to old (moved or destroyed) connections. + // => players do move all the time. we want them to always be in the + // correct grid position. + // => note that the actual 'rebuildall' doesn't need to happen all + // the time. + // NOTE: consider refreshing grid only every 'interval' too. but not + // for now. stability & correctness matter. + + // clear old grid results before we update everyone's position. + // (this way we get rid of destroyed connections automatically) + // + // NOTE: keeps allocated HashSets internally. + // clearing & populating every frame works without allocations + grid.ClearNonAlloc(); + + // put every connection into the grid at it's main player's position + // NOTE: player sees in a radius around him. NOT around his pet too. + foreach (NetworkConnectionToClient connection in NetworkServer.connections.Values) + { + // authenticated and joined world with a player? + if (connection.isAuthenticated && connection.identity != null) + { + // calculate current grid position + Vector2Int position = ProjectToGrid(connection.identity.transform.position); + + // put into grid + grid.Add(position, connection); + } + } + + // rebuild all spawned entities' observers every 'interval' + // this will call OnRebuildObservers which then returns the + // observers at grid[position] for each entity. + if (NetworkTime.localTime >= lastRebuildTime + rebuildInterval) + { + RebuildAll(); + lastRebuildTime = NetworkTime.localTime; + } + } + +// OnGUI allocates even if it does nothing. avoid in release. +#if UNITY_EDITOR || DEVELOPMENT_BUILD + // slider from dotsnet. it's nice to play around with in the benchmark + // demo. + void OnGUI() + { + if (!showSlider) return; + + // only show while server is running. not on client, etc. + if (!NetworkServer.active) return; + + int height = 30; + int width = 250; + GUILayout.BeginArea(new Rect(Screen.width / 2 - width / 2, Screen.height - height, width, height)); + GUILayout.BeginHorizontal("Box"); + GUILayout.Label("Radius:"); + visRange = Mathf.RoundToInt(GUILayout.HorizontalSlider(visRange, 0, 200, GUILayout.Width(150))); + GUILayout.Label(visRange.ToString()); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + } +#endif + } +} diff --git a/Assets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs.meta b/Assets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs.meta new file mode 100644 index 0000000..271e433 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/SpatialHashing/SpatialHashingInterestManagement.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 39adc6e09d5544ed955a50ce8600355a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/Team.meta b/Assets/Mirror/Components/InterestManagement/Team.meta new file mode 100644 index 0000000..fe40aa4 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Team.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2d418e60072433b4bbebbf5f3a7de1bb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs b/Assets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs new file mode 100644 index 0000000..ee02a07 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs @@ -0,0 +1,17 @@ +// simple component that holds team information +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [AddComponentMenu("Network/ Interest Management/ Team/Network Team")] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public class NetworkTeam : NetworkBehaviour + { + [Tooltip("Set this to the same value on all networked objects that belong to a given team")] + [SyncVar] public string teamId = string.Empty; + + [Tooltip("When enabled this object is visible to all clients. Typically this would be true for player objects")] + [SyncVar] public bool forceShown; + } +} diff --git a/Assets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs.meta b/Assets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs.meta new file mode 100644 index 0000000..ca75a7a --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Team/NetworkTeam.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2576730625b1632468cbcbfe5e721f88 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs b/Assets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs new file mode 100644 index 0000000..7701c38 --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs @@ -0,0 +1,196 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/ Interest Management/ Team/Team Interest Management")] + public class TeamInterestManagement : InterestManagement + { + readonly Dictionary> teamObjects = new Dictionary>(); + readonly Dictionary lastObjectTeam = new Dictionary(); + readonly HashSet dirtyTeams = new HashSet(); + + [ServerCallback] + public override void OnSpawned(NetworkIdentity identity) + { + if (!identity.TryGetComponent(out NetworkTeam identityNetworkTeam)) + return; + + string networkTeamId = identityNetworkTeam.teamId; + lastObjectTeam[identity] = networkTeamId; + + // Null / Empty string is never a valid teamId...do not add to teamObjects collection + if (string.IsNullOrWhiteSpace(networkTeamId)) + return; + + //Debug.Log($"TeamInterestManagement.OnSpawned {identity.name} {networkTeamId}"); + + if (!teamObjects.TryGetValue(networkTeamId, out HashSet objects)) + { + objects = new HashSet(); + teamObjects.Add(networkTeamId, objects); + } + + objects.Add(identity); + + // Team ID could have been set in NetworkBehaviour::OnStartServer on this object. + // Since that's after OnCheckObserver is called it would be missed, so force Rebuild here. + // Add the current team to dirtyTeams for Update to rebuild it. + dirtyTeams.Add(networkTeamId); + } + + [ServerCallback] + public override void OnDestroyed(NetworkIdentity identity) + { + // Don't RebuildSceneObservers here - that will happen in Update. + // Multiple objects could be destroyed in same frame and we don't + // want to rebuild for each one...let Update do it once. + // We must add the current team to dirtyTeams for Update to rebuild it. + if (lastObjectTeam.TryGetValue(identity, out string currentTeam)) + { + lastObjectTeam.Remove(identity); + if (!string.IsNullOrWhiteSpace(currentTeam) && teamObjects.TryGetValue(currentTeam, out HashSet objects) && objects.Remove(identity)) + dirtyTeams.Add(currentTeam); + } + } + + // internal so we can update from tests + [ServerCallback] + internal void Update() + { + // for each spawned: + // if team changed: + // add previous to dirty + // add new to dirty + foreach (NetworkIdentity netIdentity in NetworkServer.spawned.Values) + { + // Ignore objects that don't have a NetworkTeam component + if (!netIdentity.TryGetComponent(out NetworkTeam identityNetworkTeam)) + continue; + + string networkTeamId = identityNetworkTeam.teamId; + if (!lastObjectTeam.TryGetValue(netIdentity, out string currentTeam)) + continue; + + // Null / Empty string is never a valid teamId + // Nothing to do if teamId hasn't changed + if (string.IsNullOrWhiteSpace(networkTeamId) || networkTeamId == currentTeam) + continue; + + // Mark new/old Teams as dirty so they get rebuilt + UpdateDirtyTeams(networkTeamId, currentTeam); + + // This object is in a new team so observers in the prior team + // and the new team need to rebuild their respective observers lists. + UpdateTeamObjects(netIdentity, networkTeamId, currentTeam); + } + + // rebuild all dirty teams + foreach (string dirtyTeam in dirtyTeams) + RebuildTeamObservers(dirtyTeam); + + dirtyTeams.Clear(); + } + + void UpdateDirtyTeams(string newTeam, string currentTeam) + { + // Null / Empty string is never a valid teamId + if (!string.IsNullOrWhiteSpace(currentTeam)) + dirtyTeams.Add(currentTeam); + + dirtyTeams.Add(newTeam); + } + + void UpdateTeamObjects(NetworkIdentity netIdentity, string newTeam, string currentTeam) + { + // Remove this object from the hashset of the team it just left + // string.Empty is never a valid teamId + if (!string.IsNullOrWhiteSpace(currentTeam)) + teamObjects[currentTeam].Remove(netIdentity); + + // Set this to the new team this object just entered + lastObjectTeam[netIdentity] = newTeam; + + // Make sure this new team is in the dictionary + if (!teamObjects.ContainsKey(newTeam)) + teamObjects.Add(newTeam, new HashSet()); + + // Add this object to the hashset of the new team + teamObjects[newTeam].Add(netIdentity); + } + + void RebuildTeamObservers(string teamId) + { + foreach (NetworkIdentity netIdentity in teamObjects[teamId]) + if (netIdentity != null) + NetworkServer.RebuildObservers(netIdentity, false); + } + + public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver) + { + // Always observed if no NetworkTeam component + if (!identity.TryGetComponent(out NetworkTeam identityNetworkTeam)) + return true; + + if (identityNetworkTeam.forceShown) + return true; + + // string.Empty is never a valid teamId + if (string.IsNullOrWhiteSpace(identityNetworkTeam.teamId)) + return false; + + // Always observed if no NetworkTeam component + if (!newObserver.identity.TryGetComponent(out NetworkTeam newObserverNetworkTeam)) + return true; + + // Null / Empty string is never a valid teamId + if (string.IsNullOrWhiteSpace(newObserverNetworkTeam.teamId)) + return false; + + //Debug.Log($"TeamInterestManagement.OnCheckObserver {identity.name} {identityNetworkTeam.teamId} | {newObserver.identity.name} {newObserverNetworkTeam.teamId}"); + + // Observed only if teamId's match + return identityNetworkTeam.teamId == newObserverNetworkTeam.teamId; + } + + public override void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers) + { + // If this object doesn't have a NetworkTeam then it's visible to all clients + if (!identity.TryGetComponent(out NetworkTeam networkTeam)) + { + AddAllConnections(newObservers); + return; + } + + // If this object has NetworkTeam and forceShown == true then it's visible to all clients + if (networkTeam.forceShown) + { + AddAllConnections(newObservers); + return; + } + + // Null / Empty string is never a valid teamId + if (string.IsNullOrWhiteSpace(networkTeam.teamId)) + return; + + // Abort if this team hasn't been created yet by OnSpawned or UpdateTeamObjects + if (!teamObjects.TryGetValue(networkTeam.teamId, out HashSet objects)) + return; + + // Add everything in the hashset for this object's current team + foreach (NetworkIdentity networkIdentity in objects) + if (networkIdentity != null && networkIdentity.connectionToClient != null) + newObservers.Add(networkIdentity.connectionToClient); + } + + void AddAllConnections(HashSet newObservers) + { + foreach (NetworkConnectionToClient conn in NetworkServer.connections.Values) + { + // authenticated and joined world with a player? + if (conn != null && conn.isAuthenticated && conn.identity != null) + newObservers.Add(conn); + } + } + } +} diff --git a/Assets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs.meta b/Assets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs.meta new file mode 100644 index 0000000..6e8748a --- /dev/null +++ b/Assets/Mirror/Components/InterestManagement/Team/TeamInterestManagement.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dceb9a7085758fd4590419ff5b14b636 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/LagCompensation.meta b/Assets/Mirror/Components/LagCompensation.meta new file mode 100644 index 0000000..669a5b8 --- /dev/null +++ b/Assets/Mirror/Components/LagCompensation.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 00ac1d0527f234939aba22b4d7cbf280 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/LagCompensation/HistoryCollider.cs b/Assets/Mirror/Components/LagCompensation/HistoryCollider.cs new file mode 100644 index 0000000..8e841a4 --- /dev/null +++ b/Assets/Mirror/Components/LagCompensation/HistoryCollider.cs @@ -0,0 +1,107 @@ +// Applies HistoryBounds to the physics world by projecting to a trigger Collider. +// This way we can use Physics.Raycast on it. +using UnityEngine; + +namespace Mirror +{ + public class HistoryCollider : MonoBehaviour + { + [Header("Components")] + [Tooltip("The object's actual collider. We need to know where it is, and how large it is.")] + public Collider actualCollider; + + [Tooltip("The helper collider that the history bounds are projected onto.\nNeeds to be added to a child GameObject to counter-rotate an axis aligned Bounding Box onto it.\nThis is only used by this component.")] + public BoxCollider boundsCollider; + + [Header("History")] + [Tooltip("Keep this many past bounds in the buffer. The larger this is, the further we can raycast into the past.\nMaximum time := historyAmount * captureInterval")] + public int boundsLimit = 8; + + [Tooltip("Gather N bounds at a time into a bucket for faster encapsulation. A factor of 2 will be twice as fast, etc.")] + public int boundsPerBucket = 2; + + [Tooltip("Capture bounds every 'captureInterval' seconds. Larger values will require fewer computations, but may not capture every small move.")] + public float captureInterval = 0.100f; // 100 ms + double lastCaptureTime = 0; + + [Header("Debug")] + public Color historyColor = new Color(1.0f, 0.5f, 0.0f, 1.0f); + public Color currentColor = Color.red; + + protected HistoryBounds history = null; + + protected virtual void Awake() + { + history = new HistoryBounds(boundsLimit, boundsPerBucket); + + // ensure colliders were set. + // bounds collider should always be a trigger. + if (actualCollider == null) Debug.LogError("HistoryCollider: actualCollider was not set."); + if (boundsCollider == null) Debug.LogError("HistoryCollider: boundsCollider was not set."); + if (boundsCollider.transform.parent != transform) Debug.LogError("HistoryCollider: boundsCollider must be a child of this GameObject."); + if (!boundsCollider.isTrigger) Debug.LogError("HistoryCollider: boundsCollider must be a trigger."); + } + + // capturing and projecting onto colliders should use physics update + protected virtual void FixedUpdate() + { + // capture current bounds every interval + if (NetworkTime.localTime >= lastCaptureTime + captureInterval) + { + lastCaptureTime = NetworkTime.localTime; + CaptureBounds(); + } + + // project bounds onto helper collider + ProjectBounds(); + } + + protected virtual void CaptureBounds() + { + // grab current collider bounds + // this is in world space coordinates, and axis aligned + // TODO double check + Bounds bounds = actualCollider.bounds; + + // insert into history + history.Insert(bounds); + } + + protected virtual void ProjectBounds() + { + // grab total collider encapsulating all of history + Bounds total = history.total; + + // don't assign empty bounds, this will throw a Unity warning + if (history.boundsCount == 0) return; + + // scale projection doesn't work yet. + // for now, don't allow scale changes. + if (transform.lossyScale != Vector3.one) + { + Debug.LogWarning($"HistoryCollider: {name}'s transform global scale must be (1,1,1)."); + return; + } + + // counter rotate the child collider against the gameobject's rotation. + // we need this to always be axis aligned. + boundsCollider.transform.localRotation = Quaternion.Inverse(transform.rotation); + + // project world space bounds to collider's local space + boundsCollider.center = boundsCollider.transform.InverseTransformPoint(total.center); + boundsCollider.size = total.size; // TODO projection? + } + + // TODO runtime drawing for debugging? + protected virtual void OnDrawGizmos() + { + // draw total bounds + Gizmos.color = historyColor; + Gizmos.DrawWireCube(history.total.center, history.total.size); + + // draw current bounds + Gizmos.color = currentColor; + Gizmos.DrawWireCube(actualCollider.bounds.center, actualCollider.bounds.size); + } + } +} diff --git a/Assets/Mirror/Components/LagCompensation/HistoryCollider.cs.meta b/Assets/Mirror/Components/LagCompensation/HistoryCollider.cs.meta new file mode 100644 index 0000000..6275ff1 --- /dev/null +++ b/Assets/Mirror/Components/LagCompensation/HistoryCollider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f5f2158d9776d4b569858f793be4da60 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/Mirror.Components.asmdef b/Assets/Mirror/Components/Mirror.Components.asmdef new file mode 100644 index 0000000..90c360e --- /dev/null +++ b/Assets/Mirror/Components/Mirror.Components.asmdef @@ -0,0 +1,16 @@ +{ + "name": "Mirror.Components", + "rootNamespace": "", + "references": [ + "GUID:30817c1a0e6d646d99c048fc403f5979" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Mirror/Components/Mirror.Components.asmdef.meta b/Assets/Mirror/Components/Mirror.Components.asmdef.meta new file mode 100644 index 0000000..263b6f0 --- /dev/null +++ b/Assets/Mirror/Components/Mirror.Components.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 72872094b21c16e48b631b2224833d49 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkAnimator.cs b/Assets/Mirror/Components/NetworkAnimator.cs new file mode 100644 index 0000000..9e9a929 --- /dev/null +++ b/Assets/Mirror/Components/NetworkAnimator.cs @@ -0,0 +1,619 @@ +using System.Linq; +using UnityEngine; +using UnityEngine.Serialization; + +namespace Mirror +{ + /// + /// A component to synchronize Mecanim animation states for networked objects. + /// + /// + /// The animation of game objects can be networked by this component. There are two models of authority for networked movement: + /// If the object has authority on the client, then it should be animated locally on the owning client. The animation state information will be sent from the owning client to the server, then broadcast to all of the other clients. This is common for player objects. + /// If the object has authority on the server, then it should be animated on the server and state information will be sent to all clients. This is common for objects not related to a specific client, such as an enemy unit. + /// The NetworkAnimator synchronizes all animation parameters of the selected Animator. It does not automatically synchronize triggers. The function SetTrigger can by used by an object with authority to fire an animation trigger on other clients. + /// + // [RequireComponent(typeof(NetworkIdentity))] disabled to allow child NetworkBehaviours + [AddComponentMenu("Network/Network Animator")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-animator")] + public class NetworkAnimator : NetworkBehaviour + { + [Header("Authority")] + [Tooltip("Set to true if animations come from owner client, set to false if animations always come from server")] + public bool clientAuthority; + + /// + /// The animator component to synchronize. + /// + [FormerlySerializedAs("m_Animator")] + [Header("Animator")] + [Tooltip("Animator that will have parameters synchronized")] + public Animator animator; + + /// + /// Syncs animator.speed + /// + [SyncVar(hook = nameof(OnAnimatorSpeedChanged))] + float animatorSpeed; + float previousSpeed; + + // Note: not an object[] array because otherwise initialization is real annoying + int[] lastIntParameters; + float[] lastFloatParameters; + bool[] lastBoolParameters; + AnimatorControllerParameter[] parameters; + + // multiple layers + int[] animationHash; + int[] transitionHash; + float[] layerWeight; + double nextSendTime; + + bool SendMessagesAllowed + { + get + { + if (isServer) + { + if (!clientAuthority) + return true; + + // This is a special case where we have client authority but we have not assigned the client who has + // authority over it, no animator data will be sent over the network by the server. + // + // So we check here for a connectionToClient and if it is null we will + // let the server send animation data until we receive an owner. + if (netIdentity != null && netIdentity.connectionToClient == null) + return true; + } + + return (isOwned && clientAuthority); + } + } + + void Awake() + { + // store the animator parameters in a variable - the "Animator.parameters" getter allocates + // a new parameter array every time it is accessed so we should avoid doing it in a loop + parameters = animator.parameters + .Where(par => !animator.IsParameterControlledByCurve(par.nameHash)) + .ToArray(); + lastIntParameters = new int[parameters.Length]; + lastFloatParameters = new float[parameters.Length]; + lastBoolParameters = new bool[parameters.Length]; + + animationHash = new int[animator.layerCount]; + transitionHash = new int[animator.layerCount]; + layerWeight = new float[animator.layerCount]; + } + + void FixedUpdate() + { + if (!SendMessagesAllowed) + return; + + if (!animator.enabled) + return; + + CheckSendRate(); + + for (int i = 0; i < animator.layerCount; i++) + { + int stateHash; + float normalizedTime; + if (!CheckAnimStateChanged(out stateHash, out normalizedTime, i)) + { + continue; + } + + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + WriteParameters(writer); + SendAnimationMessage(stateHash, normalizedTime, i, layerWeight[i], writer.ToArray()); + } + } + + CheckSpeed(); + } + + void CheckSpeed() + { + float newSpeed = animator.speed; + if (Mathf.Abs(previousSpeed - newSpeed) > 0.001f) + { + previousSpeed = newSpeed; + if (isServer) + { + animatorSpeed = newSpeed; + } + else if (isClient) + { + CmdSetAnimatorSpeed(newSpeed); + } + } + } + + void OnAnimatorSpeedChanged(float _, float value) + { + // skip if host or client with authority + // they will have already set the speed so don't set again + if (isServer || (isOwned && clientAuthority)) + return; + + animator.speed = value; + } + + bool CheckAnimStateChanged(out int stateHash, out float normalizedTime, int layerId) + { + bool change = false; + stateHash = 0; + normalizedTime = 0; + + float lw = animator.GetLayerWeight(layerId); + if (Mathf.Abs(lw - layerWeight[layerId]) > 0.001f) + { + layerWeight[layerId] = lw; + change = true; + } + + if (animator.IsInTransition(layerId)) + { + AnimatorTransitionInfo tt = animator.GetAnimatorTransitionInfo(layerId); + if (tt.fullPathHash != transitionHash[layerId]) + { + // first time in this transition + transitionHash[layerId] = tt.fullPathHash; + animationHash[layerId] = 0; + return true; + } + return change; + } + + AnimatorStateInfo st = animator.GetCurrentAnimatorStateInfo(layerId); + if (st.fullPathHash != animationHash[layerId]) + { + // first time in this animation state + if (animationHash[layerId] != 0) + { + // came from another animation directly - from Play() + stateHash = st.fullPathHash; + normalizedTime = st.normalizedTime; + } + transitionHash[layerId] = 0; + animationHash[layerId] = st.fullPathHash; + return true; + } + return change; + } + + void CheckSendRate() + { + double now = NetworkTime.localTime; + if (SendMessagesAllowed && syncInterval >= 0 && now > nextSendTime) + { + nextSendTime = now + syncInterval; + + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + if (WriteParameters(writer)) + SendAnimationParametersMessage(writer.ToArray()); + } + } + } + + void SendAnimationMessage(int stateHash, float normalizedTime, int layerId, float weight, byte[] parameters) + { + if (isServer) + { + RpcOnAnimationClientMessage(stateHash, normalizedTime, layerId, weight, parameters); + } + else if (isClient) + { + CmdOnAnimationServerMessage(stateHash, normalizedTime, layerId, weight, parameters); + } + } + + void SendAnimationParametersMessage(byte[] parameters) + { + if (isServer) + { + RpcOnAnimationParametersClientMessage(parameters); + } + else if (isClient) + { + CmdOnAnimationParametersServerMessage(parameters); + } + } + + void HandleAnimMsg(int stateHash, float normalizedTime, int layerId, float weight, NetworkReader reader) + { + if (isOwned && clientAuthority) + return; + + // usually transitions will be triggered by parameters, if not, play anims directly. + // NOTE: this plays "animations", not transitions, so any transitions will be skipped. + // NOTE: there is no API to play a transition(?) + if (stateHash != 0 && animator.enabled) + { + animator.Play(stateHash, layerId, normalizedTime); + } + + animator.SetLayerWeight(layerId, weight); + + ReadParameters(reader); + } + + void HandleAnimParamsMsg(NetworkReader reader) + { + if (isOwned && clientAuthority) + return; + + ReadParameters(reader); + } + + void HandleAnimTriggerMsg(int hash) + { + if (animator.enabled) + animator.SetTrigger(hash); + } + + void HandleAnimResetTriggerMsg(int hash) + { + if (animator.enabled) + animator.ResetTrigger(hash); + } + + ulong NextDirtyBits() + { + ulong dirtyBits = 0; + for (int i = 0; i < parameters.Length; i++) + { + AnimatorControllerParameter par = parameters[i]; + bool changed = false; + if (par.type == AnimatorControllerParameterType.Int) + { + int newIntValue = animator.GetInteger(par.nameHash); + changed = newIntValue != lastIntParameters[i]; + if (changed) + lastIntParameters[i] = newIntValue; + } + else if (par.type == AnimatorControllerParameterType.Float) + { + float newFloatValue = animator.GetFloat(par.nameHash); + changed = Mathf.Abs(newFloatValue - lastFloatParameters[i]) > 0.001f; + // only set lastValue if it was changed, otherwise value could slowly drift within the 0.001f limit each frame + if (changed) + lastFloatParameters[i] = newFloatValue; + } + else if (par.type == AnimatorControllerParameterType.Bool) + { + bool newBoolValue = animator.GetBool(par.nameHash); + changed = newBoolValue != lastBoolParameters[i]; + if (changed) + lastBoolParameters[i] = newBoolValue; + } + if (changed) + { + dirtyBits |= 1ul << i; + } + } + return dirtyBits; + } + + bool WriteParameters(NetworkWriter writer, bool forceAll = false) + { + ulong dirtyBits = forceAll ? (~0ul) : NextDirtyBits(); + writer.WriteULong(dirtyBits); + for (int i = 0; i < parameters.Length; i++) + { + if ((dirtyBits & (1ul << i)) == 0) + continue; + + AnimatorControllerParameter par = parameters[i]; + if (par.type == AnimatorControllerParameterType.Int) + { + int newIntValue = animator.GetInteger(par.nameHash); + writer.WriteInt(newIntValue); + } + else if (par.type == AnimatorControllerParameterType.Float) + { + float newFloatValue = animator.GetFloat(par.nameHash); + writer.WriteFloat(newFloatValue); + } + else if (par.type == AnimatorControllerParameterType.Bool) + { + bool newBoolValue = animator.GetBool(par.nameHash); + writer.WriteBool(newBoolValue); + } + } + return dirtyBits != 0; + } + + void ReadParameters(NetworkReader reader) + { + bool animatorEnabled = animator.enabled; + // need to read values from NetworkReader even if animator is disabled + + ulong dirtyBits = reader.ReadULong(); + for (int i = 0; i < parameters.Length; i++) + { + if ((dirtyBits & (1ul << i)) == 0) + continue; + + AnimatorControllerParameter par = parameters[i]; + if (par.type == AnimatorControllerParameterType.Int) + { + int newIntValue = reader.ReadInt(); + if (animatorEnabled) + animator.SetInteger(par.nameHash, newIntValue); + } + else if (par.type == AnimatorControllerParameterType.Float) + { + float newFloatValue = reader.ReadFloat(); + if (animatorEnabled) + animator.SetFloat(par.nameHash, newFloatValue); + } + else if (par.type == AnimatorControllerParameterType.Bool) + { + bool newBoolValue = reader.ReadBool(); + if (animatorEnabled) + animator.SetBool(par.nameHash, newBoolValue); + } + } + } + + public override void OnSerialize(NetworkWriter writer, bool initialState) + { + base.OnSerialize(writer, initialState); + if (initialState) + { + for (int i = 0; i < animator.layerCount; i++) + { + if (animator.IsInTransition(i)) + { + AnimatorStateInfo st = animator.GetNextAnimatorStateInfo(i); + writer.WriteInt(st.fullPathHash); + writer.WriteFloat(st.normalizedTime); + } + else + { + AnimatorStateInfo st = animator.GetCurrentAnimatorStateInfo(i); + writer.WriteInt(st.fullPathHash); + writer.WriteFloat(st.normalizedTime); + } + writer.WriteFloat(animator.GetLayerWeight(i)); + } + WriteParameters(writer, initialState); + } + } + + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + base.OnDeserialize(reader, initialState); + if (initialState) + { + for (int i = 0; i < animator.layerCount; i++) + { + int stateHash = reader.ReadInt(); + float normalizedTime = reader.ReadFloat(); + animator.SetLayerWeight(i, reader.ReadFloat()); + animator.Play(stateHash, i, normalizedTime); + } + + ReadParameters(reader); + } + } + + /// + /// Causes an animation trigger to be invoked for a networked object. + /// If local authority is set, and this is called from the client, then the trigger will be invoked on the server and all clients. If not, then this is called on the server, and the trigger will be called on all clients. + /// + /// Name of trigger. + public void SetTrigger(string triggerName) + { + SetTrigger(Animator.StringToHash(triggerName)); + } + + /// + /// Causes an animation trigger to be invoked for a networked object. + /// + /// Hash id of trigger (from the Animator). + public void SetTrigger(int hash) + { + if (clientAuthority) + { + if (!isClient) + { + Debug.LogWarning("Tried to set animation in the server for a client-controlled animator"); + return; + } + + if (!isOwned) + { + Debug.LogWarning("Only the client with authority can set animations"); + return; + } + + if (isClient) + CmdOnAnimationTriggerServerMessage(hash); + + // call on client right away + HandleAnimTriggerMsg(hash); + } + else + { + if (!isServer) + { + Debug.LogWarning("Tried to set animation in the client for a server-controlled animator"); + return; + } + + HandleAnimTriggerMsg(hash); + RpcOnAnimationTriggerClientMessage(hash); + } + } + + /// + /// Causes an animation trigger to be reset for a networked object. + /// If local authority is set, and this is called from the client, then the trigger will be reset on the server and all clients. If not, then this is called on the server, and the trigger will be reset on all clients. + /// + /// Name of trigger. + public void ResetTrigger(string triggerName) + { + ResetTrigger(Animator.StringToHash(triggerName)); + } + + /// Causes an animation trigger to be reset for a networked object. + /// Hash id of trigger (from the Animator). + public void ResetTrigger(int hash) + { + if (clientAuthority) + { + if (!isClient) + { + Debug.LogWarning("Tried to reset animation in the server for a client-controlled animator"); + return; + } + + if (!isOwned) + { + Debug.LogWarning("Only the client with authority can reset animations"); + return; + } + + if (isClient) + CmdOnAnimationResetTriggerServerMessage(hash); + + // call on client right away + HandleAnimResetTriggerMsg(hash); + } + else + { + if (!isServer) + { + Debug.LogWarning("Tried to reset animation in the client for a server-controlled animator"); + return; + } + + HandleAnimResetTriggerMsg(hash); + RpcOnAnimationResetTriggerClientMessage(hash); + } + } + + #region server message handlers + + [Command] + void CmdOnAnimationServerMessage(int stateHash, float normalizedTime, int layerId, float weight, byte[] parameters) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + //Debug.Log($"OnAnimationMessage for netId {netId}"); + + // handle and broadcast + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(parameters)) + { + HandleAnimMsg(stateHash, normalizedTime, layerId, weight, networkReader); + RpcOnAnimationClientMessage(stateHash, normalizedTime, layerId, weight, parameters); + } + } + + [Command] + void CmdOnAnimationParametersServerMessage(byte[] parameters) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + // handle and broadcast + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(parameters)) + { + HandleAnimParamsMsg(networkReader); + RpcOnAnimationParametersClientMessage(parameters); + } + } + + [Command] + void CmdOnAnimationTriggerServerMessage(int hash) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + // handle and broadcast + // host should have already the trigger + bool isHostOwner = isClient && isOwned; + if (!isHostOwner) + { + HandleAnimTriggerMsg(hash); + } + + RpcOnAnimationTriggerClientMessage(hash); + } + + [Command] + void CmdOnAnimationResetTriggerServerMessage(int hash) + { + // Ignore messages from client if not in client authority mode + if (!clientAuthority) + return; + + // handle and broadcast + // host should have already the trigger + bool isHostOwner = isClient && isOwned; + if (!isHostOwner) + { + HandleAnimResetTriggerMsg(hash); + } + + RpcOnAnimationResetTriggerClientMessage(hash); + } + + [Command] + void CmdSetAnimatorSpeed(float newSpeed) + { + // set animator + animator.speed = newSpeed; + animatorSpeed = newSpeed; + } + + #endregion + + #region client message handlers + + [ClientRpc] + void RpcOnAnimationClientMessage(int stateHash, float normalizedTime, int layerId, float weight, byte[] parameters) + { + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(parameters)) + HandleAnimMsg(stateHash, normalizedTime, layerId, weight, networkReader); + } + + [ClientRpc] + void RpcOnAnimationParametersClientMessage(byte[] parameters) + { + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(parameters)) + HandleAnimParamsMsg(networkReader); + } + + [ClientRpc] + void RpcOnAnimationTriggerClientMessage(int hash) + { + // host/owner handles this before it is sent + if (isServer || (clientAuthority && isOwned)) return; + + HandleAnimTriggerMsg(hash); + } + + [ClientRpc] + void RpcOnAnimationResetTriggerClientMessage(int hash) + { + // host/owner handles this before it is sent + if (isServer || (clientAuthority && isOwned)) return; + + HandleAnimResetTriggerMsg(hash); + } + + #endregion + } +} diff --git a/Assets/Mirror/Components/NetworkAnimator.cs.meta b/Assets/Mirror/Components/NetworkAnimator.cs.meta new file mode 100644 index 0000000..211ce78 --- /dev/null +++ b/Assets/Mirror/Components/NetworkAnimator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f6f3bf89aa97405989c802ba270f815 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkLobbyManager.cs b/Assets/Mirror/Components/NetworkLobbyManager.cs new file mode 100644 index 0000000..3dcd4ea --- /dev/null +++ b/Assets/Mirror/Components/NetworkLobbyManager.cs @@ -0,0 +1,18 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + /// + /// This is a specialized NetworkManager that includes a networked lobby. + /// + /// + /// The lobby has slots that track the joined players, and a maximum player count that is enforced. It requires that the NetworkLobbyPlayer component be on the lobby player objects. + /// NetworkLobbyManager is derived from NetworkManager, and so it implements many of the virtual functions provided by the NetworkManager class. To avoid accidentally replacing functionality of the NetworkLobbyManager, there are new virtual functions on the NetworkLobbyManager that begin with "OnLobby". These should be used on classes derived from NetworkLobbyManager instead of the virtual functions on NetworkManager. + /// The OnLobby*() functions have empty implementations on the NetworkLobbyManager base class, so the base class functions do not have to be called. + /// + [AddComponentMenu("Network/Network Lobby Manager")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-room-manager")] + [Obsolete("Use / inherit from NetworkRoomManager instead")] + public class NetworkLobbyManager : NetworkRoomManager {} +} diff --git a/Assets/Mirror/Components/NetworkLobbyManager.cs.meta b/Assets/Mirror/Components/NetworkLobbyManager.cs.meta new file mode 100644 index 0000000..a32c8c7 --- /dev/null +++ b/Assets/Mirror/Components/NetworkLobbyManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a4c96e6dd99826849ab1431f94547141 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkLobbyPlayer.cs b/Assets/Mirror/Components/NetworkLobbyPlayer.cs new file mode 100644 index 0000000..95ffbbc --- /dev/null +++ b/Assets/Mirror/Components/NetworkLobbyPlayer.cs @@ -0,0 +1,15 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + /// + /// This component works in conjunction with the NetworkLobbyManager to make up the multiplayer lobby system. + /// The LobbyPrefab object of the NetworkLobbyManager must have this component on it. This component holds basic lobby player data required for the lobby to function. Game specific data for lobby players can be put in other components on the LobbyPrefab or in scripts derived from NetworkLobbyPlayer. + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Lobby Player")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-room-player")] + [Obsolete("Use / inherit from NetworkRoomPlayer instead")] + public class NetworkLobbyPlayer : NetworkRoomPlayer {} +} diff --git a/Assets/Mirror/Components/NetworkLobbyPlayer.cs.meta b/Assets/Mirror/Components/NetworkLobbyPlayer.cs.meta new file mode 100644 index 0000000..7a21eec --- /dev/null +++ b/Assets/Mirror/Components/NetworkLobbyPlayer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 777a368af85f2e84da7ea5666581921b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkPingDisplay.cs b/Assets/Mirror/Components/NetworkPingDisplay.cs new file mode 100644 index 0000000..11f55f4 --- /dev/null +++ b/Assets/Mirror/Components/NetworkPingDisplay.cs @@ -0,0 +1,39 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + /// + /// Component that will display the clients ping in milliseconds + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Ping Display")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-ping-display")] + public class NetworkPingDisplay : MonoBehaviour + { + public Color color = Color.white; + public int padding = 2; + public int width = 180; + public int height = 25; + + void OnGUI() + { + // only while client is active + if (!NetworkClient.active) return; + + // show stats in bottom right corner, right aligned + GUI.color = color; + Rect rect = new Rect(Screen.width - width - padding, Screen.height - height - padding, width, height); + GUILayout.BeginArea(rect); + GUIStyle style = GUI.skin.GetStyle("Label"); + style.alignment = TextAnchor.MiddleRight; + GUILayout.BeginHorizontal(style); + GUILayout.Label($"RTT: {Math.Round(NetworkTime.rtt * 1000)}ms"); + GUI.color = NetworkClient.connectionQuality.ColorCode(); + GUILayout.Label($"Q: {NetworkClient.connectionQuality}"); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + GUI.color = Color.white; + } + } +} diff --git a/Assets/Mirror/Components/NetworkPingDisplay.cs.meta b/Assets/Mirror/Components/NetworkPingDisplay.cs.meta new file mode 100644 index 0000000..221a745 --- /dev/null +++ b/Assets/Mirror/Components/NetworkPingDisplay.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bc654f29862fc2643b948f772ebb9e68 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkRigidbody.meta b/Assets/Mirror/Components/NetworkRigidbody.meta new file mode 100644 index 0000000..a67178e --- /dev/null +++ b/Assets/Mirror/Components/NetworkRigidbody.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 80106690aef541a5b8e2f8fb3d5949ad +timeCreated: 1686733778 \ No newline at end of file diff --git a/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs new file mode 100644 index 0000000..cec7477 --- /dev/null +++ b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs @@ -0,0 +1,97 @@ +using UnityEngine; + +namespace Mirror +{ + // [RequireComponent(typeof(Rigidbody))] <- OnValidate ensures this is on .target + public class NetworkRigidbodyReliable : NetworkTransformReliable + { + new bool clientAuthority => + syncDirection == SyncDirection.ClientToServer; + + Rigidbody rb; + bool wasKinematic; + + // cach Rigidbody and original isKinematic setting + protected override void Awake() + { + // we can't overwrite .target to be a Rigidbody. + // but we can use its Rigidbody component. + rb = target.GetComponent(); + if (rb == null) + { + Debug.LogError($"{name}'s NetworkRigidbody.target {target.name} is missing a Rigidbody", this); + return; + } + wasKinematic = rb.isKinematic; + base.Awake(); + } + + // reset forced isKinematic flag to original. + // otherwise the overwritten value would remain between sessions forever. + // for example, a game may run as client, set rigidbody.iskinematic=true, + // then run as server, where .iskinematic isn't touched and remains at + // the overwritten=true, even though the user set it to false originally. + public override void OnStopServer() => rb.isKinematic = wasKinematic; + public override void OnStopClient() => rb.isKinematic = wasKinematic; + + // overwriting Construct() and Apply() to set Rigidbody.MovePosition + // would give more jittery movement. + + // FixedUpdate for physics + void FixedUpdate() + { + // who ever has authority moves the Rigidbody with physics. + // everyone else simply sets it to kinematic. + // so that only the Transform component is synced. + + // host mode + if (isServer && isClient) + { + // in host mode, we own it it if: + // clientAuthority is disabled (hence server / we own it) + // clientAuthority is enabled and we have authority over this object. + bool owned = !clientAuthority || IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // client only + else if (isClient) + { + // on the client, we own it only if clientAuthority is enabled, + // and we have authority over this object. + bool owned = IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // server only + else if (isServer) + { + // on the server, we always own it if clientAuthority is disabled. + bool owned = !clientAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + } + + protected override void OnValidate() + { + base.OnValidate(); + + // we can't overwrite .target to be a Rigidbody. + // but we can ensure that .target has a Rigidbody, and use it. + if (target.GetComponent() == null) + { + Debug.LogWarning($"{name}'s NetworkRigidbody.target {target.name} is missing a Rigidbody", this); + } + } + } +} diff --git a/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs.meta b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs.meta new file mode 100644 index 0000000..b3b61c9 --- /dev/null +++ b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cb803efbe62c34d7baece46c9ffebad9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs new file mode 100644 index 0000000..3530c8c --- /dev/null +++ b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs @@ -0,0 +1,97 @@ +using UnityEngine; + +namespace Mirror +{ + // [RequireComponent(typeof(Rigidbody))] <- OnValidate ensures this is on .target + public class NetworkRigidbodyReliable2D : NetworkTransformReliable + { + new bool clientAuthority => + syncDirection == SyncDirection.ClientToServer; + + Rigidbody2D rb; + bool wasKinematic; + + // cach Rigidbody and original isKinematic setting + protected override void Awake() + { + // we can't overwrite .target to be a Rigidbody. + // but we can use its Rigidbody component. + rb = target.GetComponent(); + if (rb == null) + { + Debug.LogError($"{name}'s NetworkRigidbody2D.target {target.name} is missing a Rigidbody2D", this); + return; + } + wasKinematic = rb.isKinematic; + base.Awake(); + } + + // reset forced isKinematic flag to original. + // otherwise the overwritten value would remain between sessions forever. + // for example, a game may run as client, set rigidbody.iskinematic=true, + // then run as server, where .iskinematic isn't touched and remains at + // the overwritten=true, even though the user set it to false originally. + public override void OnStopServer() => rb.isKinematic = wasKinematic; + public override void OnStopClient() => rb.isKinematic = wasKinematic; + + // overwriting Construct() and Apply() to set Rigidbody.MovePosition + // would give more jittery movement. + + // FixedUpdate for physics + void FixedUpdate() + { + // who ever has authority moves the Rigidbody with physics. + // everyone else simply sets it to kinematic. + // so that only the Transform component is synced. + + // host mode + if (isServer && isClient) + { + // in host mode, we own it it if: + // clientAuthority is disabled (hence server / we own it) + // clientAuthority is enabled and we have authority over this object. + bool owned = !clientAuthority || IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // client only + else if (isClient) + { + // on the client, we own it only if clientAuthority is enabled, + // and we have authority over this object. + bool owned = IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // server only + else if (isServer) + { + // on the server, we always own it if clientAuthority is disabled. + bool owned = !clientAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + } + + protected override void OnValidate() + { + base.OnValidate(); + + // we can't overwrite .target to be a Rigidbody. + // but we can ensure that .target has a Rigidbody, and use it. + if (target.GetComponent() == null) + { + Debug.LogWarning($"{name}'s NetworkRigidbody2D.target {target.name} is missing a Rigidbody2D", this); + } + } + } +} diff --git a/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs.meta b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs.meta new file mode 100644 index 0000000..172c8a4 --- /dev/null +++ b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyReliable2D.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7ec4f7556ca1e4b55a3381fc6a02b1bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs new file mode 100644 index 0000000..7f8b9f7 --- /dev/null +++ b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs @@ -0,0 +1,97 @@ +using UnityEngine; + +namespace Mirror +{ + // [RequireComponent(typeof(Rigidbody))] <- OnValidate ensures this is on .target + public class NetworkRigidbodyUnreliable : NetworkTransformUnreliable + { + new bool clientAuthority => + syncDirection == SyncDirection.ClientToServer; + + Rigidbody rb; + bool wasKinematic; + + // cach Rigidbody and original isKinematic setting + protected override void Awake() + { + // we can't overwrite .target to be a Rigidbody. + // but we can use its Rigidbody component. + rb = target.GetComponent(); + if (rb == null) + { + Debug.LogError($"{name}'s NetworkRigidbody.target {target.name} is missing a Rigidbody", this); + return; + } + wasKinematic = rb.isKinematic; + base.Awake(); + } + + // reset forced isKinematic flag to original. + // otherwise the overwritten value would remain between sessions forever. + // for example, a game may run as client, set rigidbody.iskinematic=true, + // then run as server, where .iskinematic isn't touched and remains at + // the overwritten=true, even though the user set it to false originally. + public override void OnStopServer() => rb.isKinematic = wasKinematic; + public override void OnStopClient() => rb.isKinematic = wasKinematic; + + // overwriting Construct() and Apply() to set Rigidbody.MovePosition + // would give more jittery movement. + + // FixedUpdate for physics + void FixedUpdate() + { + // who ever has authority moves the Rigidbody with physics. + // everyone else simply sets it to kinematic. + // so that only the Transform component is synced. + + // host mode + if (isServer && isClient) + { + // in host mode, we own it it if: + // clientAuthority is disabled (hence server / we own it) + // clientAuthority is enabled and we have authority over this object. + bool owned = !clientAuthority || IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // client only + else if (isClient) + { + // on the client, we own it only if clientAuthority is enabled, + // and we have authority over this object. + bool owned = IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // server only + else if (isServer) + { + // on the server, we always own it if clientAuthority is disabled. + bool owned = !clientAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + } + + protected override void OnValidate() + { + base.OnValidate(); + + // we can't overwrite .target to be a Rigidbody. + // but we can ensure that .target has a Rigidbody, and use it. + if (target.GetComponent() == null) + { + Debug.LogWarning($"{name}'s NetworkRigidbody.target {target.name} is missing a Rigidbody", this); + } + } + } +} diff --git a/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs.meta b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs.meta new file mode 100644 index 0000000..2dfb14b --- /dev/null +++ b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b20dc110904e47f8a154cdcf6433eae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs new file mode 100644 index 0000000..ead771f --- /dev/null +++ b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs @@ -0,0 +1,97 @@ +using UnityEngine; + +namespace Mirror +{ + // [RequireComponent(typeof(Rigidbody))] <- OnValidate ensures this is on .target + public class NetworkRigidbodyUnreliable2D : NetworkTransformUnreliable + { + new bool clientAuthority => + syncDirection == SyncDirection.ClientToServer; + + Rigidbody2D rb; + bool wasKinematic; + + // cach Rigidbody and original isKinematic setting + protected override void Awake() + { + // we can't overwrite .target to be a Rigidbody. + // but we can use its Rigidbody component. + rb = target.GetComponent(); + if (rb == null) + { + Debug.LogError($"{name}'s NetworkRigidbody2D.target {target.name} is missing a Rigidbody2D", this); + return; + } + wasKinematic = rb.isKinematic; + base.Awake(); + } + + // reset forced isKinematic flag to original. + // otherwise the overwritten value would remain between sessions forever. + // for example, a game may run as client, set rigidbody.iskinematic=true, + // then run as server, where .iskinematic isn't touched and remains at + // the overwritten=true, even though the user set it to false originally. + public override void OnStopServer() => rb.isKinematic = wasKinematic; + public override void OnStopClient() => rb.isKinematic = wasKinematic; + + // overwriting Construct() and Apply() to set Rigidbody.MovePosition + // would give more jittery movement. + + // FixedUpdate for physics + void FixedUpdate() + { + // who ever has authority moves the Rigidbody with physics. + // everyone else simply sets it to kinematic. + // so that only the Transform component is synced. + + // host mode + if (isServer && isClient) + { + // in host mode, we own it it if: + // clientAuthority is disabled (hence server / we own it) + // clientAuthority is enabled and we have authority over this object. + bool owned = !clientAuthority || IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // client only + else if (isClient) + { + // on the client, we own it only if clientAuthority is enabled, + // and we have authority over this object. + bool owned = IsClientWithAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + // server only + else if (isServer) + { + // on the server, we always own it if clientAuthority is disabled. + bool owned = !clientAuthority; + + // only set to kinematic if we don't own it + // otherwise don't touch isKinematic. + // the authority owner might use it either way. + if (!owned) rb.isKinematic = true; + } + } + + protected override void OnValidate() + { + base.OnValidate(); + + // we can't overwrite .target to be a Rigidbody. + // but we can ensure that .target has a Rigidbody, and use it. + if (target.GetComponent() == null) + { + Debug.LogWarning($"{name}'s NetworkRigidbody2D.target {target.name} is missing a Rigidbody2D", this); + } + } + } +} diff --git a/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs.meta b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs.meta new file mode 100644 index 0000000..8a19149 --- /dev/null +++ b/Assets/Mirror/Components/NetworkRigidbody/NetworkRigidbodyUnreliable2D.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1c7e12ad9b9ae443c9fdf37e9f5ecd36 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkRoomManager.cs b/Assets/Mirror/Components/NetworkRoomManager.cs new file mode 100644 index 0000000..e210e73 --- /dev/null +++ b/Assets/Mirror/Components/NetworkRoomManager.cs @@ -0,0 +1,684 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.Serialization; + +namespace Mirror +{ + /// + /// This is a specialized NetworkManager that includes a networked room. + /// + /// + /// The room has slots that track the joined players, and a maximum player count that is enforced. It requires that the NetworkRoomPlayer component be on the room player objects. + /// NetworkRoomManager is derived from NetworkManager, and so it implements many of the virtual functions provided by the NetworkManager class. To avoid accidentally replacing functionality of the NetworkRoomManager, there are new virtual functions on the NetworkRoomManager that begin with "OnRoom". These should be used on classes derived from NetworkRoomManager instead of the virtual functions on NetworkManager. + /// The OnRoom*() functions have empty implementations on the NetworkRoomManager base class, so the base class functions do not have to be called. + /// + [AddComponentMenu("Network/Network Room Manager")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-room-manager")] + public class NetworkRoomManager : NetworkManager + { + public struct PendingPlayer + { + public NetworkConnectionToClient conn; + public GameObject roomPlayer; + } + + [Header("Room Settings")] + [FormerlySerializedAs("m_ShowRoomGUI")] + [SerializeField] + [Tooltip("This flag controls whether the default UI is shown for the room")] + public bool showRoomGUI = true; + + [FormerlySerializedAs("m_MinPlayers")] + [SerializeField] + [Tooltip("Minimum number of players to auto-start the game")] + public int minPlayers = 1; + + [FormerlySerializedAs("m_RoomPlayerPrefab")] + [SerializeField] + [Tooltip("Prefab to use for the Room Player")] + public NetworkRoomPlayer roomPlayerPrefab; + + /// + /// The scene to use for the room. This is similar to the offlineScene of the NetworkManager. + /// + [Scene] + public string RoomScene; + + /// + /// The scene to use for the playing the game from the room. This is similar to the onlineScene of the NetworkManager. + /// + [Scene] + public string GameplayScene; + + /// + /// List of players that are in the Room + /// + [FormerlySerializedAs("m_PendingPlayers")] + public List pendingPlayers = new List(); + + [Header("Diagnostics")] + /// + /// True when all players have submitted a Ready message + /// + [Tooltip("Diagnostic flag indicating all players are ready to play")] + [FormerlySerializedAs("allPlayersReady")] + [SerializeField] bool _allPlayersReady; + + /// + /// These slots track players that enter the room. + /// The slotId on players is global to the game - across all players. + /// + [Tooltip("List of Room Player objects")] + public List roomSlots = new List(); + + public bool allPlayersReady + { + get => _allPlayersReady; + set + { + bool wasReady = _allPlayersReady; + bool nowReady = value; + + if (wasReady != nowReady) + { + _allPlayersReady = value; + + if (nowReady) + { + OnRoomServerPlayersReady(); + } + else + { + OnRoomServerPlayersNotReady(); + } + } + } + } + + public override void OnValidate() + { + base.OnValidate(); + + // always <= maxConnections + minPlayers = Mathf.Min(minPlayers, maxConnections); + + // always >= 0 + minPlayers = Mathf.Max(minPlayers, 0); + + if (roomPlayerPrefab != null) + { + NetworkIdentity identity = roomPlayerPrefab.GetComponent(); + if (identity == null) + { + roomPlayerPrefab = null; + Debug.LogError("RoomPlayer prefab must have a NetworkIdentity component."); + } + } + } + + void SceneLoadedForPlayer(NetworkConnectionToClient conn, GameObject roomPlayer) + { + Debug.Log($"NetworkRoom SceneLoadedForPlayer scene: {SceneManager.GetActiveScene().path} {conn}"); + + if (Utils.IsSceneActive(RoomScene)) + { + // cant be ready in room, add to ready list + PendingPlayer pending; + pending.conn = conn; + pending.roomPlayer = roomPlayer; + pendingPlayers.Add(pending); + return; + } + + GameObject gamePlayer = OnRoomServerCreateGamePlayer(conn, roomPlayer); + if (gamePlayer == null) + { + // get start position from base class + Transform startPos = GetStartPosition(); + gamePlayer = startPos != null + ? Instantiate(playerPrefab, startPos.position, startPos.rotation) + : Instantiate(playerPrefab, Vector3.zero, Quaternion.identity); + } + + if (!OnRoomServerSceneLoadedForPlayer(conn, roomPlayer, gamePlayer)) + return; + + // replace room player with game player + NetworkServer.ReplacePlayerForConnection(conn, gamePlayer, true); + } + + internal void CallOnClientEnterRoom() + { + OnRoomClientEnter(); + foreach (NetworkRoomPlayer player in roomSlots) + if (player != null) + { + player.OnClientEnterRoom(); + } + } + + internal void CallOnClientExitRoom() + { + OnRoomClientExit(); + foreach (NetworkRoomPlayer player in roomSlots) + if (player != null) + { + player.OnClientExitRoom(); + } + } + + /// + /// CheckReadyToBegin checks all of the players in the room to see if their readyToBegin flag is set. + /// If all of the players are ready, then the server switches from the RoomScene to the PlayScene, essentially starting the game. This is called automatically in response to NetworkRoomPlayer.CmdChangeReadyState. + /// + public void CheckReadyToBegin() + { + if (!Utils.IsSceneActive(RoomScene)) + return; + + int numberOfReadyPlayers = NetworkServer.connections.Count(conn => + conn.Value != null && + conn.Value.identity != null && + conn.Value.identity.TryGetComponent(out NetworkRoomPlayer nrp) && + nrp.readyToBegin); + + bool enoughReadyPlayers = minPlayers <= 0 || numberOfReadyPlayers >= minPlayers; + if (enoughReadyPlayers) + { + pendingPlayers.Clear(); + allPlayersReady = true; + } + else + allPlayersReady = false; + } + + #region server handlers + + /// + /// Called on the server when a new client connects. + /// Unity calls this on the Server when a Client connects to the Server. Use an override to tell the NetworkManager what to do when a client connects to the server. + /// + /// Connection from client. + public override void OnServerConnect(NetworkConnectionToClient conn) + { + // cannot join game in progress + if (!Utils.IsSceneActive(RoomScene)) + { + Debug.Log($"Not in Room scene...disconnecting {conn}"); + conn.Disconnect(); + return; + } + + base.OnServerConnect(conn); + OnRoomServerConnect(conn); + } + + /// + /// Called on the server when a client disconnects. + /// This is called on the Server when a Client disconnects from the Server. Use an override to decide what should happen when a disconnection is detected. + /// + /// Connection from client. + public override void OnServerDisconnect(NetworkConnectionToClient conn) + { + if (conn.identity != null) + { + NetworkRoomPlayer roomPlayer = conn.identity.GetComponent(); + + if (roomPlayer != null) + roomSlots.Remove(roomPlayer); + + foreach (NetworkIdentity clientOwnedObject in conn.owned) + { + roomPlayer = clientOwnedObject.GetComponent(); + if (roomPlayer != null) + roomSlots.Remove(roomPlayer); + } + } + + allPlayersReady = false; + + foreach (NetworkRoomPlayer player in roomSlots) + { + if (player != null) + player.GetComponent().readyToBegin = false; + } + + if (Utils.IsSceneActive(RoomScene)) + RecalculateRoomPlayerIndices(); + + OnRoomServerDisconnect(conn); + base.OnServerDisconnect(conn); + +#if UNITY_SERVER + if (numPlayers < 1) + StopServer(); +#endif + } + + // Sequential index used in round-robin deployment of players into instances and score positioning + public int clientIndex; + + /// + /// Called on the server when a client is ready. + /// The default implementation of this function calls NetworkServer.SetClientReady() to continue the network setup process. + /// + /// Connection from client. + public override void OnServerReady(NetworkConnectionToClient conn) + { + Debug.Log($"NetworkRoomManager OnServerReady {conn}"); + base.OnServerReady(conn); + + if (conn != null && conn.identity != null) + { + GameObject roomPlayer = conn.identity.gameObject; + + // if null or not a room player, don't replace it + if (roomPlayer != null && roomPlayer.GetComponent() != null) + SceneLoadedForPlayer(conn, roomPlayer); + } + } + + /// + /// Called on the server when a client adds a new player with NetworkClient.AddPlayer. + /// The default implementation for this function creates a new player object from the playerPrefab. + /// + /// Connection from client. + public override void OnServerAddPlayer(NetworkConnectionToClient conn) + { + // increment the index before adding the player, so first player starts at 1 + clientIndex++; + + if (Utils.IsSceneActive(RoomScene)) + { + allPlayersReady = false; + + //Debug.Log("NetworkRoomManager.OnServerAddPlayer playerPrefab: {roomPlayerPrefab.name}"); + + GameObject newRoomGameObject = OnRoomServerCreateRoomPlayer(conn); + if (newRoomGameObject == null) + newRoomGameObject = Instantiate(roomPlayerPrefab.gameObject, Vector3.zero, Quaternion.identity); + + NetworkServer.AddPlayerForConnection(conn, newRoomGameObject); + } + else + { + // Late joiners not supported...should've been kicked by OnServerDisconnect + Debug.Log($"Not in Room scene...disconnecting {conn}"); + conn.Disconnect(); + } + } + + [Server] + public void RecalculateRoomPlayerIndices() + { + if (roomSlots.Count > 0) + { + for (int i = 0; i < roomSlots.Count; i++) + { + roomSlots[i].index = i; + } + } + } + + /// + /// This causes the server to switch scenes and sets the networkSceneName. + /// Clients that connect to this server will automatically switch to this scene. This is called automatically if onlineScene or offlineScene are set, but it can be called from user code to switch scenes again while the game is in progress. This automatically sets clients to be not-ready. The clients must call NetworkClient.Ready() again to participate in the new scene. + /// + /// + public override void ServerChangeScene(string newSceneName) + { + if (newSceneName == RoomScene) + { + foreach (NetworkRoomPlayer roomPlayer in roomSlots) + { + if (roomPlayer == null) + continue; + + // find the game-player object for this connection, and destroy it + NetworkIdentity identity = roomPlayer.GetComponent(); + + if (NetworkServer.active) + { + // re-add the room object + roomPlayer.GetComponent().readyToBegin = false; + NetworkServer.ReplacePlayerForConnection(identity.connectionToClient, roomPlayer.gameObject); + } + } + + allPlayersReady = false; + } + + base.ServerChangeScene(newSceneName); + } + + /// + /// Called on the server when a scene is completed loaded, when the scene load was initiated by the server with ServerChangeScene(). + /// + /// The name of the new scene. + public override void OnServerSceneChanged(string sceneName) + { + if (sceneName != RoomScene) + { + // call SceneLoadedForPlayer on any players that become ready while we were loading the scene. + foreach (PendingPlayer pending in pendingPlayers) + SceneLoadedForPlayer(pending.conn, pending.roomPlayer); + + pendingPlayers.Clear(); + } + + OnRoomServerSceneChanged(sceneName); + } + + /// + /// This is invoked when a server is started - including when a host is started. + /// StartServer has multiple signatures, but they all cause this hook to be called. + /// + public override void OnStartServer() + { + if (string.IsNullOrWhiteSpace(RoomScene)) + { + Debug.LogError("NetworkRoomManager RoomScene is empty. Set the RoomScene in the inspector for the NetworkRoomManager"); + return; + } + + if (string.IsNullOrWhiteSpace(GameplayScene)) + { + Debug.LogError("NetworkRoomManager PlayScene is empty. Set the PlayScene in the inspector for the NetworkRoomManager"); + return; + } + + OnRoomStartServer(); + } + + /// + /// This is invoked when a host is started. + /// StartHost has multiple signatures, but they all cause this hook to be called. + /// + public override void OnStartHost() + { + OnRoomStartHost(); + } + + /// + /// This is called when a server is stopped - including when a host is stopped. + /// + public override void OnStopServer() + { + roomSlots.Clear(); + OnRoomStopServer(); + } + + /// + /// This is called when a host is stopped. + /// + public override void OnStopHost() + { + OnRoomStopHost(); + } + + #endregion + + #region client handlers + + /// + /// This is invoked when the client is started. + /// + public override void OnStartClient() + { + if (roomPlayerPrefab == null || roomPlayerPrefab.gameObject == null) + Debug.LogError("NetworkRoomManager no RoomPlayer prefab is registered. Please add a RoomPlayer prefab."); + else + NetworkClient.RegisterPrefab(roomPlayerPrefab.gameObject); + + if (playerPrefab == null) + Debug.LogError("NetworkRoomManager no GamePlayer prefab is registered. Please add a GamePlayer prefab."); + + OnRoomStartClient(); + } + + /// + /// Called on the client when connected to a server. + /// The default implementation of this function sets the client as ready and adds a player. Override the function to dictate what happens when the client connects. + /// + public override void OnClientConnect() + { + OnRoomClientConnect(); + base.OnClientConnect(); + } + + /// + /// Called on clients when disconnected from a server. + /// This is called on the client when it disconnects from the server. Override this function to decide what happens when the client disconnects. + /// + public override void OnClientDisconnect() + { + OnRoomClientDisconnect(); + base.OnClientDisconnect(); + } + + /// + /// This is called when a client is stopped. + /// + public override void OnStopClient() + { + OnRoomStopClient(); + CallOnClientExitRoom(); + roomSlots.Clear(); + } + + /// + /// Called on clients when a scene has completed loaded, when the scene load was initiated by the server. + /// Scene changes can cause player objects to be destroyed. The default implementation of OnClientSceneChanged in the NetworkManager is to add a player object for the connection if no player object exists. + /// + public override void OnClientSceneChanged() + { + if (Utils.IsSceneActive(RoomScene)) + { + if (NetworkClient.isConnected) + CallOnClientEnterRoom(); + } + else + CallOnClientExitRoom(); + + base.OnClientSceneChanged(); + OnRoomClientSceneChanged(); + } + + #endregion + + #region room server virtuals + + /// + /// This is called on the host when a host is started. + /// + public virtual void OnRoomStartHost() {} + + /// + /// This is called on the host when the host is stopped. + /// + public virtual void OnRoomStopHost() {} + + /// + /// This is called on the server when the server is started - including when a host is started. + /// + public virtual void OnRoomStartServer() {} + + /// + /// This is called on the server when the server is started - including when a host is stopped. + /// + public virtual void OnRoomStopServer() {} + + /// + /// This is called on the server when a new client connects to the server. + /// + /// The new connection. + public virtual void OnRoomServerConnect(NetworkConnectionToClient conn) {} + + /// + /// This is called on the server when a client disconnects. + /// + /// The connection that disconnected. + public virtual void OnRoomServerDisconnect(NetworkConnectionToClient conn) {} + + /// + /// This is called on the server when a networked scene finishes loading. + /// + /// Name of the new scene. + public virtual void OnRoomServerSceneChanged(string sceneName) {} + + /// + /// This allows customization of the creation of the room-player object on the server. + /// By default the roomPlayerPrefab is used to create the room-player, but this function allows that behaviour to be customized. + /// + /// The connection the player object is for. + /// The new room-player object. + public virtual GameObject OnRoomServerCreateRoomPlayer(NetworkConnectionToClient conn) + { + return null; + } + + /// + /// This allows customization of the creation of the GamePlayer object on the server. + /// By default the gamePlayerPrefab is used to create the game-player, but this function allows that behaviour to be customized. The object returned from the function will be used to replace the room-player on the connection. + /// + /// The connection the player object is for. + /// The room player object for this connection. + /// A new GamePlayer object. + public virtual GameObject OnRoomServerCreateGamePlayer(NetworkConnectionToClient conn, GameObject roomPlayer) + { + return null; + } + + /// + /// This allows customization of the creation of the GamePlayer object on the server. + /// This is only called for subsequent GamePlay scenes after the first one. + /// See OnRoomServerCreateGamePlayer(NetworkConnection, GameObject) to customize the player object for the initial GamePlay scene. + /// + /// The connection the player object is for. + public virtual void OnRoomServerAddPlayer(NetworkConnectionToClient conn) + { + base.OnServerAddPlayer(conn); + } + + // for users to apply settings from their room player object to their in-game player object + /// + /// This is called on the server when it is told that a client has finished switching from the room scene to a game player scene. + /// When switching from the room, the room-player is replaced with a game-player object. This callback function gives an opportunity to apply state from the room-player to the game-player object. + /// + /// The connection of the player + /// The room player object. + /// The game player object. + /// False to not allow this player to replace the room player. + public virtual bool OnRoomServerSceneLoadedForPlayer(NetworkConnectionToClient conn, GameObject roomPlayer, GameObject gamePlayer) + { + return true; + } + + /// + /// This is called on server from NetworkRoomPlayer.CmdChangeReadyState when client indicates change in Ready status. + /// + public virtual void ReadyStatusChanged() + { + int CurrentPlayers = 0; + int ReadyPlayers = 0; + + foreach (NetworkRoomPlayer item in roomSlots) + { + if (item != null) + { + CurrentPlayers++; + if (item.readyToBegin) + ReadyPlayers++; + } + } + + if (CurrentPlayers == ReadyPlayers) + CheckReadyToBegin(); + else + allPlayersReady = false; + } + + /// + /// This is called on the server when all the players in the room are ready. + /// The default implementation of this function uses ServerChangeScene() to switch to the game player scene. By implementing this callback you can customize what happens when all the players in the room are ready, such as adding a countdown or a confirmation for a group leader. + /// + public virtual void OnRoomServerPlayersReady() + { + // all players are readyToBegin, start the game + ServerChangeScene(GameplayScene); + } + + /// + /// This is called on the server when CheckReadyToBegin finds that players are not ready + /// May be called multiple times while not ready players are joining + /// + public virtual void OnRoomServerPlayersNotReady() {} + + #endregion + + #region room client virtuals + + /// + /// This is a hook to allow custom behaviour when the game client enters the room. + /// + public virtual void OnRoomClientEnter() {} + + /// + /// This is a hook to allow custom behaviour when the game client exits the room. + /// + public virtual void OnRoomClientExit() {} + + /// + /// This is called on the client when it connects to server. + /// + public virtual void OnRoomClientConnect() {} + + /// + /// This is called on the client when disconnected from a server. + /// + public virtual void OnRoomClientDisconnect() {} + + /// + /// This is called on the client when a client is started. + /// + public virtual void OnRoomStartClient() {} + + /// + /// This is called on the client when the client stops. + /// + public virtual void OnRoomStopClient() {} + + /// + /// This is called on the client when the client is finished loading a new networked scene. + /// + public virtual void OnRoomClientSceneChanged() {} + + #endregion + + #region optional UI + + /// + /// virtual so inheriting classes can roll their own + /// + public virtual void OnGUI() + { + if (!showRoomGUI) + return; + + if (NetworkServer.active && Utils.IsSceneActive(GameplayScene)) + { + GUILayout.BeginArea(new Rect(Screen.width - 150f, 10f, 140f, 30f)); + if (GUILayout.Button("Return to Room")) + ServerChangeScene(RoomScene); + GUILayout.EndArea(); + } + + if (Utils.IsSceneActive(RoomScene)) + GUI.Box(new Rect(10f, 180f, 520f, 150f), "PLAYERS"); + } + + #endregion + } +} diff --git a/Assets/Mirror/Components/NetworkRoomManager.cs.meta b/Assets/Mirror/Components/NetworkRoomManager.cs.meta new file mode 100644 index 0000000..76e7d42 --- /dev/null +++ b/Assets/Mirror/Components/NetworkRoomManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 615e6c6589cf9e54cad646b5a11e0529 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkRoomPlayer.cs b/Assets/Mirror/Components/NetworkRoomPlayer.cs new file mode 100644 index 0000000..28e5051 --- /dev/null +++ b/Assets/Mirror/Components/NetworkRoomPlayer.cs @@ -0,0 +1,195 @@ +using UnityEngine; + +namespace Mirror +{ + /// + /// This component works in conjunction with the NetworkRoomManager to make up the multiplayer room system. + /// The RoomPrefab object of the NetworkRoomManager must have this component on it. This component holds basic room player data required for the room to function. Game specific data for room players can be put in other components on the RoomPrefab or in scripts derived from NetworkRoomPlayer. + /// + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Room Player")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-room-player")] + public class NetworkRoomPlayer : NetworkBehaviour + { + /// + /// This flag controls whether the default UI is shown for the room player. + /// As this UI is rendered using the old GUI system, it is only recommended for testing purposes. + /// + [Tooltip("This flag controls whether the default UI is shown for the room player")] + public bool showRoomGUI = true; + + [Header("Diagnostics")] + + /// + /// Diagnostic flag indicating whether this player is ready for the game to begin. + /// Invoke CmdChangeReadyState method on the client to set this flag. + /// When all players are ready to begin, the game will start. This should not be set directly, CmdChangeReadyState should be called on the client to set it on the server. + /// + [Tooltip("Diagnostic flag indicating whether this player is ready for the game to begin")] + [SyncVar(hook = nameof(ReadyStateChanged))] + public bool readyToBegin; + + /// + /// Diagnostic index of the player, e.g. Player1, Player2, etc. + /// + [Tooltip("Diagnostic index of the player, e.g. Player1, Player2, etc.")] + [SyncVar(hook = nameof(IndexChanged))] + public int index; + + #region Unity Callbacks + + /// + /// Do not use Start - Override OnStartHost / OnStartClient instead! + /// + public virtual void Start() + { + if (NetworkManager.singleton is NetworkRoomManager room) + { + // NetworkRoomPlayer object must be set to DontDestroyOnLoad along with NetworkRoomManager + // in server and all clients, otherwise it will be respawned in the game scene which would + // have undesirable effects. + if (room.dontDestroyOnLoad) + DontDestroyOnLoad(gameObject); + + room.roomSlots.Add(this); + + if (NetworkServer.active) + room.RecalculateRoomPlayerIndices(); + + if (NetworkClient.active) + room.CallOnClientEnterRoom(); + } + else Debug.LogError("RoomPlayer could not find a NetworkRoomManager. The RoomPlayer requires a NetworkRoomManager object to function. Make sure that there is one in the scene."); + } + + public virtual void OnDisable() + { + if (NetworkClient.active && NetworkManager.singleton is NetworkRoomManager room) + { + // only need to call this on client as server removes it before object is destroyed + room.roomSlots.Remove(this); + + room.CallOnClientExitRoom(); + } + } + + #endregion + + #region Commands + + [Command] + public void CmdChangeReadyState(bool readyState) + { + readyToBegin = readyState; + NetworkRoomManager room = NetworkManager.singleton as NetworkRoomManager; + if (room != null) + { + room.ReadyStatusChanged(); + } + } + + #endregion + + #region SyncVar Hooks + + /// + /// This is a hook that is invoked on clients when the index changes. + /// + /// The old index value + /// The new index value + public virtual void IndexChanged(int oldIndex, int newIndex) {} + + /// + /// This is a hook that is invoked on clients when a RoomPlayer switches between ready or not ready. + /// This function is called when the a client player calls CmdChangeReadyState. + /// + /// New Ready State + public virtual void ReadyStateChanged(bool oldReadyState, bool newReadyState) {} + + #endregion + + #region Room Client Virtuals + + /// + /// This is a hook that is invoked on clients for all room player objects when entering the room. + /// Note: isLocalPlayer is not guaranteed to be set until OnStartLocalPlayer is called. + /// + public virtual void OnClientEnterRoom() {} + + /// + /// This is a hook that is invoked on clients for all room player objects when exiting the room. + /// + public virtual void OnClientExitRoom() {} + + #endregion + + #region Optional UI + + /// + /// Render a UI for the room. Override to provide your own UI + /// + public virtual void OnGUI() + { + if (!showRoomGUI) + return; + + NetworkRoomManager room = NetworkManager.singleton as NetworkRoomManager; + if (room) + { + if (!room.showRoomGUI) + return; + + if (!Utils.IsSceneActive(room.RoomScene)) + return; + + DrawPlayerReadyState(); + DrawPlayerReadyButton(); + } + } + + void DrawPlayerReadyState() + { + GUILayout.BeginArea(new Rect(20f + (index * 100), 200f, 90f, 130f)); + + GUILayout.Label($"Player [{index + 1}]"); + + if (readyToBegin) + GUILayout.Label("Ready"); + else + GUILayout.Label("Not Ready"); + + if (((isServer && index > 0) || isServerOnly) && GUILayout.Button("REMOVE")) + { + // This button only shows on the Host for all players other than the Host + // Host and Players can't remove themselves (stop the client instead) + // Host can kick a Player this way. + GetComponent().connectionToClient.Disconnect(); + } + + GUILayout.EndArea(); + } + + void DrawPlayerReadyButton() + { + if (NetworkClient.active && isLocalPlayer) + { + GUILayout.BeginArea(new Rect(20f, 300f, 120f, 20f)); + + if (readyToBegin) + { + if (GUILayout.Button("Cancel")) + CmdChangeReadyState(false); + } + else + { + if (GUILayout.Button("Ready")) + CmdChangeReadyState(true); + } + + GUILayout.EndArea(); + } + } + + #endregion + } +} diff --git a/Assets/Mirror/Components/NetworkRoomPlayer.cs.meta b/Assets/Mirror/Components/NetworkRoomPlayer.cs.meta new file mode 100644 index 0000000..0299bea --- /dev/null +++ b/Assets/Mirror/Components/NetworkRoomPlayer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79874ac94d5b1314788ecf0e86bd23fd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkStatistics.cs b/Assets/Mirror/Components/NetworkStatistics.cs new file mode 100644 index 0000000..c00bb19 --- /dev/null +++ b/Assets/Mirror/Components/NetworkStatistics.cs @@ -0,0 +1,194 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + /// + /// Shows Network messages and bytes sent and received per second. + /// + /// + /// Add this component to the same object as Network Manager. + /// + [AddComponentMenu("Network/Network Statistics")] + [DisallowMultipleComponent] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-statistics")] + public class NetworkStatistics : MonoBehaviour + { + // update interval + double intervalStartTime; + + // --------------------------------------------------------------------- + + // CLIENT (public fields for other components to grab statistics) + // long bytes to support >2GB + [HideInInspector] public int clientIntervalReceivedPackets; + [HideInInspector] public long clientIntervalReceivedBytes; + [HideInInspector] public int clientIntervalSentPackets; + [HideInInspector] public long clientIntervalSentBytes; + + // results from last interval + // long bytes to support >2GB + [HideInInspector] public int clientReceivedPacketsPerSecond; + [HideInInspector] public long clientReceivedBytesPerSecond; + [HideInInspector] public int clientSentPacketsPerSecond; + [HideInInspector] public long clientSentBytesPerSecond; + + // --------------------------------------------------------------------- + + // SERVER (public fields for other components to grab statistics) + // capture interval + // long bytes to support >2GB + [HideInInspector] public int serverIntervalReceivedPackets; + [HideInInspector] public long serverIntervalReceivedBytes; + [HideInInspector] public int serverIntervalSentPackets; + [HideInInspector] public long serverIntervalSentBytes; + + // results from last interval + // long bytes to support >2GB + [HideInInspector] public int serverReceivedPacketsPerSecond; + [HideInInspector] public long serverReceivedBytesPerSecond; + [HideInInspector] public int serverSentPacketsPerSecond; + [HideInInspector] public long serverSentBytesPerSecond; + + // NetworkManager sets Transport.active in Awake(). + // so let's hook into it in Start(). + void Start() + { + // find available transport + Transport transport = Transport.active; + if (transport != null) + { + transport.OnClientDataReceived += OnClientReceive; + transport.OnClientDataSent += OnClientSend; + transport.OnServerDataReceived += OnServerReceive; + transport.OnServerDataSent += OnServerSend; + } + else Debug.LogError($"NetworkStatistics: no available or active Transport found on this platform: {Application.platform}"); + } + + void OnDestroy() + { + // remove transport hooks + Transport transport = Transport.active; + if (transport != null) + { + transport.OnClientDataReceived -= OnClientReceive; + transport.OnClientDataSent -= OnClientSend; + transport.OnServerDataReceived -= OnServerReceive; + transport.OnServerDataSent -= OnServerSend; + } + } + + void OnClientReceive(ArraySegment data, int channelId) + { + ++clientIntervalReceivedPackets; + clientIntervalReceivedBytes += data.Count; + } + + void OnClientSend(ArraySegment data, int channelId) + { + ++clientIntervalSentPackets; + clientIntervalSentBytes += data.Count; + } + + void OnServerReceive(int connectionId, ArraySegment data, int channelId) + { + ++serverIntervalReceivedPackets; + serverIntervalReceivedBytes += data.Count; + } + + void OnServerSend(int connectionId, ArraySegment data, int channelId) + { + ++serverIntervalSentPackets; + serverIntervalSentBytes += data.Count; + } + + void Update() + { + // calculate results every second + if (NetworkTime.localTime >= intervalStartTime + 1) + { + if (NetworkClient.active) UpdateClient(); + if (NetworkServer.active) UpdateServer(); + + intervalStartTime = NetworkTime.localTime; + } + } + + void UpdateClient() + { + clientReceivedPacketsPerSecond = clientIntervalReceivedPackets; + clientReceivedBytesPerSecond = clientIntervalReceivedBytes; + clientSentPacketsPerSecond = clientIntervalSentPackets; + clientSentBytesPerSecond = clientIntervalSentBytes; + + clientIntervalReceivedPackets = 0; + clientIntervalReceivedBytes = 0; + clientIntervalSentPackets = 0; + clientIntervalSentBytes = 0; + } + + void UpdateServer() + { + serverReceivedPacketsPerSecond = serverIntervalReceivedPackets; + serverReceivedBytesPerSecond = serverIntervalReceivedBytes; + serverSentPacketsPerSecond = serverIntervalSentPackets; + serverSentBytesPerSecond = serverIntervalSentBytes; + + serverIntervalReceivedPackets = 0; + serverIntervalReceivedBytes = 0; + serverIntervalSentPackets = 0; + serverIntervalSentBytes = 0; + } + + void OnGUI() + { + // only show if either server or client active + if (NetworkClient.active || NetworkServer.active) + { + // create main GUI area + // 120 is below NetworkManager HUD in all cases. + GUILayout.BeginArea(new Rect(10, 120, 215, 300)); + + // show client / server stats if active + if (NetworkClient.active) OnClientGUI(); + if (NetworkServer.active) OnServerGUI(); + + // end of GUI area + GUILayout.EndArea(); + } + } + + void OnClientGUI() + { + // background + GUILayout.BeginVertical("Box"); + GUILayout.Label("Client Statistics"); + + // sending ("msgs" instead of "packets" to fit larger numbers) + GUILayout.Label($"Send: {clientSentPacketsPerSecond} msgs @ {Utils.PrettyBytes(clientSentBytesPerSecond)}/s"); + + // receiving ("msgs" instead of "packets" to fit larger numbers) + GUILayout.Label($"Recv: {clientReceivedPacketsPerSecond} msgs @ {Utils.PrettyBytes(clientReceivedBytesPerSecond)}/s"); + + // end background + GUILayout.EndVertical(); + } + + void OnServerGUI() + { + // background + GUILayout.BeginVertical("Box"); + GUILayout.Label("Server Statistics"); + + // sending ("msgs" instead of "packets" to fit larger numbers) + GUILayout.Label($"Send: {serverSentPacketsPerSecond} msgs @ {Utils.PrettyBytes(serverSentBytesPerSecond)}/s"); + + // receiving ("msgs" instead of "packets" to fit larger numbers) + GUILayout.Label($"Recv: {serverReceivedPacketsPerSecond} msgs @ {Utils.PrettyBytes(serverReceivedBytesPerSecond)}/s"); + + // end background + GUILayout.EndVertical(); + } + } +} diff --git a/Assets/Mirror/Components/NetworkStatistics.cs.meta b/Assets/Mirror/Components/NetworkStatistics.cs.meta new file mode 100644 index 0000000..0bf4251 --- /dev/null +++ b/Assets/Mirror/Components/NetworkStatistics.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d7da4e566d24ea7b0e12178d934b648 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkTransform.meta b/Assets/Mirror/Components/NetworkTransform.meta new file mode 100644 index 0000000..1b6770d --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 36de72d9255741659bcbd1971ed29822 +timeCreated: 1668358590 \ No newline at end of file diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransform.cs b/Assets/Mirror/Components/NetworkTransform/NetworkTransform.cs new file mode 100644 index 0000000..8a1a24a --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransform.cs @@ -0,0 +1,8 @@ +using System; + +namespace Mirror +{ + // DEPRECATED 2023-06-15 + [Obsolete("NetworkTransform was renamed to NetworkTransformUnreliable.\nYou can easily swap the component's script by going into the Unity Inspector debug mode:\n1. Click the vertical dots on the top right in the Inspector tab.\n2. Find your NetworkTransform component\n3. Drag NetworkTransformUnreliable into the 'Script' field in the Inspector.\n4. Find the three dots and return to Normal mode.")] + public class NetworkTransform : NetworkTransformUnreliable {} +} diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransform.cs.meta b/Assets/Mirror/Components/NetworkTransform/NetworkTransform.cs.meta new file mode 100644 index 0000000..a569990 --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransform.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2f74aedd71d9a4f55b3ce499326d45fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs b/Assets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs new file mode 100644 index 0000000..5a6b9da --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs @@ -0,0 +1,475 @@ +// Snapshot Interpolation: https://gafferongames.com/post/snapshot_interpolation/ +// +// Base class for NetworkTransform and NetworkTransformChild. +// => simple unreliable sync without any interpolation for now. +// => which means we don't need teleport detection either +// +// NOTE: several functions are virtual in case someone needs to modify a part. +// +// Channel: uses UNRELIABLE at all times. +// -> out of order packets are dropped automatically +// -> it's better than RELIABLE for several reasons: +// * head of line blocking would add delay +// * resending is mostly pointless +// * bigger data race: +// -> if we use a Cmd() at position X over reliable +// -> client gets Cmd() and X at the same time, but buffers X for bufferTime +// -> for unreliable, it would get X before the reliable Cmd(), still +// buffer for bufferTime but end up closer to the original time +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + public enum CoordinateSpace { Local, World } + + public abstract class NetworkTransformBase : NetworkBehaviour + { + // target transform to sync. can be on a child. + // TODO this field is kind of unnecessary since we now support child NetworkBehaviours + [Header("Target")] + [Tooltip("The Transform component to sync. May be on on this GameObject, or on a child.")] + public Transform target; + + // TODO SyncDirection { ClientToServer, ServerToClient } is easier? + // Deprecated 2022-10-25 + [Obsolete("NetworkTransform clientAuthority was replaced with syncDirection. To enable client authority, set SyncDirection to ClientToServer in the Inspector.")] + [Header("[Obsolete]")] // Unity doesn't show obsolete warning for fields. do it manually. + [Tooltip("Obsolete: NetworkTransform clientAuthority was replaced with syncDirection. To enable client authority, set SyncDirection to ClientToServer in the Inspector.")] + public bool clientAuthority; + // Is this a client with authority over this transform? + // This component could be on the player object or any object that has been assigned authority to this client. + protected bool IsClientWithAuthority => isClient && authority; + + // snapshots with initial capacity to avoid early resizing & allocations: see NetworkRigidbodyBenchmark example. + public readonly SortedList clientSnapshots = new SortedList(16); + public readonly SortedList serverSnapshots = new SortedList(16); + + // selective sync ////////////////////////////////////////////////////// + [Header("Selective Sync\nDon't change these at Runtime")] + public bool syncPosition = true; // do not change at runtime! + public bool syncRotation = true; // do not change at runtime! + public bool syncScale = false; // do not change at runtime! rare. off by default. + + // interpolation is on by default, but can be disabled to jump to + // the destination immediately. some projects need this. + [Header("Interpolation")] + [Tooltip("Set to false to have a snap-like effect on position movement.")] + public bool interpolatePosition = true; + [Tooltip("Set to false to have a snap-like effect on rotations.")] + public bool interpolateRotation = true; + [Tooltip("Set to false to remove scale smoothing. Example use-case: Instant flipping of sprites that use -X and +X for direction.")] + public bool interpolateScale = true; + + // CoordinateSpace /////////////////////////////////////////////////////////// + [Header("Coordinate Space")] + [Tooltip("Local by default. World may be better when changing hierarchy, or non-NetworkTransforms root position/rotation/scale values.")] + public CoordinateSpace coordinateSpace = CoordinateSpace.Local; + + [Header("Send Interval Multiplier")] + [Tooltip("Check/Sync every multiple of Network Manager send interval (= 1 / NM Send Rate), instead of every send interval.\n(30 NM send rate, and 3 interval, is a send every 0.1 seconds)\nA larger interval means less network sends, which has a variety of upsides. The drawbacks are delays and lower accuracy, you should find a nice balance between not sending too much, but the results looking good for your particular scenario.")] + [Range(1, 120)] + public uint sendIntervalMultiplier = 1; + + [Header("Timeline Offset")] + [Tooltip("Add a small timeline offset to account for decoupled arrival of NetworkTime and NetworkTransform snapshots.\nfixes: https://github.com/MirrorNetworking/Mirror/issues/3427")] + public bool timelineOffset = false; + + // Ninja's Notes on offset & mulitplier: + // + // In a no multiplier scenario: + // 1. Snapshots are sent every frame (frame being 1 NM send interval). + // 2. Time Interpolation is set to be 'behind' by 2 frames times. + // In theory where everything works, we probably have around 2 snapshots before we need to interpolate snapshots. From NT perspective, we should always have around 2 snapshots ready, so no stutter. + // + // In a multiplier scenario: + // 1. Snapshots are sent every 10 frames. + // 2. Time Interpolation remains 'behind by 2 frames'. + // When everything works, we are receiving NT snapshots every 10 frames, but start interpolating after 2. + // Even if I assume we had 2 snapshots to begin with to start interpolating (which we don't), by the time we reach 13th frame, we are out of snapshots, and have to wait 7 frames for next snapshot to come. This is the reason why we absolutely need the timestamp adjustment. We are starting way too early to interpolate. + // + protected double timeStampAdjustment => NetworkServer.sendInterval * (sendIntervalMultiplier - 1); + protected double offset => timelineOffset ? NetworkServer.sendInterval * sendIntervalMultiplier : 0; + + // debugging /////////////////////////////////////////////////////////// + [Header("Debug")] + public bool showGizmos; + public bool showOverlay; + public Color overlayColor = new Color(0, 0, 0, 0.5f); + + // initialization ////////////////////////////////////////////////////// + // make sure to call this when inheriting too! + protected virtual void Awake() { } + + protected override void OnValidate() + { + base.OnValidate(); + + // set target to self if none yet + if (target == null) target = transform; + + // time snapshot interpolation happens globally. + // value (transform) happens in here. + // both always need to be on the same send interval. + // force the setting to '0' in OnValidate to make it obvious that we + // actually use NetworkServer.sendInterval. + syncInterval = 0; + + // Unity doesn't support setting world scale. + // OnValidate force disables syncScale in world mode. + if (coordinateSpace == CoordinateSpace.World) syncScale = false; + + // obsolete clientAuthority compatibility: + // if it was used, then set the new SyncDirection automatically. + // if it wasn't used, then don't touch syncDirection. +#pragma warning disable CS0618 + if (clientAuthority) + { + syncDirection = SyncDirection.ClientToServer; + Debug.LogWarning($"{name}'s NetworkTransform component has obsolete .clientAuthority enabled. Please disable it and set SyncDirection to ClientToServer instead."); + } +#pragma warning restore CS0618 + } + + // snapshot functions ////////////////////////////////////////////////// + // get local/world position + protected Vector3 GetPosition() => + coordinateSpace == CoordinateSpace.Local ? target.localPosition : target.position; + + // get local/world rotation + protected Quaternion GetRotation() => + coordinateSpace == CoordinateSpace.Local ? target.localRotation : target.rotation; + + // get local/world scale + protected Vector3 GetScale() => + coordinateSpace == CoordinateSpace.Local ? target.localScale : target.lossyScale; + + // set local/world position + protected void SetPosition(Vector3 position) + { + if (coordinateSpace == CoordinateSpace.Local) + target.localPosition = position; + else + target.position = position; + } + + // set local/world rotation + protected void SetRotation(Quaternion rotation) + { + if (coordinateSpace == CoordinateSpace.Local) + target.localRotation = rotation; + else + target.rotation = rotation; + } + + // set local/world position + protected void SetScale(Vector3 scale) + { + if (coordinateSpace == CoordinateSpace.Local) + target.localScale = scale; + // Unity doesn't support setting world scale. + // OnValidate disables syncScale in world mode. + // else + // target.lossyScale = scale; // TODO + } + + // construct a snapshot of the current state + // => internal for testing + protected virtual TransformSnapshot Construct() + { + // NetworkTime.localTime for double precision until Unity has it too + return new TransformSnapshot( + // our local time is what the other end uses as remote time + NetworkTime.localTime, // Unity 2019 doesn't have timeAsDouble yet + 0, // the other end fills out local time itself + GetPosition(), + GetRotation(), + GetScale() + ); + } + + protected void AddSnapshot(SortedList snapshots, double timeStamp, Vector3? position, Quaternion? rotation, Vector3? scale) + { + // position, rotation, scale can have no value if same as last time. + // saves bandwidth. + // but we still need to feed it to snapshot interpolation. we can't + // just have gaps in there if nothing has changed. for example, if + // client sends snapshot at t=0 + // client sends nothing for 10s because not moved + // client sends snapshot at t=10 + // then the server would assume that it's one super slow move and + // replay it for 10 seconds. + + if (!position.HasValue) position = snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].position : GetPosition(); + if (!rotation.HasValue) rotation = snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].rotation : GetRotation(); + if (!scale.HasValue) scale = snapshots.Count > 0 ? snapshots.Values[snapshots.Count - 1].scale : GetScale(); + + // insert transform snapshot + SnapshotInterpolation.InsertIfNotExists( + snapshots, + NetworkClient.snapshotSettings.bufferLimit, + new TransformSnapshot( + timeStamp, // arrival remote timestamp. NOT remote time. + NetworkTime.localTime, // Unity 2019 doesn't have timeAsDouble yet + position.Value, + rotation.Value, + scale.Value + ) + ); + } + + // apply a snapshot to the Transform. + // -> start, end, interpolated are all passed in caes they are needed + // -> a regular game would apply the 'interpolated' snapshot + // -> a board game might want to jump to 'goal' directly + // (it's easier to always interpolate and then apply selectively, + // instead of manually interpolating x, y, z, ... depending on flags) + // => internal for testing + // + // NOTE: stuck detection is unnecessary here. + // we always set transform.position anyway, we can't get stuck. + protected virtual void Apply(TransformSnapshot interpolated, TransformSnapshot endGoal) + { + // local position/rotation for VR support + // + // if syncPosition/Rotation/Scale is disabled then we received nulls + // -> current position/rotation/scale would've been added as snapshot + // -> we still interpolated + // -> but simply don't apply it. if the user doesn't want to sync + // scale, then we should not touch scale etc. + + // interpolate parts + if (syncPosition) SetPosition(interpolatePosition ? interpolated.position : endGoal.position); + if (syncRotation) SetRotation(interpolateRotation ? interpolated.rotation : endGoal.rotation); + if (syncScale) SetScale(interpolateScale ? interpolated.scale : endGoal.scale); + } + + // client->server teleport to force position without interpolation. + // otherwise it would interpolate to a (far away) new position. + // => manually calling Teleport is the only 100% reliable solution. + [Command] + public void CmdTeleport(Vector3 destination) + { + // client can only teleport objects that it has authority over. + if (syncDirection != SyncDirection.ClientToServer) return; + + // TODO what about host mode? + OnTeleport(destination); + + // if a client teleports, we need to broadcast to everyone else too + // TODO the teleported client should ignore the rpc though. + // otherwise if it already moved again after teleporting, + // the rpc would come a little bit later and reset it once. + // TODO or not? if client ONLY calls Teleport(pos), the position + // would only be set after the rpc. unless the client calls + // BOTH Teleport(pos) and target.position=pos + RpcTeleport(destination); + } + + // client->server teleport to force position and rotation without interpolation. + // otherwise it would interpolate to a (far away) new position. + // => manually calling Teleport is the only 100% reliable solution. + [Command] + public void CmdTeleport(Vector3 destination, Quaternion rotation) + { + // client can only teleport objects that it has authority over. + if (syncDirection != SyncDirection.ClientToServer) return; + + // TODO what about host mode? + OnTeleport(destination, rotation); + + // if a client teleports, we need to broadcast to everyone else too + // TODO the teleported client should ignore the rpc though. + // otherwise if it already moved again after teleporting, + // the rpc would come a little bit later and reset it once. + // TODO or not? if client ONLY calls Teleport(pos), the position + // would only be set after the rpc. unless the client calls + // BOTH Teleport(pos) and target.position=pos + RpcTeleport(destination, rotation); + } + + // server->client teleport to force position without interpolation. + // otherwise it would interpolate to a (far away) new position. + // => manually calling Teleport is the only 100% reliable solution. + [ClientRpc] + public void RpcTeleport(Vector3 destination) + { + // NOTE: even in client authority mode, the server is always allowed + // to teleport the player. for example: + // * CmdEnterPortal() might teleport the player + // * Some people use client authority with server sided checks + // so the server should be able to reset position if needed. + + // TODO what about host mode? + OnTeleport(destination); + } + + // server->client teleport to force position and rotation without interpolation. + // otherwise it would interpolate to a (far away) new position. + // => manually calling Teleport is the only 100% reliable solution. + [ClientRpc] + public void RpcTeleport(Vector3 destination, Quaternion rotation) + { + // NOTE: even in client authority mode, the server is always allowed + // to teleport the player. for example: + // * CmdEnterPortal() might teleport the player + // * Some people use client authority with server sided checks + // so the server should be able to reset position if needed. + + // TODO what about host mode? + OnTeleport(destination, rotation); + } + + [ClientRpc] + void RpcReset() + { + Reset(); + } + + // common Teleport code for client->server and server->client + protected virtual void OnTeleport(Vector3 destination) + { + // reset any in-progress interpolation & buffers + Reset(); + + // set the new position. + // interpolation will automatically continue. + target.position = destination; + + // TODO + // what if we still receive a snapshot from before the interpolation? + // it could easily happen over unreliable. + // -> maybe add destination as first entry? + } + + // common Teleport code for client->server and server->client + protected virtual void OnTeleport(Vector3 destination, Quaternion rotation) + { + // reset any in-progress interpolation & buffers + Reset(); + + // set the new position. + // interpolation will automatically continue. + target.position = destination; + target.rotation = rotation; + + // TODO + // what if we still receive a snapshot from before the interpolation? + // it could easily happen over unreliable. + // -> maybe add destination as first entry? + } + + public virtual void Reset() + { + // disabled objects aren't updated anymore. + // so let's clear the buffers. + serverSnapshots.Clear(); + clientSnapshots.Clear(); + } + + protected virtual void OnEnable() + { + Reset(); + + if (NetworkServer.active) + NetworkIdentity.clientAuthorityCallback += OnClientAuthorityChanged; + } + + protected virtual void OnDisable() + { + Reset(); + + if (NetworkServer.active) + NetworkIdentity.clientAuthorityCallback -= OnClientAuthorityChanged; + } + + [ServerCallback] + void OnClientAuthorityChanged(NetworkConnectionToClient conn, NetworkIdentity identity, bool authorityState) + { + if (identity != netIdentity) return; + + // If server gets authority or syncdirection is server to client, + // we don't reset buffers. + // This is because if syncdirection is S to C, we will never have + // snapshot issues since there is only ever 1 source. + + if (syncDirection == SyncDirection.ClientToServer) + { + Reset(); + RpcReset(); + } + } + + // OnGUI allocates even if it does nothing. avoid in release. +#if UNITY_EDITOR || DEVELOPMENT_BUILD + // debug /////////////////////////////////////////////////////////////// + protected virtual void OnGUI() + { + if (!showOverlay) return; + if (!Camera.main) return; + + // show data next to player for easier debugging. this is very useful! + // IMPORTANT: this is basically an ESP hack for shooter games. + // DO NOT make this available with a hotkey in release builds + if (!Debug.isDebugBuild) return; + + // project position to screen + Vector3 point = Camera.main.WorldToScreenPoint(target.position); + + // enough alpha, in front of camera and in screen? + if (point.z >= 0 && Utils.IsPointInScreen(point)) + { + GUI.color = overlayColor; + GUILayout.BeginArea(new Rect(point.x, Screen.height - point.y, 200, 100)); + + // always show both client & server buffers so it's super + // obvious if we accidentally populate both. + GUILayout.Label($"Server Buffer:{serverSnapshots.Count}"); + GUILayout.Label($"Client Buffer:{clientSnapshots.Count}"); + + GUILayout.EndArea(); + GUI.color = Color.white; + } + } + + protected virtual void DrawGizmos(SortedList buffer) + { + // only draw if we have at least two entries + if (buffer.Count < 2) return; + + // calculate threshold for 'old enough' snapshots + double threshold = NetworkTime.localTime - NetworkClient.bufferTime; + Color oldEnoughColor = new Color(0, 1, 0, 0.5f); + Color notOldEnoughColor = new Color(0.5f, 0.5f, 0.5f, 0.3f); + + // draw the whole buffer for easier debugging. + // it's worth seeing how much we have buffered ahead already + for (int i = 0; i < buffer.Count; ++i) + { + // color depends on if old enough or not + TransformSnapshot entry = buffer.Values[i]; + bool oldEnough = entry.localTime <= threshold; + Gizmos.color = oldEnough ? oldEnoughColor : notOldEnoughColor; + Gizmos.DrawWireCube(entry.position, Vector3.one); + } + + // extra: lines between start<->position<->goal + Gizmos.color = Color.green; + Gizmos.DrawLine(buffer.Values[0].position, target.position); + Gizmos.color = Color.white; + Gizmos.DrawLine(target.position, buffer.Values[1].position); + } + + protected virtual void OnDrawGizmos() + { + // This fires in edit mode but that spams NRE's so check isPlaying + if (!Application.isPlaying) return; + if (!showGizmos) return; + + if (isServer) DrawGizmos(serverSnapshots); + if (isClient) DrawGizmos(clientSnapshots); + } +#endif + } +} diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs.meta b/Assets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs.meta new file mode 100644 index 0000000..ef58471 --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransformBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c44135fde488424eaf28566206ce473 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs b/Assets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs new file mode 100644 index 0000000..a844d9d --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs @@ -0,0 +1,12 @@ +// A component to synchronize the position of child transforms of networked objects. +// There must be a NetworkTransform on the root object of the hierarchy. There can be multiple NetworkTransformChild components on an object. This does not use physics for synchronization, it simply synchronizes the localPosition and localRotation of the child transform and lerps towards the recieved values. +using System; +using UnityEngine; + +namespace Mirror +{ + // Deprecated 2022-10-25 + [AddComponentMenu("")] + [Obsolete("NetworkTransformChild is not needed anymore. The .target is now exposed in NetworkTransform itself. Note you can open the Inspector in debug view and replace the source script instead of reassigning everything.")] + public class NetworkTransformChild : NetworkTransform {} +} diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs.meta b/Assets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs.meta new file mode 100644 index 0000000..ae36756 --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransformChild.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 734b48bea0b204338958ee3d885e11f0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs b/Assets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs new file mode 100644 index 0000000..f3d4afd --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs @@ -0,0 +1,423 @@ +// NetworkTransform V3 (reliable) by mischa (2022-10) +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/Network Transform (Reliable)")] + public class NetworkTransformReliable : NetworkTransformBase + { + [Header("Sync Only If Changed")] + [Tooltip("When true, changes are not sent unless greater than sensitivity values below.")] + public bool onlySyncOnChange = true; + + uint sendIntervalCounter = 0; + double lastSendIntervalTime = double.MinValue; + + [Tooltip("If we only sync on change, then we need to correct old snapshots if more time than sendInterval * multiplier has elapsed.\n\nOtherwise the first move will always start interpolating from the last move sequence's time, which will make it stutter when starting every time.")] + public float onlySyncOnChangeCorrectionMultiplier = 2; + + [Header("Rotation")] + [Tooltip("Sensitivity of changes needed before an updated state is sent over the network")] + public float rotationSensitivity = 0.01f; + [Tooltip("Apply smallest-three quaternion compression. This is lossy, you can disable it if the small rotation inaccuracies are noticeable in your project.")] + public bool compressRotation = false; + + // delta compression is capable of detecting byte-level changes. + // if we scale float position to bytes, + // then small movements will only change one byte. + // this gives optimal bandwidth. + // benchmark with 0.01 precision: 130 KB/s => 60 KB/s + // benchmark with 0.1 precision: 130 KB/s => 30 KB/s + [Header("Precision")] + [Tooltip("Position is rounded in order to drastically minimize bandwidth.\n\nFor example, a precision of 0.01 rounds to a centimeter. In other words, sub-centimeter movements aren't synced until they eventually exceeded an actual centimeter.\n\nDepending on how important the object is, a precision of 0.01-0.10 (1-10 cm) is recommended.\n\nFor example, even a 1cm precision combined with delta compression cuts the Benchmark demo's bandwidth in half, compared to sending every tiny change.")] + [Range(0.00_01f, 1f)] // disallow 0 division. 1mm to 1m precision is enough range. + public float positionPrecision = 0.01f; // 1 cm + [Range(0.00_01f, 1f)] // disallow 0 division. 1mm to 1m precision is enough range. + public float scalePrecision = 0.01f; // 1 cm + + // delta compression needs to remember 'last' to compress against + protected Vector3Long lastSerializedPosition = Vector3Long.zero; + protected Vector3Long lastDeserializedPosition = Vector3Long.zero; + + protected Vector3Long lastSerializedScale = Vector3Long.zero; + protected Vector3Long lastDeserializedScale = Vector3Long.zero; + + // Used to store last sent snapshots + protected TransformSnapshot last; + + protected int lastClientCount = 1; + + // update ////////////////////////////////////////////////////////////// + void Update() + { + // if server then always sync to others. + if (isServer) UpdateServer(); + // 'else if' because host mode shouldn't send anything to server. + // it is the server. don't overwrite anything there. + else if (isClient) UpdateClient(); + } + + void LateUpdate() + { + // set dirty to trigger OnSerialize. either always, or only if changed. + // It has to be checked in LateUpdate() for onlySyncOnChange to avoid + // the possibility of Update() running first before the object's movement + // script's Update(), which then causes NT to send every alternate frame + // instead. + if (isServer || (IsClientWithAuthority && NetworkClient.ready)) + { + if (sendIntervalCounter == sendIntervalMultiplier && (!onlySyncOnChange || Changed(Construct()))) + SetDirty(); + + CheckLastSendTime(); + } + } + + protected virtual void UpdateServer() + { + // apply buffered snapshots IF client authority + // -> in server authority, server moves the object + // so no need to apply any snapshots there. + // -> don't apply for host mode player objects either, even if in + // client authority mode. if it doesn't go over the network, + // then we don't need to do anything. + // -> connectionToClient is briefly null after scene changes: + // https://github.com/MirrorNetworking/Mirror/issues/3329 + if (syncDirection == SyncDirection.ClientToServer && + connectionToClient != null && + !isOwned) + { + if (serverSnapshots.Count > 0) + { + // step the transform interpolation without touching time. + // NetworkClient is responsible for time globally. + SnapshotInterpolation.StepInterpolation( + serverSnapshots, + connectionToClient.remoteTimeline, + out TransformSnapshot from, + out TransformSnapshot to, + out double t); + + // interpolate & apply + TransformSnapshot computed = TransformSnapshot.Interpolate(from, to, t); + Apply(computed, to); + } + } + } + + protected virtual void UpdateClient() + { + // client authority, and local player (= allowed to move myself)? + if (!IsClientWithAuthority) + { + // only while we have snapshots + if (clientSnapshots.Count > 0) + { + // step the interpolation without touching time. + // NetworkClient is responsible for time globally. + SnapshotInterpolation.StepInterpolation( + clientSnapshots, + NetworkTime.time, // == NetworkClient.localTimeline from snapshot interpolation + out TransformSnapshot from, + out TransformSnapshot to, + out double t); + + // interpolate & apply + TransformSnapshot computed = TransformSnapshot.Interpolate(from, to, t); + Apply(computed, to); + } + + lastClientCount = clientSnapshots.Count; + } + } + + protected virtual void CheckLastSendTime() + { + // timeAsDouble not available in older Unity versions. + if (AccurateInterval.Elapsed(NetworkTime.localTime, NetworkServer.sendInterval, ref lastSendIntervalTime)) + { + if (sendIntervalCounter == sendIntervalMultiplier) + sendIntervalCounter = 0; + sendIntervalCounter++; + } + } + + // check if position / rotation / scale changed since last sync + protected virtual bool Changed(TransformSnapshot current) => + // position is quantized and delta compressed. + // only consider it changed if the quantized representation is changed. + // careful: don't use 'serialized / deserialized last'. as it depends on sync mode etc. + QuantizedChanged(last.position, current.position, positionPrecision) || + // rotation isn't quantized / delta compressed. + // check with sensitivity. + Quaternion.Angle(last.rotation, current.rotation) > rotationSensitivity || + // scale is quantized and delta compressed. + // only consider it changed if the quantized representation is changed. + // careful: don't use 'serialized / deserialized last'. as it depends on sync mode etc. + QuantizedChanged(last.scale, current.scale, scalePrecision); + + // helper function to compare quantized representations of a Vector3 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected bool QuantizedChanged(Vector3 u, Vector3 v, float precision) + { + Compression.ScaleToLong(u, precision, out Vector3Long uQuantized); + Compression.ScaleToLong(v, precision, out Vector3Long vQuantized); + return uQuantized != vQuantized; + } + + // NT may be used on client/server/host to Owner/Observers with + // ServerToClient or ClientToServer. + // however, OnSerialize should always delta against last. + public override void OnSerialize(NetworkWriter writer, bool initialState) + { + // get current snapshot for broadcasting. + TransformSnapshot snapshot = Construct(); + + // ClientToServer optimization: + // for interpolated client owned identities, + // always broadcast the latest known snapshot so other clients can + // interpolate immediately instead of catching up too + + // TODO dirty mask? [compression is very good w/o it already] + // each vector's component is delta compressed. + // an unchanged component would still require 1 byte. + // let's use a dirty bit mask to filter those out as well. + + // initial + if (initialState) + { + // If there is a last serialized snapshot, we use it. + // This prevents the new client getting a snapshot that is different + // from what the older clients last got. If this happens, and on the next + // regular serialisation the delta compression will get wrong values. + // Notes: + // 1. Interestingly only the older clients have it wrong, because at the end + // of this function, last = snapshot which is the initial state's snapshot + // 2. Regular NTR gets by this bug because it sends every frame anyway so initialstate + // snapshot constructed would have been the same as the last anyway. + if (last.remoteTime > 0) snapshot = last; + if (syncPosition) writer.WriteVector3(snapshot.position); + if (syncRotation) + { + // (optional) smallest three compression for now. no delta. + if (compressRotation) + writer.WriteUInt(Compression.CompressQuaternion(snapshot.rotation)); + else + writer.WriteQuaternion(snapshot.rotation); + } + if (syncScale) writer.WriteVector3(snapshot.scale); + } + // delta + else + { + // int before = writer.Position; + + if (syncPosition) + { + // quantize -> delta -> varint + Compression.ScaleToLong(snapshot.position, positionPrecision, out Vector3Long quantized); + DeltaCompression.Compress(writer, lastSerializedPosition, quantized); + } + if (syncRotation) + { + // (optional) smallest three compression for now. no delta. + if (compressRotation) + writer.WriteUInt(Compression.CompressQuaternion(snapshot.rotation)); + else + writer.WriteQuaternion(snapshot.rotation); + } + if (syncScale) + { + // quantize -> delta -> varint + Compression.ScaleToLong(snapshot.scale, scalePrecision, out Vector3Long quantized); + DeltaCompression.Compress(writer, lastSerializedScale, quantized); + } + } + + // save serialized as 'last' for next delta compression + if (syncPosition) Compression.ScaleToLong(snapshot.position, positionPrecision, out lastSerializedPosition); + if (syncScale) Compression.ScaleToLong(snapshot.scale, scalePrecision, out lastSerializedScale); + + // set 'last' + last = snapshot; + } + + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + Vector3? position = null; + Quaternion? rotation = null; + Vector3? scale = null; + + // initial + if (initialState) + { + if (syncPosition) position = reader.ReadVector3(); + if (syncRotation) + { + // (optional) smallest three compression for now. no delta. + if (compressRotation) + rotation = Compression.DecompressQuaternion(reader.ReadUInt()); + else + rotation = reader.ReadQuaternion(); + } + if (syncScale) scale = reader.ReadVector3(); + } + // delta + else + { + // varint -> delta -> quantize + if (syncPosition) + { + Vector3Long quantized = DeltaCompression.Decompress(reader, lastDeserializedPosition); + position = Compression.ScaleToFloat(quantized, positionPrecision); + } + if (syncRotation) + { + // (optional) smallest three compression for now. no delta. + if (compressRotation) + rotation = Compression.DecompressQuaternion(reader.ReadUInt()); + else + rotation = reader.ReadQuaternion(); + } + if (syncScale) + { + Vector3Long quantized = DeltaCompression.Decompress(reader, lastDeserializedScale); + scale = Compression.ScaleToFloat(quantized, scalePrecision); + } + } + + // handle depending on server / client / host. + // server has priority for host mode. + if (isServer) OnClientToServerSync(position, rotation, scale); + else if (isClient) OnServerToClientSync(position, rotation, scale); + + // save deserialized as 'last' for next delta compression + if (syncPosition) Compression.ScaleToLong(position.Value, positionPrecision, out lastDeserializedPosition); + if (syncScale) Compression.ScaleToLong(scale.Value, scalePrecision, out lastDeserializedScale); + } + + // sync //////////////////////////////////////////////////////////////// + + // local authority client sends sync message to server for broadcasting + protected virtual void OnClientToServerSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + // only apply if in client authority mode + if (syncDirection != SyncDirection.ClientToServer) return; + + // protect against ever growing buffer size attacks + if (serverSnapshots.Count >= connectionToClient.snapshotBufferSizeLimit) return; + + // 'only sync on change' needs a correction on every new move sequence. + if (onlySyncOnChange && + NeedsCorrection(serverSnapshots, connectionToClient.remoteTimeStamp, NetworkServer.sendInterval * sendIntervalMultiplier, onlySyncOnChangeCorrectionMultiplier)) + { + RewriteHistory( + serverSnapshots, + connectionToClient.remoteTimeStamp, + NetworkTime.localTime, // arrival remote timestamp. NOT remote timeline. + NetworkServer.sendInterval * sendIntervalMultiplier, // Unity 2019 doesn't have timeAsDouble yet + GetPosition(), + GetRotation(), + GetScale()); + } + + // add a small timeline offset to account for decoupled arrival of + // NetworkTime and NetworkTransform snapshots. + // needs to be sendInterval. half sendInterval doesn't solve it. + // https://github.com/MirrorNetworking/Mirror/issues/3427 + // remove this after LocalWorldState. + AddSnapshot(serverSnapshots, connectionToClient.remoteTimeStamp + timeStampAdjustment + offset, position, rotation, scale); + } + + // server broadcasts sync message to all clients + protected virtual void OnServerToClientSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + // don't apply for local player with authority + if (IsClientWithAuthority) return; + + // 'only sync on change' needs a correction on every new move sequence. + if (onlySyncOnChange && + NeedsCorrection(clientSnapshots, NetworkClient.connection.remoteTimeStamp, NetworkClient.sendInterval * sendIntervalMultiplier, onlySyncOnChangeCorrectionMultiplier)) + { + RewriteHistory( + clientSnapshots, + NetworkClient.connection.remoteTimeStamp, // arrival remote timestamp. NOT remote timeline. + NetworkTime.localTime, // Unity 2019 doesn't have timeAsDouble yet + NetworkClient.sendInterval * sendIntervalMultiplier, + GetPosition(), + GetRotation(), + GetScale()); + } + + // add a small timeline offset to account for decoupled arrival of + // NetworkTime and NetworkTransform snapshots. + // needs to be sendInterval. half sendInterval doesn't solve it. + // https://github.com/MirrorNetworking/Mirror/issues/3427 + // remove this after LocalWorldState. + AddSnapshot(clientSnapshots, NetworkClient.connection.remoteTimeStamp + timeStampAdjustment + offset, position, rotation, scale); + } + + // only sync on change ///////////////////////////////////////////////// + // snap interp. needs a continous flow of packets. + // 'only sync on change' interrupts it while not changed. + // once it restarts, snap interp. will interp from the last old position. + // this will cause very noticeable stutter for the first move each time. + // the fix is quite simple. + + // 1. detect if the remaining snapshot is too old from a past move. + static bool NeedsCorrection( + SortedList snapshots, + double remoteTimestamp, + double bufferTime, + double toleranceMultiplier) => + snapshots.Count == 1 && + remoteTimestamp - snapshots.Keys[0] >= bufferTime * toleranceMultiplier; + + // 2. insert a fake snapshot at current position, + // exactly one 'sendInterval' behind the newly received one. + static void RewriteHistory( + SortedList snapshots, + // timestamp of packet arrival, not interpolated remote time! + double remoteTimeStamp, + double localTime, + double sendInterval, + Vector3 position, + Quaternion rotation, + Vector3 scale) + { + // clear the previous snapshot + snapshots.Clear(); + + // insert a fake one at where we used to be, + // 'sendInterval' behind the new one. + SnapshotInterpolation.InsertIfNotExists( + snapshots, + NetworkClient.snapshotSettings.bufferLimit, + new TransformSnapshot( + remoteTimeStamp - sendInterval, // arrival remote timestamp. NOT remote time. + localTime - sendInterval, // Unity 2019 doesn't have timeAsDouble yet + position, + rotation, + scale + ) + ); + } + + public override void Reset() + { + base.Reset(); + + // reset delta + lastSerializedPosition = Vector3Long.zero; + lastDeserializedPosition = Vector3Long.zero; + + lastSerializedScale = Vector3Long.zero; + lastDeserializedScale = Vector3Long.zero; + + // reset 'last' for delta too + last = new TransformSnapshot(0, 0, Vector3.zero, Quaternion.identity, Vector3.zero); + } + } +} diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs.meta b/Assets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs.meta new file mode 100644 index 0000000..ece9c7d --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransformReliable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8ff3ba0becae47b8b9381191598957c8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs b/Assets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs new file mode 100644 index 0000000..29c0369 --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs @@ -0,0 +1,382 @@ +// NetworkTransform V2 by mischa (2021-07) +// comment out the below line to quickly revert the onlySyncOnChange feature +#define onlySyncOnChange_BANDWIDTH_SAVING +using UnityEngine; + +namespace Mirror +{ + [AddComponentMenu("Network/Network Transform (Unreliable)")] + public class NetworkTransformUnreliable : NetworkTransformBase + { + // only sync when changed hack ///////////////////////////////////////// +#if onlySyncOnChange_BANDWIDTH_SAVING + [Header("Sync Only If Changed")] + [Tooltip("When true, changes are not sent unless greater than sensitivity values below.")] + public bool onlySyncOnChange = true; + + uint sendIntervalCounter = 0; + double lastSendIntervalTime = double.MinValue; + + // Testing under really bad network conditions, 2%-5% packet loss and 250-1200ms ping, 5 proved to eliminate any twitching, however this should not be the default as it is a rare case Developers may want to cover. + [Tooltip("How much time, as a multiple of send interval, has passed before clearing buffers.\nA larger buffer means more delay, but results in smoother movement.\nExample: 1 for faster responses minimal smoothing, 5 covers bad pings but has noticable delay, 3 is recommended for balanced results,.")] + public float bufferResetMultiplier = 3; + + [Header("Sensitivity"), Tooltip("Sensitivity of changes needed before an updated state is sent over the network")] + public float positionSensitivity = 0.01f; + public float rotationSensitivity = 0.01f; + public float scaleSensitivity = 0.01f; + + protected bool positionChanged; + protected bool rotationChanged; + protected bool scaleChanged; + + // Used to store last sent snapshots + protected TransformSnapshot lastSnapshot; + protected bool cachedSnapshotComparison; + protected bool hasSentUnchangedPosition; +#endif + + // update ////////////////////////////////////////////////////////////// + // Update applies interpolation + void Update() + { + if (isServer) UpdateServerInterpolation(); + // for all other clients (and for local player if !authority), + // we need to apply snapshots from the buffer. + // 'else if' because host mode shouldn't interpolate client + else if (isClient && !IsClientWithAuthority) UpdateClientInterpolation(); + } + + // LateUpdate broadcasts. + // movement scripts may change positions in Update. + // use LateUpdate to ensure changes are detected in the same frame. + // otherwise this may run before user update, delaying detection until next frame. + // this could cause visible jitter. + void LateUpdate() + { + // if server then always sync to others. + if (isServer) UpdateServerBroadcast(); + // client authority, and local player (= allowed to move myself)? + // 'else if' because host mode shouldn't send anything to server. + // it is the server. don't overwrite anything there. + else if (isClient && IsClientWithAuthority) UpdateClientBroadcast(); + } + + protected virtual void CheckLastSendTime() + { + // We check interval every frame, and then send if interval is reached. + // So by the time sendIntervalCounter == sendIntervalMultiplier, data is sent, + // thus we reset the counter here. + // This fixes previous issue of, if sendIntervalMultiplier = 1, we send every frame, + // because intervalCounter is always = 1 in the previous version. + + if (sendIntervalCounter == sendIntervalMultiplier) + sendIntervalCounter = 0; + + // timeAsDouble not available in older Unity versions. + if (AccurateInterval.Elapsed(NetworkTime.localTime, NetworkServer.sendInterval, ref lastSendIntervalTime)) + sendIntervalCounter++; + } + + void UpdateServerBroadcast() + { + // broadcast to all clients each 'sendInterval' + // (client with authority will drop the rpc) + // NetworkTime.localTime for double precision until Unity has it too + // + // IMPORTANT: + // snapshot interpolation requires constant sending. + // DO NOT only send if position changed. for example: + // --- + // * client sends first position at t=0 + // * ... 10s later ... + // * client moves again, sends second position at t=10 + // --- + // * server gets first position at t=0 + // * server gets second position at t=10 + // * server moves from first to second within a time of 10s + // => would be a super slow move, instead of a wait & move. + // + // IMPORTANT: + // DO NOT send nulls if not changed 'since last send' either. we + // send unreliable and don't know which 'last send' the other end + // received successfully. + // + // Checks to ensure server only sends snapshots if object is + // on server authority(!clientAuthority) mode because on client + // authority mode snapshots are broadcasted right after the authoritative + // client updates server in the command function(see above), OR, + // since host does not send anything to update the server, any client + // authoritative movement done by the host will have to be broadcasted + // here by checking IsClientWithAuthority. + // TODO send same time that NetworkServer sends time snapshot? + CheckLastSendTime(); + + if (sendIntervalCounter == sendIntervalMultiplier && // same interval as time interpolation! + (syncDirection == SyncDirection.ServerToClient || IsClientWithAuthority)) + { + // send snapshot without timestamp. + // receiver gets it from batch timestamp to save bandwidth. + TransformSnapshot snapshot = Construct(); +#if onlySyncOnChange_BANDWIDTH_SAVING + cachedSnapshotComparison = CompareSnapshots(snapshot); + if (cachedSnapshotComparison && hasSentUnchangedPosition && onlySyncOnChange) { return; } +#endif + +#if onlySyncOnChange_BANDWIDTH_SAVING + RpcServerToClientSync( + // only sync what the user wants to sync + syncPosition && positionChanged ? snapshot.position : default(Vector3?), + syncRotation && rotationChanged ? snapshot.rotation : default(Quaternion?), + syncScale && scaleChanged ? snapshot.scale : default(Vector3?) + ); +#else + RpcServerToClientSync( + // only sync what the user wants to sync + syncPosition ? snapshot.position : default(Vector3?), + syncRotation ? snapshot.rotation : default(Quaternion?), + syncScale ? snapshot.scale : default(Vector3?) + ); +#endif + +#if onlySyncOnChange_BANDWIDTH_SAVING + if (cachedSnapshotComparison) + { + hasSentUnchangedPosition = true; + } + else + { + hasSentUnchangedPosition = false; + lastSnapshot = snapshot; + } +#endif + } + } + + void UpdateServerInterpolation() + { + // apply buffered snapshots IF client authority + // -> in server authority, server moves the object + // so no need to apply any snapshots there. + // -> don't apply for host mode player objects either, even if in + // client authority mode. if it doesn't go over the network, + // then we don't need to do anything. + // -> connectionToClient is briefly null after scene changes: + // https://github.com/MirrorNetworking/Mirror/issues/3329 + if (syncDirection == SyncDirection.ClientToServer && + connectionToClient != null && + !isOwned) + { + if (serverSnapshots.Count == 0) return; + + // step the transform interpolation without touching time. + // NetworkClient is responsible for time globally. + SnapshotInterpolation.StepInterpolation( + serverSnapshots, + connectionToClient.remoteTimeline, + out TransformSnapshot from, + out TransformSnapshot to, + out double t); + + // interpolate & apply + TransformSnapshot computed = TransformSnapshot.Interpolate(from, to, t); + Apply(computed, to); + } + } + + void UpdateClientBroadcast() + { + // https://github.com/vis2k/Mirror/pull/2992/ + if (!NetworkClient.ready) return; + + // send to server each 'sendInterval' + // NetworkTime.localTime for double precision until Unity has it too + // + // IMPORTANT: + // snapshot interpolation requires constant sending. + // DO NOT only send if position changed. for example: + // --- + // * client sends first position at t=0 + // * ... 10s later ... + // * client moves again, sends second position at t=10 + // --- + // * server gets first position at t=0 + // * server gets second position at t=10 + // * server moves from first to second within a time of 10s + // => would be a super slow move, instead of a wait & move. + // + // IMPORTANT: + // DO NOT send nulls if not changed 'since last send' either. we + // send unreliable and don't know which 'last send' the other end + // received successfully. + CheckLastSendTime(); + if (sendIntervalCounter == sendIntervalMultiplier) // same interval as time interpolation! + { + // send snapshot without timestamp. + // receiver gets it from batch timestamp to save bandwidth. + TransformSnapshot snapshot = Construct(); +#if onlySyncOnChange_BANDWIDTH_SAVING + cachedSnapshotComparison = CompareSnapshots(snapshot); + if (cachedSnapshotComparison && hasSentUnchangedPosition && onlySyncOnChange) { return; } +#endif + +#if onlySyncOnChange_BANDWIDTH_SAVING + CmdClientToServerSync( + // only sync what the user wants to sync + syncPosition && positionChanged ? snapshot.position : default(Vector3?), + syncRotation && rotationChanged ? snapshot.rotation : default(Quaternion?), + syncScale && scaleChanged ? snapshot.scale : default(Vector3?) + ); +#else + CmdClientToServerSync( + // only sync what the user wants to sync + syncPosition ? snapshot.position : default(Vector3?), + syncRotation ? snapshot.rotation : default(Quaternion?), + syncScale ? snapshot.scale : default(Vector3?) + ); +#endif + +#if onlySyncOnChange_BANDWIDTH_SAVING + if (cachedSnapshotComparison) + { + hasSentUnchangedPosition = true; + } + else + { + hasSentUnchangedPosition = false; + lastSnapshot = snapshot; + } +#endif + } + } + + void UpdateClientInterpolation() + { + // only while we have snapshots + if (clientSnapshots.Count == 0) return; + + // step the interpolation without touching time. + // NetworkClient is responsible for time globally. + SnapshotInterpolation.StepInterpolation( + clientSnapshots, + NetworkTime.time, // == NetworkClient.localTimeline from snapshot interpolation + out TransformSnapshot from, + out TransformSnapshot to, + out double t); + + // interpolate & apply + TransformSnapshot computed = TransformSnapshot.Interpolate(from, to, t); + Apply(computed, to); + } + + public override void OnSerialize(NetworkWriter writer, bool initialState) + { + // sync target component's position on spawn. + // fixes https://github.com/vis2k/Mirror/pull/3051/ + // (Spawn message wouldn't sync NTChild positions either) + if (initialState) + { + if (syncPosition) writer.WriteVector3(GetPosition()); + if (syncRotation) writer.WriteQuaternion(GetRotation()); + if (syncScale) writer.WriteVector3(GetScale()); + } + } + + public override void OnDeserialize(NetworkReader reader, bool initialState) + { + // sync target component's position on spawn. + // fixes https://github.com/vis2k/Mirror/pull/3051/ + // (Spawn message wouldn't sync NTChild positions either) + if (initialState) + { + if (syncPosition) SetPosition(reader.ReadVector3()); + if (syncRotation) SetRotation(reader.ReadQuaternion()); + if (syncScale) SetScale(reader.ReadVector3()); + } + } + +#if onlySyncOnChange_BANDWIDTH_SAVING + // Returns true if position, rotation AND scale are unchanged, within given sensitivity range. + protected virtual bool CompareSnapshots(TransformSnapshot currentSnapshot) + { + positionChanged = Vector3.SqrMagnitude(lastSnapshot.position - currentSnapshot.position) > positionSensitivity * positionSensitivity; + rotationChanged = Quaternion.Angle(lastSnapshot.rotation, currentSnapshot.rotation) > rotationSensitivity; + scaleChanged = Vector3.SqrMagnitude(lastSnapshot.scale - currentSnapshot.scale) > scaleSensitivity * scaleSensitivity; + + return (!positionChanged && !rotationChanged && !scaleChanged); + } +#endif + // cmd ///////////////////////////////////////////////////////////////// + // only unreliable. see comment above of this file. + [Command(channel = Channels.Unreliable)] + void CmdClientToServerSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + OnClientToServerSync(position, rotation, scale); + //For client authority, immediately pass on the client snapshot to all other + //clients instead of waiting for server to send its snapshots. + if (syncDirection == SyncDirection.ClientToServer) + RpcServerToClientSync(position, rotation, scale); + } + + // local authority client sends sync message to server for broadcasting + protected virtual void OnClientToServerSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + // only apply if in client authority mode + if (syncDirection != SyncDirection.ClientToServer) return; + + // protect against ever growing buffer size attacks + if (serverSnapshots.Count >= connectionToClient.snapshotBufferSizeLimit) return; + + // only player owned objects (with a connection) can send to + // server. we can get the timestamp from the connection. + double timestamp = connectionToClient.remoteTimeStamp; +#if onlySyncOnChange_BANDWIDTH_SAVING + if (onlySyncOnChange) + { + double timeIntervalCheck = bufferResetMultiplier * sendIntervalMultiplier * NetworkClient.sendInterval; + + if (serverSnapshots.Count > 0 && serverSnapshots.Values[serverSnapshots.Count - 1].remoteTime + timeIntervalCheck < timestamp) + Reset(); + } +#endif + AddSnapshot(serverSnapshots, connectionToClient.remoteTimeStamp + timeStampAdjustment + offset, position, rotation, scale); + } + + // rpc ///////////////////////////////////////////////////////////////// + // only unreliable. see comment above of this file. + [ClientRpc(channel = Channels.Unreliable)] + void RpcServerToClientSync(Vector3? position, Quaternion? rotation, Vector3? scale) => + OnServerToClientSync(position, rotation, scale); + + // server broadcasts sync message to all clients + protected virtual void OnServerToClientSync(Vector3? position, Quaternion? rotation, Vector3? scale) + { + // in host mode, the server sends rpcs to all clients. + // the host client itself will receive them too. + // -> host server is always the source of truth + // -> we can ignore any rpc on the host client + // => otherwise host objects would have ever growing clientBuffers + // (rpc goes to clients. if isServer is true too then we are host) + if (isServer) return; + + // don't apply for local player with authority + if (IsClientWithAuthority) return; + + // on the client, we receive rpcs for all entities. + // not all of them have a connectionToServer. + // but all of them go through NetworkClient.connection. + // we can get the timestamp from there. + double timestamp = NetworkClient.connection.remoteTimeStamp; +#if onlySyncOnChange_BANDWIDTH_SAVING + if (onlySyncOnChange) + { + double timeIntervalCheck = bufferResetMultiplier * sendIntervalMultiplier * NetworkServer.sendInterval; + + if (clientSnapshots.Count > 0 && clientSnapshots.Values[clientSnapshots.Count - 1].remoteTime + timeIntervalCheck < timestamp) + Reset(); + } +#endif + AddSnapshot(clientSnapshots, NetworkClient.connection.remoteTimeStamp + timeStampAdjustment + offset, position, rotation, scale); + } + } +} diff --git a/Assets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs.meta b/Assets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs.meta new file mode 100644 index 0000000..3a4a75a --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/NetworkTransformUnreliable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a553cb17010b2403e8523b558bffbc14 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/NetworkTransform/TransformSnapshot.cs b/Assets/Mirror/Components/NetworkTransform/TransformSnapshot.cs new file mode 100644 index 0000000..912b10d --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/TransformSnapshot.cs @@ -0,0 +1,65 @@ +// snapshot for snapshot interpolation +// https://gafferongames.com/post/snapshot_interpolation/ +// position, rotation, scale for compatibility for now. +using UnityEngine; + +namespace Mirror +{ + // NetworkTransform Snapshot + public struct TransformSnapshot : Snapshot + { + // time or sequence are needed to throw away older snapshots. + // + // glenn fiedler starts with a 16 bit sequence number. + // supposedly this is meant as a simplified example. + // in the end we need the remote timestamp for accurate interpolation + // and buffering over time. + // + // note: in theory, IF server sends exactly(!) at the same interval then + // the 16 bit ushort timestamp would be enough to calculate the + // remote time (sequence * sendInterval). but Unity's update is + // not guaranteed to run on the exact intervals / do catchup. + // => remote timestamp is better for now + // + // [REMOTE TIME, NOT LOCAL TIME] + // => DOUBLE for long term accuracy & batching gives us double anyway + public double remoteTime { get; set; } + + // the local timestamp (when we received it) + // used to know if the first two snapshots are old enough to start. + public double localTime { get; set; } + + public Vector3 position; + public Quaternion rotation; + public Vector3 scale; + + public TransformSnapshot(double remoteTime, double localTime, Vector3 position, Quaternion rotation, Vector3 scale) + { + this.remoteTime = remoteTime; + this.localTime = localTime; + this.position = position; + this.rotation = rotation; + this.scale = scale; + } + + public static TransformSnapshot Interpolate(TransformSnapshot from, TransformSnapshot to, double t) + { + // NOTE: + // Vector3 & Quaternion components are float anyway, so we can + // keep using the functions with 't' as float instead of double. + return new TransformSnapshot( + // interpolated snapshot is applied directly. don't need timestamps. + 0, 0, + // lerp position/rotation/scale unclamped in case we ever need + // to extrapolate. atm SnapshotInterpolation never does. + Vector3.LerpUnclamped(from.position, to.position, (float)t), + // IMPORTANT: LerpUnclamped(0, 60, 1.5) extrapolates to ~86. + // SlerpUnclamped(0, 60, 1.5) extrapolates to 90! + // (0, 90, 1.5) is even worse. for Lerp. + // => Slerp works way better for our euler angles. + Quaternion.SlerpUnclamped(from.rotation, to.rotation, (float)t), + Vector3.LerpUnclamped(from.scale, to.scale, (float)t) + ); + } + } +} diff --git a/Assets/Mirror/Components/NetworkTransform/TransformSnapshot.cs.meta b/Assets/Mirror/Components/NetworkTransform/TransformSnapshot.cs.meta new file mode 100644 index 0000000..f43458f --- /dev/null +++ b/Assets/Mirror/Components/NetworkTransform/TransformSnapshot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d3dae77b43dc4e1dbb2012924b2da79c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Components/RemoteStatistics.cs b/Assets/Mirror/Components/RemoteStatistics.cs new file mode 100644 index 0000000..aa18815 --- /dev/null +++ b/Assets/Mirror/Components/RemoteStatistics.cs @@ -0,0 +1,441 @@ +// remote statistics panel from Mirror II to show connections, load, etc. +// server syncs statistics to clients if authenticated. +// +// attach this to a player. +// requires NetworkStatistics component on the Network object. +// +// Unity's OnGUI is the easiest to use solution at the moment. +// * playfab is super complex to set up +// * http servers would be nice, but still need to open ports, live refresh, etc +// +// for safety reasons, let's keep this read-only. +// at least until there's safe authentication. +using System; +using System.IO; +using UnityEngine; + +namespace Mirror +{ + // server -> client + struct Stats + { + // general + public int connections; + public double uptime; + public int configuredTickRate; + public int actualTickRate; + + // traffic + public long sentBytesPerSecond; + public long receiveBytesPerSecond; + + // cpu + public float serverTickInterval; + public double fullUpdateAvg; + public double serverEarlyAvg; + public double serverLateAvg; + public double transportEarlyAvg; + public double transportLateAvg; + + // C# boilerplate + public Stats( + // general + int connections, + double uptime, + int configuredTickRate, + int actualTickRate, + // traffic + long sentBytesPerSecond, + long receiveBytesPerSecond, + // cpu + float serverTickInterval, + double fullUpdateAvg, + double serverEarlyAvg, + double serverLateAvg, + double transportEarlyAvg, + double transportLateAvg + ) + { + // general + this.connections = connections; + this.uptime = uptime; + this.configuredTickRate = configuredTickRate; + this.actualTickRate = actualTickRate; + + // traffic + this.sentBytesPerSecond = sentBytesPerSecond; + this.receiveBytesPerSecond = receiveBytesPerSecond; + + // cpu + this.serverTickInterval = serverTickInterval; + this.fullUpdateAvg = fullUpdateAvg; + this.serverEarlyAvg = serverEarlyAvg; + this.serverLateAvg = serverLateAvg; + this.transportEarlyAvg = transportEarlyAvg; + this.transportLateAvg = transportLateAvg; + } + } + + // [RequireComponent(typeof(NetworkStatistics))] <- needs to be on Network GO, not on NI + public class RemoteStatistics : NetworkBehaviour + { + // components ("fake statics" for similar API) + protected NetworkStatistics NetworkStatistics; + + // broadcast to client. + // stats are quite huge, let's only send every few seconds via TargetRpc. + // instead of sending multiple times per second via NB.OnSerialize. + [Tooltip("Send stats every 'interval' seconds to client.")] + public float sendInterval = 1; + double lastSendTime; + + [Header("GUI")] + public bool showGui; + public KeyCode hotKey = KeyCode.F11; + Rect windowRect = new Rect(0, 0, 400, 400); + + // password can't be stored in code or in Unity project. + // it would be available in clients otherwise. + // this is not perfectly secure. that's why RemoteStatistics is read-only. + [Header("Authentication")] + public string passwordFile = "remote_statistics.txt"; + protected bool serverAuthenticated; // client needs to authenticate + protected bool clientAuthenticated; // show GUI until authenticated + protected string serverPassword = null; // null means not found, auth impossible + protected string clientPassword = ""; // for GUI + + // statistics synced to client + Stats stats; + + void LoadPassword() + { + // TODO only load once, not for all players? + // let's avoid static state for now. + + // load the password + string path = Path.GetFullPath(passwordFile); + if (File.Exists(path)) + { + // don't spam the server logs for every player's loaded file + // Debug.Log($"RemoteStatistics: loading password file: {path}"); + try + { + serverPassword = File.ReadAllText(path); + } + catch (Exception exception) + { + Debug.LogWarning($"RemoteStatistics: failed to read password file: {exception}"); + } + } + else + { + Debug.LogWarning($"RemoteStatistics: password file has not been created. Authentication will be impossible. Please save the password in: {path}"); + } + } + + protected override void OnValidate() + { + base.OnValidate(); + syncMode = SyncMode.Owner; + } + + // make sure to call base function when overwriting! + // public so it can also be called from tests (and be overwritten by users) + public override void OnStartServer() + { + NetworkStatistics = NetworkManager.singleton.GetComponent(); + if (NetworkStatistics == null) throw new Exception($"RemoteStatistics requires a NetworkStatistics component on {NetworkManager.singleton.name}!"); + + // server needs to load the password + LoadPassword(); + } + + public override void OnStartLocalPlayer() + { + // center the window initially + windowRect.x = Screen.width / 2 - windowRect.width / 2; + windowRect.y = Screen.height / 2 - windowRect.height / 2; + } + + [TargetRpc] + void TargetRpcSync(Stats v) + { + // store stats and flag as authenticated + clientAuthenticated = true; + stats = v; + } + + [Command] + public void CmdAuthenticate(string v) + { + // was a valid password loaded on the server, + // and did the client send the correct one? + if (!string.IsNullOrWhiteSpace(serverPassword) && + serverPassword.Equals(v)) + { + serverAuthenticated = true; + Debug.Log($"RemoteStatistics: connectionId {connectionToClient.connectionId} authenticated with player {name}"); + } + } + + void UpdateServer() + { + // only sync if client has authenticated on the server + if (!serverAuthenticated) return; + + // NetworkTime.localTime has defines for 2019 / 2020 compatibility + if (NetworkTime.localTime >= lastSendTime + sendInterval) + { + lastSendTime = NetworkTime.localTime; + + // target rpc to owner client + TargetRpcSync(new Stats( + // general + NetworkServer.connections.Count, + NetworkTime.time, + NetworkServer.tickRate, + NetworkServer.actualTickRate, + + // traffic + NetworkStatistics.serverSentBytesPerSecond, + NetworkStatistics.serverReceivedBytesPerSecond, + + // cpu + NetworkServer.tickInterval, + NetworkServer.fullUpdateDuration.average, + NetworkServer.earlyUpdateDuration.average, + NetworkServer.lateUpdateDuration.average, + 0, // TODO ServerTransport.earlyUpdateDuration.average, + 0 // TODO ServerTransport.lateUpdateDuration.average + )); + } + } + + void UpdateClient() + { + if (Input.GetKeyDown(hotKey)) + showGui = !showGui; + } + + void Update() + { + if (isServer) UpdateServer(); + if (isLocalPlayer) UpdateClient(); + } + + void OnGUI() + { + if (!isLocalPlayer) return; + if (!showGui) return; + + windowRect = GUILayout.Window(0, windowRect, OnWindow, "Remote Statistics"); + windowRect = Utils.KeepInScreen(windowRect); + } + + // Text: value + void GUILayout_TextAndValue(string text, string value) + { + GUILayout.BeginHorizontal(); + GUILayout.Label(text); + GUILayout.FlexibleSpace(); + GUILayout.Label(value); + GUILayout.EndHorizontal(); + } + + // fake a progress bar via horizontal scroll bar with ratio as width + void GUILayout_ProgressBar(double ratio, int width) + { + // clamp ratio, otherwise >1 would make it extremely large + ratio = Mathd.Clamp01(ratio); + GUILayout.HorizontalScrollbar(0, (float)ratio, 0, 1, GUILayout.Width(width)); + } + + // need to specify progress bar & caption width, + // otherwise differently sized captions would always misalign the + // progress bars. + void GUILayout_TextAndProgressBar(string text, double ratio, int progressbarWidth, string caption, int captionWidth, Color captionColor) + { + GUILayout.BeginHorizontal(); + GUILayout.Label(text); + GUILayout.FlexibleSpace(); + GUILayout_ProgressBar(ratio, progressbarWidth); + + // coloring the caption is enough. otherwise it's too much. + GUI.color = captionColor; + GUILayout.Label(caption, GUILayout.Width(captionWidth)); + GUI.color = Color.white; + + GUILayout.EndHorizontal(); + } + + void GUI_Authenticate() + { + GUILayout.BeginVertical("Box"); // start general + GUILayout.Label("Authentication"); + + // warning if insecure connection + // if (ClientTransport.IsEncrypted()) + // { + // GUILayout.Label("Connection is encrypted!"); + // } + // else + // { + GUILayout.Label("Connection is not encrypted. Use with care!"); + // } + + // input + clientPassword = GUILayout.PasswordField(clientPassword, '*'); + + // button + GUI.enabled = !string.IsNullOrWhiteSpace(clientPassword); + if (GUILayout.Button("Authenticate")) + { + CmdAuthenticate(clientPassword); + } + GUI.enabled = true; + + GUILayout.EndVertical(); // end general + } + + void GUI_General( + int connections, + double uptime, + int configuredTickRate, + int actualTickRate) + { + GUILayout.BeginVertical("Box"); // start general + GUILayout.Label("General"); + + // connections + GUILayout_TextAndValue("Connections:", $"{connections}"); + + // uptime + GUILayout_TextAndValue("Uptime:", $"{Utils.PrettySeconds(uptime)}"); // TODO + + // tick rate + // might be lower under heavy load. + // might be higher in editor if targetFrameRate can't be set. + GUI.color = actualTickRate < configuredTickRate ? Color.red : Color.green; + GUILayout_TextAndValue("Tick Rate:", $"{actualTickRate} Hz / {configuredTickRate} Hz"); + GUI.color = Color.white; + + GUILayout.EndVertical(); // end general + } + + void GUI_Traffic( + long serverSentBytesPerSecond, + long serverReceivedBytesPerSecond) + { + GUILayout.BeginVertical("Box"); + GUILayout.Label("Network"); + + GUILayout_TextAndValue("Outgoing:", $"{Utils.PrettyBytes(serverSentBytesPerSecond) }/s"); + GUILayout_TextAndValue("Incoming:", $"{Utils.PrettyBytes(serverReceivedBytesPerSecond)}/s"); + + GUILayout.EndVertical(); + } + + void GUI_Cpu( + float serverTickInterval, + double fullUpdateAvg, + double serverEarlyAvg, + double serverLateAvg, + double transportEarlyAvg, + double transportLateAvg) + { + const int barWidth = 120; + const int captionWidth = 90; + + GUILayout.BeginVertical("Box"); + GUILayout.Label("CPU"); + + // unity update + // happens every 'tickInterval'. progress bar shows it in relation. + // <= 90% load is green, otherwise red + double fullRatio = fullUpdateAvg / serverTickInterval; + GUILayout_TextAndProgressBar( + "World Update Avg:", + fullRatio, + barWidth, $"{fullUpdateAvg * 1000:F1} ms", + captionWidth, + fullRatio <= 0.9 ? Color.green : Color.red); + + // server update + // happens every 'tickInterval'. progress bar shows it in relation. + // <= 90% load is green, otherwise red + double serverRatio = (serverEarlyAvg + serverLateAvg) / serverTickInterval; + GUILayout_TextAndProgressBar( + "Server Update Avg:", + serverRatio, + barWidth, $"{serverEarlyAvg * 1000:F1} + {serverLateAvg * 1000:F1} ms", + captionWidth, + serverRatio <= 0.9 ? Color.green : Color.red); + + // transport: early + late update milliseconds. + // for threaded transport, this is the thread's update time. + // happens every 'tickInterval'. progress bar shows it in relation. + // <= 90% load is green, otherwise red + // double transportRatio = (transportEarlyAvg + transportLateAvg) / serverTickInterval; + // GUILayout_TextAndProgressBar( + // "Transport Avg:", + // transportRatio, + // barWidth, + // $"{transportEarlyAvg * 1000:F1} + {transportLateAvg * 1000:F1} ms", + // captionWidth, + // transportRatio <= 0.9 ? Color.green : Color.red); + + GUILayout.EndVertical(); + } + + void GUI_Notice() + { + // for security reasons, let's keep this read-only for now. + + // single line keeps input & visuals simple + // GUILayout.BeginVertical("Box"); + // GUILayout.Label("Global Notice"); + // notice = GUILayout.TextField(notice); + // if (GUILayout.Button("Send")) + // { + // // TODO + // } + // GUILayout.EndVertical(); + } + + void OnWindow(int windowID) + { + if (!clientAuthenticated) + { + GUI_Authenticate(); + } + else + { + GUI_General( + stats.connections, + stats.uptime, + stats.configuredTickRate, + stats.actualTickRate + ); + + GUI_Traffic( + stats.sentBytesPerSecond, + stats.receiveBytesPerSecond + ); + + GUI_Cpu( + stats.serverTickInterval, + stats.fullUpdateAvg, + stats.serverEarlyAvg, + stats.serverLateAvg, + stats.transportEarlyAvg, + stats.transportLateAvg + ); + + GUI_Notice(); + } + + // dragable window in any case + GUI.DragWindow(new Rect(0, 0, 10000, 10000)); + } + } +} diff --git a/Assets/Mirror/Components/RemoteStatistics.cs.meta b/Assets/Mirror/Components/RemoteStatistics.cs.meta new file mode 100644 index 0000000..4c4d043 --- /dev/null +++ b/Assets/Mirror/Components/RemoteStatistics.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ba360e4ff6b44fc6898f56322b90c6c8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core.meta b/Assets/Mirror/Core.meta new file mode 100644 index 0000000..85ee3eb --- /dev/null +++ b/Assets/Mirror/Core.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9f4328ccc5f724e45afe2215d275b5d5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/AssemblyInfo.cs b/Assets/Mirror/Core/AssemblyInfo.cs new file mode 100644 index 0000000..f342716 --- /dev/null +++ b/Assets/Mirror/Core/AssemblyInfo.cs @@ -0,0 +1,12 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Mirror.Tests.Common")] +[assembly: InternalsVisibleTo("Mirror.Tests")] +// need to use Unity.*.CodeGen assembly name to import Unity.CompilationPipeline +// for ILPostProcessor tests. +[assembly: InternalsVisibleTo("Unity.Mirror.Tests.CodeGen")] +[assembly: InternalsVisibleTo("Mirror.Tests.Generated")] +[assembly: InternalsVisibleTo("Mirror.Tests.Runtime")] +[assembly: InternalsVisibleTo("Mirror.Tests.Performance.Editor")] +[assembly: InternalsVisibleTo("Mirror.Tests.Performance.Runtime")] +[assembly: InternalsVisibleTo("Mirror.Editor")] diff --git a/Assets/Mirror/Core/AssemblyInfo.cs.meta b/Assets/Mirror/Core/AssemblyInfo.cs.meta new file mode 100644 index 0000000..50cc028 --- /dev/null +++ b/Assets/Mirror/Core/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e28d5f410e25b42e6a76a2ffc10e4675 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Attributes.cs b/Assets/Mirror/Core/Attributes.cs new file mode 100644 index 0000000..39b06fd --- /dev/null +++ b/Assets/Mirror/Core/Attributes.cs @@ -0,0 +1,85 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + /// + /// SyncVars are used to synchronize a variable from the server to all clients automatically. + /// Value must be changed on server, not directly by clients. Hook parameter allows you to define a client-side method to be invoked when the client gets an update from the server. + /// + [AttributeUsage(AttributeTargets.Field)] + public class SyncVarAttribute : PropertyAttribute + { + public string hook; + } + + /// + /// Call this from a client to run this function on the server. + /// Make sure to validate input etc. It's not possible to call this from a server. + /// + [AttributeUsage(AttributeTargets.Method)] + public class CommandAttribute : Attribute + { + public int channel = Channels.Reliable; + public bool requiresAuthority = true; + } + + /// + /// The server uses a Remote Procedure Call (RPC) to run this function on clients. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ClientRpcAttribute : Attribute + { + public int channel = Channels.Reliable; + public bool includeOwner = true; + } + + /// + /// The server uses a Remote Procedure Call (RPC) to run this function on a specific client. + /// + [AttributeUsage(AttributeTargets.Method)] + public class TargetRpcAttribute : Attribute + { + public int channel = Channels.Reliable; + } + + /// + /// Prevents clients from running this method. + /// Prints a warning if a client tries to execute this method. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ServerAttribute : Attribute {} + + /// + /// Prevents clients from running this method. + /// No warning is thrown. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ServerCallbackAttribute : Attribute {} + + /// + /// Prevents the server from running this method. + /// Prints a warning if the server tries to execute this method. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ClientAttribute : Attribute {} + + /// + /// Prevents the server from running this method. + /// No warning is printed. + /// + [AttributeUsage(AttributeTargets.Method)] + public class ClientCallbackAttribute : Attribute {} + + /// + /// Converts a string property into a Scene property in the inspector + /// + public class SceneAttribute : PropertyAttribute {} + + /// + /// Used to show private SyncList in the inspector, + /// Use instead of SerializeField for non Serializable types + /// + [AttributeUsage(AttributeTargets.Field)] + public class ShowInInspectorAttribute : Attribute {} +} diff --git a/Assets/Mirror/Core/Attributes.cs.meta b/Assets/Mirror/Core/Attributes.cs.meta new file mode 100644 index 0000000..c50a489 --- /dev/null +++ b/Assets/Mirror/Core/Attributes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c04c722ee2ffd49c8a56ab33667b10b0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Batching.meta b/Assets/Mirror/Core/Batching.meta new file mode 100644 index 0000000..bf23600 --- /dev/null +++ b/Assets/Mirror/Core/Batching.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1c38e1bebe9947f8b842a8a57aa2b71c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Batching/Batcher.cs b/Assets/Mirror/Core/Batching/Batcher.cs new file mode 100644 index 0000000..5e30f08 --- /dev/null +++ b/Assets/Mirror/Core/Batching/Batcher.cs @@ -0,0 +1,150 @@ +// batching functionality encapsulated into one class. +// -> less complexity +// -> easy to test +// +// IMPORTANT: we use THRESHOLD batching, not MAXED SIZE batching. +// see threshold comments below. +// +// includes timestamp for tick batching. +// -> allows NetworkTransform etc. to use timestamp without including it in +// every single message +using System; +using System.Collections.Generic; + +namespace Mirror +{ + public class Batcher + { + // batching threshold instead of max size. + // -> small messages are fit into threshold sized batches + // -> messages larger than threshold are single batches + // + // in other words, we fit up to 'threshold' but still allow larger ones + // for two reasons: + // 1.) data races: skipping batching for larger messages would send a + // large spawn message immediately, while others are batched and + // only flushed at the end of the frame + // 2) timestamp batching: if each batch is expected to contain a + // timestamp, then large messages have to be a batch too. otherwise + // they would not contain a timestamp + readonly int threshold; + + // TimeStamp header size. each batch has one. + public const int TimestampSize = sizeof(double); + + // Message header size. each message has one. + public static int MessageHeaderSize(int messageSize) => + Compression.VarUIntSize((ulong)messageSize); + + // maximum overhead for a single message. + // useful for the outside to calculate max message sizes. + public static int MaxMessageOverhead(int messageSize) => + TimestampSize + MessageHeaderSize(messageSize); + + // full batches ready to be sent. + // DO NOT queue NetworkMessage, it would box. + // DO NOT queue each serialization separately. + // it would allocate too many writers. + // https://github.com/vis2k/Mirror/pull/3127 + // => best to build batches on the fly. + readonly Queue batches = new Queue(); + + // current batch in progress + NetworkWriterPooled batch; + + public Batcher(int threshold) + { + this.threshold = threshold; + } + + // add a message for batching + // we allow any sized messages. + // caller needs to make sure they are within max packet size. + public void AddMessage(ArraySegment message, double timeStamp) + { + // predict the needed size, which is varint(size) + content + int headerSize = Compression.VarUIntSize((ulong)message.Count); + int neededSize = headerSize + message.Count; + + // when appending to a batch in progress, check final size. + // if it expands beyond threshold, then we should finalize it first. + // => less than or exactly threshold is fine. + // GetBatch() will finalize it. + // => see unit tests. + if (batch != null && + batch.Position + neededSize > threshold) + { + batches.Enqueue(batch); + batch = null; + } + + // initialize a new batch if necessary + if (batch == null) + { + // borrow from pool. we return it in GetBatch. + batch = NetworkWriterPool.Get(); + + // write timestamp first. + // -> double precision for accuracy over long periods of time + // -> batches are per-frame, it doesn't matter which message's + // timestamp we use. + batch.WriteDouble(timeStamp); + } + + // add serialization to current batch. even if > threshold. + // -> we do allow > threshold sized messages as single batch + // -> WriteBytes instead of WriteSegment because the latter + // would add a size header. we want to write directly. + // + // include size prefix as varint! + // -> fixes NetworkMessage serialization mismatch corrupting the + // next message in a batch. + // -> a _lot_ of time was wasted debugging corrupt batches. + // no easy way to figure out which NetworkMessage has a mismatch. + // -> this is worth everyone's sanity. + // -> varint means we prefix with 1 byte most of the time. + // -> the same issue in NetworkIdentity was why Mirror started! + Compression.CompressVarUInt(batch, (ulong)message.Count); + batch.WriteBytes(message.Array, message.Offset, message.Count); + } + + // helper function to copy a batch to writer and return it to pool + static void CopyAndReturn(NetworkWriterPooled batch, NetworkWriter writer) + { + // make sure the writer is fresh to avoid uncertain situations + if (writer.Position != 0) + throw new ArgumentException($"GetBatch needs a fresh writer!"); + + // copy to the target writer + ArraySegment segment = batch.ToArraySegment(); + writer.WriteBytes(segment.Array, segment.Offset, segment.Count); + + // return batch to pool for reuse + NetworkWriterPool.Return(batch); + } + + // get the next batch which is available for sending (if any). + // TODO safely get & return a batch instead of copying to writer? + // TODO could return pooled writer & use GetBatch in a 'using' statement! + public bool GetBatch(NetworkWriter writer) + { + // get first batch from queue (if any) + if (batches.TryDequeue(out NetworkWriterPooled first)) + { + CopyAndReturn(first, writer); + return true; + } + + // if queue was empty, we can send the batch in progress. + if (batch != null) + { + CopyAndReturn(batch, writer); + batch = null; + return true; + } + + // nothing was written + return false; + } + } +} diff --git a/Assets/Mirror/Core/Batching/Batcher.cs.meta b/Assets/Mirror/Core/Batching/Batcher.cs.meta new file mode 100644 index 0000000..a774908 --- /dev/null +++ b/Assets/Mirror/Core/Batching/Batcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0afaaa611a2142d48a07bdd03b68b2b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Batching/Unbatcher.cs b/Assets/Mirror/Core/Batching/Unbatcher.cs new file mode 100644 index 0000000..6b2c405 --- /dev/null +++ b/Assets/Mirror/Core/Batching/Unbatcher.cs @@ -0,0 +1,129 @@ +// un-batching functionality encapsulated into one class. +// -> less complexity +// -> easy to test +// +// includes timestamp for tick batching. +// -> allows NetworkTransform etc. to use timestamp without including it in +// every single message +using System; +using System.Collections.Generic; + +namespace Mirror +{ + public class Unbatcher + { + // supporting adding multiple batches before GetNextMessage is called. + // just in case. + readonly Queue batches = new Queue(); + + public int BatchesCount => batches.Count; + + // NetworkReader is only created once, + // then pointed to the first batch. + readonly NetworkReader reader = new NetworkReader(new byte[0]); + + // timestamp that was written into the batch remotely. + // for the batch that our reader is currently pointed at. + double readerRemoteTimeStamp; + + // helper function to start reading a batch. + void StartReadingBatch(NetworkWriterPooled batch) + { + // point reader to it + reader.SetBuffer(batch.ToArraySegment()); + + // read remote timestamp (double) + // -> AddBatch quarantees that we have at least 8 bytes to read + readerRemoteTimeStamp = reader.ReadDouble(); + } + + // add a new batch. + // returns true if valid. + // returns false if not, in which case the connection should be disconnected. + public bool AddBatch(ArraySegment batch) + { + // IMPORTANT: ArraySegment is only valid until returning. we copy it! + // + // NOTE: it's not possible to create empty ArraySegments, so we + // don't need to check against that. + + // make sure we have at least 8 bytes to read for tick timestamp + if (batch.Count < Batcher.TimestampSize) + return false; + + // put into a (pooled) writer + // -> WriteBytes instead of WriteSegment because the latter + // would add a size header. we want to write directly. + // -> will be returned to pool when sending! + NetworkWriterPooled writer = NetworkWriterPool.Get(); + writer.WriteBytes(batch.Array, batch.Offset, batch.Count); + + // first batch? then point reader there + if (batches.Count == 0) + StartReadingBatch(writer); + + // add batch + batches.Enqueue(writer); + //Debug.Log($"Adding Batch {BitConverter.ToString(batch.Array, batch.Offset, batch.Count)} => batches={batches.Count} reader={reader}"); + return true; + } + + // get next message, unpacked from batch (if any) + // message ArraySegment is only valid until the next call. + // timestamp is the REMOTE time when the batch was created remotely. + public bool GetNextMessage(out ArraySegment message, out double remoteTimeStamp) + { + message = default; + remoteTimeStamp = 0; + + // do nothing if we don't have any batches. + // otherwise the below queue.Dequeue() would throw an + // InvalidOperationException if operating on empty queue. + if (batches.Count == 0) + return false; + + // was our reader pointed to anything yet? + if (reader.Capacity == 0) + return false; + + // no more data to read? + if (reader.Remaining == 0) + { + // retire the batch + NetworkWriterPooled writer = batches.Dequeue(); + NetworkWriterPool.Return(writer); + + // do we have another batch? + if (batches.Count > 0) + { + // point reader to the next batch. + // we'll return the reader below. + NetworkWriterPooled next = batches.Peek(); + StartReadingBatch(next); + } + // otherwise there's nothing more to read + else return false; + } + + // use the current batch's remote timestamp + // AFTER potentially moving to the next batch ABOVE! + remoteTimeStamp = readerRemoteTimeStamp; + + // enough data to read the size prefix? + if (reader.Remaining == 0) + return false; + + // read the size prefix as varint + // see Batcher.AddMessage comments for explanation. + int size = (int)Compression.DecompressVarUInt(reader); + + // validate size prefix, in case attackers send malicious data + if (reader.Remaining < size) + return false; + + // return the message of size + message = reader.ReadBytesSegment(size); + return true; + } + } +} diff --git a/Assets/Mirror/Core/Batching/Unbatcher.cs.meta b/Assets/Mirror/Core/Batching/Unbatcher.cs.meta new file mode 100644 index 0000000..26038b0 --- /dev/null +++ b/Assets/Mirror/Core/Batching/Unbatcher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 328562d71e1c45c58581b958845aa7a4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/ConnectionQuality.cs b/Assets/Mirror/Core/ConnectionQuality.cs new file mode 100644 index 0000000..25bd793 --- /dev/null +++ b/Assets/Mirror/Core/ConnectionQuality.cs @@ -0,0 +1,68 @@ +// standalone, Unity-independent connection-quality algorithm & enum. +// don't need to use this directly, it's built into Mirror's NetworkClient. +using UnityEngine; + +namespace Mirror +{ + public enum ConnectionQuality : byte + { + EXCELLENT, // ideal experience for high level competitors + GOOD, // very playable for everyone but high level competitors + FAIR, // very noticeable latency, not very enjoyable anymore + POOR, // unplayable + ESTIMATING, // still estimating + } + + // provide different heuristics for users to choose from. + // simple heuristics to get started. + // this will be iterated on over time based on user feedback. + public static class ConnectionQualityHeuristics + { + // convenience extension to color code Connection Quality + public static Color ColorCode(this ConnectionQuality quality) + { + switch (quality) + { + case ConnectionQuality.EXCELLENT: return Color.green; + case ConnectionQuality.GOOD: return Color.yellow; + case ConnectionQuality.FAIR: return new Color(1.0f, 0.647f, 0.0f); + case ConnectionQuality.POOR: return Color.red; + default: return Color.gray; + } + } + + // straight forward estimation + // rtt: average round trip time in seconds. + // jitter: average latency variance. + public static ConnectionQuality Simple(double rtt, double jitter) + { + if (rtt <= 0.100 && jitter <= 0.10) return ConnectionQuality.EXCELLENT; + if (rtt <= 0.200 && jitter <= 0.20) return ConnectionQuality.GOOD; + if (rtt <= 0.400 && jitter <= 0.50) return ConnectionQuality.FAIR; + return ConnectionQuality.POOR; + } + + // snapshot interpolation based estimation. + // snap. interp. adjusts buffer time based on connection quality. + // based on this, we can measure how far away we are from the ideal. + // the returned quality will always directly correlate with gameplay. + // => requires SnapshotInterpolation dynamicAdjustment to be enabled! + public static ConnectionQuality Pragmatic(double targetBufferTime, double currentBufferTime) + { + // buffer time is set by the game developer. + // estimating in multiples is a great way to be game independent. + // for example, a fast paced shooter and a slow paced RTS will both + // have poor connection if the multiplier is >10. + double multiplier = currentBufferTime / targetBufferTime; + + // empirically measured with Tanks demo + LatencySimulation. + // it's not obvious to estimate on paper. + if (multiplier <= 1.15) return ConnectionQuality.EXCELLENT; + if (multiplier <= 1.25) return ConnectionQuality.GOOD; + if (multiplier <= 1.50) return ConnectionQuality.FAIR; + + // anything else is poor + return ConnectionQuality.POOR; + } + } +} diff --git a/Assets/Mirror/Core/ConnectionQuality.cs.meta b/Assets/Mirror/Core/ConnectionQuality.cs.meta new file mode 100644 index 0000000..1712ffe --- /dev/null +++ b/Assets/Mirror/Core/ConnectionQuality.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ff663b880e33e4606b545c8b497041c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty.meta b/Assets/Mirror/Core/Empty.meta new file mode 100644 index 0000000..e702402 --- /dev/null +++ b/Assets/Mirror/Core/Empty.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a99666a026b14cf6ba1a2b65946b1b27 +timeCreated: 1615288671 \ No newline at end of file diff --git a/Assets/Mirror/Core/Empty/ClientScene.cs b/Assets/Mirror/Core/Empty/ClientScene.cs new file mode 100644 index 0000000..0d1b96e --- /dev/null +++ b/Assets/Mirror/Core/Empty/ClientScene.cs @@ -0,0 +1 @@ +// moved into NetworkClient on 2021-03-07 diff --git a/Assets/Mirror/Core/Empty/ClientScene.cs.meta b/Assets/Mirror/Core/Empty/ClientScene.cs.meta new file mode 100644 index 0000000..82b617e --- /dev/null +++ b/Assets/Mirror/Core/Empty/ClientScene.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96fc7967f813e4960b9119d7c2118494 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud.meta b/Assets/Mirror/Core/Empty/Cloud.meta new file mode 100644 index 0000000..e2c44de --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 73a9bb2dacafa8141bce8feef34e33a7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ApiConnector.cs b/Assets/Mirror/Core/Empty/Cloud/ApiConnector.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ApiConnector.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ApiConnector.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ApiConnector.cs.meta new file mode 100644 index 0000000..9279c0c --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ApiConnector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8bdb99a29e179d14cb0acc43f175d9ad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ApiUpdater.cs b/Assets/Mirror/Core/Empty/Cloud/ApiUpdater.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ApiUpdater.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ApiUpdater.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ApiUpdater.cs.meta new file mode 100644 index 0000000..98a4c11 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ApiUpdater.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f6e5d5acb5879f45a2235ae0f44dc92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/Ball.cs b/Assets/Mirror/Core/Empty/Cloud/Ball.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Ball.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/Ball.cs.meta b/Assets/Mirror/Core/Empty/Cloud/Ball.cs.meta new file mode 100644 index 0000000..a6fc272 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Ball.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4e9cc0829b13e54594a80883836bda7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/BallManager.cs b/Assets/Mirror/Core/Empty/Cloud/BallManager.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/BallManager.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/BallManager.cs.meta b/Assets/Mirror/Core/Empty/Cloud/BallManager.cs.meta new file mode 100644 index 0000000..b914a33 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/BallManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9cc796972dc396a42ba3686bd952e329 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/BaseApi.cs b/Assets/Mirror/Core/Empty/Cloud/BaseApi.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/BaseApi.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/BaseApi.cs.meta b/Assets/Mirror/Core/Empty/Cloud/BaseApi.cs.meta new file mode 100644 index 0000000..f66b84e --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/BaseApi.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 70f563b7a7210ae43bbcde5cb7721a94 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/Events.cs b/Assets/Mirror/Core/Empty/Cloud/Events.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Events.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/Events.cs.meta b/Assets/Mirror/Core/Empty/Cloud/Events.cs.meta new file mode 100644 index 0000000..150d85b --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Events.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c7c472a3ea1bc4348bd5a0b05bf7cc3b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/Extensions.cs b/Assets/Mirror/Core/Empty/Cloud/Extensions.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Extensions.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/Extensions.cs.meta b/Assets/Mirror/Core/Empty/Cloud/Extensions.cs.meta new file mode 100644 index 0000000..6bf6291 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Extensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 97501e783fc67a4459b15d10e6c63563 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs b/Assets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs.meta new file mode 100644 index 0000000..f1149a9 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ICoroutineRunner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 43472c60a7c72e54eafe559290dd0fc6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/IRequestCreator.cs b/Assets/Mirror/Core/Empty/Cloud/IRequestCreator.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/IRequestCreator.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/IRequestCreator.cs.meta b/Assets/Mirror/Core/Empty/Cloud/IRequestCreator.cs.meta new file mode 100644 index 0000000..966c503 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/IRequestCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b80b95532a9d6e8418aa676a261e4f69 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs b/Assets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs.meta b/Assets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs.meta new file mode 100644 index 0000000..7cb2a59 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/IUnityEqualCheck.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 05185b973ba389a4588fc8a99c75a4f6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs b/Assets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs.meta b/Assets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs.meta new file mode 100644 index 0000000..4b7219b --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/InstantiateNetworkManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dbabb497385c20346a3c8bda4ae69508 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/JsonStructs.cs b/Assets/Mirror/Core/Empty/Cloud/JsonStructs.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/JsonStructs.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/JsonStructs.cs.meta b/Assets/Mirror/Core/Empty/Cloud/JsonStructs.cs.meta new file mode 100644 index 0000000..2c04009 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/JsonStructs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0688c0fdae5376e4ea74d5c3904eed17 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServer.cs b/Assets/Mirror/Core/Empty/Cloud/ListServer.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServer.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServer.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ListServer.cs.meta new file mode 100644 index 0000000..519876d --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6f0311899162c5b49a3c11fa9bd9c133 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs b/Assets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs.meta new file mode 100644 index 0000000..a9d32ea --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServerBaseApi.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b6838f9df45594d48873518cbb75b329 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs b/Assets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs.meta new file mode 100644 index 0000000..306bf7c --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServerClientApi.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d49649fb32cb96b46b10f013b38a4b50 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServerJson.cs b/Assets/Mirror/Core/Empty/Cloud/ListServerJson.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServerJson.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServerJson.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ListServerJson.cs.meta new file mode 100644 index 0000000..7e206f1 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServerJson.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a963606335eae0f47abe7ecb5fd028ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs b/Assets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs.meta new file mode 100644 index 0000000..82e23fd --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ListServerServerApi.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 675f0d0fd4e82b04290c4d30c8d78ede +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/Logger.cs b/Assets/Mirror/Core/Empty/Cloud/Logger.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Logger.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/Logger.cs.meta b/Assets/Mirror/Core/Empty/Cloud/Logger.cs.meta new file mode 100644 index 0000000..5984ce3 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Logger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 457ba2df6cb6e1542996c17c715ee81b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs b/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs.meta b/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs.meta new file mode 100644 index 0000000..86775df --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 95bebb8e810e2954485291a26324f7d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs b/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs.meta b/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs.meta new file mode 100644 index 0000000..5c4294f --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/NetworkManagerListServerPong.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 068feff770f710141afa4a90063a5e6c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/Player.cs b/Assets/Mirror/Core/Empty/Cloud/Player.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Player.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/Player.cs.meta b/Assets/Mirror/Core/Empty/Cloud/Player.cs.meta new file mode 100644 index 0000000..1c85828 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/Player.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b6cfd54b79bb464dbc6ae7f331ed45f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs b/Assets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs.meta b/Assets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs.meta new file mode 100644 index 0000000..4a22565 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/QuickListServerDebug.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 07d1ea5260bc06e4d831c4b61d494bff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs b/Assets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs.meta b/Assets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs.meta new file mode 100644 index 0000000..67341ea --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/QuitButtonHUD.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 76dab753e7255254687cd57985d8d675 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/RequestCreator.cs b/Assets/Mirror/Core/Empty/Cloud/RequestCreator.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/RequestCreator.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/RequestCreator.cs.meta b/Assets/Mirror/Core/Empty/Cloud/RequestCreator.cs.meta new file mode 100644 index 0000000..eb139af --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/RequestCreator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cfaa626443cc7c94eae138a2e3a04d7c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ServerListManager.cs b/Assets/Mirror/Core/Empty/Cloud/ServerListManager.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ServerListManager.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ServerListManager.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ServerListManager.cs.meta new file mode 100644 index 0000000..74c6a0f --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ServerListManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bfc354d4a7f63ca45a653bf5d479afa0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ServerListUI.cs b/Assets/Mirror/Core/Empty/Cloud/ServerListUI.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ServerListUI.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ServerListUI.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ServerListUI.cs.meta new file mode 100644 index 0000000..f7fe4f2 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ServerListUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ed11184fcffcdc04c9850d82c8014926 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs b/Assets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs new file mode 100644 index 0000000..2f11787 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs @@ -0,0 +1 @@ +// removed 2021-05-13 diff --git a/Assets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs.meta b/Assets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs.meta new file mode 100644 index 0000000..d8857e8 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Cloud/ServerListUIItem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c67eda1b451338a428df87fda1e3a7c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/DotNetCompatibility.cs b/Assets/Mirror/Core/Empty/DotNetCompatibility.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Core/Empty/DotNetCompatibility.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Core/Empty/DotNetCompatibility.cs.meta b/Assets/Mirror/Core/Empty/DotNetCompatibility.cs.meta new file mode 100644 index 0000000..8742197 --- /dev/null +++ b/Assets/Mirror/Core/Empty/DotNetCompatibility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b307f850ccbbe450295acf24d70e5c28 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/FallbackTransport.cs b/Assets/Mirror/Core/Empty/FallbackTransport.cs new file mode 100644 index 0000000..57f3344 --- /dev/null +++ b/Assets/Mirror/Core/Empty/FallbackTransport.cs @@ -0,0 +1 @@ +// removed 2021-05-13 \ No newline at end of file diff --git a/Assets/Mirror/Core/Empty/FallbackTransport.cs.meta b/Assets/Mirror/Core/Empty/FallbackTransport.cs.meta new file mode 100644 index 0000000..509a58f --- /dev/null +++ b/Assets/Mirror/Core/Empty/FallbackTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 330c9aab13d2d42069c6ebbe582b73ca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/LogFactory.cs b/Assets/Mirror/Core/Empty/LogFactory.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Core/Empty/LogFactory.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Core/Empty/LogFactory.cs.meta b/Assets/Mirror/Core/Empty/LogFactory.cs.meta new file mode 100644 index 0000000..0715501 --- /dev/null +++ b/Assets/Mirror/Core/Empty/LogFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 353c7c9e14e82f349b1679112050b196 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/LogFilter.cs b/Assets/Mirror/Core/Empty/LogFilter.cs new file mode 100644 index 0000000..391c5bd --- /dev/null +++ b/Assets/Mirror/Core/Empty/LogFilter.cs @@ -0,0 +1 @@ +// removed 2021-03-08 diff --git a/Assets/Mirror/Core/Empty/LogFilter.cs.meta b/Assets/Mirror/Core/Empty/LogFilter.cs.meta new file mode 100644 index 0000000..aab4fa0 --- /dev/null +++ b/Assets/Mirror/Core/Empty/LogFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f6928b080072948f7b2909b4025fcc79 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Logging.meta b/Assets/Mirror/Core/Empty/Logging.meta new file mode 100644 index 0000000..867da74 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 63d647500ca1bfa4a845bc1f4cff9dcc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs b/Assets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs.meta b/Assets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs.meta new file mode 100644 index 0000000..329c6eb --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/ConsoleColorLogHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2a9618569c20a504aa86feb5913c70e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs b/Assets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs.meta b/Assets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs.meta new file mode 100644 index 0000000..81b33e9 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/EditorLogSettingsLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a39aa1e48aa54eb4e964f0191c1dcdce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Logging/LogFactory.cs b/Assets/Mirror/Core/Empty/Logging/LogFactory.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/LogFactory.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Core/Empty/Logging/LogFactory.cs.meta b/Assets/Mirror/Core/Empty/Logging/LogFactory.cs.meta new file mode 100644 index 0000000..acf3b63 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/LogFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d06522432d5a44e1587967a4731cd279 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Logging/LogSettings.cs b/Assets/Mirror/Core/Empty/Logging/LogSettings.cs new file mode 100644 index 0000000..264a1cd --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/LogSettings.cs @@ -0,0 +1,2 @@ +// removed 2021-02-16 + diff --git a/Assets/Mirror/Core/Empty/Logging/LogSettings.cs.meta b/Assets/Mirror/Core/Empty/Logging/LogSettings.cs.meta new file mode 100644 index 0000000..90c4e4d --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/LogSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 633889a39717fde4fa28dd6b948dfac7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs b/Assets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs.meta b/Assets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs.meta new file mode 100644 index 0000000..221a61b --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/NetworkHeadlessLogger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c7627623f2b9fad4484082517cd73e67 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs b/Assets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs.meta b/Assets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs.meta new file mode 100644 index 0000000..2f7ecdf --- /dev/null +++ b/Assets/Mirror/Core/Empty/Logging/NetworkLogSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ac6e8eccf4b6f4dc7b24c276ef47fde8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/NetworkMatchChecker.cs b/Assets/Mirror/Core/Empty/NetworkMatchChecker.cs new file mode 100644 index 0000000..3797620 --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkMatchChecker.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/Mirror/Core/Empty/NetworkMatchChecker.cs.meta b/Assets/Mirror/Core/Empty/NetworkMatchChecker.cs.meta new file mode 100644 index 0000000..7c7d6cf --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkMatchChecker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1020a74962faada4b807ac5dc053a4cf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/NetworkOwnerChecker.cs b/Assets/Mirror/Core/Empty/NetworkOwnerChecker.cs new file mode 100644 index 0000000..712833c --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkOwnerChecker.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/Mirror/Core/Empty/NetworkOwnerChecker.cs.meta b/Assets/Mirror/Core/Empty/NetworkOwnerChecker.cs.meta new file mode 100644 index 0000000..fee7725 --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkOwnerChecker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 25fd0c51bbe07c140bc30978b91e9182 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/NetworkProximityChecker.cs b/Assets/Mirror/Core/Empty/NetworkProximityChecker.cs new file mode 100644 index 0000000..3797620 --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkProximityChecker.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/Mirror/Core/Empty/NetworkProximityChecker.cs.meta b/Assets/Mirror/Core/Empty/NetworkProximityChecker.cs.meta new file mode 100644 index 0000000..c5aa112 --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkProximityChecker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1731d8de2d0c84333b08ebe1e79f4118 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/NetworkSceneChecker.cs b/Assets/Mirror/Core/Empty/NetworkSceneChecker.cs new file mode 100644 index 0000000..3797620 --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkSceneChecker.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/Mirror/Core/Empty/NetworkSceneChecker.cs.meta b/Assets/Mirror/Core/Empty/NetworkSceneChecker.cs.meta new file mode 100644 index 0000000..b451655 --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkSceneChecker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b7fdb599e1359924bad6255660370252 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/NetworkTransformBase.cs b/Assets/Mirror/Core/Empty/NetworkTransformBase.cs new file mode 100644 index 0000000..79e858f --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkTransformBase.cs @@ -0,0 +1 @@ +// removed 2022-10-24 diff --git a/Assets/Mirror/Core/Empty/NetworkTransformBase.cs.meta b/Assets/Mirror/Core/Empty/NetworkTransformBase.cs.meta new file mode 100644 index 0000000..ab649d9 --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkTransformBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2e77294d8ccbc4e7cb8ca2bd0d3e99ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/NetworkVisibility.cs b/Assets/Mirror/Core/Empty/NetworkVisibility.cs new file mode 100644 index 0000000..3797620 --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkVisibility.cs @@ -0,0 +1 @@ +// removed 2022-01-06 diff --git a/Assets/Mirror/Core/Empty/NetworkVisibility.cs.meta b/Assets/Mirror/Core/Empty/NetworkVisibility.cs.meta new file mode 100644 index 0000000..f71b7be --- /dev/null +++ b/Assets/Mirror/Core/Empty/NetworkVisibility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c08f1a030234d49d391d7223a8592f15 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/StringHash.cs b/Assets/Mirror/Core/Empty/StringHash.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Core/Empty/StringHash.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Core/Empty/StringHash.cs.meta b/Assets/Mirror/Core/Empty/StringHash.cs.meta new file mode 100644 index 0000000..6198581 --- /dev/null +++ b/Assets/Mirror/Core/Empty/StringHash.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 733f020f9b76d453da841089579fd7a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/SyncVar.cs b/Assets/Mirror/Core/Empty/SyncVar.cs new file mode 100644 index 0000000..aaa3b9d --- /dev/null +++ b/Assets/Mirror/Core/Empty/SyncVar.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/Mirror/Core/Empty/SyncVar.cs.meta b/Assets/Mirror/Core/Empty/SyncVar.cs.meta new file mode 100644 index 0000000..fffb472 --- /dev/null +++ b/Assets/Mirror/Core/Empty/SyncVar.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e87cb681af8459fbbb1f467e1c7632c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/SyncVarGameObject.cs b/Assets/Mirror/Core/Empty/SyncVarGameObject.cs new file mode 100644 index 0000000..aaa3b9d --- /dev/null +++ b/Assets/Mirror/Core/Empty/SyncVarGameObject.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/Mirror/Core/Empty/SyncVarGameObject.cs.meta b/Assets/Mirror/Core/Empty/SyncVarGameObject.cs.meta new file mode 100644 index 0000000..4e924f0 --- /dev/null +++ b/Assets/Mirror/Core/Empty/SyncVarGameObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 84da90dae05442e3a149753c9b25ae98 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs b/Assets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs new file mode 100644 index 0000000..aaa3b9d --- /dev/null +++ b/Assets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs.meta b/Assets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs.meta new file mode 100644 index 0000000..0ceab50 --- /dev/null +++ b/Assets/Mirror/Core/Empty/SyncVarNetworkBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c0fff77f1a624ba8ad6e4bdef6c14a8b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs b/Assets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs new file mode 100644 index 0000000..aaa3b9d --- /dev/null +++ b/Assets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs.meta b/Assets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs.meta new file mode 100644 index 0000000..53271d4 --- /dev/null +++ b/Assets/Mirror/Core/Empty/SyncVarNetworkIdentity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f9a6d4d2741477999ad9588261870fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/HostMode.cs b/Assets/Mirror/Core/HostMode.cs new file mode 100644 index 0000000..e5bb2c0 --- /dev/null +++ b/Assets/Mirror/Core/HostMode.cs @@ -0,0 +1,48 @@ +// host mode related helper functions. +// usually they set up both server & client. +// it's cleaner to keep them in one place, instead of only in server / client. +using System; + +namespace Mirror +{ + public static class HostMode + { + // keep the local connections setup in one function. + // makes host setup easier to follow. + internal static void SetupConnections() + { + // create local connections pair, both are connected + Utils.CreateLocalConnections( + out LocalConnectionToClient connectionToClient, + out LocalConnectionToServer connectionToServer); + + // set client connection + NetworkClient.connection = connectionToServer; + + // set server connection + NetworkServer.SetLocalConnection(connectionToClient); + } + + // call OnConnected on server & client. + // public because NetworkClient.ConnectLocalServer was public before too. + public static void InvokeOnConnected() + { + // call server OnConnected with server's connection to client + NetworkServer.OnConnected(NetworkServer.localConnection); + + // call client OnConnected with client's connection to server + // => previously we used to send a ConnectMessage to + // NetworkServer.localConnection. this would queue the message + // until NetworkClient.Update processes it. + // => invoking the client's OnConnected event directly here makes + // tests fail. so let's do it exactly the same order as before by + // queueing the event for next Update! + //OnConnectedEvent?.Invoke(connection); + ((LocalConnectionToServer)NetworkClient.connection).QueueConnectedEvent(); + } + + // DEPRECATED 2023-01-28 + [Obsolete("ActivateHostScene did nothing, since identities all had .isClient set in NetworkServer.SpawnObjects.")] + public static void ActivateHostScene() {} + } +} diff --git a/Assets/Mirror/Core/HostMode.cs.meta b/Assets/Mirror/Core/HostMode.cs.meta new file mode 100644 index 0000000..bf6faed --- /dev/null +++ b/Assets/Mirror/Core/HostMode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d27175a08d5341fc97645b49ee533d5a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/InterestManagement.cs b/Assets/Mirror/Core/InterestManagement.cs new file mode 100644 index 0000000..3516339 --- /dev/null +++ b/Assets/Mirror/Core/InterestManagement.cs @@ -0,0 +1,146 @@ +// interest management component for custom solutions like +// distance based, spatial hashing, raycast based, etc. + +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public abstract class InterestManagement : InterestManagementBase + { + // allocate newObservers helper HashSet + readonly HashSet newObservers = + new HashSet(); + + // rebuild observers for the given NetworkIdentity. + // Server will automatically spawn/despawn added/removed ones. + // newObservers: cached hashset to put the result into + // initialize: true if being rebuilt for the first time + // + // IMPORTANT: + // => global rebuild would be more simple, BUT + // => local rebuild is way faster for spawn/despawn because we can + // simply rebuild a select NetworkIdentity only + // => having both .observers and .observing is necessary for local + // rebuilds + // + // in other words, this is the perfect solution even though it's not + // completely simple (due to .observers & .observing). + // + // Mirror maintains .observing automatically in the background. best of + // both worlds without any worrying now! + public abstract void OnRebuildObservers(NetworkIdentity identity, HashSet newObservers); + + // helper function to trigger a full rebuild. + // most implementations should call this in a certain interval. + // some might call this all the time, or only on team changes or + // scene changes and so on. + // + // IMPORTANT: check if NetworkServer.active when using Update()! + [ServerCallback] + protected void RebuildAll() + { + foreach (NetworkIdentity identity in NetworkServer.spawned.Values) + { + NetworkServer.RebuildObservers(identity, false); + } + } + + public override void Rebuild(NetworkIdentity identity, bool initialize) + { + // clear newObservers hashset before using it + newObservers.Clear(); + + // not force hidden? + if (identity.visible != Visibility.ForceHidden) + { + OnRebuildObservers(identity, newObservers); + } + + // IMPORTANT: AFTER rebuilding add own player connection in any case + // to ensure player always sees himself no matter what. + // -> OnRebuildObservers might clear observers, so we need to add + // the player's own connection AFTER. 100% fail safe. + // -> fixes https://github.com/vis2k/Mirror/issues/692 where a + // player might teleport out of the ProximityChecker's cast, + // losing the own connection as observer. + if (identity.connectionToClient != null) + { + newObservers.Add(identity.connectionToClient); + } + + bool changed = false; + + // add all newObservers that aren't in .observers yet + foreach (NetworkConnectionToClient conn in newObservers) + { + // only add ready connections. + // otherwise the player might not be in the world yet or anymore + if (conn != null && conn.isReady) + { + if (initialize || !identity.observers.ContainsKey(conn.connectionId)) + { + // new observer + conn.AddToObserving(identity); + // Debug.Log($"New Observer for {gameObject} {conn}"); + changed = true; + } + } + } + + // remove all old .observers that aren't in newObservers anymore + foreach (NetworkConnectionToClient conn in identity.observers.Values) + { + if (!newObservers.Contains(conn)) + { + // removed observer + conn.RemoveFromObserving(identity, false); + // Debug.Log($"Removed Observer for {gameObject} {conn}"); + changed = true; + } + } + + // copy new observers to observers + if (changed) + { + identity.observers.Clear(); + foreach (NetworkConnectionToClient conn in newObservers) + { + if (conn != null && conn.isReady) + identity.observers.Add(conn.connectionId, conn); + } + } + + // special case for host mode: we use SetHostVisibility to hide + // NetworkIdentities that aren't in observer range from host. + // this is what games like Dota/Counter-Strike do too, where a host + // does NOT see all players by default. they are in memory, but + // hidden to the host player. + // + // this code is from UNET, it's a bit strange but it works: + // * it hides newly connected identities in host mode + // => that part was the intended behaviour + // * it hides ALL NetworkIdentities in host mode when the host + // connects but hasn't selected a character yet + // => this only works because we have no .localConnection != null + // check. at this stage, localConnection is null because + // StartHost starts the server first, then calls this code, + // then starts the client and sets .localConnection. so we can + // NOT add a null check without breaking host visibility here. + // * it hides ALL NetworkIdentities in server-only mode because + // observers never contain the 'null' .localConnection + // => that was not intended, but let's keep it as it is so we + // don't break anything in host mode. it's way easier than + // iterating all identities in a special function in StartHost. + if (initialize) + { + if (!newObservers.Contains(NetworkServer.localConnection)) + { + SetHostVisibility(identity, false); + } + } + } + } +} diff --git a/Assets/Mirror/Core/InterestManagement.cs.meta b/Assets/Mirror/Core/InterestManagement.cs.meta new file mode 100644 index 0000000..bfabf6b --- /dev/null +++ b/Assets/Mirror/Core/InterestManagement.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41d809934003479f97e992eebb7ed6af +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/InterestManagementBase.cs b/Assets/Mirror/Core/InterestManagementBase.cs new file mode 100644 index 0000000..aef7a65 --- /dev/null +++ b/Assets/Mirror/Core/InterestManagementBase.cs @@ -0,0 +1,84 @@ +// interest management component for custom solutions like +// distance based, spatial hashing, raycast based, etc. +// low level base class allows for low level spatial hashing etc., which is 3-5x faster. +using UnityEngine; + +namespace Mirror +{ + [DisallowMultipleComponent] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/interest-management")] + public abstract class InterestManagementBase : MonoBehaviour + { + // Configures InterestManagementBase in NetworkServer/Client + // Do NOT check for active server or client here. + // OnEnable must always set the static aoi references. + // make sure to call base.OnEnable when overwriting! + // Previously used Awake() + protected virtual void OnEnable() + { + if (NetworkServer.aoi == null) + { + NetworkServer.aoi = this; + } + else Debug.LogError($"Only one InterestManagement component allowed. {NetworkServer.aoi.GetType()} has been set up already."); + + if (NetworkClient.aoi == null) + { + NetworkClient.aoi = this; + } + else Debug.LogError($"Only one InterestManagement component allowed. {NetworkClient.aoi.GetType()} has been set up already."); + } + + [ServerCallback] + public virtual void Reset() {} + + // Callback used by the visibility system to determine if an observer + // (player) can see the NetworkIdentity. If this function returns true, + // the network connection will be added as an observer. + // conn: Network connection of a player. + // returns True if the player can see this object. + public abstract bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver); + + + // Callback used by the visibility system for objects on a host. + // Objects on a host (with a local client) cannot be disabled or + // destroyed when they are not visible to the local client. So this + // function is called to allow custom code to hide these objects. A + // typical implementation will disable renderer components on the + // object. This is only called on local clients on a host. + // => need the function in here and virtual so people can overwrite! + // => not everyone wants to hide renderers! + [ServerCallback] + public virtual void SetHostVisibility(NetworkIdentity identity, bool visible) + { + foreach (Renderer rend in identity.GetComponentsInChildren()) + rend.enabled = visible; + } + + /// Called on the server when a new networked object is spawned. + // (useful for 'only rebuild if changed' interest management algorithms) + [ServerCallback] + public virtual void OnSpawned(NetworkIdentity identity) {} + + /// Called on the server when a networked object is destroyed. + // (useful for 'only rebuild if changed' interest management algorithms) + [ServerCallback] + public virtual void OnDestroyed(NetworkIdentity identity) {} + + public abstract void Rebuild(NetworkIdentity identity, bool initialize); + + /// Adds the specified connection to the observers of identity + protected void AddObserver(NetworkConnectionToClient connection, NetworkIdentity identity) + { + connection.AddToObserving(identity); + identity.observers.Add(connection.connectionId, connection); + } + + /// Removes the specified connection from the observers of identity + protected void RemoveObserver(NetworkConnectionToClient connection, NetworkIdentity identity) + { + connection.RemoveFromObserving(identity, false); + identity.observers.Remove(connection.connectionId); + } + } +} diff --git a/Assets/Mirror/Core/InterestManagementBase.cs.meta b/Assets/Mirror/Core/InterestManagementBase.cs.meta new file mode 100644 index 0000000..b2b5ad6 --- /dev/null +++ b/Assets/Mirror/Core/InterestManagementBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18bd2ffe65a444f3b13d59bdac7f2228 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/LagCompensation.meta b/Assets/Mirror/Core/LagCompensation.meta new file mode 100644 index 0000000..b5583ef --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d2656015ded44e83a24f4c4776bafd40 +timeCreated: 1687920405 \ No newline at end of file diff --git a/Assets/Mirror/Core/LagCompensation/Capture.cs b/Assets/Mirror/Core/LagCompensation/Capture.cs new file mode 100644 index 0000000..e4fdabe --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/Capture.cs @@ -0,0 +1,13 @@ +namespace Mirror +{ + public interface Capture + { + // server timestamp at time of capture. + double timestamp { get; set; } + + // optional gizmo drawing for visual debugging. + // history is only known on the server, which usually doesn't render. + // showing Gizmos in the Editor is enough. + void DrawGizmo(); + } +} diff --git a/Assets/Mirror/Core/LagCompensation/Capture.cs.meta b/Assets/Mirror/Core/LagCompensation/Capture.cs.meta new file mode 100644 index 0000000..2d5a41d --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/Capture.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 347e831952e943a49095cadd39a5aeb2 +timeCreated: 1687921461 \ No newline at end of file diff --git a/Assets/Mirror/Core/LagCompensation/HistoryBounds.cs b/Assets/Mirror/Core/LagCompensation/HistoryBounds.cs new file mode 100644 index 0000000..29ebc2e --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/HistoryBounds.cs @@ -0,0 +1,139 @@ +// HistoryBounds keeps a bounding box of all the object's bounds in the past N seconds. +// useful to decide which objects to rollback, instead of rolling back all of them. +// https://www.youtube.com/watch?v=zrIY0eIyqmI (37:00) +// standalone C# implementation to be engine (and language) agnostic. + +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // FakeByte: gather bounds in smaller buckets. + // for example, bucket(t0,t1,t2), bucket(t3,t4,t5), ... + // instead of removing old bounds t0, t1, ... + // we remove a whole bucket every 3 times: bucket(t0,t1,t2) + // and when building total bounds, we encapsulate a few larger buckets + // instead of many smaller bounds. + // + // => a bucket is encapsulate(bounds0, bounds1, bounds2) so we don't + // need a custom struct, simply reuse bounds but remember that each + // entry includes N timestamps. + // + // => note that simply reducing capture interval is _not_ the same. + // we want to capture in detail in case players run in zig-zag. + // but still grow larger buckets internally. + public class HistoryBounds + { + // mischa: use MinMaxBounds to avoid Unity Bounds.Encapsulate conversions. + readonly int boundsPerBucket; + readonly Queue fullBuckets; + + // full bucket limit. older ones will be removed. + readonly int bucketLimit; + + // bucket in progress, contains 0..boundsPerBucket bounds encapsulated. + MinMaxBounds? currentBucket; + int currentBucketSize; + + // amount of total bounds, including bounds in full buckets + current + public int boundsCount { get; private set; } + + // total bounds encapsulating all of the bounds history. + // totalMinMax is used for internal calculations. + // public total is used for Unity representation. + MinMaxBounds totalMinMax; + public Bounds total + { + get + { + Bounds bounds = new Bounds(); + bounds.SetMinMax(totalMinMax.min, totalMinMax.max); + return bounds; + } + } + + public HistoryBounds(int boundsLimit, int boundsPerBucket) + { + // bucketLimit via '/' cuts off remainder. + // that's what we want, since we always have a 'currentBucket'. + this.boundsPerBucket = boundsPerBucket; + this.bucketLimit = (boundsLimit / boundsPerBucket); + + // initialize queue with maximum capacity to avoid runtime resizing + // capacity +1 because it makes the code easier if we insert first, and then remove. + fullBuckets = new Queue(bucketLimit + 1); + } + + // insert new bounds into history. calculates new total bounds. + // Queue.Dequeue() always has the oldest bounds. + public void Insert(Bounds bounds) + { + // convert to MinMax representation for faster .Encapsulate() + MinMaxBounds minmax = new MinMaxBounds + { + min = bounds.min, + max = bounds.max + }; + + // initialize 'total' if not initialized yet. + // we don't want to call (0,0).Encapsulate(bounds). + if (boundsCount == 0) + { + totalMinMax = minmax; + } + + // add to current bucket: + // either initialize new one, or encapsulate into existing one + if (currentBucket == null) + { + currentBucket = minmax; + } + else + { + currentBucket.Value.Encapsulate(minmax); + } + + // current bucket has one more bounds. + // total bounds increased as well. + currentBucketSize += 1; + boundsCount += 1; + + // always encapsulate into total immediately. + // this is free. + totalMinMax.Encapsulate(minmax); + + // current bucket full? + if (currentBucketSize == boundsPerBucket) + { + // move it to full buckets + fullBuckets.Enqueue(currentBucket.Value); + currentBucket = null; + currentBucketSize = 0; + + // full bucket capacity reached? + if (fullBuckets.Count > bucketLimit) + { + // remove oldest bucket + fullBuckets.Dequeue(); + boundsCount -= boundsPerBucket; + + // recompute total bounds + // instead of iterating N buckets, we iterate N / boundsPerBucket buckets. + // TODO technically we could reuse 'currentBucket' before clearing instead of encapsulating again + totalMinMax = minmax; + foreach (MinMaxBounds bucket in fullBuckets) + totalMinMax.Encapsulate(bucket); + } + } + } + + public void Reset() + { + fullBuckets.Clear(); + currentBucket = null; + currentBucketSize = 0; + boundsCount = 0; + totalMinMax = new MinMaxBounds(); + } + } +} diff --git a/Assets/Mirror/Core/LagCompensation/HistoryBounds.cs.meta b/Assets/Mirror/Core/LagCompensation/HistoryBounds.cs.meta new file mode 100644 index 0000000..373d8ea --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/HistoryBounds.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ca9ea58b98a34f73801b162cd5de724e +timeCreated: 1690172331 \ No newline at end of file diff --git a/Assets/Mirror/Core/LagCompensation/LagCompensation.cs b/Assets/Mirror/Core/LagCompensation/LagCompensation.cs new file mode 100644 index 0000000..ae37a3f --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/LagCompensation.cs @@ -0,0 +1,144 @@ +// standalone lag compensation algorithm +// based on the Valve Networking Model: +// https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking +using System.Collections.Generic; + +namespace Mirror +{ + public static class LagCompensation + { + // history is of . + // Queue allows for fast 'remove first' and 'append last'. + // + // make sure to always insert in order. + // inserting out of order like [1,2,4,3] would cause issues. + // can't safeguard this because Queue doesn't have .Last access. + public static void Insert( + Queue> history, + int historyLimit, + double timestamp, + T capture) + where T : Capture + { + // make space according to history limit. + // do this before inserting, to avoid resizing past capacity. + if (history.Count >= historyLimit) + history.Dequeue(); + + // insert + history.Enqueue(new KeyValuePair(timestamp, capture)); + } + + // get the two snapshots closest to a given timestamp. + // those can be used to interpolate the exact snapshot at that time. + // if timestamp is newer than the newest history entry, then we extrapolate. + // 't' will be between 1 and 2, before is second last, after is last. + // callers should Lerp(before, after, t=1.5) to extrapolate the hit. + // see comments below for extrapolation. + public static bool Sample( + Queue> history, + double timestamp, // current server time + double interval, // capture interval + out T before, + out T after, + out double t) // interpolation factor + where T : Capture + { + before = default; + after = default; + t = 0; + + // can't sample an empty history + // interpolation needs at least one entry. + // extrapolation needs at least two entries. + // can't Lerp(A, A, 1.5). dist(A, A) * 1.5 is always 0. + if(history.Count < 2) { + return false; + } + + // older than oldest + if (timestamp < history.Peek().Key) { + return false; + } + + // iterate through the history + // TODO faster version: guess start index by how many 'intervals' we are behind. + // search around that area. + // should be O(1) most of the time, unless sampling was off. + KeyValuePair prev = new KeyValuePair(); + KeyValuePair prevPrev = new KeyValuePair(); + foreach(KeyValuePair entry in history) { + // exact match? + if (timestamp == entry.Key) { + before = entry.Value; + after = entry.Value; + t = Mathd.InverseLerp(before.timestamp, after.timestamp, timestamp); + return true; + } + + // did we check beyond timestamp? then return the previous two. + if (entry.Key > timestamp) { + before = prev.Value; + after = entry.Value; + t = Mathd.InverseLerp(before.timestamp, after.timestamp, timestamp); + return true; + } + + // remember the last two for extrapolation. + // Queue doesn't have access to .Last. + prevPrev = prev; + prev = entry; + } + + // newer than newest: extrapolate up to one interval. + // let's say we capture every 100 ms: + // 100, 200, 300, 400 + // and the server is at 499 + // if a client sends CmdFire at time 480, then there's no history entry. + // => adding the current entry every time would be too expensive. + // worst case we would capture at 401, 402, 403, 404, ... 100 times + // => not extrapolating isn't great. low latency clients would be + // punished by missing their targets since no entry at 'time' was found. + // => extrapolation is the best solution. make sure this works as + // expected and within limits. + if (prev.Key < timestamp && timestamp <= prev.Key + interval) { + // return the last two valid snapshots. + // can't just return (after, after) because we can't extrapolate + // if their distance is 0. + before = prevPrev.Value; + after = prev.Value; + + // InverseLerp will give [after, after+interval]. + // but we return [before, after, t]. + // so add +1 for the distance from before->after + t = 1 + Mathd.InverseLerp(after.timestamp, after.timestamp + interval, timestamp); + return true; + } + + return false; + } + + // never trust the client. + // we estimate when a message was sent. + // don't trust the client to tell us the time. + // https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking + // Command Execution Time = Current Server Time - Packet Latency - Client View Interpolation + // => lag compensation demo estimation is off by only ~6ms + public static double EstimateTime(double serverTime, double rtt, double bufferTime) + { + // packet latency is one trip from client to server, so rtt / 2 + // client view interpolation is the snapshot interpolation buffer time + double latency = rtt / 2; + return serverTime - latency - bufferTime; + } + + // convenience function to draw all history gizmos. + // this should be called from OnDrawGizmos. + public static void DrawGizmos(Queue> history) + where T : Capture + { + foreach (KeyValuePair entry in history) + entry.Value.DrawGizmo(); + } + } +} diff --git a/Assets/Mirror/Core/LagCompensation/LagCompensation.cs.meta b/Assets/Mirror/Core/LagCompensation/LagCompensation.cs.meta new file mode 100644 index 0000000..f85a6c3 --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/LagCompensation.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ad53cc7d12144d0ba3a8b0a4515e5d17 +timeCreated: 1687921483 \ No newline at end of file diff --git a/Assets/Mirror/Core/LagCompensation/LagCompensationSettings.cs b/Assets/Mirror/Core/LagCompensation/LagCompensationSettings.cs new file mode 100644 index 0000000..a7ec944 --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/LagCompensationSettings.cs @@ -0,0 +1,19 @@ +// snapshot interpolation settings struct. +// can easily be exposed in Unity inspectors. +using System; +using UnityEngine; + +namespace Mirror +{ + // class so we can define defaults easily + [Serializable] + public class LagCompensationSettings + { + [Header("Buffering")] + [Tooltip("Keep this many past snapshots in the buffer. The larger this is, the further we can rewind into the past.\nMaximum rewind time := historyAmount * captureInterval")] + public int historyLimit = 6; + + [Tooltip("Capture state every 'captureInterval' seconds. Larger values will space out the captures more, which gives a longer history but with possible gaps inbetween.\nSmaller values will have fewer gaps, with shorter history.")] + public float captureInterval = 0.100f; // 100 ms + } +} diff --git a/Assets/Mirror/Core/LagCompensation/LagCompensationSettings.cs.meta b/Assets/Mirror/Core/LagCompensation/LagCompensationSettings.cs.meta new file mode 100644 index 0000000..c5b9c47 --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/LagCompensationSettings.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fa80bec245f94bf8a28ec78777992a1c +timeCreated: 1687920412 \ No newline at end of file diff --git a/Assets/Mirror/Core/LagCompensation/MinMaxBounds.cs b/Assets/Mirror/Core/LagCompensation/MinMaxBounds.cs new file mode 100644 index 0000000..3cf6991 --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/MinMaxBounds.cs @@ -0,0 +1,61 @@ +// Unity's Bounds struct is represented as (center, extents). +// HistoryBounds make heavy use of .Encapsulate(), which has to convert +// Unity's (center, extents) to (min, max) every time, and then convert back. +// +// It's faster to use a (min, max) representation directly instead. +using System; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + public struct MinMaxBounds: IEquatable + { + public Vector3 min; + public Vector3 max; + + // encapsulate a single point + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Encapsulate(Vector3 point) + { + min = Vector3.Min(this.min, point); + max = Vector3.Max(this.max, point); + } + + // encapsulate another bounds + public void Encapsulate(MinMaxBounds bounds) + { + Encapsulate(bounds.min); + Encapsulate(bounds.max); + } + + // convenience comparison with Unity's bounds, for unit tests etc. + public static bool operator ==(MinMaxBounds lhs, Bounds rhs) => + lhs.min == rhs.min && + lhs.max == rhs.max; + + public static bool operator !=(MinMaxBounds lhs, Bounds rhs) => + !(lhs == rhs); + + public override bool Equals(object obj) => + obj is MinMaxBounds other && + min == other.min && + max == other.max; + + public bool Equals(MinMaxBounds other) => + min.Equals(other.min) && max.Equals(other.max); + + public bool Equals(Bounds other) => + min.Equals(other.min) && max.Equals(other.max); + +#if UNITY_2021_3_OR_NEWER + // Unity 2019/2020 don't have HashCode.Combine yet. + // this is only to avoid reflection. without defining, it works too. + // default generated by rider + public override int GetHashCode() => HashCode.Combine(min, max); +#endif + + // tostring + public override string ToString() => $"({min}, {max})"; + } +} diff --git a/Assets/Mirror/Core/LagCompensation/MinMaxBounds.cs.meta b/Assets/Mirror/Core/LagCompensation/MinMaxBounds.cs.meta new file mode 100644 index 0000000..8b189f2 --- /dev/null +++ b/Assets/Mirror/Core/LagCompensation/MinMaxBounds.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4372b1e1a1cc4c669cc7bf0925f59d29 +timeCreated: 1690367013 \ No newline at end of file diff --git a/Assets/Mirror/Core/LocalConnectionToClient.cs b/Assets/Mirror/Core/LocalConnectionToClient.cs new file mode 100644 index 0000000..5b62122 --- /dev/null +++ b/Assets/Mirror/Core/LocalConnectionToClient.cs @@ -0,0 +1,50 @@ +using System; + +namespace Mirror +{ + // a server's connection TO a LocalClient. + // sending messages on this connection causes the client's handler function to be invoked directly + public class LocalConnectionToClient : NetworkConnectionToClient + { + internal LocalConnectionToServer connectionToServer; + + public LocalConnectionToClient() : base(LocalConnectionId) {} + + public override string address => "localhost"; + + // Send stage two: serialized NetworkMessage as ArraySegment + internal override void Send(ArraySegment segment, int channelId = Channels.Reliable) + { + // get a writer to copy the message into since the segment is only + // valid until returning. + // => pooled writer will be returned to pool when dequeuing. + // => WriteBytes instead of WriteArraySegment because the latter + // includes a 4 bytes header. we just want to write raw. + //Debug.Log($"Enqueue {BitConverter.ToString(segment.Array, segment.Offset, segment.Count)}"); + NetworkWriterPooled writer = NetworkWriterPool.Get(); + writer.WriteBytes(segment.Array, segment.Offset, segment.Count); + connectionToServer.queue.Enqueue(writer); + } + + // true because local connections never timeout + internal override bool IsAlive(float timeout) => true; + + // don't ping host client in host mode + protected override void UpdatePing() {} + + internal void DisconnectInternal() + { + // set not ready and handle clientscene disconnect in any case + // (might be client or host mode here) + isReady = false; + RemoveFromObservingsObservers(); + } + + /// Disconnects this connection. + public override void Disconnect() + { + DisconnectInternal(); + connectionToServer.DisconnectInternal(); + } + } +} diff --git a/Assets/Mirror/Core/LocalConnectionToClient.cs.meta b/Assets/Mirror/Core/LocalConnectionToClient.cs.meta new file mode 100644 index 0000000..a4f2d2c --- /dev/null +++ b/Assets/Mirror/Core/LocalConnectionToClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a88758df7db2043d6a9d926e0b6d4191 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/LocalConnectionToServer.cs b/Assets/Mirror/Core/LocalConnectionToServer.cs new file mode 100644 index 0000000..dff12a4 --- /dev/null +++ b/Assets/Mirror/Core/LocalConnectionToServer.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // a localClient's connection TO a server. + // send messages on this connection causes the server's handler function to be invoked directly. + public class LocalConnectionToServer : NetworkConnectionToServer + { + internal LocalConnectionToClient connectionToClient; + + // packet queue + internal readonly Queue queue = new Queue(); + + // Deprecated 2023-02-23 + [Obsolete("Use LocalConnectionToClient.address instead.")] + public string address => "localhost"; + + // see caller for comments on why we need this + bool connectedEventPending; + bool disconnectedEventPending; + internal void QueueConnectedEvent() => connectedEventPending = true; + internal void QueueDisconnectedEvent() => disconnectedEventPending = true; + + // Send stage two: serialized NetworkMessage as ArraySegment + internal override void Send(ArraySegment segment, int channelId = Channels.Reliable) + { + if (segment.Count == 0) + { + Debug.LogError("LocalConnection.SendBytes cannot send zero bytes"); + return; + } + + // OnTransportData assumes batching. + // so let's make a batch with proper timestamp prefix. + Batcher batcher = GetBatchForChannelId(channelId); + batcher.AddMessage(segment, NetworkTime.localTime); + + // flush it to the server's OnTransportData immediately. + // local connection to server always invokes immediately. + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // make a batch with our local time (double precision) + if (batcher.GetBatch(writer)) + { + NetworkServer.OnTransportData(connectionId, writer.ToArraySegment(), channelId); + } + else Debug.LogError("Local connection failed to make batch. This should never happen."); + } + } + + internal override void Update() + { + base.Update(); + + // should we still process a connected event? + if (connectedEventPending) + { + connectedEventPending = false; + NetworkClient.OnConnectedEvent?.Invoke(); + } + + // process internal messages so they are applied at the correct time + while (queue.Count > 0) + { + // call receive on queued writer's content, return to pool + NetworkWriterPooled writer = queue.Dequeue(); + ArraySegment message = writer.ToArraySegment(); + + // OnTransportData assumes a proper batch with timestamp etc. + // let's make a proper batch and pass it to OnTransportData. + Batcher batcher = GetBatchForChannelId(Channels.Reliable); + batcher.AddMessage(message, NetworkTime.localTime); + + using (NetworkWriterPooled batchWriter = NetworkWriterPool.Get()) + { + // make a batch with our local time (double precision) + if (batcher.GetBatch(batchWriter)) + { + NetworkClient.OnTransportData(batchWriter.ToArraySegment(), Channels.Reliable); + } + } + + NetworkWriterPool.Return(writer); + } + + // should we still process a disconnected event? + if (disconnectedEventPending) + { + disconnectedEventPending = false; + NetworkClient.OnDisconnectedEvent?.Invoke(); + } + } + + /// Disconnects this connection. + internal void DisconnectInternal() + { + // set not ready and handle clientscene disconnect in any case + // (might be client or host mode here) + // TODO remove redundant state. have one source of truth for .ready! + isReady = false; + NetworkClient.ready = false; + } + + /// Disconnects this connection. + public override void Disconnect() + { + connectionToClient.DisconnectInternal(); + DisconnectInternal(); + + // simulate what a true remote connection would do: + // first, the server should remove it: + // TODO should probably be in connectionToClient.DisconnectInternal + // because that's the NetworkServer's connection! + NetworkServer.RemoveLocalConnection(); + + // then call OnTransportDisconnected for proper disconnect handling, + // callbacks & cleanups. + // => otherwise OnClientDisconnected() is never called! + // => see NetworkClientTests.DisconnectCallsOnClientDisconnect_HostMode() + NetworkClient.OnTransportDisconnected(); + } + + // true because local connections never timeout + internal override bool IsAlive(float timeout) => true; + } +} diff --git a/Assets/Mirror/Core/LocalConnectionToServer.cs.meta b/Assets/Mirror/Core/LocalConnectionToServer.cs.meta new file mode 100644 index 0000000..856b255 --- /dev/null +++ b/Assets/Mirror/Core/LocalConnectionToServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cdfff390c3504158a269e8b8662e2a40 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Messages.cs b/Assets/Mirror/Core/Messages.cs new file mode 100644 index 0000000..38cd14c --- /dev/null +++ b/Assets/Mirror/Core/Messages.cs @@ -0,0 +1,122 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + // need to send time every sendInterval. + // batching automatically includes remoteTimestamp. + // all we need to do is ensure that an empty message is sent. + // and react to it. + // => we don't want to insert a snapshot on every batch. + // => do it exactly every sendInterval on every TimeSnapshotMessage. + public struct TimeSnapshotMessage : NetworkMessage {} + + public struct ReadyMessage : NetworkMessage {} + + public struct NotReadyMessage : NetworkMessage {} + + public struct AddPlayerMessage : NetworkMessage {} + + public struct SceneMessage : NetworkMessage + { + public string sceneName; + // Normal = 0, LoadAdditive = 1, UnloadAdditive = 2 + public SceneOperation sceneOperation; + public bool customHandling; + } + + public enum SceneOperation : byte + { + Normal, + LoadAdditive, + UnloadAdditive + } + + public struct CommandMessage : NetworkMessage + { + public uint netId; + public byte componentIndex; + public ushort functionHash; + // the parameters for the Cmd function + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + } + + public struct RpcMessage : NetworkMessage + { + public uint netId; + public byte componentIndex; + public ushort functionHash; + // the parameters for the Cmd function + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + } + + public struct SpawnMessage : NetworkMessage + { + // netId of new or existing object + public uint netId; + public bool isLocalPlayer; + // Sets hasAuthority on the spawned object + public bool isOwner; + public ulong sceneId; + // If sceneId != 0 then it is used instead of assetId + public uint assetId; + // Local position + public Vector3 position; + // Local rotation + public Quaternion rotation; + // Local scale + public Vector3 scale; + // serialized component data + // ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + } + + public struct ChangeOwnerMessage : NetworkMessage + { + public uint netId; + public bool isOwner; + public bool isLocalPlayer; + } + + public struct ObjectSpawnStartedMessage : NetworkMessage {} + + public struct ObjectSpawnFinishedMessage : NetworkMessage {} + + public struct ObjectDestroyMessage : NetworkMessage + { + public uint netId; + } + + public struct ObjectHideMessage : NetworkMessage + { + public uint netId; + } + + public struct EntityStateMessage : NetworkMessage + { + public uint netId; + // the serialized component data + // -> ArraySegment to avoid unnecessary allocations + public ArraySegment payload; + } + + // whoever wants to measure rtt, sends this to the other end. + public struct NetworkPingMessage : NetworkMessage + { + public double localTime; + + public NetworkPingMessage(double value) + { + localTime = value; + } + } + + // the other end responds with this message. + // we can use this to calculate rtt. + public struct NetworkPongMessage : NetworkMessage + { + public double localTime; + } +} diff --git a/Assets/Mirror/Core/Messages.cs.meta b/Assets/Mirror/Core/Messages.cs.meta new file mode 100644 index 0000000..5d119e2 --- /dev/null +++ b/Assets/Mirror/Core/Messages.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 938f6f28a6c5b48a0bbd7782342d763b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Mirror.asmdef b/Assets/Mirror/Core/Mirror.asmdef new file mode 100644 index 0000000..2fa8d95 --- /dev/null +++ b/Assets/Mirror/Core/Mirror.asmdef @@ -0,0 +1,16 @@ +{ + "name": "Mirror", + "rootNamespace": "", + "references": [ + "GUID:325984b52e4128546bc7558552f8b1d2" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Mirror/Core/Mirror.asmdef.meta b/Assets/Mirror/Core/Mirror.asmdef.meta new file mode 100644 index 0000000..202009b --- /dev/null +++ b/Assets/Mirror/Core/Mirror.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 30817c1a0e6d646d99c048fc403f5979 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkAuthenticator.cs b/Assets/Mirror/Core/NetworkAuthenticator.cs new file mode 100644 index 0000000..aa1e7f7 --- /dev/null +++ b/Assets/Mirror/Core/NetworkAuthenticator.cs @@ -0,0 +1,84 @@ +using System; +using UnityEngine; +using UnityEngine.Events; + +namespace Mirror +{ + [Serializable] public class UnityEventNetworkConnection : UnityEvent {} + + /// Base class for implementing component-based authentication during the Connect phase + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-authenticators")] + public abstract class NetworkAuthenticator : MonoBehaviour + { + /// Notify subscribers on the server when a client is authenticated + [Header("Event Listeners (optional)")] + [Tooltip("Mirror has an internal subscriber to this event. You can add your own here.")] + public UnityEventNetworkConnection OnServerAuthenticated = new UnityEventNetworkConnection(); + + /// Notify subscribers on the client when the client is authenticated + [Tooltip("Mirror has an internal subscriber to this event. You can add your own here.")] + public UnityEvent OnClientAuthenticated = new UnityEvent(); + + /// Called when server starts, used to register message handlers if needed. + public virtual void OnStartServer() {} + + /// Called when server stops, used to unregister message handlers if needed. + public virtual void OnStopServer() {} + + /// Called on server from OnServerConnectInternal when a client needs to authenticate + public virtual void OnServerAuthenticate(NetworkConnectionToClient conn) {} + + protected void ServerAccept(NetworkConnectionToClient conn) + { + OnServerAuthenticated.Invoke(conn); + } + + protected void ServerReject(NetworkConnectionToClient conn) + { + conn.Disconnect(); + } + + /// Called when client starts, used to register message handlers if needed. + public virtual void OnStartClient() {} + + /// Called when client stops, used to unregister message handlers if needed. + public virtual void OnStopClient() {} + + /// Called on client from OnClientConnectInternal when a client needs to authenticate + public virtual void OnClientAuthenticate() {} + + protected void ClientAccept() + { + OnClientAuthenticated.Invoke(); + } + + protected void ClientReject() + { + // Set this on the client for local reference + NetworkClient.connection.isAuthenticated = false; + + // disconnect the client + NetworkClient.connection.Disconnect(); + } + + // Reset() instead of OnValidate(): + // Any NetworkAuthenticator assigns itself to the NetworkManager, this is fine on first adding it, + // but if someone intentionally sets Authenticator to null on the NetworkManager again then the + // Authenticator will reassign itself if a value in the inspector is changed. + // My change switches OnValidate to Reset since Reset is only called when the component is first + // added (or reset is pressed). + void Reset() + { +#if UNITY_EDITOR + // automatically assign authenticator field if we add this to NetworkManager + NetworkManager manager = GetComponent(); + if (manager != null && manager.authenticator == null) + { + // undo has to be called before the change happens + UnityEditor.Undo.RecordObject(manager, "Assigned NetworkManager authenticator"); + manager.authenticator = this; + } +#endif + } + } +} diff --git a/Assets/Mirror/Core/NetworkAuthenticator.cs.meta b/Assets/Mirror/Core/NetworkAuthenticator.cs.meta new file mode 100644 index 0000000..d37db68 --- /dev/null +++ b/Assets/Mirror/Core/NetworkAuthenticator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 407fc95d4a8257f448799f26cdde0c2a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkBehaviour.cs b/Assets/Mirror/Core/NetworkBehaviour.cs new file mode 100644 index 0000000..affca80 --- /dev/null +++ b/Assets/Mirror/Core/NetworkBehaviour.cs @@ -0,0 +1,1361 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + // SyncMode decides if a component is synced to all observers, or only owner + public enum SyncMode { Observers, Owner } + + // SyncDirection decides if a component is synced from: + // * server to all clients + // * owner client, to server, to all other clients + // + // naming: 'ClientToServer' etc. instead of 'ClientAuthority', because + // that wouldn't be accurate. server's OnDeserialize can still validate + // client data before applying. it's really about direction, not authority. + public enum SyncDirection { ServerToClient, ClientToServer } + + /// Base class for networked components. + // [RequireComponent(typeof(NetworkIdentity))] disabled to allow child NetworkBehaviours + [AddComponentMenu("")] + [HelpURL("https://mirror-networking.gitbook.io/docs/guides/networkbehaviour")] + public abstract class NetworkBehaviour : MonoBehaviour + { + /// Sync direction for OnSerialize. ServerToClient by default. ClientToServer for client authority. + [Tooltip("Server Authority calls OnSerialize on the server and syncs it to clients.\n\nClient Authority calls OnSerialize on the owning client, syncs it to server, which then broadcasts it to all other clients.\n\nUse server authority for cheat safety.")] + [HideInInspector] public SyncDirection syncDirection = SyncDirection.ServerToClient; + + /// sync mode for OnSerialize + // hidden because NetworkBehaviourInspector shows it only if has OnSerialize. + [Tooltip("By default synced data is sent from the server to all Observers of the object.\nChange this to Owner to only have the server update the client that has ownership authority for this object")] + [HideInInspector] public SyncMode syncMode = SyncMode.Observers; + + /// sync interval for OnSerialize (in seconds) + // hidden because NetworkBehaviourInspector shows it only if has OnSerialize. + // [0,2] should be enough. anything >2s is too laggy anyway. + // + // NetworkServer & NetworkClient broadcast() are behind a sendInterval timer now. + // it makes sense to keep every component's syncInterval setting at '0' by default. + // otherwise, the overlapping timers could introduce unexpected latency. + // careful: default of '0.1' may + [Tooltip("Time in seconds until next change is synchronized to the client. '0' means send immediately if changed. '0.5' means only send changes every 500ms.\n(This is for state synchronization like SyncVars, SyncLists, OnSerialize. Not for Cmds, Rpcs, etc.)")] + [Range(0, 2)] + [HideInInspector] public float syncInterval = 0; + internal double lastSyncTime; + + /// True if this object is on the server and has been spawned. + // This is different from NetworkServer.active, which is true if the + // server itself is active rather than this object being active. + public bool isServer => netIdentity.isServer; + + /// True if this object is on the client and has been spawned by the server. + public bool isClient => netIdentity.isClient; + + /// True if this object is the the client's own local player. + public bool isLocalPlayer => netIdentity.isLocalPlayer; + + /// True if this object is on the server-only, not host. + public bool isServerOnly => netIdentity.isServerOnly; + + /// True if this object is on the client-only, not host. + public bool isClientOnly => netIdentity.isClientOnly; + + /// isOwned is true on the client if this NetworkIdentity is one of the .owned entities of our connection on the server. + // for example: main player & pets are owned. monsters & npcs aren't. + public bool isOwned => netIdentity.isOwned; + + // Deprecated 2022-10-13 + [Obsolete(".hasAuthority was renamed to .isOwned. This is easier to understand and prepares for SyncDirection, where there is a difference betwen isOwned and authority.")] + public bool hasAuthority => isOwned; + + /// authority is true if we are allowed to modify this component's state. On server, it's true if SyncDirection is ServerToClient. On client, it's true if SyncDirection is ClientToServer and(!) if this object is owned by the client. + // on the client: if owned and if clientAuthority sync direction + // on the server: if serverAuthority sync direction + // + // for example, NetworkTransform: + // client may modify position if ClientAuthority mode and owned + // server may modify position only if server authority + // + // note that in original Mirror, hasAuthority only meant 'isOwned'. + // there was no syncDirection to check. + // + // also note that this is a per-NetworkBehaviour flag. + // another component may not be client authoritative, etc. + public bool authority => + isClient + ? syncDirection == SyncDirection.ClientToServer && isOwned + : syncDirection == SyncDirection.ServerToClient; + + /// The unique network Id of this object (unique at runtime). + public uint netId => netIdentity.netId; + + /// Client's network connection to the server. This is only valid for player objects on the client. + // TODO change to NetworkConnectionToServer, but might cause some breaking + public NetworkConnection connectionToServer => netIdentity.connectionToServer; + + /// Server's network connection to the client. This is only valid for player objects on the server. + public NetworkConnectionToClient connectionToClient => netIdentity.connectionToClient; + + // SyncLists, SyncSets, etc. + protected readonly List syncObjects = new List(); + + // NetworkBehaviourInspector needs to know if we have SyncObjects + internal bool HasSyncObjects() => syncObjects.Count > 0; + + // NetworkIdentity based values set from NetworkIdentity.Awake(), + // which is way more simple and way faster than trying to figure out + // component index from in here by searching all NetworkComponents. + + /// Returns the NetworkIdentity of this object + public NetworkIdentity netIdentity { get; internal set; } + + /// Returns the index of the component on this object + public byte ComponentIndex { get; internal set; } + + // to avoid fully serializing entities every time, we have two options: + // * run a delta compression algorithm + // -> for fixed size types this is as easy as varint(b-a) for all + // -> for dynamically sized types like strings this is not easy. + // algorithms need to detect inserts/deletions, i.e. Myers Diff. + // those are very cpu intensive and barely fast enough for large + // scale multiplayer games (in Unity) + // * or we use dirty bits as meta data about which fields have changed + // -> spares us from running delta algorithms + // -> still supports dynamically sized types + // + // 64 bit mask, tracking up to 64 SyncVars. + protected ulong syncVarDirtyBits { get; private set; } + // 64 bit mask, tracking up to 64 sync collections (internal for tests). + // internal for tests, field for faster access (instead of property) + // TODO 64 SyncLists are too much. consider smaller mask later. + internal ulong syncObjectDirtyBits; + + // Weaver replaces '[SyncVar] int health' with 'Networkhealth' property. + // setter calls the hook if value changed. + // if we then modify the [SyncVar] from inside the setter, + // the setter would call the hook and we deadlock. + // hook guard prevents that. + ulong syncVarHookGuard; + + // USED BY WEAVER to set syncvars in host mode without deadlocking + protected bool GetSyncVarHookGuard(ulong dirtyBit) => + (syncVarHookGuard & dirtyBit) != 0UL; + + // USED BY WEAVER to set syncvars in host mode without deadlocking + protected void SetSyncVarHookGuard(ulong dirtyBit, bool value) + { + // set the bit + if (value) + syncVarHookGuard |= dirtyBit; + // clear the bit + else + syncVarHookGuard &= ~dirtyBit; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void SetSyncObjectDirtyBit(ulong dirtyBit) + { + syncObjectDirtyBits |= dirtyBit; + } + + /// Set as dirty so that it's synced to clients again. + // these are masks, not bit numbers, ie. 110011b not '2' for 2nd bit. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetSyncVarDirtyBit(ulong dirtyBit) + { + syncVarDirtyBits |= dirtyBit; + } + + /// Set as dirty to trigger OnSerialize & send. Dirty bits are cleared after the send. + // previously one had to use SetSyncVarDirtyBit(1), which is confusing. + // simply reuse SetSyncVarDirtyBit for now. + // instead of adding another field. + // syncVarDirtyBits does trigger OnSerialize as well. + // + // it's important to set _all_ bits as dirty. + // for example, server needs to broadcast ClientToServer components. + // if we only set the first bit, only that SyncVar would be broadcast. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetDirty() => SetSyncVarDirtyBit(ulong.MaxValue); + + // true if syncInterval elapsed and any SyncVar or SyncObject is dirty + // OR both bitmasks. != 0 if either was dirty. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsDirty() => + // check bits first. this is basically free. + (syncVarDirtyBits | syncObjectDirtyBits) != 0UL && + // only check time if bits were dirty. this is more expensive. + NetworkTime.localTime - lastSyncTime >= syncInterval; + + /// Clears all the dirty bits that were set by SetSyncVarDirtyBit() (formally SetDirtyBits) + // automatically invoked when an update is sent for this object, but can + // be called manually as well. + public void ClearAllDirtyBits() + { + lastSyncTime = NetworkTime.localTime; + syncVarDirtyBits = 0L; + syncObjectDirtyBits = 0L; + + // clear all unsynchronized changes in syncobjects + // (Linq allocates, use for instead) + for (int i = 0; i < syncObjects.Count; ++i) + { + syncObjects[i].ClearChanges(); + } + } + + // this gets called in the constructor by the weaver + // for every SyncObject in the component (e.g. SyncLists). + // We collect all of them and we synchronize them with OnSerialize/OnDeserialize + protected void InitSyncObject(SyncObject syncObject) + { + if (syncObject == null) + { + Debug.LogError("Uninitialized SyncObject. Manually call the constructor on your SyncList, SyncSet, SyncDictionary or SyncField"); + return; + } + + // add it, remember the index in list (if Count=0, index=0 etc.) + int index = syncObjects.Count; + syncObjects.Add(syncObject); + + // OnDirty needs to set nth bit in our dirty mask + ulong nthBit = 1UL << index; + syncObject.OnDirty = () => SetSyncObjectDirtyBit(nthBit); + + // who is allowed to modify SyncList/SyncSet/etc.: + // on client: only if owned ClientToserver + // on server: only if ServerToClient. + // but also for initial state when spawning. + // need to set a lambda because 'isClient' isn't available in + // InitSyncObject yet, which is called from the constructor. + syncObject.IsWritable = () => + { + // carefully check each mode separately to ensure correct results. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3342 + + // normally we would check isServer / isClient here. + // users may add to SyncLists before the object was spawned. + // isServer / isClient would still be false. + // so we need to check NetworkServer/Client.active here instead. + + // host mode: any ServerToClient and any local client owned + if (NetworkServer.active && NetworkClient.active) + return syncDirection == SyncDirection.ServerToClient || isOwned; + + // server only: any ServerToClient + if (NetworkServer.active) + return syncDirection == SyncDirection.ServerToClient; + + // client only: only ClientToServer and owned + if (NetworkClient.active) + { + // spawned: only ClientToServer and owned + if (netId != 0) return syncDirection == SyncDirection.ClientToServer && isOwned; + + // not spawned (character selection previews, etc.): always allow + // fixes https://github.com/MirrorNetworking/Mirror/issues/3343 + return true; + } + + // undefined behaviour should throw to make it very obvious + throw new Exception("InitSyncObject: IsWritable: neither NetworkServer nor NetworkClient are active."); + }; + + // when do we record changes: + // on client: only if owned ClientToServer + // on server: only if we have observers. + // prevents ever growing .changes lists: + // if a monster has no observers but we keep modifing a SyncObject, + // then the changes would never be flushed and keep growing, + // because OnSerialize isn't called without observers. + syncObject.IsRecording = () => + { + // carefully check each mode separately to ensure correct results. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3342 + + // host mode: only if observed + if (isServer && isClient) return netIdentity.observers.Count > 0; + + // server only: only if observed + if (isServer) return netIdentity.observers.Count > 0; + + // client only: only ClientToServer and owned + if (isClient) return syncDirection == SyncDirection.ClientToServer && isOwned; + + // users may add to SyncLists before the object was spawned. + // isServer / isClient would still be false. + // in that case, allow modifying but don't record changes yet. + return false; + }; + } + + protected virtual void OnValidate() + { + // we now allow child NetworkBehaviours. + // we can not [RequireComponent(typeof(NetworkIdentity))] anymore. + // instead, we need to ensure a NetworkIdentity is somewhere in the + // parents. + // only run this in Editor. don't add more runtime overhead. + + // GetComponentInParent(includeInactive) is needed because Prefabs are not + // considered active, so this check requires to scan inactive. +#if UNITY_EDITOR +#if UNITY_2021_3_OR_NEWER // 2021 has GetComponentInParents(active) + if (GetComponent() == null && + GetComponentInParent(true) == null) + { + Debug.LogError($"{GetType()} on {name} requires a NetworkIdentity. Please add a NetworkIdentity component to {name} or it's parents."); + } +#elif UNITY_2020_3_OR_NEWER // 2020 only has GetComponentsInParents(active), we can use this too + NetworkIdentity[] parentsIds = GetComponentsInParent(true); + int parentIdsCount = parentsIds != null ? parentsIds.Length : 0; + if (GetComponent() == null && parentIdsCount == 0) + { + Debug.LogError($"{GetType()} on {name} requires a NetworkIdentity. Please add a NetworkIdentity component to {name} or it's parents."); + } +#endif +#endif + } + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + protected void SendCommandInternal(string functionFullName, int functionHashCode, NetworkWriter writer, int channelId, bool requiresAuthority = true) + { + // this was in Weaver before + // NOTE: we could remove this later to allow calling Cmds on Server + // to avoid Wrapper functions. a lot of people requested this. + if (!NetworkClient.active) + { + Debug.LogError($"Command {functionFullName} called on {name} without an active client.", gameObject); + return; + } + + // previously we used NetworkClient.readyConnection. + // now we check .ready separately. + if (!NetworkClient.ready) + { + // Unreliable Cmds from NetworkTransform may be generated, + // or client may have been set NotReady intentionally, so + // only warn if on the reliable channel. + if (channelId == Channels.Reliable) + Debug.LogWarning($"Command {functionFullName} called on {name} while NetworkClient is not ready.\nThis may be ignored if client intentionally set NotReady.", gameObject); + return; + } + + // local players can always send commands, regardless of authority, + // other objects must have authority. + if (!(!requiresAuthority || isLocalPlayer || isOwned)) + { + Debug.LogWarning($"Command {functionFullName} called on {name} without authority.", gameObject); + return; + } + + // IMPORTANT: can't use .connectionToServer here because calling + // a command on other objects is allowed if requireAuthority is + // false. other objects don't have a .connectionToServer. + // => so we always need to use NetworkClient.connection instead. + // => see also: https://github.com/vis2k/Mirror/issues/2629 + if (NetworkClient.connection == null) + { + Debug.LogError($"Command {functionFullName} called on {name} with no client running.", gameObject); + return; + } + + // construct the message + CommandMessage message = new CommandMessage + { + netId = netId, + componentIndex = ComponentIndex, + // type+func so Inventory.RpcUse != Equipment.RpcUse + functionHash = (ushort)functionHashCode, + // segment to avoid reader allocations + payload = writer.ToArraySegment() + }; + + // IMPORTANT: can't use .connectionToServer here because calling + // a command on other objects is allowed if requireAuthority is + // false. other objects don't have a .connectionToServer. + // => so we always need to use NetworkClient.connection instead. + // => see also: https://github.com/vis2k/Mirror/issues/2629 + // This bypasses the null check in NetworkClient.Send but we have + // a null check above with a detailed error log. + NetworkClient.connection.Send(message, channelId); + } + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + protected void SendRPCInternal(string functionFullName, int functionHashCode, NetworkWriter writer, int channelId, bool includeOwner) + { + // this was in Weaver before + if (!NetworkServer.active) + { + Debug.LogError($"RPC Function {functionFullName} called without an active server.", gameObject); + return; + } + + // This cannot use NetworkServer.active, as that is not specific to this object. + if (!isServer) + { + Debug.LogWarning($"ClientRpc {functionFullName} called on un-spawned object: {name}", gameObject); + return; + } + + // construct the message + RpcMessage message = new RpcMessage + { + netId = netId, + componentIndex = ComponentIndex, + // type+func so Inventory.RpcUse != Equipment.RpcUse + functionHash = (ushort)functionHashCode, + // segment to avoid reader allocations + payload = writer.ToArraySegment() + }; + + // serialize it to each ready observer's connection's rpc buffer. + // send them all at once, instead of sending one message per rpc. + // NetworkServer.SendToReadyObservers(netIdentity, message, includeOwner, channelId); + + // safety check used to be in SendToReadyObservers. keep it for now. + if (netIdentity.observers == null || netIdentity.observers.Count == 0) + return; + + // serialize the message only once + using (NetworkWriterPooled serialized = NetworkWriterPool.Get()) + { + serialized.Write(message); + + // send to every observer. + // batching buffers this automatically. + foreach (NetworkConnectionToClient conn in netIdentity.observers.Values) + { + bool isOwner = conn == netIdentity.connectionToClient; + if ((!isOwner || includeOwner) && conn.isReady) + { + conn.Send(message, channelId); + } + } + } + } + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + protected void SendTargetRPCInternal(NetworkConnection conn, string functionFullName, int functionHashCode, NetworkWriter writer, int channelId) + { + if (!NetworkServer.active) + { + Debug.LogError($"TargetRPC {functionFullName} was called on {name} when server not active.", gameObject); + return; + } + + if (!isServer) + { + Debug.LogWarning($"TargetRpc {functionFullName} called on {name} but that object has not been spawned or has been unspawned.", gameObject); + return; + } + + // connection parameter is optional. assign if null. + if (conn is null) + { + conn = connectionToClient; + } + + // if still null + if (conn is null) + { + Debug.LogError($"TargetRPC {functionFullName} can't be sent because it was given a null connection. Make sure {name} is owned by a connection, or if you pass a connection manually then make sure it's not null. For example, TargetRpcs can be called on Player/Pet which are owned by a connection. However, they can not be called on Monsters/Npcs which don't have an owner connection.", gameObject); + return; + } + + // TODO change conn type to NetworkConnectionToClient to begin with. + if (!(conn is NetworkConnectionToClient connToClient)) + { + Debug.LogError($"TargetRPC {functionFullName} called on {name} requires a NetworkConnectionToClient but was given {conn.GetType().Name}", gameObject); + return; + } + + // construct the message + RpcMessage message = new RpcMessage + { + netId = netId, + componentIndex = ComponentIndex, + // type+func so Inventory.RpcUse != Equipment.RpcUse + functionHash = (ushort)functionHashCode, + // segment to avoid reader allocations + payload = writer.ToArraySegment() + }; + + // send it to the connection. + // batching buffers this automatically. + conn.Send(message, channelId); + } + + // move the [SyncVar] generated property's .set into C# to avoid much IL + // + // public int health = 42; + // + // public int Networkhealth + // { + // get + // { + // return health; + // } + // [param: In] + // set + // { + // if (!NetworkBehaviour.SyncVarEqual(value, ref health)) + // { + // int oldValue = health; + // SetSyncVar(value, ref health, 1uL); + // if (NetworkServer.activeHost && !GetSyncVarHookGuard(1uL)) + // { + // SetSyncVarHookGuard(1uL, value: true); + // OnChanged(oldValue, value); + // SetSyncVarHookGuard(1uL, value: false); + // } + // } + // } + // } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GeneratedSyncVarSetter(T value, ref T field, ulong dirtyBit, Action OnChanged) + { + if (!SyncVarEqual(value, ref field)) + { + T oldValue = field; + SetSyncVar(value, ref field, dirtyBit); + + // call hook (if any) + if (OnChanged != null) + { + // in host mode, setting a SyncVar calls the hook directly. + // in client-only mode, OnDeserialize would call it. + // we use hook guard to protect against deadlock where hook + // changes syncvar, calling hook again. + if (NetworkServer.activeHost && !GetSyncVarHookGuard(dirtyBit)) + { + SetSyncVarHookGuard(dirtyBit, true); + OnChanged(oldValue, value); + SetSyncVarHookGuard(dirtyBit, false); + } + } + } + } + + // GameObject needs custom handling for persistence via netId. + // has one extra parameter. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GeneratedSyncVarSetter_GameObject(GameObject value, ref GameObject field, ulong dirtyBit, Action OnChanged, ref uint netIdField) + { + if (!SyncVarGameObjectEqual(value, netIdField)) + { + GameObject oldValue = field; + SetSyncVarGameObject(value, ref field, dirtyBit, ref netIdField); + + // call hook (if any) + if (OnChanged != null) + { + // in host mode, setting a SyncVar calls the hook directly. + // in client-only mode, OnDeserialize would call it. + // we use hook guard to protect against deadlock where hook + // changes syncvar, calling hook again. + if (NetworkServer.activeHost && !GetSyncVarHookGuard(dirtyBit)) + { + SetSyncVarHookGuard(dirtyBit, true); + OnChanged(oldValue, value); + SetSyncVarHookGuard(dirtyBit, false); + } + } + } + } + + // NetworkIdentity needs custom handling for persistence via netId. + // has one extra parameter. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GeneratedSyncVarSetter_NetworkIdentity(NetworkIdentity value, ref NetworkIdentity field, ulong dirtyBit, Action OnChanged, ref uint netIdField) + { + if (!SyncVarNetworkIdentityEqual(value, netIdField)) + { + NetworkIdentity oldValue = field; + SetSyncVarNetworkIdentity(value, ref field, dirtyBit, ref netIdField); + + // call hook (if any) + if (OnChanged != null) + { + // in host mode, setting a SyncVar calls the hook directly. + // in client-only mode, OnDeserialize would call it. + // we use hook guard to protect against deadlock where hook + // changes syncvar, calling hook again. + if (NetworkServer.activeHost && !GetSyncVarHookGuard(dirtyBit)) + { + SetSyncVarHookGuard(dirtyBit, true); + OnChanged(oldValue, value); + SetSyncVarHookGuard(dirtyBit, false); + } + } + } + } + + // NetworkBehaviour needs custom handling for persistence via netId. + // has one extra parameter. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void GeneratedSyncVarSetter_NetworkBehaviour(T value, ref T field, ulong dirtyBit, Action OnChanged, ref NetworkBehaviourSyncVar netIdField) + where T : NetworkBehaviour + { + if (!SyncVarNetworkBehaviourEqual(value, netIdField)) + { + T oldValue = field; + SetSyncVarNetworkBehaviour(value, ref field, dirtyBit, ref netIdField); + + // call hook (if any) + if (OnChanged != null) + { + // in host mode, setting a SyncVar calls the hook directly. + // in client-only mode, OnDeserialize would call it. + // we use hook guard to protect against deadlock where hook + // changes syncvar, calling hook again. + if (NetworkServer.activeHost && !GetSyncVarHookGuard(dirtyBit)) + { + SetSyncVarHookGuard(dirtyBit, true); + OnChanged(oldValue, value); + SetSyncVarHookGuard(dirtyBit, false); + } + } + } + } + + // helper function for [SyncVar] GameObjects. + // needs to be public so that tests & NetworkBehaviours from other + // assemblies both find it + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool SyncVarGameObjectEqual(GameObject newGameObject, uint netIdField) + { + uint newNetId = 0; + if (newGameObject != null) + { + if (newGameObject.TryGetComponent(out NetworkIdentity identity)) + { + newNetId = identity.netId; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarGameObject GameObject {newGameObject} has a zero netId. Maybe it is not spawned yet?"); + } + } + } + + return newNetId == netIdField; + } + + // helper function for [SyncVar] GameObjects. + // dirtyBit is a mask like 00010 + protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, ulong dirtyBit, ref uint netIdField) + { + if (GetSyncVarHookGuard(dirtyBit)) + return; + + uint newNetId = 0; + if (newGameObject != null) + { + if (newGameObject.TryGetComponent(out NetworkIdentity identity)) + { + newNetId = identity.netId; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarGameObject GameObject {newGameObject} has a zero netId. Maybe it is not spawned yet?"); + } + } + } + + //Debug.Log($"SetSyncVar GameObject {GetType().Name} bit:{dirtyBit} netfieldId:{netIdField} -> {newNetId}"); + SetSyncVarDirtyBit(dirtyBit); + // assign new one on the server, and in case we ever need it on client too + gameObjectField = newGameObject; + netIdField = newNetId; + } + + // helper function for [SyncVar] GameObjects. + // -> ref GameObject as second argument makes OnDeserialize processing easier + protected GameObject GetSyncVarGameObject(uint netId, ref GameObject gameObjectField) + { + // server always uses the field + // if neither, fallback to original field + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3447 + if (isServer || !isClient) + { + return gameObjectField; + } + + // client always looks up based on netId because objects might get in and out of range + // over and over again, which shouldn't null them forever + if (NetworkClient.spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null) + return gameObjectField = identity.gameObject; + return null; + } + + // helper function for [SyncVar] NetworkIdentities. + // needs to be public so that tests & NetworkBehaviours from other + // assemblies both find it + [EditorBrowsable(EditorBrowsableState.Never)] + public static bool SyncVarNetworkIdentityEqual(NetworkIdentity newIdentity, uint netIdField) + { + uint newNetId = 0; + if (newIdentity != null) + { + newNetId = newIdentity.netId; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newIdentity} has a zero netId. Maybe it is not spawned yet?"); + } + } + + // netId changed? + return newNetId == netIdField; + } + + // move the [SyncVar] generated OnDeserialize C# to avoid much IL. + // + // before: + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // int num = health; + // Networkhealth = reader.ReadInt(); + // if (!NetworkBehaviour.SyncVarEqual(num, ref health)) + // { + // OnChanged(num, health); + // } + // return; + // } + // long num2 = (long)reader.ReadULong(); + // if ((num2 & 1L) != 0L) + // { + // int num3 = health; + // Networkhealth = reader.ReadInt(); + // if (!NetworkBehaviour.SyncVarEqual(num3, ref health)) + // { + // OnChanged(num3, health); + // } + // } + // } + // + // after: + // + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // GeneratedSyncVarDeserialize(reader, ref health, null, reader.ReadInt()); + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // GeneratedSyncVarDeserialize(reader, ref health, null, reader.ReadInt()); + // } + // } + public void GeneratedSyncVarDeserialize(ref T field, Action OnChanged, T value) + { + T previous = field; + field = value; + + // any hook? then call if changed. + if (OnChanged != null && !SyncVarEqual(previous, ref field)) + { + OnChanged(previous, field); + } + } + + // move the [SyncVar] generated OnDeserialize C# to avoid much IL. + // + // before: + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // uint __targetNetId = ___targetNetId; + // GameObject networktarget = Networktarget; + // ___targetNetId = reader.ReadUInt(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId, ref ___targetNetId)) + // { + // OnChangedNB(networktarget, Networktarget); + // } + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // uint __targetNetId2 = ___targetNetId; + // GameObject networktarget2 = Networktarget; + // ___targetNetId = reader.ReadUInt(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId2, ref ___targetNetId)) + // { + // OnChangedNB(networktarget2, Networktarget); + // } + // } + // } + // + // after: + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // GeneratedSyncVarDeserialize_GameObject(reader, ref target, OnChangedNB, ref ___targetNetId); + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // GeneratedSyncVarDeserialize_GameObject(reader, ref target, OnChangedNB, ref ___targetNetId); + // } + // } + public void GeneratedSyncVarDeserialize_GameObject(ref GameObject field, Action OnChanged, NetworkReader reader, ref uint netIdField) + { + uint previousNetId = netIdField; + GameObject previousGameObject = field; + netIdField = reader.ReadUInt(); + + // get the new GameObject now that netId field is set + field = GetSyncVarGameObject(netIdField, ref field); + + // any hook? then call if changed. + if (OnChanged != null && !SyncVarEqual(previousNetId, ref netIdField)) + { + OnChanged(previousGameObject, field); + } + } + + // move the [SyncVar] generated OnDeserialize C# to avoid much IL. + // + // before: + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // uint __targetNetId = ___targetNetId; + // NetworkIdentity networktarget = Networktarget; + // ___targetNetId = reader.ReadUInt(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId, ref ___targetNetId)) + // { + // OnChangedNI(networktarget, Networktarget); + // } + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // uint __targetNetId2 = ___targetNetId; + // NetworkIdentity networktarget2 = Networktarget; + // ___targetNetId = reader.ReadUInt(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId2, ref ___targetNetId)) + // { + // OnChangedNI(networktarget2, Networktarget); + // } + // } + // } + // + // after: + // + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // GeneratedSyncVarDeserialize_NetworkIdentity(reader, ref target, OnChangedNI, ref ___targetNetId); + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // GeneratedSyncVarDeserialize_NetworkIdentity(reader, ref target, OnChangedNI, ref ___targetNetId); + // } + // } + public void GeneratedSyncVarDeserialize_NetworkIdentity(ref NetworkIdentity field, Action OnChanged, NetworkReader reader, ref uint netIdField) + { + uint previousNetId = netIdField; + NetworkIdentity previousIdentity = field; + netIdField = reader.ReadUInt(); + + // get the new NetworkIdentity now that netId field is set + field = GetSyncVarNetworkIdentity(netIdField, ref field); + + // any hook? then call if changed. + if (OnChanged != null && !SyncVarEqual(previousNetId, ref netIdField)) + { + OnChanged(previousIdentity, field); + } + } + + // move the [SyncVar] generated OnDeserialize C# to avoid much IL. + // + // before: + // + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // NetworkBehaviourSyncVar __targetNetId = ___targetNetId; + // Tank networktarget = Networktarget; + // ___targetNetId = reader.ReadNetworkBehaviourSyncVar(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId, ref ___targetNetId)) + // { + // OnChangedNB(networktarget, Networktarget); + // } + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // NetworkBehaviourSyncVar __targetNetId2 = ___targetNetId; + // Tank networktarget2 = Networktarget; + // ___targetNetId = reader.ReadNetworkBehaviourSyncVar(); + // if (!NetworkBehaviour.SyncVarEqual(__targetNetId2, ref ___targetNetId)) + // { + // OnChangedNB(networktarget2, Networktarget); + // } + // } + // } + // + // after: + // + // public override void DeserializeSyncVars(NetworkReader reader, bool initialState) + // { + // base.DeserializeSyncVars(reader, initialState); + // if (initialState) + // { + // GeneratedSyncVarDeserialize_NetworkBehaviour(reader, ref target, OnChangedNB, ref ___targetNetId); + // return; + // } + // long num = (long)reader.ReadULong(); + // if ((num & 1L) != 0L) + // { + // GeneratedSyncVarDeserialize_NetworkBehaviour(reader, ref target, OnChangedNB, ref ___targetNetId); + // } + // } + public void GeneratedSyncVarDeserialize_NetworkBehaviour(ref T field, Action OnChanged, NetworkReader reader, ref NetworkBehaviourSyncVar netIdField) + where T : NetworkBehaviour + { + NetworkBehaviourSyncVar previousNetId = netIdField; + T previousBehaviour = field; + netIdField = reader.ReadNetworkBehaviourSyncVar(); + + // get the new NetworkBehaviour now that netId field is set + field = GetSyncVarNetworkBehaviour(netIdField, ref field); + + // any hook? then call if changed. + if (OnChanged != null && !SyncVarEqual(previousNetId, ref netIdField)) + { + OnChanged(previousBehaviour, field); + } + } + + // helper function for [SyncVar] NetworkIdentities. + // dirtyBit is a mask like 00010 + protected void SetSyncVarNetworkIdentity(NetworkIdentity newIdentity, ref NetworkIdentity identityField, ulong dirtyBit, ref uint netIdField) + { + if (GetSyncVarHookGuard(dirtyBit)) + return; + + uint newNetId = 0; + if (newIdentity != null) + { + newNetId = newIdentity.netId; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newIdentity} has a zero netId. Maybe it is not spawned yet?"); + } + } + + //Debug.Log($"SetSyncVarNetworkIdentity NetworkIdentity {GetType().Name} bit:{dirtyBit} netIdField:{netIdField} -> {newNetId}"); + SetSyncVarDirtyBit(dirtyBit); + netIdField = newNetId; + // assign new one on the server, and in case we ever need it on client too + identityField = newIdentity; + } + + // helper function for [SyncVar] NetworkIdentities. + // -> ref GameObject as second argument makes OnDeserialize processing easier + protected NetworkIdentity GetSyncVarNetworkIdentity(uint netId, ref NetworkIdentity identityField) + { + // server always uses the field + // if neither, fallback to original field + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3447 + if (isServer || !isClient) + { + return identityField; + } + + // client always looks up based on netId because objects might get in and out of range + // over and over again, which shouldn't null them forever + NetworkClient.spawned.TryGetValue(netId, out identityField); + return identityField; + } + + protected static bool SyncVarNetworkBehaviourEqual(T newBehaviour, NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour + { + uint newNetId = 0; + byte newComponentIndex = 0; + if (newBehaviour != null) + { + newNetId = newBehaviour.netId; + newComponentIndex = newBehaviour.ComponentIndex; + if (newNetId == 0) + { + Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newBehaviour} has a zero netId. Maybe it is not spawned yet?"); + } + } + + // netId changed? + return syncField.Equals(newNetId, newComponentIndex); + } + + // helper function for [SyncVar] NetworkIdentities. + // dirtyBit is a mask like 00010 + protected void SetSyncVarNetworkBehaviour(T newBehaviour, ref T behaviourField, ulong dirtyBit, ref NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour + { + if (GetSyncVarHookGuard(dirtyBit)) + return; + + uint newNetId = 0; + byte componentIndex = 0; + if (newBehaviour != null) + { + newNetId = newBehaviour.netId; + componentIndex = newBehaviour.ComponentIndex; + if (newNetId == 0) + { + Debug.LogWarning($"{nameof(SetSyncVarNetworkBehaviour)} NetworkIdentity {newBehaviour} has a zero netId. Maybe it is not spawned yet?"); + } + } + + syncField = new NetworkBehaviourSyncVar(newNetId, componentIndex); + + SetSyncVarDirtyBit(dirtyBit); + + // assign new one on the server, and in case we ever need it on client too + behaviourField = newBehaviour; + + // Debug.Log($"SetSyncVarNetworkBehaviour NetworkIdentity {GetType().Name} bit [{dirtyBit}] netIdField:{oldField}->{syncField}"); + } + + // helper function for [SyncVar] NetworkIdentities. + // -> ref GameObject as second argument makes OnDeserialize processing easier + protected T GetSyncVarNetworkBehaviour(NetworkBehaviourSyncVar syncNetBehaviour, ref T behaviourField) where T : NetworkBehaviour + { + // server always uses the field + // if neither, fallback to original field + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3447 + if (isServer || !isClient) + { + return behaviourField; + } + + // client always looks up based on netId because objects might get in and out of range + // over and over again, which shouldn't null them forever + if (!NetworkClient.spawned.TryGetValue(syncNetBehaviour.netId, out NetworkIdentity identity)) + { + return null; + } + + behaviourField = identity.NetworkBehaviours[syncNetBehaviour.componentIndex] as T; + return behaviourField; + } + + protected static bool SyncVarEqual(T value, ref T fieldValue) + { + // newly initialized or changed value? + // value.Equals(fieldValue) allocates without 'where T : IEquatable' + // seems like we use EqualityComparer to avoid allocations, + // because not all SyncVars are IEquatable + return EqualityComparer.Default.Equals(value, fieldValue); + } + + // dirtyBit is a mask like 00010 + protected void SetSyncVar(T value, ref T fieldValue, ulong dirtyBit) + { + //Debug.Log($"SetSyncVar {GetType().Name} bit:{dirtyBit} fieldValue:{value}"); + SetSyncVarDirtyBit(dirtyBit); + fieldValue = value; + } + + /// Override to do custom serialization (instead of SyncVars/SyncLists). Use OnDeserialize too. + // if a class has syncvars, then OnSerialize/OnDeserialize are added + // automatically. + // + // initialState is true for full spawns, false for delta syncs. + // note: SyncVar hooks are only called when inital=false + public virtual void OnSerialize(NetworkWriter writer, bool initialState) + { + SerializeSyncObjects(writer, initialState); + SerializeSyncVars(writer, initialState); + } + + /// Override to do custom deserialization (instead of SyncVars/SyncLists). Use OnSerialize too. + public virtual void OnDeserialize(NetworkReader reader, bool initialState) + { + DeserializeSyncObjects(reader, initialState); + DeserializeSyncVars(reader, initialState); + } + + void SerializeSyncObjects(NetworkWriter writer, bool initialState) + { + // if initialState: write all SyncVars. + // otherwise write dirtyBits+dirty SyncVars + if (initialState) + SerializeObjectsAll(writer); + else + SerializeObjectsDelta(writer); + } + + void DeserializeSyncObjects(NetworkReader reader, bool initialState) + { + if (initialState) + { + DeserializeObjectsAll(reader); + } + else + { + DeserializeObjectsDelta(reader); + } + } + + // USED BY WEAVER + protected virtual void SerializeSyncVars(NetworkWriter writer, bool initialState) + { + // SyncVar are written here in subclass + + // if initialState + // write all SyncVars + // else + // write syncVarDirtyBits + // write dirty SyncVars + } + + // USED BY WEAVER + protected virtual void DeserializeSyncVars(NetworkReader reader, bool initialState) + { + // SyncVars are read here in subclass + + // if initialState + // read all SyncVars + // else + // read syncVarDirtyBits + // read dirty SyncVars + } + + public void SerializeObjectsAll(NetworkWriter writer) + { + for (int i = 0; i < syncObjects.Count; i++) + { + SyncObject syncObject = syncObjects[i]; + syncObject.OnSerializeAll(writer); + } + } + + public void SerializeObjectsDelta(NetworkWriter writer) + { + // write the mask + writer.WriteULong(syncObjectDirtyBits); + + // serializable objects, such as synclists + for (int i = 0; i < syncObjects.Count; i++) + { + // check dirty mask at nth bit + SyncObject syncObject = syncObjects[i]; + if ((syncObjectDirtyBits & (1UL << i)) != 0) + { + syncObject.OnSerializeDelta(writer); + } + } + } + + internal void DeserializeObjectsAll(NetworkReader reader) + { + for (int i = 0; i < syncObjects.Count; i++) + { + SyncObject syncObject = syncObjects[i]; + syncObject.OnDeserializeAll(reader); + } + } + + internal void DeserializeObjectsDelta(NetworkReader reader) + { + ulong dirty = reader.ReadULong(); + for (int i = 0; i < syncObjects.Count; i++) + { + // check dirty mask at nth bit + SyncObject syncObject = syncObjects[i]; + if ((dirty & (1UL << i)) != 0) + { + syncObject.OnDeserializeDelta(reader); + } + } + } + + // safely serialize each component in a way that one reading too much or + // too few bytes will show obvious, easy to resolve error messages. + // + // prevents the original UNET bug which started Mirror: + // https://github.com/vis2k/Mirror/issues/2617 + // where one component would read too much, and then all following reads + // on other entities would be mismatched, causing the weirdest errors. + // + // reads <> for 100% safety. + internal void Serialize(NetworkWriter writer, bool initialState) + { + // reserve length header to ensure the correct amount will be read. + // originally we used a 4 byte header (too bandwidth heavy). + // instead, let's "& 0xFF" the size. + // + // this is cleaner than barriers at the end of payload, because: + // - ensures the correct safety is read _before_ payload. + // - it's quite hard to break the check. + // a component would need to read/write the intented amount + // multiplied by 255 in order to miss the check. + // with barriers, reading 1 byte too much may still succeed if the + // next component's first byte matches the expected barrier. + // - we can still attempt to correct the invalid position via the + // safety length byte (we know that one is correct). + // + // it's just overall cleaner, and still low on bandwidth. + + // write placeholder length byte + // (jumping back later is WAY faster than allocating a temporary + // writer for the payload, then writing payload.size, payload) + int headerPosition = writer.Position; + writer.WriteByte(0); + int contentPosition = writer.Position; + + // write payload + try + { + // note this may not write anything if no syncIntervals elapsed + OnSerialize(writer, initialState); + } + catch (Exception e) + { + // show a detailed error and let the user know what went wrong + Debug.LogError($"OnSerialize failed for: object={name} component={GetType()} sceneId={netIdentity.sceneId:X}\n\n{e}"); + } + int endPosition = writer.Position; + + // fill in length hash as the last byte of the 4 byte length + writer.Position = headerPosition; + int size = endPosition - contentPosition; + byte safety = (byte)(size & 0xFF); + writer.WriteByte(safety); + writer.Position = endPosition; + + //Debug.Log($"OnSerializeSafely written for object {name} component:{GetType()} sceneId:{sceneId:X} header:{headerPosition} content:{contentPosition} end:{endPosition} contentSize:{endPosition - contentPosition}"); + } + + // correct the read size with the 1 byte length hash (by mischa). + // -> the component most likely read a few too many/few bytes. + // -> we know the correct last byte of the expected size (=the safety). + // -> attempt to reconstruct the size via safety byte. + // it will be correct unless someone wrote way way too much, + // as in > 255 bytes worth too much. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int ErrorCorrection(int size, byte safety) + { + // clear the last byte which most likely contains the error + uint cleared = (uint)size & 0xFFFFFF00; + + // insert the safety which we know to be correct + return (int)(cleared | safety); + } + + // returns false in case of errors. + // server needs to know in order to disconnect on error. + internal bool Deserialize(NetworkReader reader, bool initialState) + { + // detect errors, but attempt to correct before returning + bool result = true; + + // read 1 byte length hash safety & capture beginning for size check + byte safety = reader.ReadByte(); + int chunkStart = reader.Position; + + // call OnDeserialize and wrap it in a try-catch block so there's no + // way to mess up another component's deserialization + try + { + //Debug.Log($"OnDeserializeSafely: {name} component:{GetType()} sceneId:{sceneId:X} length:{contentSize}"); + OnDeserialize(reader, initialState); + } + catch (Exception e) + { + // show a detailed error and let the user know what went wrong + Debug.LogError($"OnDeserialize failed Exception={e.GetType()} (see below) object={name} component={GetType()} netId={netId}. Possible Reasons:\n" + + $" * Do {GetType()}'s OnSerialize and OnDeserialize calls write the same amount of data? \n" + + $" * Was there an exception in {GetType()}'s OnSerialize/OnDeserialize code?\n" + + $" * Are the server and client the exact same project?\n" + + $" * Maybe this OnDeserialize call was meant for another GameObject? The sceneIds can easily get out of sync if the Hierarchy was modified only in the client OR the server. Try rebuilding both.\n\n" + + $"Exception {e}"); + result = false; + } + + // compare bytes read with length hash + int size = reader.Position - chunkStart; + byte sizeHash = (byte)(size & 0xFF); + if (sizeHash != safety) + { + // warn the user. + Debug.LogWarning($"{name} (netId={netId}): {GetType()} OnDeserialize size mismatch. It read {size} bytes, which caused a size hash mismatch of {sizeHash:X2} vs. {safety:X2}. Make sure that OnSerialize and OnDeserialize write/read the same amount of data in all cases."); + + // attempt to fix the position, so the following components + // don't all fail. this is very likely to work, unless the user + // read more than 255 bytes too many / too few. + // + // see test: SerializationSizeMismatch. + int correctedSize = ErrorCorrection(size, safety); + reader.Position = chunkStart + correctedSize; + result = false; + } + + return result; + } + + internal void ResetSyncObjects() + { + foreach (SyncObject syncObject in syncObjects) + { + syncObject.Reset(); + } + } + + /// Like Start(), but only called on server and host. + public virtual void OnStartServer() {} + + /// Stop event, only called on server and host. + public virtual void OnStopServer() {} + + /// Like Start(), but only called on client and host. + public virtual void OnStartClient() {} + + /// Stop event, only called on client and host. + public virtual void OnStopClient() {} + + /// Like Start(), but only called on client and host for the local player object. + public virtual void OnStartLocalPlayer() {} + + /// Stop event, but only called on client and host for the local player object. + public virtual void OnStopLocalPlayer() {} + + /// Like Start(), but only called for objects the client has authority over. + public virtual void OnStartAuthority() {} + + /// Stop event, only called for objects the client has authority over. + public virtual void OnStopAuthority() {} + + // Weaver injects this into inheriting classes to return true. + // allows runtime & tests to check if a type was weaved. + [EditorBrowsable(EditorBrowsableState.Never)] + public virtual bool Weaved() => false; + } +} diff --git a/Assets/Mirror/Core/NetworkBehaviour.cs.meta b/Assets/Mirror/Core/NetworkBehaviour.cs.meta new file mode 100644 index 0000000..f0bc195 --- /dev/null +++ b/Assets/Mirror/Core/NetworkBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 655ee8cba98594f70880da5cc4dc442d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkBehaviourSyncVar.cs b/Assets/Mirror/Core/NetworkBehaviourSyncVar.cs new file mode 100644 index 0000000..e9ed726 --- /dev/null +++ b/Assets/Mirror/Core/NetworkBehaviourSyncVar.cs @@ -0,0 +1,33 @@ +using System; + +namespace Mirror +{ + // backing field for sync NetworkBehaviour + public struct NetworkBehaviourSyncVar : IEquatable + { + public uint netId; + // limited to 255 behaviours per identity + public byte componentIndex; + + public NetworkBehaviourSyncVar(uint netId, int componentIndex) : this() + { + this.netId = netId; + this.componentIndex = (byte)componentIndex; + } + + public bool Equals(NetworkBehaviourSyncVar other) + { + return other.netId == netId && other.componentIndex == componentIndex; + } + + public bool Equals(uint netId, int componentIndex) + { + return this.netId == netId && this.componentIndex == componentIndex; + } + + public override string ToString() + { + return $"[netId:{netId} compIndex:{componentIndex}]"; + } + } +} diff --git a/Assets/Mirror/Core/NetworkBehaviourSyncVar.cs.meta b/Assets/Mirror/Core/NetworkBehaviourSyncVar.cs.meta new file mode 100644 index 0000000..47e3893 --- /dev/null +++ b/Assets/Mirror/Core/NetworkBehaviourSyncVar.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b04fe7518657486089dfaf811db0b3ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkClient.cs b/Assets/Mirror/Core/NetworkClient.cs new file mode 100644 index 0000000..83b67b9 --- /dev/null +++ b/Assets/Mirror/Core/NetworkClient.cs @@ -0,0 +1,1725 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Mirror.RemoteCalls; +using UnityEngine; + +namespace Mirror +{ + public enum ConnectState + { + None, + // connecting between Connect() and OnTransportConnected() + Connecting, + Connected, + // disconnecting between Disconnect() and OnTransportDisconnected() + Disconnecting, + Disconnected + } + + /// NetworkClient with connection to server. + public static partial class NetworkClient + { + // time & value snapshot interpolation are separate. + // -> time is interpolated globally on NetworkClient / NetworkConnection + // -> value is interpolated per-component, i.e. NetworkTransform. + // however, both need to be on the same send interval. + // + // additionally, server & client need to use the same send interval. + // otherwise it's too easy to accidentally cause interpolation issues if + // a component sends with client.interval but interpolates with + // server.interval, etc. + public static int sendRate => NetworkServer.sendRate; + public static float sendInterval => sendRate < int.MaxValue ? 1f / sendRate : 0; // for 30 Hz, that's 33ms + static double lastSendTime; + + // message handlers by messageId + internal static readonly Dictionary handlers = + new Dictionary(); + + /// All spawned NetworkIdentities by netId. + // client sees OBSERVED spawned ones. + public static readonly Dictionary spawned = + new Dictionary(); + + /// Client's NetworkConnection to server. + public static NetworkConnection connection { get; internal set; } + + /// True if client is ready (= joined world). + // TODO redundant state. point it to .connection.isReady instead (& test) + // TODO OR remove NetworkConnection.isReady? unless it's used on server + // + // TODO maybe ClientState.Connected/Ready/AddedPlayer/etc.? + // way better for security if we can check states in callbacks + public static bool ready; + + /// NetworkIdentity of the localPlayer + public static NetworkIdentity localPlayer { get; internal set; } + + // NetworkClient state + internal static ConnectState connectState = ConnectState.None; + + /// active is true while a client is connecting/connected either as standalone or as host client. + // (= while the network is active) + public static bool active => connectState == ConnectState.Connecting || + connectState == ConnectState.Connected; + + /// active is true while the client is connected in host mode. + // naming consistent with NetworkServer.activeHost. + public static bool activeHost => connection is LocalConnectionToServer; + + /// Check if client is connecting (before connected). + public static bool isConnecting => connectState == ConnectState.Connecting; + + /// Check if client is connected (after connecting). + public static bool isConnected => connectState == ConnectState.Connected; + + // Deprecated 2022-12-12 + [Obsolete("NetworkClient.isHostClient was renamed to .activeHost to be more obvious")] + public static bool isHostClient => activeHost; + + // OnConnected / OnDisconnected used to be NetworkMessages that were + // invoked. this introduced a bug where external clients could send + // Connected/Disconnected messages over the network causing undefined + // behaviour. + // => public so that custom NetworkManagers can hook into it + public static Action OnConnectedEvent; + public static Action OnDisconnectedEvent; + public static Action OnErrorEvent; + + /// Registered spawnable prefabs by assetId. + public static readonly Dictionary prefabs = + new Dictionary(); + + // custom spawn / unspawn handlers by assetId. + // useful to support prefab pooling etc.: + // https://mirror-networking.gitbook.io/docs/guides/gameobjects/custom-spawnfunctions + internal static readonly Dictionary spawnHandlers = + new Dictionary(); + internal static readonly Dictionary unspawnHandlers = + new Dictionary(); + + // spawning + // internal for tests + internal static bool isSpawnFinished; + + // Disabled scene objects that can be spawned again, by sceneId. + internal static readonly Dictionary spawnableObjects = + new Dictionary(); + + internal static Unbatcher unbatcher = new Unbatcher(); + + // interest management component (optional) + // only needed for SetHostVisibility + public static InterestManagementBase aoi; + + // scene loading + public static bool isLoadingScene; + + // connection quality + // this is set by a virtual function in NetworkManager, + // which allows users to overwrite it with their own estimations. + public static ConnectionQuality connectionQuality = ConnectionQuality.ESTIMATING; + + // initialization ////////////////////////////////////////////////////// + static void AddTransportHandlers() + { + // community Transports may forget to call OnDisconnected. + // which could cause handlers to be added twice with +=. + // ensure we always clear the old ones first. + // fixes: https://github.com/vis2k/Mirror/issues/3152 + RemoveTransportHandlers(); + + // += so that other systems can also hook into it (i.e. statistics) + Transport.active.OnClientConnected += OnTransportConnected; + Transport.active.OnClientDataReceived += OnTransportData; + Transport.active.OnClientDisconnected += OnTransportDisconnected; + Transport.active.OnClientError += OnTransportError; + } + + static void RemoveTransportHandlers() + { + // -= so that other systems can also hook into it (i.e. statistics) + Transport.active.OnClientConnected -= OnTransportConnected; + Transport.active.OnClientDataReceived -= OnTransportData; + Transport.active.OnClientDisconnected -= OnTransportDisconnected; + Transport.active.OnClientError -= OnTransportError; + } + + // connect ///////////////////////////////////////////////////////////// + // initialize is called before every connect + static void Initialize(bool hostMode) + { + // safety: ensure Weaving succeded. + // if it silently failed, we would get lots of 'writer not found' + // and other random errors at runtime instead. this is cleaner. + if (!WeaverFuse.Weaved()) + { + // if it failed, throw an exception to early exit all Connect calls. + throw new Exception("NetworkClient won't start because Weaving failed or didn't run."); + } + + // Debug.Log($"Client Connect: {address}"); + Debug.Assert(Transport.active != null, "There was no active transport when calling NetworkClient.Connect, If you are calling Connect manually then make sure to set 'Transport.active' first"); + + // reset unbatcher in case any batches from last session remain. + // need to do this in Initialize() so it runs for the host as well. + // fixes host mode scene transition receiving data from previous scene. + // credits: BigBoxVR + unbatcher = new Unbatcher(); + + // reset time interpolation on every new connect. + // ensures last sessions' state is cleared before starting again. + InitTimeInterpolation(); + + RegisterMessageHandlers(hostMode); + Transport.active.enabled = true; + } + + /// Connect client to a NetworkServer by address. + public static void Connect(string address) + { + Initialize(false); + + AddTransportHandlers(); + connectState = ConnectState.Connecting; + Transport.active.ClientConnect(address); + connection = new NetworkConnectionToServer(); + } + + /// Connect client to a NetworkServer by Uri. + public static void Connect(Uri uri) + { + Initialize(false); + + AddTransportHandlers(); + connectState = ConnectState.Connecting; + Transport.active.ClientConnect(uri); + connection = new NetworkConnectionToServer(); + } + + // TODO why are there two connect host methods? + // called from NetworkManager.FinishStartHost() + public static void ConnectHost() + { + Initialize(true); + connectState = ConnectState.Connected; + HostMode.SetupConnections(); + } + + // Deprecated 2022-12-12 + [Obsolete("NetworkClient.ConnectLocalServer was moved to HostMode.InvokeOnConnected")] + public static void ConnectLocalServer() => HostMode.InvokeOnConnected(); + + // disconnect ////////////////////////////////////////////////////////// + /// Disconnect from server. + public static void Disconnect() + { + // only if connected or connecting. + // don't disconnect() again if already in the process of + // disconnecting or fully disconnected. + if (connectState != ConnectState.Connecting && + connectState != ConnectState.Connected) + return; + + // we are disconnecting until OnTransportDisconnected is called. + // setting state to Disconnected would stop OnTransportDisconnected + // from calling cleanup code because it would think we are already + // disconnected fully. + // TODO move to 'cleanup' code below if safe + connectState = ConnectState.Disconnecting; + ready = false; + + // call Disconnect on the NetworkConnection + connection?.Disconnect(); + + // IMPORTANT: do NOT clear connection here yet. + // we still need it in OnTransportDisconnected for callbacks. + // connection = null; + } + + // transport events //////////////////////////////////////////////////// + // called by Transport + static void OnTransportConnected() + { + if (connection != null) + { + // reset network time stats + NetworkTime.ResetStatics(); + + // the handler may want to send messages to the client + // thus we should set the connected state before calling the handler + connectState = ConnectState.Connected; + NetworkTime.UpdateClient(); + OnConnectedEvent?.Invoke(); + } + else Debug.LogError("Skipped Connect message handling because connection is null."); + } + + // helper function + static bool UnpackAndInvoke(NetworkReader reader, int channelId) + { + if (NetworkMessages.UnpackId(reader, out ushort msgType)) + { + // try to invoke the handler for that message + if (handlers.TryGetValue(msgType, out NetworkMessageDelegate handler)) + { + handler.Invoke(connection, reader, channelId); + + // message handler may disconnect client, making connection = null + // therefore must check for null to avoid NRE. + if (connection != null) + connection.lastMessageTime = Time.time; + + return true; + } + else + { + // message in a batch are NOT length prefixed to save bandwidth. + // every message needs to be handled and read until the end. + // otherwise it would overlap into the next message. + // => need to warn and disconnect to avoid undefined behaviour. + // => WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning($"Unknown message id: {msgType}. This can happen if no handler was registered for this message."); + // simply return false. caller is responsible for disconnecting. + //connection.Disconnect(); + return false; + } + } + else + { + // => WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning("Invalid message header."); + // simply return false. caller is responsible for disconnecting. + //connection.Disconnect(); + return false; + } + } + + // called by Transport + internal static void OnTransportData(ArraySegment data, int channelId) + { + if (connection != null) + { + // server might batch multiple messages into one packet. + // feed it to the Unbatcher. + // NOTE: we don't need to associate a channelId because we + // always process all messages in the batch. + if (!unbatcher.AddBatch(data)) + { + Debug.LogWarning($"NetworkClient: failed to add batch, disconnecting."); + connection.Disconnect(); + return; + } + + // process all messages in the batch. + // only while NOT loading a scene. + // if we get a scene change message, then we need to stop + // processing. otherwise we might apply them to the old scene. + // => fixes https://github.com/vis2k/Mirror/issues/2651 + // + // NOTE: is scene starts loading, then the rest of the batch + // would only be processed when OnTransportData is called + // the next time. + // => consider moving processing to NetworkEarlyUpdate. + while (!isLoadingScene && + unbatcher.GetNextMessage(out ArraySegment message, out double remoteTimestamp)) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message)) + { + // enough to read at least header size? + if (reader.Remaining >= NetworkMessages.IdSize) + { + // make remoteTimeStamp available to the user + connection.remoteTimeStamp = remoteTimestamp; + + // handle message + if (!UnpackAndInvoke(reader, channelId)) + { + // warn, disconnect and return if failed + // -> warning because attackers might send random data + // -> messages in a batch aren't length prefixed. + // failing to read one would cause undefined + // behaviour for every message afterwards. + // so we need to disconnect. + // -> return to avoid the below unbatches.count error. + // we already disconnected and handled it. + Debug.LogWarning($"NetworkClient: failed to unpack and invoke message. Disconnecting."); + connection.Disconnect(); + return; + } + } + // otherwise disconnect + else + { + // WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning($"NetworkClient: received Message was too short (messages should start with message id)"); + connection.Disconnect(); + return; + } + } + } + + // if we weren't interrupted by a scene change, + // then all batched messages should have been processed now. + // if not, we need to log an error to avoid debugging hell. + // otherwise batches would silently grow. + // we need to log an error to avoid debugging hell. + // + // EXAMPLE: https://github.com/vis2k/Mirror/issues/2882 + // -> UnpackAndInvoke silently returned because no handler for id + // -> Reader would never be read past the end + // -> Batch would never be retired because end is never reached + // + // NOTE: prefixing every message in a batch with a length would + // avoid ever not reading to the end. for extra bandwidth. + // + // IMPORTANT: always keep this check to detect memory leaks. + // this took half a day to debug last time. + if (!isLoadingScene && unbatcher.BatchesCount > 0) + { + Debug.LogError($"Still had {unbatcher.BatchesCount} batches remaining after processing, even though processing was not interrupted by a scene change. This should never happen, as it would cause ever growing batches.\nPossible reasons:\n* A message didn't deserialize as much as it serialized\n*There was no message handler for a message id, so the reader wasn't read until the end."); + } + } + else Debug.LogError("Skipped Data message handling because connection is null."); + } + + // called by Transport + // IMPORTANT: often times when disconnecting, we call this from Mirror + // too because we want to remove the connection and handle + // the disconnect immediately. + // => which is fine as long as we guarantee it only runs once + // => which we do by setting the state to Disconnected! + internal static void OnTransportDisconnected() + { + // StopClient called from user code triggers Disconnected event + // from transport which calls StopClient again, so check here + // and short circuit running the Shutdown process twice. + if (connectState == ConnectState.Disconnected) return; + + // Raise the event before changing ConnectState + // because 'active' depends on this during shutdown + // + // previously OnDisconnected was only invoked if connection != null. + // however, if DNS resolve fails in Transport.Connect(), + // OnDisconnected would never be called because 'connection' is only + // created after the Transport.Connect() call. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3365 + OnDisconnectedEvent?.Invoke(); + + connectState = ConnectState.Disconnected; + ready = false; + snapshots.Clear(); + localTimeline = 0; + + // now that everything was handled, clear the connection. + // previously this was done in Disconnect() already, but we still + // need it for the above OnDisconnectedEvent. + connection = null; + + // transport handlers are only added when connecting. + // so only remove when actually disconnecting. + RemoveTransportHandlers(); + } + + // transport errors are forwarded to high level + static void OnTransportError(TransportError error, string reason) + { + // transport errors will happen. logging a warning is enough. + // make sure the user does not panic. + Debug.LogWarning($"Client Transport Error: {error}: {reason}. This is fine."); + OnErrorEvent?.Invoke(error, reason); + } + + // send //////////////////////////////////////////////////////////////// + /// Send a NetworkMessage to the server over the given channel. + public static void Send(T message, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + if (connection != null) + { + if (connectState == ConnectState.Connected) + { + connection.Send(message, channelId); + } + else Debug.LogError("NetworkClient Send when not connected to a server"); + } + else Debug.LogError("NetworkClient Send with no connection"); + } + + // message handlers //////////////////////////////////////////////////// + internal static void RegisterMessageHandlers(bool hostMode) + { + // host mode client / remote client react to some messages differently. + // but we still need to add handlers for all of them to avoid + // 'message id not found' errors. + if (hostMode) + { + RegisterHandler(OnHostClientObjectDestroy); + RegisterHandler(OnHostClientObjectHide); + RegisterHandler(_ => { }, false); + RegisterHandler(OnHostClientSpawn); + // host mode doesn't need spawning + RegisterHandler(_ => { }); + // host mode doesn't need spawning + RegisterHandler(_ => { }); + // host mode doesn't need state updates + RegisterHandler(_ => { }); + } + else + { + RegisterHandler(OnObjectDestroy); + RegisterHandler(OnObjectHide); + RegisterHandler(NetworkTime.OnClientPong, false); + RegisterHandler(NetworkTime.OnClientPing, false); + RegisterHandler(OnSpawn); + RegisterHandler(OnObjectSpawnStarted); + RegisterHandler(OnObjectSpawnFinished); + RegisterHandler(OnEntityStateMessage); + } + + // These handlers are the same for host and remote clients + RegisterHandler(OnTimeSnapshotMessage); + RegisterHandler(OnChangeOwner); + RegisterHandler(OnRPCMessage); + } + + /// Register a handler for a message type T. Most should require authentication. + public static void RegisterHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + if (handlers.ContainsKey(msgType)) + { + Debug.LogWarning($"NetworkClient.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning."); + } + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + // we use the same WrapHandler function for server and client. + // so let's wrap it to ignore the NetworkConnection parameter. + // it's not needed on client. it's always NetworkClient.connection. + void HandlerWrapped(NetworkConnection _, T value) => handler(value); + handlers[msgType] = NetworkMessages.WrapHandler((Action)HandlerWrapped, requireAuthentication); + } + + /// Replace a handler for a particular message type. Should require authentication by default. + // RegisterHandler throws a warning (as it should) if a handler is assigned twice + // Use of ReplaceHandler makes it clear the user intended to replace the handler + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + handlers[msgType] = NetworkMessages.WrapHandler(handler, requireAuthentication); + } + + /// Replace a handler for a particular message type. Should require authentication by default. + // RegisterHandler throws a warning (as it should) if a handler is assigned twice + // Use of ReplaceHandler makes it clear the user intended to replace the handler + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ReplaceHandler((NetworkConnection _, T value) => { handler(value); }, requireAuthentication); + } + + /// Unregister a message handler of type T. + public static bool UnregisterHandler() + where T : struct, NetworkMessage + { + // use int to minimize collisions + ushort msgType = NetworkMessageId.Id; + return handlers.Remove(msgType); + } + + // spawnable prefabs /////////////////////////////////////////////////// + /// Find the registered prefab for this asset id. + // Useful for debuggers + public static bool GetPrefab(uint assetId, out GameObject prefab) + { + prefab = null; + return assetId != 0 && + prefabs.TryGetValue(assetId, out prefab) && + prefab != null; + } + + /// Validates Prefab then adds it to prefabs dictionary. + static void RegisterPrefabIdentity(NetworkIdentity prefab) + { + if (prefab.assetId == 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead"); + return; + } + + if (prefab.sceneId != 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene."); + return; + } + + // disallow child NetworkIdentities. + // TODO likely not necessary anymore due to the new check in + // NetworkIdentity.OnValidate. + NetworkIdentity[] identities = prefab.GetComponentsInChildren(); + if (identities.Length > 1) + { + Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object."); + } + + if (prefabs.ContainsKey(prefab.assetId)) + { + GameObject existingPrefab = prefabs[prefab.assetId]; + Debug.LogWarning($"Replacing existing prefab with assetId '{prefab.assetId}'. Old prefab '{existingPrefab.name}', New prefab '{prefab.name}'"); + } + + if (spawnHandlers.ContainsKey(prefab.assetId) || unspawnHandlers.ContainsKey(prefab.assetId)) + { + Debug.LogWarning($"Adding prefab '{prefab.name}' with assetId '{prefab.assetId}' when spawnHandlers with same assetId already exists. If you want to use custom spawn handling, then remove the prefab from NetworkManager's registered prefabs first."); + } + + // Debug.Log($"Registering prefab '{prefab.name}' as asset:{prefab.assetId}"); + + prefabs[prefab.assetId] = prefab.gameObject; + } + + /// Register spawnable prefab with custom assetId. + // Note: newAssetId can not be set on GameObjects that already have an assetId + // Note: registering with assetId is useful for assetbundles etc. a lot + // of people use this. + public static void RegisterPrefab(GameObject prefab, uint newAssetId) + { + if (prefab == null) + { + Debug.LogError("Could not register prefab because it was null"); + return; + } + + if (newAssetId == 0) + { + Debug.LogError($"Could not register '{prefab.name}' with new assetId because the new assetId was empty"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + if (identity.assetId != 0 && identity.assetId != newAssetId) + { + Debug.LogError($"Could not register '{prefab.name}' to {newAssetId} because it already had an AssetId, Existing assetId {identity.assetId}"); + return; + } + + identity.assetId = newAssetId; + + RegisterPrefabIdentity(identity); + } + + /// Register spawnable prefab. + public static void RegisterPrefab(GameObject prefab) + { + if (prefab == null) + { + Debug.LogError("Could not register prefab because it was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + RegisterPrefabIdentity(identity); + } + + /// Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers. + // Note: newAssetId can not be set on GameObjects that already have an assetId + // Note: registering with assetId is useful for assetbundles etc. a lot + // of people use this. + // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate? + public static void RegisterPrefab(GameObject prefab, uint newAssetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + // We need this check here because we don't want a null handler in the lambda expression below + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {newAssetId}"); + return; + } + + RegisterPrefab(prefab, newAssetId, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler); + } + + /// Register a spawnable prefab with custom spawn/unspawn handlers. + // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate? + public static void RegisterPrefab(GameObject prefab, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (prefab == null) + { + Debug.LogError("Could not register handler for prefab because the prefab was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + if (identity.sceneId != 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene."); + return; + } + + if (identity.assetId == 0) + { + Debug.LogError($"Can not Register handler for '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead"); + return; + } + + // We need this check here because we don't want a null handler in the lambda expression below + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {identity.assetId}"); + return; + } + + RegisterPrefab(prefab, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler); + } + + /// Register a spawnable prefab with custom assetId and custom spawn/unspawn handlers. + // Note: newAssetId can not be set on GameObjects that already have an assetId + // Note: registering with assetId is useful for assetbundles etc. a lot + // of people use this. + // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate? + public static void RegisterPrefab(GameObject prefab, uint newAssetId, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (newAssetId == 0) + { + Debug.LogError($"Could not register handler for '{prefab.name}' with new assetId because the new assetId was empty"); + return; + } + + if (prefab == null) + { + Debug.LogError("Could not register handler for prefab because the prefab was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + if (identity.assetId != 0 && identity.assetId != newAssetId) + { + Debug.LogError($"Could not register Handler for '{prefab.name}' to {newAssetId} because it already had an AssetId, Existing assetId {identity.assetId}"); + return; + } + + if (identity.sceneId != 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene."); + return; + } + + identity.assetId = newAssetId; + uint assetId = identity.assetId; + + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {assetId}"); + return; + } + + if (unspawnHandler == null) + { + Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}"); + return; + } + + if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId)) + { + Debug.LogWarning($"Replacing existing spawnHandlers for prefab '{prefab.name}' with assetId '{assetId}'"); + } + + if (prefabs.ContainsKey(assetId)) + { + // this is error because SpawnPrefab checks prefabs before handler + Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}', unregister the prefab first before trying to add handler"); + } + + NetworkIdentity[] identities = prefab.GetComponentsInChildren(); + if (identities.Length > 1) + { + Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object."); + } + + //Debug.Log($"Registering custom prefab {prefab.name} as asset:{assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}"); + + spawnHandlers[assetId] = spawnHandler; + unspawnHandlers[assetId] = unspawnHandler; + } + + /// Register a spawnable prefab with custom spawn/unspawn handlers. + // TODO why do we have one with SpawnDelegate and one with SpawnHandlerDelegate? + public static void RegisterPrefab(GameObject prefab, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (prefab == null) + { + Debug.LogError("Could not register handler for prefab because the prefab was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not register handler for '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + if (identity.sceneId != 0) + { + Debug.LogError($"Can not Register '{prefab.name}' because it has a sceneId, make sure you are passing in the original prefab and not an instance in the scene."); + return; + } + + uint assetId = identity.assetId; + + if (assetId == 0) + { + Debug.LogError($"Can not Register handler for '{prefab.name}' because it had empty assetid. If this is a scene Object use RegisterSpawnHandler instead"); + return; + } + + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {assetId}"); + return; + } + + if (unspawnHandler == null) + { + Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}"); + return; + } + + if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId)) + { + Debug.LogWarning($"Replacing existing spawnHandlers for prefab '{prefab.name}' with assetId '{assetId}'"); + } + + if (prefabs.ContainsKey(assetId)) + { + // this is error because SpawnPrefab checks prefabs before handler + Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}', unregister the prefab first before trying to add handler"); + } + + NetworkIdentity[] identities = prefab.GetComponentsInChildren(); + if (identities.Length > 1) + { + Debug.LogError($"Prefab '{prefab.name}' has multiple NetworkIdentity components. There should only be one NetworkIdentity on a prefab, and it must be on the root object."); + } + + //Debug.Log($"Registering custom prefab {prefab.name} as asset:{assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}"); + + spawnHandlers[assetId] = spawnHandler; + unspawnHandlers[assetId] = unspawnHandler; + } + + /// Removes a registered spawn prefab that was setup with NetworkClient.RegisterPrefab. + public static void UnregisterPrefab(GameObject prefab) + { + if (prefab == null) + { + Debug.LogError("Could not unregister prefab because it was null"); + return; + } + + if (!prefab.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Could not unregister '{prefab.name}' since it contains no NetworkIdentity component"); + return; + } + + uint assetId = identity.assetId; + + prefabs.Remove(assetId); + spawnHandlers.Remove(assetId); + unspawnHandlers.Remove(assetId); + } + + // spawn handlers ////////////////////////////////////////////////////// + /// This is an advanced spawning function that registers a custom assetId with the spawning system. + // This can be used to register custom spawning methods for an assetId - + // instead of the usual method of registering spawning methods for a + // prefab. This should be used when no prefab exists for the spawned + // objects - such as when they are constructed dynamically at runtime + // from configuration data. + public static void RegisterSpawnHandler(uint assetId, SpawnDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + // We need this check here because we don't want a null handler in the lambda expression below + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {assetId}"); + return; + } + + RegisterSpawnHandler(assetId, msg => spawnHandler(msg.position, msg.assetId), unspawnHandler); + } + + /// This is an advanced spawning function that registers a custom assetId with the spawning system. + // This can be used to register custom spawning methods for an assetId - + // instead of the usual method of registering spawning methods for a + // prefab. This should be used when no prefab exists for the spawned + // objects - such as when they are constructed dynamically at runtime + // from configuration data. + public static void RegisterSpawnHandler(uint assetId, SpawnHandlerDelegate spawnHandler, UnSpawnDelegate unspawnHandler) + { + if (spawnHandler == null) + { + Debug.LogError($"Can not Register null SpawnHandler for {assetId}"); + return; + } + + if (unspawnHandler == null) + { + Debug.LogError($"Can not Register null UnSpawnHandler for {assetId}"); + return; + } + + if (assetId == 0) + { + Debug.LogError("Can not Register SpawnHandler for empty assetId"); + return; + } + + if (spawnHandlers.ContainsKey(assetId) || unspawnHandlers.ContainsKey(assetId)) + { + Debug.LogWarning($"Replacing existing spawnHandlers for {assetId}"); + } + + if (prefabs.ContainsKey(assetId)) + { + // this is error because SpawnPrefab checks prefabs before handler + Debug.LogError($"assetId '{assetId}' is already used by prefab '{prefabs[assetId].name}'"); + } + + // Debug.Log("RegisterSpawnHandler asset {assetId} {spawnHandler.GetMethodName()}/{unspawnHandler.GetMethodName()}"); + + spawnHandlers[assetId] = spawnHandler; + unspawnHandlers[assetId] = unspawnHandler; + } + + /// Removes a registered spawn handler function that was registered with NetworkClient.RegisterHandler(). + public static void UnregisterSpawnHandler(uint assetId) + { + spawnHandlers.Remove(assetId); + unspawnHandlers.Remove(assetId); + } + + /// This clears the registered spawn prefabs and spawn handler functions for this client. + public static void ClearSpawners() + { + prefabs.Clear(); + spawnHandlers.Clear(); + unspawnHandlers.Clear(); + } + + internal static bool InvokeUnSpawnHandler(uint assetId, GameObject obj) + { + if (unspawnHandlers.TryGetValue(assetId, out UnSpawnDelegate handler) && handler != null) + { + handler(obj); + return true; + } + return false; + } + + // ready /////////////////////////////////////////////////////////////// + /// Sends Ready message to server, indicating that we loaded the scene, ready to enter the game. + // This could be for example when a client enters an ongoing game and + // has finished loading the current scene. The server should respond to + // the SYSTEM_READY event with an appropriate handler which instantiates + // the players object for example. + public static bool Ready() + { + // Debug.Log($"NetworkClient.Ready() called with connection {conn}"); + if (ready) + { + Debug.LogError("NetworkClient is already ready. It shouldn't be called twice."); + return false; + } + + // need a valid connection to become ready + if (connection == null) + { + Debug.LogError("Ready() called with invalid connection object: conn=null"); + return false; + } + + // Set these before sending the ReadyMessage, otherwise host client + // will fail in InternalAddPlayer with null readyConnection. + // TODO this is redundant. have one source of truth for .ready + ready = true; + connection.isReady = true; + + // Tell server we're ready to have a player object spawned + connection.Send(new ReadyMessage()); + return true; + } + + // add player ////////////////////////////////////////////////////////// + // called from message handler for Owner message + internal static void InternalAddPlayer(NetworkIdentity identity) + { + //Debug.Log("NetworkClient.InternalAddPlayer"); + + // NOTE: It can be "normal" when changing scenes for the player to be destroyed and recreated. + // But, the player structures are not cleaned up, we'll just replace the old player + localPlayer = identity; + + // NOTE: we DONT need to set isClient=true here, because OnStartClient + // is called before OnStartLocalPlayer, hence it's already set. + // localPlayer.isClient = true; + + // TODO this check might not be necessary + //if (readyConnection != null) + if (ready && connection != null) + { + connection.identity = identity; + } + else Debug.LogWarning("NetworkClient can't AddPlayer before being ready. Please call NetworkClient.Ready() first. Clients are considered ready after joining the game world."); + } + + /// Sends AddPlayer message to the server, indicating that we want to join the world. + public static bool AddPlayer() + { + // ensure valid ready connection + if (connection == null) + { + Debug.LogError("AddPlayer requires a valid NetworkClient.connection."); + return false; + } + + // UNET checked 'if readyConnection != null'. + // in other words, we need a connection and we need to be ready. + if (!ready) + { + Debug.LogError("AddPlayer requires a ready NetworkClient."); + return false; + } + + if (connection.identity != null) + { + Debug.LogError("NetworkClient.AddPlayer: a PlayerController was already added. Did you call AddPlayer twice?"); + return false; + } + + // Debug.Log($"NetworkClient.AddPlayer() called with connection {readyConnection}"); + connection.Send(new AddPlayerMessage()); + return true; + } + + // spawning //////////////////////////////////////////////////////////// + internal static void ApplySpawnPayload(NetworkIdentity identity, SpawnMessage message) + { + if (message.assetId != 0) + identity.assetId = message.assetId; + + if (!identity.gameObject.activeSelf) + { + identity.gameObject.SetActive(true); + } + + // apply local values for VR support + identity.transform.localPosition = message.position; + identity.transform.localRotation = message.rotation; + identity.transform.localScale = message.scale; + + // configure flags + // the below DeserializeClient call invokes SyncVarHooks. + // flags always need to be initialized before that. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3259 + identity.isOwned = message.isOwner; + identity.netId = message.netId; + + if (message.isLocalPlayer) + InternalAddPlayer(identity); + + // configure isClient/isLocalPlayer flags. + // => after InternalAddPlayer. can't initialize .isLocalPlayer + // before InternalAddPlayer sets .localPlayer + // => before DeserializeClient, otherwise SyncVar hooks wouldn't + // have isClient/isLocalPlayer set yet. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3259 + InitializeIdentityFlags(identity); + + // deserialize components if any payload + // (Count is 0 if there were no components) + if (message.payload.Count > 0) + { + using (NetworkReaderPooled payloadReader = NetworkReaderPool.Get(message.payload)) + { + identity.DeserializeClient(payloadReader, true); + } + } + + spawned[message.netId] = identity; + if (identity.isOwned) connection?.owned.Add(identity); + + // the initial spawn with OnObjectSpawnStarted/Finished calls all + // object's OnStartClient/OnStartLocalPlayer after they were all + // spawned. + // this only happens once though. + // for all future spawns, we need to call OnStartClient/LocalPlayer + // here immediately since there won't be another OnObjectSpawnFinished. + if (isSpawnFinished) + { + InvokeIdentityCallbacks(identity); + } + } + + // Finds Existing Object with NetId or spawns a new one using AssetId or sceneId + internal static bool FindOrSpawnObject(SpawnMessage message, out NetworkIdentity identity) + { + // was the object already spawned? + identity = GetExistingObject(message.netId); + + // if found, return early + if (identity != null) + { + return true; + } + + if (message.assetId == 0 && message.sceneId == 0) + { + Debug.LogError($"OnSpawn message with netId '{message.netId}' has no AssetId or sceneId"); + return false; + } + + identity = message.sceneId == 0 ? SpawnPrefab(message) : SpawnSceneObject(message.sceneId); + + if (identity == null) + { + Debug.LogError($"Could not spawn assetId={message.assetId} scene={message.sceneId:X} netId={message.netId}"); + return false; + } + + return true; + } + + static NetworkIdentity GetExistingObject(uint netid) + { + spawned.TryGetValue(netid, out NetworkIdentity identity); + return identity; + } + + static NetworkIdentity SpawnPrefab(SpawnMessage message) + { + // custom spawn handler for this prefab? (for prefab pools etc.) + // + // IMPORTANT: look for spawn handlers BEFORE looking for registered + // prefabs. Unspawning also looks for unspawn handlers + // before falling back to regular Destroy. this needs to + // be consistent. + // https://github.com/vis2k/Mirror/issues/2705 + if (spawnHandlers.TryGetValue(message.assetId, out SpawnHandlerDelegate handler)) + { + GameObject obj = handler(message); + if (obj == null) + { + Debug.LogError($"Spawn Handler returned null, Handler assetId '{message.assetId}'"); + return null; + } + + if (!obj.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"Object Spawned by handler did not have a NetworkIdentity, Handler assetId '{message.assetId}'"); + return null; + } + + return identity; + } + + // otherwise look in NetworkManager registered prefabs + if (GetPrefab(message.assetId, out GameObject prefab)) + { + GameObject obj = GameObject.Instantiate(prefab, message.position, message.rotation); + //Debug.Log($"Client spawn handler instantiating [netId{message.netId} asset ID:{message.assetId} pos:{message.position} rotation:{message.rotation}]"); + return obj.GetComponent(); + } + + Debug.LogError($"Failed to spawn server object, did you forget to add it to the NetworkManager? assetId={message.assetId} netId={message.netId}"); + return null; + } + + static NetworkIdentity SpawnSceneObject(ulong sceneId) + { + NetworkIdentity identity = GetAndRemoveSceneObject(sceneId); + if (identity == null) + { + Debug.LogError($"Spawn scene object not found for {sceneId:X}. Make sure that client and server use exactly the same project. This only happens if the hierarchy gets out of sync."); + + // dump the whole spawnable objects dict for easier debugging + //foreach (KeyValuePair kvp in spawnableObjects) + // Debug.Log($"Spawnable: SceneId={kvp.Key:X} name={kvp.Value.name}"); + } + //else Debug.Log($"Client spawn for [netId:{msg.netId}] [sceneId:{msg.sceneId:X}] obj:{identity}"); + return identity; + } + + static NetworkIdentity GetAndRemoveSceneObject(ulong sceneId) + { + if (spawnableObjects.TryGetValue(sceneId, out NetworkIdentity identity)) + { + spawnableObjects.Remove(sceneId); + return identity; + } + return null; + } + + /// Call this after loading/unloading a scene in the client after connection to register the spawnable objects + public static void PrepareToSpawnSceneObjects() + { + // remove existing items, they will be re-added below + spawnableObjects.Clear(); + + // finds all NetworkIdentity currently loaded by unity (includes disabled objects) + NetworkIdentity[] allIdentities = Resources.FindObjectsOfTypeAll(); + foreach (NetworkIdentity identity in allIdentities) + { + // add all unspawned NetworkIdentities to spawnable objects + // need to check netId to make sure object is not spawned + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3541 + // PrepareToSpawnSceneObjects may be called multiple times in case + // the ObjectSpawnStarted message is received multiple times. + if (Utils.IsSceneObject(identity) && + identity.netId == 0) + { + if (spawnableObjects.TryGetValue(identity.sceneId, out NetworkIdentity existingIdentity)) + { + string msg = $"NetworkClient: Duplicate sceneId {identity.sceneId} detected on {identity.gameObject.name} and {existingIdentity.gameObject.name}\n" + + $"This can happen if a networked object is persisted in DontDestroyOnLoad through loading / changing to the scene where it originated,\n" + + $"otherwise you may need to open and re-save the {identity.gameObject.scene} to reset scene id's."; + Debug.LogWarning(msg, identity.gameObject); + } + else + { + spawnableObjects.Add(identity.sceneId, identity); + } + } + } + } + + internal static void OnObjectSpawnStarted(ObjectSpawnStartedMessage _) + { + // Debug.Log("SpawnStarted"); + PrepareToSpawnSceneObjects(); + isSpawnFinished = false; + } + + internal static void OnObjectSpawnFinished(ObjectSpawnFinishedMessage _) + { + // paul: Initialize the objects in the same order as they were + // initialized in the server. This is important if spawned objects + // use data from scene objects + foreach (NetworkIdentity identity in spawned.Values.OrderBy(uv => uv.netId)) + { + // NetworkIdentities should always be removed from .spawned when + // they are destroyed. for safety, let's double check here. + if (identity != null) + { + BootstrapIdentity(identity); + } + else Debug.LogWarning("Found null entry in NetworkClient.spawned. This is unexpected. Was the NetworkIdentity not destroyed properly?"); + } + isSpawnFinished = true; + } + + // host mode callbacks ///////////////////////////////////////////////// + static void OnHostClientObjectDestroy(ObjectDestroyMessage message) + { + //Debug.Log($"NetworkClient.OnLocalObjectObjDestroy netId:{message.netId}"); + + // remove from owned (if any) + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity)) + connection.owned.Remove(identity); + + spawned.Remove(message.netId); + } + + static void OnHostClientObjectHide(ObjectHideMessage message) + { + //Debug.Log($"ClientScene::OnLocalObjectObjHide netId:{message.netId}"); + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity) && + identity != null) + { + if (aoi != null) + aoi.SetHostVisibility(identity, false); + } + } + + internal static void OnHostClientSpawn(SpawnMessage message) + { + // on host mode, the object already exist in NetworkServer.spawned. + // simply add it to NetworkClient.spawned too. + if (NetworkServer.spawned.TryGetValue(message.netId, out NetworkIdentity identity) && identity != null) + { + spawned[message.netId] = identity; + if (message.isOwner) connection.owned.Add(identity); + + // now do the actual 'spawning' on host mode + if (message.isLocalPlayer) + InternalAddPlayer(identity); + + // set visibility before invoking OnStartClient etc. callbacks + if (aoi != null) + aoi.SetHostVisibility(identity, true); + + identity.isOwned = message.isOwner; + BootstrapIdentity(identity); + } + } + + // client-only mode callbacks ////////////////////////////////////////// + static void OnEntityStateMessage(EntityStateMessage message) + { + // Debug.Log($"NetworkClient.OnUpdateVarsMessage {msg.netId}"); + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity) && identity != null) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message.payload)) + identity.DeserializeClient(reader, false); + } + else Debug.LogWarning($"Did not find target for sync message for {message.netId}. Were all prefabs added to the NetworkManager's spawnable list?\nNote: this can be completely normal because UDP messages may arrive out of order, so this message might have arrived after a Destroy message."); + } + + static void OnRPCMessage(RpcMessage message) + { + // Debug.Log($"NetworkClient.OnRPCMessage hash:{message.functionHash} netId:{message.netId}"); + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity)) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message.payload)) + identity.HandleRemoteCall(message.componentIndex, message.functionHash, RemoteCallType.ClientRpc, reader); + } + // Rpcs often can't be applied if interest management unspawned them + } + + static void OnObjectHide(ObjectHideMessage message) => DestroyObject(message.netId); + + internal static void OnObjectDestroy(ObjectDestroyMessage message) => DestroyObject(message.netId); + + internal static void OnSpawn(SpawnMessage message) + { + // Debug.Log($"Client spawn handler instantiating netId={msg.netId} assetID={msg.assetId} sceneId={msg.sceneId:X} pos={msg.position}"); + if (FindOrSpawnObject(message, out NetworkIdentity identity)) + { + ApplySpawnPayload(identity, message); + } + } + + internal static void OnChangeOwner(ChangeOwnerMessage message) + { + NetworkIdentity identity = GetExistingObject(message.netId); + + if (identity != null) + ChangeOwner(identity, message); + else + Debug.LogError($"OnChangeOwner: Could not find object with netId {message.netId}"); + } + + // ChangeOwnerMessage contains new 'owned' and new 'localPlayer' + // that we need to apply to the identity. + internal static void ChangeOwner(NetworkIdentity identity, ChangeOwnerMessage message) + { + // local player before, but not anymore? + // call OnStopLocalPlayer before setting new values. + if (identity.isLocalPlayer && !message.isLocalPlayer) + { + identity.OnStopLocalPlayer(); + } + + // set ownership flag (aka authority) + identity.isOwned = message.isOwner; + + // Add / Remove to client's connectionToServer.owned hashset. + if (identity.isOwned) + connection?.owned.Add(identity); + else + connection?.owned.Remove(identity); + + // Call OnStartAuthority / OnStopAuthority + identity.NotifyAuthority(); + + // set localPlayer flag + identity.isLocalPlayer = message.isLocalPlayer; + + // identity is now local player. set our static helper field to it. + if (identity.isLocalPlayer) + { + localPlayer = identity; + identity.connectionToServer = connection; + identity.OnStartLocalPlayer(); + } + // identity's isLocalPlayer was set to false. + // clear our static localPlayer IF (and only IF) it was that one before. + else if (localPlayer == identity) + { + localPlayer = null; + // TODO set .connectionToServer to null for old local player? + // since we set it in the above 'if' case too. + } + } + + // set up NetworkIdentity flags on the client. + // needs to be separate from invoking callbacks. + // cleaner, and some places need to set flags first. + static void InitializeIdentityFlags(NetworkIdentity identity) + { + // initialize flags before invoking callbacks. + // this way isClient/isLocalPlayer is correct during callbacks. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3362 + identity.isClient = true; + identity.isLocalPlayer = localPlayer == identity; + + // .connectionToServer is only available for local players. + // set it here, before invoking any callbacks. + // this way it's available in _all_ callbacks. + if (identity.isLocalPlayer) + identity.connectionToServer = connection; + } + + // invoke NetworkIdentity callbacks on the client. + // needs to be separate from configuring flags. + // cleaner, and some places need to set flags first. + static void InvokeIdentityCallbacks(NetworkIdentity identity) + { + // invoke OnStartAuthority + identity.NotifyAuthority(); + + // invoke OnStartClient + identity.OnStartClient(); + + // invoke OnStartLocalPlayer + if (identity.isLocalPlayer) + identity.OnStartLocalPlayer(); + } + + // configure flags & invoke callbacks + static void BootstrapIdentity(NetworkIdentity identity) + { + InitializeIdentityFlags(identity); + InvokeIdentityCallbacks(identity); + } + + // broadcast /////////////////////////////////////////////////////////// + static void BroadcastTimeSnapshot() + { + Send(new TimeSnapshotMessage(), Channels.Unreliable); + } + + // make sure Broadcast() is only called every sendInterval. + // calling it every update() would require too much bandwidth. + static void Broadcast() + { + // joined the world yet? + if (!connection.isReady) return; + + // nothing to do in host mode. server already knows the state. + if (NetworkServer.active) return; + + // send time snapshot every sendInterval. + BroadcastTimeSnapshot(); + + // for each entity that the client owns + foreach (NetworkIdentity identity in connection.owned) + { + // make sure it's not null or destroyed. + // (which can happen if someone uses + // GameObject.Destroy instead of + // NetworkServer.Destroy) + if (identity != null) + { + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // get serialization for this entity viewed by this connection + // (if anything was serialized this time) + identity.SerializeClient(writer); + if (writer.Position > 0) + { + // send state update message + EntityStateMessage message = new EntityStateMessage + { + netId = identity.netId, + payload = writer.ToArraySegment() + }; + Send(message); + } + } + } + // spawned list should have no null entries because we + // always call Remove in OnObjectDestroy everywhere. + // if it does have null then we missed something. + else Debug.LogWarning($"Found 'null' entry in owned list for client. This is unexpected behaviour."); + } + } + + // update ////////////////////////////////////////////////////////////// + // NetworkEarlyUpdate called before any Update/FixedUpdate + // (we add this to the UnityEngine in NetworkLoop) + internal static void NetworkEarlyUpdate() + { + // process all incoming messages first before updating the world + if (Transport.active != null) + Transport.active.ClientEarlyUpdate(); + + // time snapshot interpolation + UpdateTimeInterpolation(); + } + + // NetworkLateUpdate called after any Update/FixedUpdate/LateUpdate + // (we add this to the UnityEngine in NetworkLoop) + internal static void NetworkLateUpdate() + { + // broadcast ClientToServer components while active + if (active) + { + // broadcast every sendInterval. + // AccurateInterval to avoid update frequency inaccuracy issues: + // https://github.com/vis2k/Mirror/pull/3153 + // + // for example, host mode server doesn't set .targetFrameRate. + // Broadcast() would be called every tick. + // snapshots might be sent way too often, etc. + // + // during tests, we always call Broadcast() though. + // + // also important for syncInterval=0 components like + // NetworkTransform, so they can sync on same interval as time + // snapshots _but_ not every single tick. + // + // Unity 2019 doesn't have Time.timeAsDouble yet + if (!Application.isPlaying || + AccurateInterval.Elapsed(NetworkTime.localTime, sendInterval, ref lastSendTime)) + { + Broadcast(); + } + } + + // update connections to flush out messages _after_ broadcast + // local connection? + if (connection is LocalConnectionToServer localConnection) + { + localConnection.Update(); + } + // remote connection? + else if (connection is NetworkConnectionToServer remoteConnection) + { + // only update things while connected + if (active && connectState == ConnectState.Connected) + { + // update NetworkTime + NetworkTime.UpdateClient(); + + // update connection to flush out batched messages + remoteConnection.Update(); + } + } + + // process all outgoing messages after updating the world + if (Transport.active != null) + Transport.active.ClientLateUpdate(); + } + + // destroy ///////////////////////////////////////////////////////////// + /// Destroys all networked objects on the client. + // Note: NetworkServer.CleanupNetworkIdentities does the same on server. + public static void DestroyAllClientObjects() + { + // user can modify spawned lists which causes InvalidOperationException + // list can modified either in UnSpawnHandler or in OnDisable/OnDestroy + // we need the Try/Catch so that the rest of the shutdown does not get stopped + try + { + foreach (NetworkIdentity identity in spawned.Values) + { + if (identity != null && identity.gameObject != null) + { + if (identity.isLocalPlayer) + identity.OnStopLocalPlayer(); + + identity.OnStopClient(); + + // NetworkClient.Shutdown calls DestroyAllClientObjects. + // which destroys all objects in NetworkClient.spawned. + // => NC.spawned contains owned & observed objects + // => in host mode, we CAN NOT destroy observed objects. + // => that would destroy them other connection's objects + // on the host server, making them disconnect. + // https://github.com/vis2k/Mirror/issues/2954 + bool hostOwned = identity.connectionToServer is LocalConnectionToServer; + bool shouldDestroy = !identity.isServer || hostOwned; + if (shouldDestroy) + { + bool wasUnspawned = InvokeUnSpawnHandler(identity.assetId, identity.gameObject); + + // unspawned objects should be reset for reuse later. + if (wasUnspawned) + { + identity.Reset(); + } + // without unspawn handler, we need to disable/destroy. + else + { + // scene objects are reset and disabled. + // they always stay in the scene, we don't destroy them. + if (identity.sceneId != 0) + { + identity.Reset(); + identity.gameObject.SetActive(false); + } + // spawned objects are destroyed + else + { + GameObject.Destroy(identity.gameObject); + } + } + } + } + } + spawned.Clear(); + connection?.owned.Clear(); + } + catch (InvalidOperationException e) + { + Debug.LogException(e); + Debug.LogError("Could not DestroyAllClientObjects because spawned list was modified during loop, make sure you are not modifying NetworkIdentity.spawned by calling NetworkServer.Destroy or NetworkServer.Spawn in OnDestroy or OnDisable."); + } + } + + static void DestroyObject(uint netId) + { + // Debug.Log($"NetworkClient.OnObjDestroy netId: {netId}"); + if (spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null) + { + if (identity.isLocalPlayer) + identity.OnStopLocalPlayer(); + + identity.OnStopClient(); + + // custom unspawn handler for this prefab? (for prefab pools etc.) + if (InvokeUnSpawnHandler(identity.assetId, identity.gameObject)) + { + // reset object after user's handler + identity.Reset(); + } + // otherwise fall back to default Destroy + else if (identity.sceneId == 0) + { + // don't call reset before destroy so that values are still set in OnDestroy + GameObject.Destroy(identity.gameObject); + } + // scene object.. disable it in scene instead of destroying + else + { + identity.gameObject.SetActive(false); + spawnableObjects[identity.sceneId] = identity; + // reset for scene objects + identity.Reset(); + } + + // remove from dictionary no matter how it is unspawned + connection.owned.Remove(identity); // if any + spawned.Remove(netId); + } + //else Debug.LogWarning($"Did not find target for destroy message for {netId}"); + } + + // shutdown //////////////////////////////////////////////////////////// + /// Shutdown the client. + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + public static void Shutdown() + { + //Debug.Log("Shutting down client."); + + // objects need to be destroyed before spawners are cleared + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3334 + DestroyAllClientObjects(); + + // calls prefabs.Clear(); + // calls spawnHandlers.Clear(); + // calls unspawnHandlers.Clear(); + ClearSpawners(); + + spawned.Clear(); + connection?.owned.Clear(); + handlers.Clear(); + spawnableObjects.Clear(); + + // IMPORTANT: do NOT call NetworkIdentity.ResetStatics() here! + // calling StopClient() in host mode would reset nextNetId to 1, + // causing next connection to have a duplicate netId accidentally. + // => see also: https://github.com/vis2k/Mirror/issues/2954 + //NetworkIdentity.ResetStatics(); + // => instead, reset only the client sided statics. + NetworkIdentity.ResetClientStatics(); + + // disconnect the client connection. + // we do NOT call Transport.Shutdown, because someone only called + // NetworkClient.Shutdown. we can't assume that the server is + // supposed to be shut down too! + if (Transport.active != null) + Transport.active.ClientDisconnect(); + + // reset statics + connectState = ConnectState.None; + connection = null; + localPlayer = null; + ready = false; + isSpawnFinished = false; + isLoadingScene = false; + lastSendTime = 0; + + unbatcher = new Unbatcher(); + + // clear events. someone might have hooked into them before, but + // we don't want to use those hooks after Shutdown anymore. + OnConnectedEvent = null; + OnDisconnectedEvent = null; + OnErrorEvent = null; + } + + // GUI ///////////////////////////////////////////////////////////////// + // called from NetworkManager to display timeline interpolation status. + // useful to indicate catchup / slowdown / dynamic adjustment etc. + public static void OnGUI() + { + // only if in world + if (!ready) return; + + GUILayout.BeginArea(new Rect(10, 5, 800, 50)); + + GUILayout.BeginHorizontal("Box"); + GUILayout.Label("Snapshot Interp.:"); + // color while catching up / slowing down + if (localTimescale > 1) GUI.color = Color.green; // green traffic light = go fast + else if (localTimescale < 1) GUI.color = Color.red; // red traffic light = go slow + else GUI.color = Color.white; + GUILayout.Box($"timeline: {localTimeline:F2}"); + GUILayout.Box($"buffer: {snapshots.Count}"); + GUILayout.Box($"DriftEMA: {NetworkClient.driftEma.Value:F2}"); + GUILayout.Box($"DelTimeEMA: {NetworkClient.deliveryTimeEma.Value:F2}"); + GUILayout.Box($"timescale: {localTimescale:F2}"); + GUILayout.Box($"BTM: {NetworkClient.bufferTimeMultiplier:F2}"); // current dynamically adjusted multiplier + GUILayout.Box($"RTT: {NetworkTime.rtt * 1000:F0}ms"); + GUILayout.EndHorizontal(); + + GUILayout.EndArea(); + } + } +} diff --git a/Assets/Mirror/Core/NetworkClient.cs.meta b/Assets/Mirror/Core/NetworkClient.cs.meta new file mode 100644 index 0000000..20cb211 --- /dev/null +++ b/Assets/Mirror/Core/NetworkClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: abe6be14204d94224a3e7cd99dd2ea73 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkClient_TimeInterpolation.cs b/Assets/Mirror/Core/NetworkClient_TimeInterpolation.cs new file mode 100644 index 0000000..963ec2b --- /dev/null +++ b/Assets/Mirror/Core/NetworkClient_TimeInterpolation.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + public static partial class NetworkClient + { + // snapshot interpolation settings ///////////////////////////////////// + // TODO expose the settings to the user later. + // via NetMan or NetworkClientConfig or NetworkClient as component etc. + public static SnapshotInterpolationSettings snapshotSettings = new SnapshotInterpolationSettings(); + + // obsolete snapshot settings access + // DEPRECATED 2023-03-11 + // [Obsolete("NetworkClient snapshot interpolation settings were moved to NetworkClient.snapshotSettings.*")] + // public static double bufferTimeMultiplier => currentBufferTimeMultiplier; + [Obsolete("NetworkClient snapshot interpolation settings were moved to NetworkClient.snapshotSettings.*")] + public static float catchupNegativeThreshold => snapshotSettings.catchupNegativeThreshold; + [Obsolete("NetworkClient snapshot interpolation settings were moved to NetworkClient.snapshotSettings.*")] + public static float catchupPositiveThreshold => snapshotSettings.catchupPositiveThreshold; + [Obsolete("NetworkClient snapshot interpolation settings were moved to NetworkClient.snapshotSettings.*")] + public static double catchupSpeed => snapshotSettings.catchupSpeed; + [Obsolete("NetworkClient snapshot interpolation settings were moved to NetworkClient.snapshotSettings.*")] + public static double slowdownSpeed => snapshotSettings.slowdownSpeed; + [Obsolete("NetworkClient snapshot interpolation settings were moved to NetworkClient.snapshotSettings.*")] + public static int driftEmaDuration => snapshotSettings.driftEmaDuration; + + // snapshot interpolation runtime data ///////////////////////////////// + // buffer time is dynamically adjusted. + // store the current multiplier here, without touching the original in settings. + // this way we can easily reset to or compare with original where needed. + public static double bufferTimeMultiplier; + + // original buffer time based on the settings + // dynamically adjusted buffer time based on dynamically adjusted multiplier + public static double initialBufferTime => NetworkServer.sendInterval * snapshotSettings.bufferTimeMultiplier; + public static double bufferTime => NetworkServer.sendInterval * bufferTimeMultiplier; + + // + public static SortedList snapshots = new SortedList(); + + // for smooth interpolation, we need to interpolate along server time. + // any other time (arrival on client, client local time, etc.) is not + // going to give smooth results. + // in other words, this is the remote server's time, but adjusted. + // + // internal for use from NetworkTime. + // double for long running servers, see NetworkTime comments. + internal static double localTimeline; + + // catchup / slowdown adjustments are applied to timescale, + // to be adjusted in every update instead of when receiving messages. + internal static double localTimescale = 1; + + // catchup ///////////////////////////////////////////////////////////// + + + // we use EMA to average the last second worth of snapshot time diffs. + // manually averaging the last second worth of values with a for loop + // would be the same, but a moving average is faster because we only + // ever add one value. + static ExponentialMovingAverage driftEma; + + // dynamic buffer time adjustment ////////////////////////////////////// + // dynamically adjusts bufferTimeMultiplier for smooth results. + // to understand how this works, try this manually: + // + // - disable dynamic adjustment + // - set jitter = 0.2 (20% is a lot!) + // - notice some stuttering + // - disable interpolation to see just how much jitter this really is(!) + // - enable interpolation again + // - manually increase bufferTimeMultiplier to 3-4 + // ... the cube slows down (blue) until it's smooth + // - with dynamic adjustment enabled, it will set 4 automatically + // ... the cube slows down (blue) until it's smooth as well + // + // note that 20% jitter is extreme. + // for this to be perfectly smooth, set the safety tolerance to '2'. + // but realistically this is not necessary, and '1' is enough. + [Header("Snapshot Interpolation: Dynamic Adjustment")] + [Tooltip("Automatically adjust bufferTimeMultiplier for smooth results.\nSets a low multiplier on stable connections, and a high multiplier on jittery connections.")] + public static bool dynamicAdjustment = true; + + [Tooltip("Safety buffer that is always added to the dynamic bufferTimeMultiplier adjustment.")] + public static float dynamicAdjustmentTolerance = 1; // 1 is realistically just fine, 2 is very very safe even for 20% jitter. can be half a frame too. (see above comments) + + [Tooltip("Dynamic adjustment is computed over n-second exponential moving average standard deviation.")] + public static int deliveryTimeEmaDuration = 2; // 1-2s recommended to capture average delivery time + static ExponentialMovingAverage deliveryTimeEma; // average delivery time (standard deviation gives average jitter) + + // OnValidate: see NetworkClient.cs + // add snapshot & initialize client interpolation time if needed + + // initialization called from Awake + static void InitTimeInterpolation() + { + // reset timeline, localTimescale & snapshots from last session (if any) + bufferTimeMultiplier = snapshotSettings.bufferTimeMultiplier; + localTimeline = 0; + localTimescale = 1; + snapshots.Clear(); + + // initialize EMA with 'emaDuration' seconds worth of history. + // 1 second holds 'sendRate' worth of values. + // multiplied by emaDuration gives n-seconds. + driftEma = new ExponentialMovingAverage(NetworkServer.sendRate * snapshotSettings.driftEmaDuration); + deliveryTimeEma = new ExponentialMovingAverage(NetworkServer.sendRate * snapshotSettings.deliveryTimeEmaDuration); + } + + // server sends TimeSnapshotMessage every sendInterval. + // batching already includes the remoteTimestamp. + // we simply insert it on-message here. + // => only for reliable channel. unreliable would always arrive earlier. + static void OnTimeSnapshotMessage(TimeSnapshotMessage _) + { + // insert another snapshot for snapshot interpolation. + // before calling OnDeserialize so components can use + // NetworkTime.time and NetworkTime.timeStamp. + + // Unity 2019 doesn't have Time.timeAsDouble yet + OnTimeSnapshot(new TimeSnapshot(connection.remoteTimeStamp, NetworkTime.localTime)); + } + + // see comments at the top of this file + public static void OnTimeSnapshot(TimeSnapshot snap) + { + // Debug.Log($"NetworkClient: OnTimeSnapshot @ {snap.remoteTime:F3}"); + + // (optional) dynamic adjustment + if (snapshotSettings.dynamicAdjustment) + { + // set bufferTime on the fly. + // shows in inspector for easier debugging :) + bufferTimeMultiplier = SnapshotInterpolation.DynamicAdjustment( + NetworkServer.sendInterval, + deliveryTimeEma.StandardDeviation, + snapshotSettings.dynamicAdjustmentTolerance + ); + } + + // insert into the buffer & initialize / adjust / catchup + SnapshotInterpolation.InsertAndAdjust( + snapshots, + snapshotSettings.bufferLimit, + snap, + ref localTimeline, + ref localTimescale, + NetworkServer.sendInterval, + bufferTime, + snapshotSettings.catchupSpeed, + snapshotSettings.slowdownSpeed, + ref driftEma, + snapshotSettings.catchupNegativeThreshold, + snapshotSettings.catchupPositiveThreshold, + ref deliveryTimeEma); + + // Debug.Log($"inserted TimeSnapshot remote={snap.remoteTime:F2} local={snap.localTime:F2} total={snapshots.Count}"); + } + + // call this from early update, so the timeline is safe to use in update + static void UpdateTimeInterpolation() + { + // only while we have snapshots. + // timeline starts when the first snapshot arrives. + if (snapshots.Count > 0) + { + // progress local timeline. + // NetworkTime uses unscaled time and ignores Time.timeScale. + // fixes Time.timeScale getting server & client time out of sync: + // https://github.com/MirrorNetworking/Mirror/issues/3409 + SnapshotInterpolation.StepTime(Time.unscaledDeltaTime, ref localTimeline, localTimescale); + + // progress local interpolation. + // TimeSnapshot doesn't interpolate anything. + // this is merely to keep removing older snapshots. + SnapshotInterpolation.StepInterpolation(snapshots, localTimeline, out _, out _, out double t); + // Debug.Log($"NetworkClient SnapshotInterpolation @ {localTimeline:F2} t={t:F2}"); + } + } + } +} diff --git a/Assets/Mirror/Core/NetworkClient_TimeInterpolation.cs.meta b/Assets/Mirror/Core/NetworkClient_TimeInterpolation.cs.meta new file mode 100644 index 0000000..3c52ae1 --- /dev/null +++ b/Assets/Mirror/Core/NetworkClient_TimeInterpolation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad039071a9cc487b9f7831d28bbe8e83 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkConnection.cs b/Assets/Mirror/Core/NetworkConnection.cs new file mode 100644 index 0000000..4827548 --- /dev/null +++ b/Assets/Mirror/Core/NetworkConnection.cs @@ -0,0 +1,206 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + /// Base NetworkConnection class for server-to-client and client-to-server connection. + public abstract class NetworkConnection + { + public const int LocalConnectionId = 0; + + /// Unique identifier for this connection that is assigned by the transport layer. + // assigned by transport, this id is unique for every connection on server. + // clients don't know their own id and they don't know other client's ids. + public readonly int connectionId; + + /// Flag that indicates the client has been authenticated. + public bool isAuthenticated; + + /// General purpose object to hold authentication data, character selection, tokens, etc. + public object authenticationData; + + /// A server connection is ready after joining the game world. + // TODO move this to ConnectionToClient so the flag only lives on server + // connections? clients could use NetworkClient.ready to avoid redundant + // state. + public bool isReady; + + /// Last time a message was received for this connection. Includes system and user messages. + public float lastMessageTime; + + /// This connection's main object (usually the player object). + public NetworkIdentity identity { get; internal set; } + + /// All NetworkIdentities owned by this connection. Can be main player, pets, etc. + // .owned is now valid both on server and on client. + // IMPORTANT: this needs to be , not . + // fixes a bug where DestroyOwnedObjects wouldn't find the + // netId anymore: https://github.com/vis2k/Mirror/issues/1380 + // Works fine with NetworkIdentity pointers though. + public readonly HashSet owned = new HashSet(); + + // batching from server to client & client to server. + // fewer transport calls give us significantly better performance/scale. + // + // for a 64KB max message transport and 64 bytes/message on average, we + // reduce transport calls by a factor of 1000. + // + // depending on the transport, this can give 10x performance. + // + // Dictionary because we have multiple channels. + protected Dictionary batches = new Dictionary(); + + /// last batch's remote timestamp. not interpolated. useful for NetworkTransform etc. + // for any given NetworkMessage/Rpc/Cmd/OnSerialize, this was the time + // on the REMOTE END when it was sent. + // + // NOTE: this is NOT in NetworkTime, it needs to be per-connection + // because the server receives different batch timestamps from + // different connections. + public double remoteTimeStamp { get; internal set; } + + internal NetworkConnection() + { + // set lastTime to current time when creating connection to make + // sure it isn't instantly kicked for inactivity + lastMessageTime = Time.time; + } + + internal NetworkConnection(int networkConnectionId) : this() + { + connectionId = networkConnectionId; + } + + // TODO if we only have Reliable/Unreliable, then we could initialize + // two batches and avoid this code + protected Batcher GetBatchForChannelId(int channelId) + { + // get existing or create new writer for the channelId + Batcher batch; + if (!batches.TryGetValue(channelId, out batch)) + { + // get max batch size for this channel + int threshold = Transport.active.GetBatchThreshold(channelId); + + // create batcher + batch = new Batcher(threshold); + batches[channelId] = batch; + } + return batch; + } + + // Send stage one: NetworkMessage + /// Send a NetworkMessage to this connection over the given channel. + public void Send(T message, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // pack message + NetworkMessages.Pack(message, writer); + + // validate packet size immediately. + // we know how much can fit into one batch at max. + // if it's larger, log an error immediately with the type . + // previously we only logged in Update() when processing batches, + // but there we don't have type information anymore. + int max = NetworkMessages.MaxMessageSize(channelId); + if (writer.Position > max) + { + Debug.LogError($"NetworkConnection.Send: message of type {typeof(T)} with a size of {writer.Position} bytes is larger than the max allowed message size in one batch: {max}.\nThe message was dropped, please make it smaller."); + return; + } + + // send allocation free + NetworkDiagnostics.OnSend(message, channelId, writer.Position, 1); + Send(writer.ToArraySegment(), channelId); + } + } + + // Send stage two: serialized NetworkMessage as ArraySegment + // internal because no one except Mirror should send bytes directly to + // the client. they would be detected as a message. send messages instead. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal virtual void Send(ArraySegment segment, int channelId = Channels.Reliable) + { + //Debug.Log($"ConnectionSend {this} bytes:{BitConverter.ToString(segment.Array, segment.Offset, segment.Count)}"); + + // add to batch no matter what. + // batching will try to fit as many as possible into MTU. + // but we still allow > MTU, e.g. kcp max packet size 144kb. + // those are simply sent as single batches. + // + // IMPORTANT: do NOT send > batch sized messages directly: + // - data race: large messages would be sent directly. small + // messages would be sent in the batch at the end of frame + // - timestamps: if batching assumes a timestamp, then large + // messages need that too. + // + // NOTE: we ALWAYS batch. it's not optional, because the + // receiver needs timestamps for NT etc. + // + // NOTE: we do NOT ValidatePacketSize here yet. the final packet + // will be the full batch, including timestamp. + GetBatchForChannelId(channelId).AddMessage(segment, NetworkTime.localTime); + } + + // Send stage three: hand off to transport + protected abstract void SendToTransport(ArraySegment segment, int channelId = Channels.Reliable); + + // flush batched messages at the end of every Update. + internal virtual void Update() + { + // go through batches for all channels + // foreach ((int key, Batcher batcher) in batches) // Unity 2020 doesn't support deconstruct yet + foreach (KeyValuePair kvp in batches) + { + // make and send as many batches as necessary from the stored + // messages. + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // make a batch with our local time (double precision) + while (kvp.Value.GetBatch(writer)) + { + // message size is validated in Send, with test coverage. + // we can send directly without checking again. + ArraySegment segment = writer.ToArraySegment(); + + // send to transport + SendToTransport(segment, kvp.Key); + //UnityEngine.Debug.Log($"sending batch of {writer.Position} bytes for channel={kvp.Key} connId={connectionId}"); + + // reset writer for each new batch + writer.Position = 0; + } + } + } + } + + /// Check if we received a message within the last 'timeout' seconds. + internal virtual bool IsAlive(float timeout) => Time.time - lastMessageTime < timeout; + + /// Disconnects this connection. + // for future reference, here is how Disconnects work in Mirror. + // + // first, there are two types of disconnects: + // * voluntary: the other end simply disconnected + // * involuntary: server disconnects a client by itself + // + // UNET had special (complex) code to handle both cases differently. + // + // Mirror handles both cases the same way: + // * Disconnect is called from TOP to BOTTOM + // NetworkServer/Client -> NetworkConnection -> Transport.Disconnect() + // * Disconnect is handled from BOTTOM to TOP + // Transport.OnDisconnected -> ... + // + // in other words, calling Disconnect() does no cleanup whatsoever. + // it simply asks the transport to disconnect. + // then later the transport events will do the clean up. + public abstract void Disconnect(); + + public override string ToString() => $"connection({connectionId})"; + } +} diff --git a/Assets/Mirror/Core/NetworkConnection.cs.meta b/Assets/Mirror/Core/NetworkConnection.cs.meta new file mode 100644 index 0000000..32c4ba2 --- /dev/null +++ b/Assets/Mirror/Core/NetworkConnection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 11ea41db366624109af1f0834bcdde2f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkConnectionToClient.cs b/Assets/Mirror/Core/NetworkConnectionToClient.cs new file mode 100644 index 0000000..b6ff49a --- /dev/null +++ b/Assets/Mirror/Core/NetworkConnectionToClient.cs @@ -0,0 +1,223 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + public class NetworkConnectionToClient : NetworkConnection + { + // rpcs are collected in a buffer, and then flushed out together. + // this way we don't need one NetworkMessage per rpc. + // => prepares for LocalWorldState as well. + // ensure max size when adding! + readonly NetworkWriter reliableRpcs = new NetworkWriter(); + readonly NetworkWriter unreliableRpcs = new NetworkWriter(); + + public virtual string address => Transport.active.ServerGetClientAddress(connectionId); + + /// NetworkIdentities that this connection can see + // TODO move to server's NetworkConnectionToClient? + public readonly HashSet observing = new HashSet(); + + // Deprecated 2022-10-13 + [Obsolete(".clientOwnedObjects was renamed to .owned :)")] + public HashSet clientOwnedObjects => owned; + + // unbatcher + public Unbatcher unbatcher = new Unbatcher(); + + // server runs a time snapshot interpolation for each client's local time. + // this is necessary for client auth movement to still be smooth on the + // server for host mode. + // TODO move them along server's timeline in the future. + // perhaps with an offset. + // for now, keep compatibility by manually constructing a timeline. + ExponentialMovingAverage driftEma; + ExponentialMovingAverage deliveryTimeEma; // average delivery time (standard deviation gives average jitter) + public double remoteTimeline; + public double remoteTimescale; + double bufferTimeMultiplier = 2; + double bufferTime => NetworkServer.sendInterval * bufferTimeMultiplier; + + // + readonly SortedList snapshots = new SortedList(); + + // Snapshot Buffer size limit to avoid ever growing list memory consumption attacks from clients. + public int snapshotBufferSizeLimit = 64; + + // ping for rtt (round trip time) + // useful for statistics, lag compensation, etc. + double lastPingTime = 0; + internal ExponentialMovingAverage _rtt = new ExponentialMovingAverage(NetworkTime.PingWindowSize); + + /// Round trip time (in seconds) that it takes a message to go server->client->server. + public double rtt => _rtt.Value; + + public NetworkConnectionToClient(int networkConnectionId) + : base(networkConnectionId) + { + // initialize EMA with 'emaDuration' seconds worth of history. + // 1 second holds 'sendRate' worth of values. + // multiplied by emaDuration gives n-seconds. + driftEma = new ExponentialMovingAverage(NetworkServer.sendRate * NetworkClient.snapshotSettings.driftEmaDuration); + deliveryTimeEma = new ExponentialMovingAverage(NetworkServer.sendRate * NetworkClient.snapshotSettings.deliveryTimeEmaDuration); + + // buffer limit should be at least multiplier to have enough in there + snapshotBufferSizeLimit = Mathf.Max((int)NetworkClient.snapshotSettings.bufferTimeMultiplier, snapshotBufferSizeLimit); + } + + public void OnTimeSnapshot(TimeSnapshot snapshot) + { + // protect against ever growing buffer size attacks + if (snapshots.Count >= snapshotBufferSizeLimit) return; + + // (optional) dynamic adjustment + if (NetworkClient.snapshotSettings.dynamicAdjustment) + { + // set bufferTime on the fly. + // shows in inspector for easier debugging :) + bufferTimeMultiplier = SnapshotInterpolation.DynamicAdjustment( + NetworkServer.sendInterval, + deliveryTimeEma.StandardDeviation, + NetworkClient.snapshotSettings.dynamicAdjustmentTolerance + ); + // Debug.Log($"[Server]: {name} delivery std={serverDeliveryTimeEma.StandardDeviation} bufferTimeMult := {bufferTimeMultiplier} "); + } + + // insert into the server buffer & initialize / adjust / catchup + SnapshotInterpolation.InsertAndAdjust( + snapshots, + NetworkClient.snapshotSettings.bufferLimit, + snapshot, + ref remoteTimeline, + ref remoteTimescale, + NetworkServer.sendInterval, + bufferTime, + NetworkClient.snapshotSettings.catchupSpeed, + NetworkClient.snapshotSettings.slowdownSpeed, + ref driftEma, + NetworkClient.snapshotSettings.catchupNegativeThreshold, + NetworkClient.snapshotSettings.catchupPositiveThreshold, + ref deliveryTimeEma + ); + } + + public void UpdateTimeInterpolation() + { + // timeline starts when the first snapshot arrives. + if (snapshots.Count > 0) + { + // progress local timeline. + SnapshotInterpolation.StepTime(Time.unscaledDeltaTime, ref remoteTimeline, remoteTimescale); + + // progress local interpolation. + // TimeSnapshot doesn't interpolate anything. + // this is merely to keep removing older snapshots. + SnapshotInterpolation.StepInterpolation(snapshots, remoteTimeline, out _, out _, out _); + // Debug.Log($"NetworkClient SnapshotInterpolation @ {localTimeline:F2} t={t:F2}"); + } + } + + // Send stage three: hand off to transport + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected override void SendToTransport(ArraySegment segment, int channelId = Channels.Reliable) => + Transport.active.ServerSend(connectionId, segment, channelId); + + protected virtual void UpdatePing() + { + // localTime (double) instead of Time.time for accuracy over days + if (NetworkTime.localTime >= lastPingTime + NetworkTime.PingInterval) + { + // TODO it would be safer for the server to store the last N + // messages' timestamp and only send a message number. + // This way client's can't just modify the timestamp. + NetworkPingMessage pingMessage = new NetworkPingMessage(NetworkTime.localTime); + Send(pingMessage, Channels.Unreliable); + lastPingTime = NetworkTime.localTime; + } + } + + internal override void Update() + { + UpdatePing(); + base.Update(); + } + + /// Disconnects this connection. + public override void Disconnect() + { + // set not ready and handle clientscene disconnect in any case + // (might be client or host mode here) + isReady = false; + reliableRpcs.Position = 0; + unreliableRpcs.Position = 0; + Transport.active.ServerDisconnect(connectionId); + + // IMPORTANT: NetworkConnection.Disconnect() is NOT called for + // voluntary disconnects from the other end. + // -> so all 'on disconnect' cleanup code needs to be in + // OnTransportDisconnect, where it's called for both voluntary + // and involuntary disconnects! + } + + internal void AddToObserving(NetworkIdentity netIdentity) + { + observing.Add(netIdentity); + + // spawn identity for this conn + NetworkServer.ShowForConnection(netIdentity, this); + } + + internal void RemoveFromObserving(NetworkIdentity netIdentity, bool isDestroyed) + { + observing.Remove(netIdentity); + + if (!isDestroyed) + { + // hide identity for this conn + NetworkServer.HideForConnection(netIdentity, this); + } + } + + internal void RemoveFromObservingsObservers() + { + foreach (NetworkIdentity netIdentity in observing) + { + netIdentity.RemoveObserver(this); + } + observing.Clear(); + } + + internal void AddOwnedObject(NetworkIdentity obj) + { + owned.Add(obj); + } + + internal void RemoveOwnedObject(NetworkIdentity obj) + { + owned.Remove(obj); + } + + internal void DestroyOwnedObjects() + { + // create a copy because the list might be modified when destroying + HashSet tmp = new HashSet(owned); + foreach (NetworkIdentity netIdentity in tmp) + { + if (netIdentity != null) + { + // unspawn scene objects, destroy instantiated objects. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3538 + if (netIdentity.sceneId != 0) + NetworkServer.UnSpawn(netIdentity.gameObject); + else + NetworkServer.Destroy(netIdentity.gameObject); + } + } + + // clear the hashset because we destroyed them all + owned.Clear(); + } + } +} diff --git a/Assets/Mirror/Core/NetworkConnectionToClient.cs.meta b/Assets/Mirror/Core/NetworkConnectionToClient.cs.meta new file mode 100644 index 0000000..6001a71 --- /dev/null +++ b/Assets/Mirror/Core/NetworkConnectionToClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bb2195f8b29d24f0680a57fde2e9fd09 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkConnectionToServer.cs b/Assets/Mirror/Core/NetworkConnectionToServer.cs new file mode 100644 index 0000000..496813d --- /dev/null +++ b/Assets/Mirror/Core/NetworkConnectionToServer.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public class NetworkConnectionToServer : NetworkConnection + { + // Send stage three: hand off to transport + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected override void SendToTransport(ArraySegment segment, int channelId = Channels.Reliable) => + Transport.active.ClientSend(segment, channelId); + + /// Disconnects this connection. + public override void Disconnect() + { + // set not ready and handle clientscene disconnect in any case + // (might be client or host mode here) + // TODO remove redundant state. have one source of truth for .ready! + isReady = false; + NetworkClient.ready = false; + Transport.active.ClientDisconnect(); + } + } +} diff --git a/Assets/Mirror/Core/NetworkConnectionToServer.cs.meta b/Assets/Mirror/Core/NetworkConnectionToServer.cs.meta new file mode 100644 index 0000000..3424b58 --- /dev/null +++ b/Assets/Mirror/Core/NetworkConnectionToServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 761977cbf38a34ded9dd89de45445675 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkDiagnostics.cs b/Assets/Mirror/Core/NetworkDiagnostics.cs new file mode 100644 index 0000000..1cdc96f --- /dev/null +++ b/Assets/Mirror/Core/NetworkDiagnostics.cs @@ -0,0 +1,63 @@ +using System; + +namespace Mirror +{ + /// Profiling statistics for tool to subscribe to (profiler etc.) + public static class NetworkDiagnostics + { + /// Describes an outgoing message + public readonly struct MessageInfo + { + /// The message being sent + public readonly NetworkMessage message; + /// channel through which the message was sent + public readonly int channel; + /// how big was the message (does not include transport headers) + public readonly int bytes; + /// How many connections was the message sent to. + public readonly int count; + + internal MessageInfo(NetworkMessage message, int channel, int bytes, int count) + { + this.message = message; + this.channel = channel; + this.bytes = bytes; + this.count = count; + } + } + + /// Event for when Mirror sends a message. Can be subscribed to. + public static event Action OutMessageEvent; + + /// Event for when Mirror receives a message. Can be subscribed to. + public static event Action InMessageEvent; + + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [UnityEngine.RuntimeInitializeOnLoadMethod] + static void ResetStatics() + { + InMessageEvent = null; + OutMessageEvent = null; + } + + internal static void OnSend(T message, int channel, int bytes, int count) + where T : struct, NetworkMessage + { + if (count > 0 && OutMessageEvent != null) + { + MessageInfo outMessage = new MessageInfo(message, channel, bytes, count); + OutMessageEvent?.Invoke(outMessage); + } + } + + internal static void OnReceive(T message, int channel, int bytes) + where T : struct, NetworkMessage + { + if (InMessageEvent != null) + { + MessageInfo inMessage = new MessageInfo(message, channel, bytes, 1); + InMessageEvent?.Invoke(inMessage); + } + } + } +} diff --git a/Assets/Mirror/Core/NetworkDiagnostics.cs.meta b/Assets/Mirror/Core/NetworkDiagnostics.cs.meta new file mode 100644 index 0000000..fe37316 --- /dev/null +++ b/Assets/Mirror/Core/NetworkDiagnostics.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c3754b39e5f8740fd93f3337b2c4274e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkIdentity.cs b/Assets/Mirror/Core/NetworkIdentity.cs new file mode 100644 index 0000000..a1d7397 --- /dev/null +++ b/Assets/Mirror/Core/NetworkIdentity.cs @@ -0,0 +1,1384 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using Mirror.RemoteCalls; +using UnityEngine; +using UnityEngine.Serialization; + +#if UNITY_EDITOR +using UnityEditor; + +#if UNITY_2021_2_OR_NEWER +using UnityEditor.SceneManagement; +#else +using UnityEditor.Experimental.SceneManagement; +#endif +#endif + +namespace Mirror +{ + // Default = use interest management + // ForceHidden = useful to hide monsters while they respawn etc. + // ForceShown = useful to have score NetworkIdentities that always broadcast + // to everyone etc. + public enum Visibility { Default, ForceHidden, ForceShown } + + public struct NetworkIdentitySerialization + { + // IMPORTANT: int tick avoids floating point inaccuracy over days/weeks + public int tick; + public NetworkWriter ownerWriter; + public NetworkWriter observersWriter; + } + + /// NetworkIdentity identifies objects across the network. + [DisallowMultipleComponent] + // NetworkIdentity.Awake initializes all NetworkComponents. + // let's make sure it's always called before their Awake's. + [DefaultExecutionOrder(-1)] + [AddComponentMenu("Network/Network Identity")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-identity")] + public sealed class NetworkIdentity : MonoBehaviour + { + /// Returns true if running as a client and this object was spawned by a server. + // + // IMPORTANT: + // OnStartClient sets it to true. we NEVER set it to false after. + // otherwise components like Skillbars couldn't use OnDestroy() + // for saving, etc. since isClient may have been reset before + // OnDestroy was called. + // + // we also DO NOT make it dependent on NetworkClient.active or similar. + // we set it, then never change it. that's the user's expectation too. + // + // => fixes https://github.com/vis2k/Mirror/issues/1475 + public bool isClient { get; internal set; } + + /// Returns true if NetworkServer.active and server is not stopped. + // + // IMPORTANT: + // OnStartServer sets it to true. we NEVER set it to false after. + // otherwise components like Skillbars couldn't use OnDestroy() + // for saving, etc. since isServer may have been reset before + // OnDestroy was called. + // + // we also DO NOT make it dependent on NetworkServer.active or similar. + // we set it, then never change it. that's the user's expectation too. + // + // => fixes https://github.com/vis2k/Mirror/issues/1484 + // => fixes https://github.com/vis2k/Mirror/issues/2533 + public bool isServer { get; internal set; } + + /// Return true if this object represents the player on the local machine. + // + // IMPORTANT: + // OnStartLocalPlayer sets it to true. we NEVER set it to false after. + // otherwise components like Skillbars couldn't use OnDestroy() + // for saving, etc. since isLocalPlayer may have been reset before + // OnDestroy was called. + // + // we also DO NOT make it dependent on NetworkClient.localPlayer or similar. + // we set it, then never change it. that's the user's expectation too. + // + // => fixes https://github.com/vis2k/Mirror/issues/2615 + public bool isLocalPlayer { get; internal set; } + + /// True if this object only exists on the server + public bool isServerOnly => isServer && !isClient; + + /// True if this object exists on a client that is not also acting as a server. + public bool isClientOnly => isClient && !isServer; + + /// isOwned is true on the client if this NetworkIdentity is one of the .owned entities of our connection on the server. + // for example: main player & pets are owned. monsters & npcs aren't. + public bool isOwned { get; internal set; } + + // Deprecated 2022-10-13 + [Obsolete(".hasAuthority was renamed to .isOwned. This is easier to understand and prepares for SyncDirection, where there is a difference betwen isOwned and authority.")] + public bool hasAuthority => isOwned; + + /// The set of network connections (players) that can see this object. + public readonly Dictionary observers = + new Dictionary(); + + /// The unique network Id of this object (unique at runtime). + public uint netId { get; internal set; } + + /// Unique identifier for NetworkIdentity objects within a scene, used for spawning scene objects. + // persistent scene id (see AssignSceneID comments) + [FormerlySerializedAs("m_SceneId"), HideInInspector] + public ulong sceneId; + + // assetId used to spawn prefabs across the network. + // originally a Guid, but a 4 byte uint is sufficient + // (as suggested by james) + // + // it's also easier to work with for serialization etc. + // serialized and visible in inspector for easier debugging + [SerializeField] uint _assetId; + + // The AssetId trick: + // Ideally we would have a serialized 'Guid m_AssetId' but Unity can't + // serialize it because Guid's internal bytes are private + // + // Using just the Guid string would work, but it's 32 chars long and + // would then be sent over the network as 64 instead of 16 bytes + // + // => The solution is to serialize the string internally here and then + // use the real 'Guid' type for everything else via .assetId + public uint assetId + { + get + { +#if UNITY_EDITOR + // old UNET comment: + // This is important because sometimes OnValidate does not run + // (like when adding NetworkIdentity to prefab with no child links) + if (_assetId == 0) + SetupIDs(); +#endif + return _assetId; + } + // assetId is set internally when creating or duplicating a prefab + internal set + { + // should never be empty + if (value == 0) + { + Debug.LogError($"Can not set AssetId to empty guid on NetworkIdentity '{name}', old assetId '{_assetId}'"); + return; + } + + // always set it otherwise. + // for new prefabs, it will set from 0 to N. + // for duplicated prefabs, it will set from N to M. + // either way, it's always set to a valid GUID. + _assetId = value; + // Debug.Log($"Setting AssetId on NetworkIdentity '{name}', new assetId '{value:X4}'"); + } + } + + /// Make this object only exist when the game is running as a server (or host). + [FormerlySerializedAs("m_ServerOnly")] + [Tooltip("Prevents this object from being spawned / enabled on clients")] + public bool serverOnly; + + // Set before Destroy is called so that OnDestroy doesn't try to destroy + // the object again + internal bool destroyCalled; + + /// Client's network connection to the server. This is only valid for player objects on the client. + // TODO change to NetworkConnectionToServer, but might cause some breaking + public NetworkConnection connectionToServer { get; internal set; } + + /// Server's network connection to the client. This is only valid for client-owned objects (including the Player object) on the server. + public NetworkConnectionToClient connectionToClient + { + get => _connectionToClient; + internal set + { + _connectionToClient?.RemoveOwnedObject(this); + _connectionToClient = value; + _connectionToClient?.AddOwnedObject(this); + } + } + NetworkConnectionToClient _connectionToClient; + + // get all NetworkBehaviour components + public NetworkBehaviour[] NetworkBehaviours { get; private set; } + + // to save bandwidth, we send one 64 bit dirty mask + // instead of 1 byte index per dirty component. + // which means we can't allow > 64 components (it's enough). + const int MaxNetworkBehaviours = 64; + + // current visibility + // + // Default = use interest management + // ForceHidden = useful to hide monsters while they respawn etc. + // ForceShown = useful to have score NetworkIdentities that always broadcast + // to everyone etc. + // + // TODO rename to 'visibility' after removing .visibility some day! + [Tooltip("Visibility can overwrite interest management. ForceHidden can be useful to hide monsters while they respawn. ForceShown can be useful for score NetworkIdentities that should always broadcast to everyone in the world.")] + public Visibility visible = Visibility.Default; + + // broadcasting serializes all entities around a player for each player. + // we don't want to serialize one entity twice in the same tick. + // so we cache the last serialization and remember the timestamp so we + // know which Update it was serialized. + // (timestamp is the same while inside Update) + // => this way we don't need to pool thousands of writers either. + // => way easier to store them per object + NetworkIdentitySerialization lastSerialization = new NetworkIdentitySerialization + { + ownerWriter = new NetworkWriter(), + observersWriter = new NetworkWriter() + }; + + // Keep track of all sceneIds to detect scene duplicates + static readonly Dictionary sceneIds = + new Dictionary(); + + // Helper function to handle Command/Rpc + internal void HandleRemoteCall(byte componentIndex, ushort functionHash, RemoteCallType remoteCallType, NetworkReader reader, NetworkConnectionToClient senderConnection = null) + { + // check if unity object has been destroyed + if (this == null) + { + Debug.LogWarning($"{remoteCallType} [{functionHash}] received for deleted object [netId={netId}]"); + return; + } + + // find the right component to invoke the function on + if (componentIndex >= NetworkBehaviours.Length) + { + Debug.LogWarning($"Component [{componentIndex}] not found for [netId={netId}]"); + return; + } + + NetworkBehaviour invokeComponent = NetworkBehaviours[componentIndex]; + if (!RemoteProcedureCalls.Invoke(functionHash, remoteCallType, reader, invokeComponent, senderConnection)) + { + Debug.LogError($"Found no receiver for incoming {remoteCallType} [{functionHash}] on {gameObject.name}, the server and client should have the same NetworkBehaviour instances [netId={netId}]."); + } + } + + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + // internal so it can be called from NetworkServer & NetworkClient + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + internal static void ResetStatics() + { + // reset ALL statics + ResetClientStatics(); + ResetServerStatics(); + } + + // reset only client sided statics. + // don't touch server statics when calling StopClient in host mode. + // https://github.com/vis2k/Mirror/issues/2954 + internal static void ResetClientStatics() + { + previousLocalPlayer = null; + clientAuthorityCallback = null; + } + + internal static void ResetServerStatics() + { + nextNetworkId = 1; + } + + /// Gets the NetworkIdentity from the sceneIds dictionary with the corresponding id + public static NetworkIdentity GetSceneIdentity(ulong id) => sceneIds[id]; + + static uint nextNetworkId = 1; + internal static uint GetNextNetworkId() => nextNetworkId++; + + /// Resets nextNetworkId = 1 + public static void ResetNextNetworkId() => nextNetworkId = 1; + + /// The delegate type for the clientAuthorityCallback. + public delegate void ClientAuthorityCallback(NetworkConnectionToClient conn, NetworkIdentity identity, bool authorityState); + + /// A callback that can be populated to be notified when the client-authority state of objects changes. + public static event ClientAuthorityCallback clientAuthorityCallback; + + // hasSpawned should always be false before runtime + [SerializeField, HideInInspector] bool hasSpawned; + public bool SpawnedFromInstantiate { get; private set; } + + // NetworkBehaviour components are initialized in Awake once. + // Changing them at runtime would get client & server out of sync. + // BUT internal so tests can add them after creating the NetworkIdentity + internal void InitializeNetworkBehaviours() + { + // Get all NetworkBehaviour components, including children. + // Some users need NetworkTransform on child bones, etc. + // => Deterministic: https://forum.unity.com/threads/getcomponentsinchildren.4582/#post-33983 + // => Never null. GetComponents returns [] if none found. + // => Include inactive. We need all child components. + NetworkBehaviours = GetComponentsInChildren(true); + ValidateComponents(); + + // initialize each one + for (int i = 0; i < NetworkBehaviours.Length; ++i) + { + NetworkBehaviour component = NetworkBehaviours[i]; + component.netIdentity = this; + component.ComponentIndex = (byte)i; + } + } + + void ValidateComponents() + { + if (NetworkBehaviours == null) + { + Debug.LogError($"NetworkBehaviours array is null on {gameObject.name}!\n" + + $"Typically this can happen when a networked object is a child of a " + + $"non-networked parent that's disabled, preventing Awake on the networked object " + + $"from being invoked, where the NetworkBehaviours array is initialized.", gameObject); + } + else if (NetworkBehaviours.Length > MaxNetworkBehaviours) + { + Debug.LogError($"NetworkIdentity {name} has too many NetworkBehaviour components: only {MaxNetworkBehaviours} NetworkBehaviour components are allowed in order to save bandwidth.", this); + } + } + + // Awake is only called in Play mode. + // internal so we can call it during unit tests too. + internal void Awake() + { + // initialize NetworkBehaviour components. + // Awake() is called immediately after initialization. + // no one can overwrite it because NetworkIdentity is sealed. + // => doing it here is the fastest and easiest solution. + InitializeNetworkBehaviours(); + + if (hasSpawned) + { + Debug.LogError($"{name} has already spawned. Don't call Instantiate for NetworkIdentities that were in the scene since the beginning (aka scene objects). Otherwise the client won't know which object to use for a SpawnSceneObject message."); + SpawnedFromInstantiate = true; + Destroy(gameObject); + } + hasSpawned = true; + } + + void OnValidate() + { + // OnValidate is not called when using Instantiate, so we can use + // it to make sure that hasSpawned is false + hasSpawned = false; + +#if UNITY_EDITOR + DisallowChildNetworkIdentities(); + SetupIDs(); +#endif + } + + // expose our AssetId Guid to uint mapping code in case projects need to map Guids to uint as well. + // this way their projects won't break if we change our mapping algorithm. + // needs to be available at runtime / builds, don't wrap in #if UNITY_EDITOR + public static uint AssetGuidToUint(Guid guid) => (uint)guid.GetHashCode(); // deterministic + +#if UNITY_EDITOR + // child NetworkIdentities are not supported. + // Disallow them and show an error for the user to fix. + // This needs to work for Prefabs & Scene objects, so the previous check + // in NetworkClient.RegisterPrefab is not enough. + void DisallowChildNetworkIdentities() + { +#if UNITY_2020_3_OR_NEWER + NetworkIdentity[] identities = GetComponentsInChildren(true); +#else + NetworkIdentity[] identities = GetComponentsInChildren(); +#endif + if (identities.Length > 1) + { + // always log the next child component so it's easy to fix. + // if there are multiple, then after removing it'll log the next. + Debug.LogError($"'{name}' has another NetworkIdentity component on '{identities[1].name}'. There should only be one NetworkIdentity, and it must be on the root object. Please remove the other one."); + } + } + + void AssignAssetID(string path) + { + // only set if not empty. fixes https://github.com/vis2k/Mirror/issues/2765 + if (!string.IsNullOrWhiteSpace(path)) + { + // if we generate the assetId then we MUST be sure to set dirty + // in order to save the prefab object properly. otherwise it + // would be regenerated every time we reopen the prefab. + // -> Undo.RecordObject is the new EditorUtility.SetDirty! + // -> we need to call it before changing. + // + // to verify this, duplicate a prefab and double click to open it. + // add a log message if "_assetId != before_". + // without RecordObject, it'll log every time because it's not saved. + Undo.RecordObject(this, "Assigned AssetId"); + + // uint before = _assetId; + Guid guid = new Guid(AssetDatabase.AssetPathToGUID(path)); + assetId = AssetGuidToUint(guid); + // if (_assetId != before) Debug.Log($"Assigned assetId={assetId} to {name}"); + } + } + + void AssignAssetID(GameObject prefab) => AssignAssetID(AssetDatabase.GetAssetPath(prefab)); + + // persistent sceneId assignment + // (because scene objects have no persistent unique ID in Unity) + // + // original UNET used OnPostProcessScene to assign an index based on + // FindObjectOfType order. + // -> this didn't work because FindObjectOfType order isn't deterministic. + // -> one workaround is to sort them by sibling paths, but it can still + // get out of sync when we open scene2 in editor and we have + // DontDestroyOnLoad objects that messed with the sibling index. + // + // we absolutely need a persistent id. challenges: + // * it needs to be 0 for prefabs + // => we set it to 0 in SetupIDs() if prefab! + // * it needs to be only assigned in edit time, not at runtime because + // only the objects that were in the scene since beginning should have + // a scene id. + // => Application.isPlaying check solves that + // * it needs to detect duplicated sceneIds after duplicating scene + // objects + // => sceneIds dict takes care of that + // * duplicating the whole scene file shouldn't result in duplicate + // scene objects + // => buildIndex is shifted into sceneId for that. + // => if we have no scenes in build index then it doesn't matter + // because by definition a build can't switch to other scenes + // => if we do have scenes in build index then it will be != -1 + // note: the duplicated scene still needs to be opened once for it to + // be set properly + // * scene objects need the correct scene index byte even if the scene's + // build index was changed or a duplicated scene wasn't opened yet. + // => OnPostProcessScene is the only function that gets called for + // each scene before runtime, so this is where we set the scene + // byte. + // * disabled scenes in build settings should result in same scene index + // in editor and in build + // => .gameObject.scene.buildIndex filters out disabled scenes by + // default + // * generated sceneIds absolutely need to set scene dirty and force the + // user to resave. + // => Undo.RecordObject does that perfectly. + // * sceneIds should never be generated temporarily for unopened scenes + // when building, otherwise editor and build get out of sync + // => BuildPipeline.isBuildingPlayer check solves that + void AssignSceneID() + { + // we only ever assign sceneIds at edit time, never at runtime. + // by definition, only the original scene objects should get one. + // -> if we assign at runtime then server and client would generate + // different random numbers! + if (Application.isPlaying) + return; + + // no valid sceneId yet, or duplicate? + bool duplicate = sceneIds.TryGetValue(sceneId, out NetworkIdentity existing) && existing != null && existing != this; + if (sceneId == 0 || duplicate) + { + // clear in any case, because it might have been a duplicate + sceneId = 0; + + // if a scene was never opened and we are building it, then a + // sceneId would be assigned to build but not saved in editor, + // resulting in them getting out of sync. + // => don't ever assign temporary ids. they always need to be + // permanent + // => throw an exception to cancel the build and let the user + // know how to fix it! + if (BuildPipeline.isBuildingPlayer) + throw new InvalidOperationException($"Scene {gameObject.scene.path} needs to be opened and resaved before building, because the scene object {name} has no valid sceneId yet."); + + // if we generate the sceneId then we MUST be sure to set dirty + // in order to save the scene object properly. otherwise it + // would be regenerated every time we reopen the scene, and + // upgrading would be very difficult. + // -> Undo.RecordObject is the new EditorUtility.SetDirty! + // -> we need to call it before changing. + Undo.RecordObject(this, "Generated SceneId"); + + // generate random sceneId part (0x00000000FFFFFFFF) + uint randomId = Utils.GetTrueRandomUInt(); + + // only assign if not a duplicate of an existing scene id + // (small chance, but possible) + duplicate = sceneIds.TryGetValue(randomId, out existing) && existing != null && existing != this; + if (!duplicate) + { + sceneId = randomId; + //Debug.Log($"{name} in scene {gameObject.scene.name} sceneId assigned to:{sceneId:X}"); + } + } + + // add to sceneIds dict no matter what + // -> even if we didn't generate anything new, because we still need + // existing sceneIds in there to check duplicates + sceneIds[sceneId] = this; + } + + // copy scene path hash into sceneId for scene objects. + // this is the only way for scene file duplication to not contain + // duplicate sceneIds as it seems. + // -> sceneId before: 0x00000000AABBCCDD + // -> then we clear the left 4 bytes, so that our 'OR' uses 0x00000000 + // -> then we OR the hash into the 0x00000000 part + // -> buildIndex is not enough, because Editor and Build have different + // build indices if there are disabled scenes in build settings, and + // if no scene is in build settings then Editor and Build have + // different indices too (Editor=0, Build=-1) + // => ONLY USE THIS FROM POSTPROCESSSCENE! + public void SetSceneIdSceneHashPartInternal() + { + // Use `ToLower` to that because BuildPipeline.BuildPlayer is case insensitive but hash is case sensitive + // If the scene in the project is `forest.unity` but `Forest.unity` is given to BuildPipeline then the + // BuildPipeline will use `Forest.unity` for the build and create a different hash than the editor will. + // Using ToLower will mean the hash will be the same for these 2 paths + // Assets/Scenes/Forest.unity + // Assets/Scenes/forest.unity + string scenePath = gameObject.scene.path.ToLower(); + + // get deterministic scene hash + uint pathHash = (uint)scenePath.GetStableHashCode(); + + // shift hash from 0x000000FFFFFFFF to 0xFFFFFFFF00000000 + ulong shiftedHash = (ulong)pathHash << 32; + + // OR into scene id + sceneId = (sceneId & 0xFFFFFFFF) | shiftedHash; + + // log it. this is incredibly useful to debug sceneId issues. + //Debug.Log($"{name} in scene {gameObject.scene.name} scene index hash {pathHash:X} copied into sceneId {sceneId:X}"); + } + + void SetupIDs() + { + // is this a prefab? + if (Utils.IsPrefab(gameObject)) + { + // force 0 for prefabs + sceneId = 0; + AssignAssetID(gameObject); + } + // are we currently in prefab editing mode? aka prefab stage + // => check prefabstage BEFORE SceneObjectWithPrefabParent + // (fixes https://github.com/vis2k/Mirror/issues/976) + // => if we don't check GetCurrentPrefabStage and only check + // GetPrefabStage(gameObject), then the 'else' case where we + // assign a sceneId and clear the assetId would still be + // triggered for prefabs. in other words: if we are in prefab + // stage, do not bother with anything else ever! + else if (PrefabStageUtility.GetCurrentPrefabStage() != null) + { + // when modifying a prefab in prefab stage, Unity calls + // OnValidate for that prefab and for all scene objects based on + // that prefab. + // + // is this GameObject the prefab that we modify, and not just a + // scene object based on the prefab? + // * GetCurrentPrefabStage = 'are we editing ANY prefab?' + // * GetPrefabStage(go) = 'are we editing THIS prefab?' + if (PrefabStageUtility.GetPrefabStage(gameObject) != null) + { + // force 0 for prefabs + sceneId = 0; + //Debug.Log($"{name} scene:{gameObject.scene.name} sceneid reset to 0 because CurrentPrefabStage={PrefabStageUtility.GetCurrentPrefabStage()} PrefabStage={PrefabStageUtility.GetPrefabStage(gameObject)}"); + + // get path from PrefabStage for this prefab +#if UNITY_2020_1_OR_NEWER + string path = PrefabStageUtility.GetPrefabStage(gameObject).assetPath; +#else + string path = PrefabStageUtility.GetPrefabStage(gameObject).prefabAssetPath; +#endif + + AssignAssetID(path); + } + } + // is this a scene object with prefab parent? + else if (Utils.IsSceneObjectWithPrefabParent(gameObject, out GameObject prefab)) + { + AssignSceneID(); + AssignAssetID(prefab); + } + else + { + AssignSceneID(); + + // IMPORTANT: DO NOT clear assetId at runtime! + // => fixes a bug where clicking any of the NetworkIdentity + // properties (like ServerOnly/ForceHidden) at runtime would + // call OnValidate + // => OnValidate gets into this else case here because prefab + // connection isn't known at runtime + // => then we would clear the previously assigned assetId + // => and NetworkIdentity couldn't be spawned on other clients + // anymore because assetId was cleared + if (!EditorApplication.isPlaying) + { + _assetId = 0; + } + // don't log. would show a lot when pressing play in uMMORPG/uSurvival/etc. + //else Debug.Log($"Avoided clearing assetId at runtime for {name} after (probably) clicking any of the NetworkIdentity properties."); + } + } +#endif + + // OnDestroy is called for all SPAWNED NetworkIdentities + // => scene objects aren't destroyed. it's not called for them. + // + // Note: Unity will Destroy all networked objects on Scene Change, so we + // have to handle that here silently. That means we cannot have any + // warning or logging in this method. + void OnDestroy() + { + // Objects spawned from Instantiate are not allowed so are destroyed right away + // we don't want to call NetworkServer.Destroy if this is the case + if (SpawnedFromInstantiate) + return; + + // If false the object has already been unspawned + // if it is still true, then we need to unspawn it + // if destroy is already called don't call it again + if (isServer && !destroyCalled) + { + // Do not add logging to this (see above) + NetworkServer.Destroy(gameObject); + } + + if (isLocalPlayer) + { + // previously there was a bug where isLocalPlayer was + // false in OnDestroy because it was dynamically defined as: + // isLocalPlayer => NetworkClient.localPlayer == this + // we fixed it by setting isLocalPlayer manually and never + // resetting it. + // + // BUT now we need to be aware of a possible data race like in + // our rooms example: + // => GamePlayer is in world + // => player returns to room + // => GamePlayer is destroyed + // => NetworkClient.localPlayer is set to RoomPlayer + // => GamePlayer.OnDestroy is called 1 frame later + // => GamePlayer.OnDestroy 'isLocalPlayer' is true, so here we + // are trying to clear NetworkClient.localPlayer + // => which would overwrite the new RoomPlayer local player + // + // FIXED by simply only clearing if NetworkClient.localPlayer + // still points to US! + // => see also: https://github.com/vis2k/Mirror/issues/2635 + if (NetworkClient.localPlayer == this) + NetworkClient.localPlayer = null; + } + + if (isClient) + { + // ServerChangeScene doesn't send destroy messages. + // some identities may persist in DDOL. + // some are destroyed by scene change. + // if an identity is still in .owned remove it. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3308 + if (NetworkClient.connection != null) + NetworkClient.connection.owned.Remove(this); + + // if an identity is still in .spawned, remove it too. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3324 + NetworkClient.spawned.Remove(netId); + } + } + + internal void OnStartServer() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartServer should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStartServer(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal void OnStopServer() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartServer should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStopServer(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + bool clientStarted; + internal void OnStartClient() + { + if (clientStarted) return; + + clientStarted = true; + + // Debug.Log($"OnStartClient {gameObject} netId:{netId}"); + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartClient should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + // user implemented startup + comp.OnStartClient(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal void OnStopClient() + { + // In case this object was destroyed already don't call + // OnStopClient if OnStartClient hasn't been called. + if (!clientStarted) return; + + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStopClient should be caught, so that + // one component's exception doesn't stop all other components + // from being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStopClient(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal static NetworkIdentity previousLocalPlayer = null; + internal void OnStartLocalPlayer() + { + // ensure OnStartLocalPlayer is only called once. + // Room demo would call it multiple times: + // - once from ApplySpawnPayload + // - once from OnObjectSpawnFinished + // + // to reproduce: + // - open room demo, add the 3 scenes to build settings + // - add OnStartLocalPlayer log to RoomPlayer prefab + // - build, run server-only + // - in editor, connect, press ready + // - in server, start game + // - notice multiple OnStartLocalPlayer logs in editor client + // + // explanation: + // we send the spawn message multiple times. Whenever an object changes + // authority, we send the spawn message again for the object. This is + // necessary because we need to reinitialize all variables when + // ownership change due to sync to owner feature. + // Without this static, the second time we get the spawn message we + // would call OnStartLocalPlayer again on the same object + if (previousLocalPlayer == this) + return; + previousLocalPlayer = this; + + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartLocalPlayer should be caught, so that + // one component's exception doesn't stop all other components + // from being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStartLocalPlayer(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal void OnStopLocalPlayer() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStopLocalPlayer should be caught, so that + // one component's exception doesn't stop all other components + // from being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStopLocalPlayer(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + // build dirty mask for server owner & observers (= all dirty components). + // faster to do it in one iteration instead of iterating separately. + (ulong, ulong) ServerDirtyMasks(bool initialState) + { + ulong ownerMask = 0; + ulong observerMask = 0; + + NetworkBehaviour[] components = NetworkBehaviours; + for (int i = 0; i < components.Length; ++i) + { + NetworkBehaviour component = components[i]; + + bool dirty = component.IsDirty(); + ulong nthBit = (1u << i); + + // owner needs to be considered for both SyncModes, because + // Observers mode always includes the Owner. + // + // for initial, it should always sync owner. + // for delta, only for ServerToClient and only if dirty. + // ClientToServer comes from the owner client. + if (initialState || (component.syncDirection == SyncDirection.ServerToClient && dirty)) + ownerMask |= nthBit; + + // observers need to be considered only in Observers mode + // + // for initial, it should always sync to observers. + // for delta, only if dirty. + // SyncDirection is irrelevant, as both are broadcast to + // observers which aren't the owner. + if (component.syncMode == SyncMode.Observers && (initialState || dirty)) + observerMask |= nthBit; + } + + return (ownerMask, observerMask); + } + + // build dirty mask for client. + // server always knows initialState, so we don't need it here. + ulong ClientDirtyMask() + { + ulong mask = 0; + + NetworkBehaviour[] components = NetworkBehaviours; + for (int i = 0; i < components.Length; ++i) + { + // on the client, we need to consider different sync scenarios: + // + // ServerToClient SyncDirection: + // do nothing. + // ClientToServer SyncDirection: + // serialize only if owned. + + // on client, only consider owned components with SyncDirection to server + NetworkBehaviour component = components[i]; + if (isOwned && component.syncDirection == SyncDirection.ClientToServer) + { + // set the n-th bit if dirty + // shifting from small to large numbers is varint-efficient. + if (component.IsDirty()) mask |= (1u << i); + } + } + + return mask; + } + + // check if n-th component is dirty. + // in other words, if it has the n-th bit set in the dirty mask. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool IsDirty(ulong mask, int index) + { + ulong nthBit = (ulong)(1 << index); + return (mask & nthBit) != 0; + } + + // serialize components into writer on the server. + // check ownerWritten/observersWritten to know if anything was written + // We pass dirtyComponentsMask into this function so that we can check + // if any Components are dirty before creating writers + internal void SerializeServer(bool initialState, NetworkWriter ownerWriter, NetworkWriter observersWriter) + { + // ensure NetworkBehaviours are valid before usage + ValidateComponents(); + NetworkBehaviour[] components = NetworkBehaviours; + + // check which components are dirty for owner / observers. + // this is quite complicated with SyncMode + SyncDirection. + // see the function for explanation. + // + // instead of writing a 1 byte index per component, + // we limit components to 64 bits and write one ulong instead. + // the ulong is also varint compressed for minimum bandwidth. + (ulong ownerMask, ulong observerMask) = ServerDirtyMasks(initialState); + + // if nothing dirty, then don't even write the mask. + // otherwise, every unchanged object would send a 1 byte dirty mask! + if (ownerMask != 0) Compression.CompressVarUInt(ownerWriter, ownerMask); + if (observerMask != 0) Compression.CompressVarUInt(observersWriter, observerMask); + + // serialize all components + // perf: only iterate if either dirty mask has dirty bits. + if ((ownerMask | observerMask) != 0) + { + for (int i = 0; i < components.Length; ++i) + { + NetworkBehaviour comp = components[i]; + + // is the component dirty for anyone (owner or observers)? + // may be serialized to owner, observer, both, or neither. + // + // OnSerialize should only be called once. + // this is faster, and it cleaner because it may set + // internal state, counters, logs, etc. + // + // previously we always serialized to owner and then copied + // the serialization to observers. however, since + // SyncDirection it's not guaranteed to be in owner anymore. + // so we need to serialize to temporary writer first. + // and then copy as needed. + bool ownerDirty = IsDirty(ownerMask, i); + bool observersDirty = IsDirty(observerMask, i); + if (ownerDirty || observersDirty) + { + // serialize into helper writer + using (NetworkWriterPooled temp = NetworkWriterPool.Get()) + { + comp.Serialize(temp, initialState); + ArraySegment segment = temp.ToArraySegment(); + + // copy to owner / observers as needed + if (ownerDirty) ownerWriter.WriteBytes(segment.Array, segment.Offset, segment.Count); + if (observersDirty) observersWriter.WriteBytes(segment.Array, segment.Offset, segment.Count); + } + + // clear dirty bits for the components that we serialized. + // do not clear for _all_ components, only the ones that + // were dirty and had their syncInterval elapsed. + // + // we don't want to clear bits before the syncInterval + // was elapsed, as then they wouldn't be synced. + // + // only clear for delta, not for full (spawn messages). + // otherwise if a player joins, we serialize monster, + // and shouldn't clear dirty bits not yet synced to + // other players. + if (!initialState) comp.ClearAllDirtyBits(); + } + } + } + } + + // serialize components into writer on the client. + internal void SerializeClient(NetworkWriter writer) + { + // ensure NetworkBehaviours are valid before usage + ValidateComponents(); + NetworkBehaviour[] components = NetworkBehaviours; + + // check which components are dirty. + // this is quite complicated with SyncMode + SyncDirection. + // see the function for explanation. + // + // instead of writing a 1 byte index per component, + // we limit components to 64 bits and write one ulong instead. + // the ulong is also varint compressed for minimum bandwidth. + ulong dirtyMask = ClientDirtyMask(); + + // varint compresses the mask to 1 byte in most cases. + // instead of writing an 8 byte ulong. + // 7 components fit into 1 byte. (previously 7 bytes) + // 11 components fit into 2 bytes. (previously 11 bytes) + // 16 components fit into 3 bytes. (previously 16 bytes) + // TODO imer: server knows amount of comps, write N bytes instead + + // if nothing dirty, then don't even write the mask. + // otherwise, every unchanged object would send a 1 byte dirty mask! + if (dirtyMask != 0) Compression.CompressVarUInt(writer, dirtyMask); + + // serialize all components + // perf: only iterate if dirty mask has dirty bits. + if (dirtyMask != 0) + { + // serialize all components + for (int i = 0; i < components.Length; ++i) + { + NetworkBehaviour comp = components[i]; + + // is this component dirty? + // reuse the mask instead of calling comp.IsDirty() again here. + if (IsDirty(dirtyMask, i)) + // if (isOwned && component.syncDirection == SyncDirection.ClientToServer) + { + // serialize into writer. + // server always knows initialState, we never need to send it + comp.Serialize(writer, false); + + // clear dirty bits for the components that we serialized. + // do not clear for _all_ components, only the ones that + // were dirty and had their syncInterval elapsed. + // + // we don't want to clear bits before the syncInterval + // was elapsed, as then they wouldn't be synced. + comp.ClearAllDirtyBits(); + } + } + } + } + + // deserialize components from the client on the server. + // there's no 'initialState'. server always knows the initial state. + internal bool DeserializeServer(NetworkReader reader) + { + // ensure NetworkBehaviours are valid before usage + ValidateComponents(); + NetworkBehaviour[] components = NetworkBehaviours; + + // first we deserialize the varinted dirty mask + ulong mask = Compression.DecompressVarUInt(reader); + + // now deserialize every dirty component + for (int i = 0; i < components.Length; ++i) + { + // was this one dirty? + if (IsDirty(mask, i)) + { + NetworkBehaviour comp = components[i]; + + // safety check to ensure clients can only modify their own + // ClientToServer components, nothing else. + if (comp.syncDirection == SyncDirection.ClientToServer) + { + // deserialize this component + // server always knows the initial state (initial=false) + // disconnect if failed, to prevent exploits etc. + if (!comp.Deserialize(reader, false)) return false; + + // server received state from the owner client. + // set dirty so it's broadcast to other clients too. + // + // note that we set the _whole_ component as dirty. + // everything will be broadcast to others. + // SetSyncVarDirtyBits() would be nicer, but not all + // components use [SyncVar]s. + comp.SetDirty(); + } + } + } + + // successfully deserialized everything + return true; + } + + // deserialize components from server on the client. + internal void DeserializeClient(NetworkReader reader, bool initialState) + { + // ensure NetworkBehaviours are valid before usage + ValidateComponents(); + NetworkBehaviour[] components = NetworkBehaviours; + + // first we deserialize the varinted dirty mask + ulong mask = Compression.DecompressVarUInt(reader); + + // now deserialize every dirty component + for (int i = 0; i < components.Length; ++i) + { + // was this one dirty? + if (IsDirty(mask, i)) + { + // deserialize this component + NetworkBehaviour comp = components[i]; + comp.Deserialize(reader, initialState); + } + } + } + + // get cached serialization for this tick (or serialize if none yet). + // IMPORTANT: int tick avoids floating point inaccuracy over days/weeks. + // calls SerializeServer, so this function is to be called on server. + internal NetworkIdentitySerialization GetServerSerializationAtTick(int tick) + { + // only rebuild serialization once per tick. reuse otherwise. + // except for tests, where Time.frameCount never increases. + // so during tests, we always rebuild. + // (otherwise [SyncVar] changes would never be serialized in tests) + // + // NOTE: != instead of < because int.max+1 overflows at some point. + if (lastSerialization.tick != tick +#if UNITY_EDITOR + || !Application.isPlaying +#endif + ) + { + // reset + lastSerialization.ownerWriter.Position = 0; + lastSerialization.observersWriter.Position = 0; + + // serialize + SerializeServer(false, + lastSerialization.ownerWriter, + lastSerialization.observersWriter); + + // set tick + lastSerialization.tick = tick; + //Debug.Log($"{name} (netId={netId}) serialized for tick={tickTimeStamp}"); + } + + // return it + return lastSerialization; + } + + internal void AddObserver(NetworkConnectionToClient conn) + { + if (observers.ContainsKey(conn.connectionId)) + { + // if we try to add a connectionId that was already added, then + // we may have generated one that was already in use. + return; + } + + // Debug.Log($"Added observer: {conn.address} added for {gameObject}"); + + // if we previously had no observers, then clear all dirty bits once. + // a monster's health may have changed while it had no observers. + // but that change (= the dirty bits) don't matter as soon as the + // first observer comes. + // -> first observer gets full spawn packet + // -> afterwards it gets delta packet + // => if we don't clear previous dirty bits, observer would get + // the health change because the bit was still set. + // => ultimately this happens because spawn doesn't reset dirty + // bits + // => which happens because spawn happens separately, instead of + // in Broadcast() (which will be changed in the future) + // + // NOTE that NetworkServer.Broadcast previously cleared dirty bits + // for ALL SPAWNED that don't have observers. that was super + // expensive. doing it when adding the first observer has the + // same result, without the O(N) iteration in Broadcast(). + // + // TODO remove this after moving spawning into Broadcast()! + if (observers.Count == 0) + { + ClearAllComponentsDirtyBits(); + } + + observers[conn.connectionId] = conn; + conn.AddToObserving(this); + } + + // clear all component's dirty bits no matter what + internal void ClearAllComponentsDirtyBits() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + comp.ClearAllDirtyBits(); + } + } + + // this is used when a connection is destroyed, since the "observers" property is read-only + internal void RemoveObserver(NetworkConnection conn) + { + observers.Remove(conn.connectionId); + } + + /// Assign control of an object to a client via the client's NetworkConnection. + // This causes hasAuthority to be set on the client that owns the object, + // and NetworkBehaviour.OnStartAuthority will be called on that client. + // This object then will be in the NetworkConnection.clientOwnedObjects + // list for the connection. + // + // Authority can be removed with RemoveClientAuthority. Only one client + // can own an object at any time. This does not need to be called for + // player objects, as their authority is setup automatically. + public bool AssignClientAuthority(NetworkConnectionToClient conn) + { + if (!isServer) + { + Debug.LogError("AssignClientAuthority can only be called on the server for spawned objects."); + return false; + } + + if (conn == null) + { + Debug.LogError($"AssignClientAuthority for {gameObject} owner cannot be null. Use RemoveClientAuthority() instead."); + return false; + } + + if (connectionToClient != null && conn != connectionToClient) + { + Debug.LogError($"AssignClientAuthority for {gameObject} already has an owner. Use RemoveClientAuthority() first."); + return false; + } + + SetClientOwner(conn); + + // The client will match to the existing object + NetworkServer.SendChangeOwnerMessage(this, conn); + + clientAuthorityCallback?.Invoke(conn, this, true); + + return true; + } + + // used when adding players + internal void SetClientOwner(NetworkConnectionToClient conn) + { + // do nothing if it already has an owner + if (connectionToClient != null && conn != connectionToClient) + { + Debug.LogError($"Object {this} netId={netId} already has an owner. Use RemoveClientAuthority() first", this); + return; + } + + // otherwise set the owner connection + connectionToClient = conn; + } + + /// Removes ownership for an object. + // Applies to objects that had authority set by AssignClientAuthority, + // or NetworkServer.Spawn with a NetworkConnection parameter included. + // Authority cannot be removed for player objects. + public void RemoveClientAuthority() + { + if (!isServer) + { + Debug.LogError("RemoveClientAuthority can only be called on the server for spawned objects."); + return; + } + + if (connectionToClient?.identity == this) + { + Debug.LogError("RemoveClientAuthority cannot remove authority for a player object"); + return; + } + + if (connectionToClient != null) + { + clientAuthorityCallback?.Invoke(connectionToClient, this, false); + NetworkConnectionToClient previousOwner = connectionToClient; + connectionToClient = null; + NetworkServer.SendChangeOwnerMessage(this, previousOwner); + } + } + + // Reset is called when the user hits the Reset button in the + // Inspector's context menu or when adding the component the first time. + // This function is only called in editor mode. + // + // Reset() seems to be called only for Scene objects. + // we can't destroy them (they are always in the scene). + // instead we disable them and call Reset(). + // + // Do not reset SyncObjects from Reset + // - Unspawned objects need to retain their list contents + // - They may be respawned, especially players, but others as well. + // + // OLD COMMENT: + // Marks the identity for future reset, this is because we cant reset + // the identity during destroy as people might want to be able to read + // the members inside OnDestroy(), and we have no way of invoking reset + // after OnDestroy is called. + internal void Reset() + { + hasSpawned = false; + clientStarted = false; + isClient = false; + isServer = false; + //isLocalPlayer = false; <- cleared AFTER ClearLocalPlayer below! + + // remove authority flag. This object may be unspawned, not destroyed, on client. + isOwned = false; + NotifyAuthority(); + + netId = 0; + connectionToServer = null; + connectionToClient = null; + + ClearObservers(); + + // clear local player if it was the local player, + // THEN reset isLocalPlayer AFTERWARDS + if (isLocalPlayer) + { + // only clear NetworkClient.localPlayer IF IT POINTS TO US! + // see OnDestroy() comments. it does the same. + // (https://github.com/vis2k/Mirror/issues/2635) + if (NetworkClient.localPlayer == this) + NetworkClient.localPlayer = null; + } + + previousLocalPlayer = null; + isLocalPlayer = false; + } + + bool hadAuthority; + internal void NotifyAuthority() + { + if (!hadAuthority && isOwned) + OnStartAuthority(); + if (hadAuthority && !isOwned) + OnStopAuthority(); + hadAuthority = isOwned; + } + + internal void OnStartAuthority() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStartAuthority should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStartAuthority(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + internal void OnStopAuthority() + { + foreach (NetworkBehaviour comp in NetworkBehaviours) + { + // an exception in OnStopAuthority should be caught, so that one + // component's exception doesn't stop all other components from + // being initialized + // => this is what Unity does for Start() etc. too. + // one exception doesn't stop all the other Start() calls! + try + { + comp.OnStopAuthority(); + } + catch (Exception e) + { + Debug.LogException(e, comp); + } + } + } + + // Called when NetworkIdentity is destroyed + internal void ClearObservers() + { + foreach (NetworkConnectionToClient conn in observers.Values) + { + conn.RemoveFromObserving(this, true); + } + observers.Clear(); + } + } +} diff --git a/Assets/Mirror/Core/NetworkIdentity.cs.meta b/Assets/Mirror/Core/NetworkIdentity.cs.meta new file mode 100644 index 0000000..7b96521 --- /dev/null +++ b/Assets/Mirror/Core/NetworkIdentity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9b91ecbcc199f4492b9a91e820070131 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkLoop.cs b/Assets/Mirror/Core/NetworkLoop.cs new file mode 100644 index 0000000..968bc00 --- /dev/null +++ b/Assets/Mirror/Core/NetworkLoop.cs @@ -0,0 +1,210 @@ +// our ideal update looks like this: +// transport.process_incoming() +// update_world() +// transport.process_outgoing() +// +// this way we avoid unnecessary latency for low-ish server tick rates. +// for example, if we were to use this tick: +// transport.process_incoming/outgoing() +// update_world() +// +// then anything sent in update_world wouldn't be actually sent out by the +// transport until the next frame. if server runs at 60Hz, then this can add +// 16ms latency for every single packet. +// +// => instead we process incoming, update world, process_outgoing in the same +// frame. it's more clear (no race conditions) and lower latency. +// => we need to add custom Update functions to the Unity engine: +// NetworkEarlyUpdate before Update()/FixedUpdate() +// NetworkLateUpdate after LateUpdate() +// this way the user can update the world in Update/FixedUpdate/LateUpdate +// and networking still runs before/after those functions no matter what! +// => see also: https://docs.unity3d.com/Manual/ExecutionOrder.html +// => update order: +// * we add to the end of EarlyUpdate so it runs after any Unity initializations +// * we add to the end of PreLateUpdate so it runs after LateUpdate(). adding +// to the beginning of PostLateUpdate doesn't actually work. +using System; +using UnityEngine; +using UnityEngine.LowLevel; +using UnityEngine.PlayerLoop; + +namespace Mirror +{ + public static class NetworkLoop + { + // helper enum to add loop to begin/end of subSystemList + internal enum AddMode { Beginning, End } + + // callbacks for others to hook into if they need Early/LateUpdate. + public static Action OnEarlyUpdate; + public static Action OnLateUpdate; + + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + static void ResetStatics() + { + OnEarlyUpdate = null; + OnLateUpdate = null; + } + + // helper function to find an update function's index in a player loop + // type. this is used for testing to guarantee our functions are added + // at the beginning/end properly. + internal static int FindPlayerLoopEntryIndex(PlayerLoopSystem.UpdateFunction function, PlayerLoopSystem playerLoop, Type playerLoopSystemType) + { + // did we find the type? e.g. EarlyUpdate/PreLateUpdate/etc. + if (playerLoop.type == playerLoopSystemType) + return Array.FindIndex(playerLoop.subSystemList, (elem => elem.updateDelegate == function)); + + // recursively keep looking + if (playerLoop.subSystemList != null) + { + for (int i = 0; i < playerLoop.subSystemList.Length; ++i) + { + int index = FindPlayerLoopEntryIndex(function, playerLoop.subSystemList[i], playerLoopSystemType); + if (index != -1) return index; + } + } + return -1; + } + + // MODIFIED AddSystemToPlayerLoopList from Unity.Entities.ScriptBehaviourUpdateOrder (ECS) + // + // => adds an update function to the Unity internal update type. + // => Unity has different update loops: + // https://medium.com/@thebeardphantom/unity-2018-and-playerloop-5c46a12a677 + // EarlyUpdate + // FixedUpdate + // PreUpdate + // Update + // PreLateUpdate + // PostLateUpdate + // + // function: the custom update function to add + // IMPORTANT: according to a comment in Unity.Entities.ScriptBehaviourUpdateOrder, + // the UpdateFunction can not be virtual because + // Mono 4.6 has problems invoking virtual methods + // as delegates from native! + // ownerType: the .type to fill in so it's obvious who the new function + // belongs to. seems to be mostly for debugging. pass any. + // addMode: prepend or append to update list + internal static bool AddToPlayerLoop(PlayerLoopSystem.UpdateFunction function, Type ownerType, ref PlayerLoopSystem playerLoop, Type playerLoopSystemType, AddMode addMode) + { + // did we find the type? e.g. EarlyUpdate/PreLateUpdate/etc. + if (playerLoop.type == playerLoopSystemType) + { + // debugging + //Debug.Log($"Found playerLoop of type {playerLoop.type} with {playerLoop.subSystemList.Length} Functions:"); + //foreach (PlayerLoopSystem sys in playerLoop.subSystemList) + // Debug.Log($" ->{sys.type}"); + + // make sure the function wasn't added yet. + // with domain reload disabled, it would otherwise be added twice: + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3392 + if (Array.FindIndex(playerLoop.subSystemList, (s => s.updateDelegate == function)) != -1) + { + // loop contains the function, so return true. + return true; + } + + // resize & expand subSystemList to fit one more entry + int oldListLength = (playerLoop.subSystemList != null) ? playerLoop.subSystemList.Length : 0; + Array.Resize(ref playerLoop.subSystemList, oldListLength + 1); + + // IMPORTANT: always insert a FRESH PlayerLoopSystem! + // We CAN NOT resize and then OVERWRITE an entry's type/loop. + // => PlayerLoopSystem has native IntPtr loop members + // => forgetting to clear those would cause undefined behaviour! + // see also: https://github.com/vis2k/Mirror/pull/2652 + PlayerLoopSystem system = new PlayerLoopSystem { + type = ownerType, + updateDelegate = function + }; + + // prepend our custom loop to the beginning + if (addMode == AddMode.Beginning) + { + // shift to the right, write into first array element + Array.Copy(playerLoop.subSystemList, 0, playerLoop.subSystemList, 1, playerLoop.subSystemList.Length - 1); + playerLoop.subSystemList[0] = system; + } + // append our custom loop to the end + else if (addMode == AddMode.End) + { + // simply write into last array element + playerLoop.subSystemList[oldListLength] = system; + } + + // debugging + //Debug.Log($"New playerLoop of type {playerLoop.type} with {playerLoop.subSystemList.Length} Functions:"); + //foreach (PlayerLoopSystem sys in playerLoop.subSystemList) + // Debug.Log($" ->{sys.type}"); + + return true; + } + + // recursively keep looking + if (playerLoop.subSystemList != null) + { + for (int i = 0; i < playerLoop.subSystemList.Length; ++i) + { + if (AddToPlayerLoop(function, ownerType, ref playerLoop.subSystemList[i], playerLoopSystemType, addMode)) + return true; + } + } + return false; + } + + // hook into Unity runtime to actually add our custom functions + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + static void RuntimeInitializeOnLoad() + { + //Debug.Log("Mirror: adding Network[Early/Late]Update to Unity..."); + + // get loop + // 2019 has GetCURRENTPlayerLoop which is safe to use without + // breaking other custom system's custom loops. + // see also: https://github.com/vis2k/Mirror/pull/2627/files + PlayerLoopSystem playerLoop = PlayerLoop.GetCurrentPlayerLoop(); + + // add NetworkEarlyUpdate to the end of EarlyUpdate so it runs after + // any Unity initializations but before the first Update/FixedUpdate + AddToPlayerLoop(NetworkEarlyUpdate, typeof(NetworkLoop), ref playerLoop, typeof(EarlyUpdate), AddMode.End); + + // add NetworkLateUpdate to the end of PreLateUpdate so it runs after + // LateUpdate(). adding to the beginning of PostLateUpdate doesn't + // actually work. + AddToPlayerLoop(NetworkLateUpdate, typeof(NetworkLoop), ref playerLoop, typeof(PreLateUpdate), AddMode.End); + + // set the new loop + PlayerLoop.SetPlayerLoop(playerLoop); + } + + static void NetworkEarlyUpdate() + { + // loop functions run in edit mode and in play mode. + // however, we only want to call NetworkServer/Client in play mode. + if (!Application.isPlaying) return; + + //Debug.Log($"NetworkEarlyUpdate {Time.time}"); + NetworkServer.NetworkEarlyUpdate(); + NetworkClient.NetworkEarlyUpdate(); + // invoke event after mirror has done it's early updating. + OnEarlyUpdate?.Invoke(); + } + + static void NetworkLateUpdate() + { + // loop functions run in edit mode and in play mode. + // however, we only want to call NetworkServer/Client in play mode. + if (!Application.isPlaying) return; + + //Debug.Log($"NetworkLateUpdate {Time.time}"); + // invoke event before mirror does its final late updating. + OnLateUpdate?.Invoke(); + NetworkServer.NetworkLateUpdate(); + NetworkClient.NetworkLateUpdate(); + } + } +} diff --git a/Assets/Mirror/Core/NetworkLoop.cs.meta b/Assets/Mirror/Core/NetworkLoop.cs.meta new file mode 100644 index 0000000..52b6e6a --- /dev/null +++ b/Assets/Mirror/Core/NetworkLoop.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c6cec4e279774b919386e05545317b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkManager.cs b/Assets/Mirror/Core/NetworkManager.cs new file mode 100644 index 0000000..98ec25d --- /dev/null +++ b/Assets/Mirror/Core/NetworkManager.cs @@ -0,0 +1,1467 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.Serialization; + +namespace Mirror +{ + public enum PlayerSpawnMethod { Random, RoundRobin } + public enum NetworkManagerMode { Offline, ServerOnly, ClientOnly, Host } + + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Manager")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-manager")] + public class NetworkManager : MonoBehaviour + { + /// Enable to keep NetworkManager alive when changing scenes. + // This should be set if your game has a single NetworkManager that exists for the lifetime of the process. If there is a NetworkManager in each scene, then this should not be set. + [Header("Configuration")] + [FormerlySerializedAs("m_DontDestroyOnLoad")] + [Tooltip("Should the Network Manager object be persisted through scene changes?")] + public bool dontDestroyOnLoad = true; + + /// Multiplayer games should always run in the background so the network doesn't time out. + [FormerlySerializedAs("m_RunInBackground")] + [Tooltip("Multiplayer games should always run in the background so the network doesn't time out.")] + public bool runInBackground = true; + + /// Should the server auto-start when 'Server Build' is checked in build settings + [Header("Headless Builds")] + [Tooltip("Should the server auto-start when 'Server Build' is checked in build settings")] + [FormerlySerializedAs("startOnHeadless")] + public bool autoStartServerBuild = true; + + [Tooltip("Automatically connect the client in headless builds. Useful for CCU tests with bot clients.\n\nAddress may be passed as command line argument.\n\nMake sure that only 'autostartServer' or 'autoconnectClient' is enabled, not both!")] + public bool autoConnectClientBuild; + + /// Server Update frequency, per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE. + [Tooltip("Server & Client send rate per second. Use 60-100Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE.")] + [FormerlySerializedAs("serverTickRate")] + public int sendRate = 60; + + // Deprecated 2022-10-31 + [Obsolete("NetworkManager.serverTickRate was renamed to sendRate because that's what it configures for both server & client now.")] + public int serverTickRate => sendRate; + + // tick rate is in Hz. + // convert to interval in seconds for convenience where needed. + // + // send interval is 1 / sendRate. + // but for tests we need a way to set it to exactly 0. + // 1 / int.max would not be exactly 0, so handel that manually. + // Deprecated 2022-10-06 + [Obsolete("NetworkManager.serverTickInterval was moved to NetworkServer.tickInterval for consistency.")] + public float serverTickInterval => NetworkServer.tickInterval; + + // client send rate follows server send rate to avoid errors for now + /// Client Update frequency, per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE. + // [Tooltip("Client broadcasts 'sendRate' times per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE.")] + // public int clientSendRate = 30; // 33 ms + + /// Automatically switch to this scene upon going offline (on start / on disconnect / on shutdown). + [Header("Scene Management")] + [Scene] + [FormerlySerializedAs("m_OfflineScene")] + [Tooltip("Scene that Mirror will switch to when the client or server is stopped")] + public string offlineScene = ""; + + /// Automatically switch to this scene upon going online (after connect/startserver). + [Scene] + [FormerlySerializedAs("m_OnlineScene")] + [Tooltip("Scene that Mirror will switch to when the server is started. Clients will recieve a Scene Message to load the server's current scene when they connect.")] + public string onlineScene = ""; + + // transport layer + [Header("Network Info")] + [Tooltip("Transport component attached to this object that server and client will use to connect")] + public Transport transport; + + /// Server's address for clients to connect to. + [FormerlySerializedAs("m_NetworkAddress")] + [Tooltip("Network Address where the client should connect to the server. Server does not use this for anything.")] + public string networkAddress = "localhost"; + + /// The maximum number of concurrent network connections to support. + [FormerlySerializedAs("m_MaxConnections")] + [Tooltip("Maximum number of concurrent connections.")] + public int maxConnections = 100; + + // Mirror global disconnect inactive option, independent of Transport. + // not all Transports do this properly, and it's easiest to configure this just once. + // this is very useful for some projects, keep it. + [Tooltip("When enabled, the server automatically disconnects inactive connections after the configured timeout.")] + public bool disconnectInactiveConnections; + + [Tooltip("Timeout in seconds for server to automatically disconnect inactive connections if 'disconnectInactiveConnections' is enabled.")] + public float disconnectInactiveTimeout = 60f; + + [Header("Authentication")] + [Tooltip("Authentication component attached to this object")] + public NetworkAuthenticator authenticator; + + /// The default prefab to be used to create player objects on the server. + // Player objects are created in the default handler for AddPlayer() on + // the server. Implementing OnServerAddPlayer overrides this behaviour. + [Header("Player Object")] + [FormerlySerializedAs("m_PlayerPrefab")] + [Tooltip("Prefab of the player object. Prefab must have a Network Identity component. May be an empty game object or a full avatar.")] + public GameObject playerPrefab; + + /// Enable to automatically create player objects on connect and on scene change. + [FormerlySerializedAs("m_AutoCreatePlayer")] + [Tooltip("Should Mirror automatically spawn the player after scene change?")] + public bool autoCreatePlayer = true; + + /// Where to spawn players. + [FormerlySerializedAs("m_PlayerSpawnMethod")] + [Tooltip("Round Robin or Random order of Start Position selection")] + public PlayerSpawnMethod playerSpawnMethod; + + /// Prefabs that can be spawned over the network need to be registered here. + [FormerlySerializedAs("m_SpawnPrefabs"), HideInInspector] + public List spawnPrefabs = new List(); + + /// List of transforms populated by NetworkStartPositions + public static List startPositions = new List(); + public static int startPositionIndex; + + [Header("Snapshot Interpolation")] + public SnapshotInterpolationSettings snapshotSettings = new SnapshotInterpolationSettings(); + + [Header("Connection Quality")] + public float connectionQualityInterval = 3; + double lastConnectionQualityUpdate; + ConnectionQuality lastConnectionQuality = ConnectionQuality.ESTIMATING; + + [Header("Debug")] + public bool timeInterpolationGui = false; + + /// The one and only NetworkManager + public static NetworkManager singleton { get; internal set; } + + /// Number of active player objects across all connections on the server. + public int numPlayers => NetworkServer.connections.Count(kv => kv.Value.identity != null); + + /// True if the server is running or client is connected/connecting. + public bool isNetworkActive => NetworkServer.active || NetworkClient.active; + + // TODO remove this + // internal for tests + internal static NetworkConnection clientReadyConnection; + + /// True if the client loaded a new scene when connecting to the server. + // This is set before OnClientConnect is called, so it can be checked + // there to perform different logic if a scene load occurred. + protected bool clientLoadedScene; + + // helper enum to know if we started the networkmanager as server/client/host. + // -> this is necessary because when StartHost changes server scene to + // online scene, FinishLoadScene is called and the host client isn't + // connected yet (no need to connect it before server was fully set up). + // in other words, we need this to know which mode we are running in + // during FinishLoadScene. + public NetworkManagerMode mode { get; private set; } + + // virtual so that inheriting classes' OnValidate() can call base.OnValidate() too + public virtual void OnValidate() + { + // always >= 0 + maxConnections = Mathf.Max(maxConnections, 0); + + if (playerPrefab != null && !playerPrefab.TryGetComponent(out NetworkIdentity _)) + { + Debug.LogError("NetworkManager - Player Prefab must have a NetworkIdentity."); + playerPrefab = null; + } + + // This avoids the mysterious "Replacing existing prefab with assetId ... Old prefab 'Player', New prefab 'Player'" warning. + if (playerPrefab != null && spawnPrefabs.Contains(playerPrefab)) + { + Debug.LogWarning("NetworkManager - Player Prefab should not be added to Registered Spawnable Prefabs list...removed it."); + spawnPrefabs.Remove(playerPrefab); + } + } + + // virtual so that inheriting classes' Reset() can call base.Reset() too + // Reset only gets called when the component is added or the user resets the component + // Thats why we validate these things that only need to be validated on adding the NetworkManager here + // If we would do it in OnValidate() then it would run this everytime a value changes + public virtual void Reset() + { + // make sure someone doesn't accidentally add another NetworkManager + // need transform.root because when adding to a child, the parent's + // Reset isn't called. + foreach (NetworkManager manager in transform.root.GetComponentsInChildren()) + { + if (manager != this) + { + Debug.LogError($"{name} detected another component of type {typeof(NetworkManager)} in its hierarchy on {manager.name}. There can only be one, please remove one of them."); + // return early so that transport component isn't auto-added + // to the duplicate NetworkManager. + return; + } + } + } + + // virtual so that inheriting classes' Awake() can call base.Awake() too + public virtual void Awake() + { + // Don't allow collision-destroyed second instance to continue. + if (!InitializeSingleton()) return; + + // Apply configuration in Awake once already + ApplyConfiguration(); + + // Set the networkSceneName to prevent a scene reload + // if client connection to server fails. + networkSceneName = offlineScene; + + // setup OnSceneLoaded callback + SceneManager.sceneLoaded += OnSceneLoaded; + } + + // virtual so that inheriting classes' Start() can call base.Start() too + public virtual void Start() + { + // headless mode? then start the server + // can't do this in Awake because Awake is for initialization. + // some transports might not be ready until Start. + // + // (tick rate is applied in StartServer!) +#if UNITY_SERVER + if (autoStartServerBuild) + { + StartServer(); + } + // only start server or client, never both + else if (autoConnectClientBuild) + { + StartClient(); + } +#endif + } + + // make sure to call base.Update() when overwriting + public virtual void Update() + { + ApplyConfiguration(); + } + + // virtual so that inheriting classes' LateUpdate() can call base.LateUpdate() too + public virtual void LateUpdate() + { + UpdateScene(); + UpdateConnectionQuality(); + } + + // Connection Quality ////////////////////////////////////////////////// + // uses 'pragmatic' version based on snapshot interpolation by default. + void UpdateConnectionQuality() + { + if (!NetworkClient.active) return; + + // only recalculate every few seconds + // we don't want to fire Good->Bad->Good->Bad hundreds of times per second. + if (NetworkTime.time < lastConnectionQualityUpdate + connectionQualityInterval) return; + lastConnectionQualityUpdate = NetworkTime.time; + + // recaclulate connection quality + CalculateConnectionQuality(); + + // call event if changed + if (NetworkClient.connectionQuality != lastConnectionQuality) + { + OnConnectionQualityChanged(lastConnectionQuality, NetworkClient.connectionQuality); + lastConnectionQuality = NetworkClient.connectionQuality; + } + } + + // users can overwrite this to run their own connection quality estimation. + protected virtual void CalculateConnectionQuality() + { + // NetworkClient.connectionQuality = ConnectionQualityHeuristics.Pragmatic(NetworkClient.initialBufferTime, NetworkClient.bufferTime); + NetworkClient.connectionQuality = ConnectionQualityHeuristics.Simple(NetworkTime.rtt, NetworkTime.rttVariance); + } + + // users can overwrite this to display connection quality warnings, etc. + protected virtual void OnConnectionQualityChanged(ConnectionQuality previous, ConnectionQuality current) + { + Debug.Log($"[Mirror] Connection Quality changed from {previous} to {current}"); + } + + //////////////////////////////////////////////////////////////////////// + + // keep the online scene change check in a separate function. + // only change scene if the requested online scene is not blank, and is not already loaded. + bool IsServerOnlineSceneChangeNeeded() => + !string.IsNullOrWhiteSpace(onlineScene) && + !Utils.IsSceneActive(onlineScene) && + onlineScene != offlineScene; + + // Deprecated 2022-12-12 + [Obsolete("NetworkManager.IsSceneActive moved to Utils.IsSceneActive")] + public static bool IsSceneActive(string scene) => Utils.IsSceneActive(scene); + + // NetworkManager exposes some NetworkServer/Client configuration. + // we apply it every Update() in order to avoid two sources of truth. + // fixes issues where NetworkServer.sendRate was never set because + // NetworkManager.StartServer was never called, etc. + // => all exposed settings should be applied at all times if NM exists. + void ApplyConfiguration() + { + NetworkServer.tickRate = sendRate; + NetworkClient.snapshotSettings = snapshotSettings; + } + + // full server setup code, without spawning objects yet + void SetupServer() + { + // Debug.Log("NetworkManager SetupServer"); + InitializeSingleton(); + + if (runInBackground) + Application.runInBackground = true; + + if (authenticator != null) + { + authenticator.OnStartServer(); + authenticator.OnServerAuthenticated.AddListener(OnServerAuthenticated); + } + + ConfigureHeadlessFrameRate(); + + NetworkServer.disconnectInactiveConnections = disconnectInactiveConnections; + NetworkServer.disconnectInactiveTimeout = disconnectInactiveTimeout; + + // start listening to network connections + NetworkServer.Listen(maxConnections); + + // this must be after Listen(), since that registers the default message handlers + RegisterServerMessages(); + + // do not call OnStartServer here yet. + // this is up to the caller. different for server-only vs. host mode. + } + + /// Starts the server, listening for incoming connections. + public void StartServer() + { + if (NetworkServer.active) + { + Debug.LogWarning("Server already started."); + return; + } + + mode = NetworkManagerMode.ServerOnly; + + // StartServer is inherently ASYNCHRONOUS (=doesn't finish immediately) + // + // Here is what it does: + // Listen + // if onlineScene: + // LoadSceneAsync + // ... + // FinishLoadSceneServerOnly + // SpawnObjects + // else: + // SpawnObjects + // + // there is NO WAY to make it synchronous because both LoadSceneAsync + // and LoadScene do not finish loading immediately. as long as we + // have the onlineScene feature, it will be asynchronous! + + SetupServer(); + + // call OnStartServer AFTER Listen, so that NetworkServer.active is + // true and we can call NetworkServer.Spawn in OnStartServer + // overrides. + // (useful for loading & spawning stuff from database etc.) + // + // note: there is no risk of someone connecting after Listen() and + // before OnStartServer() because this all runs in one thread + // and we don't start processing connects until Update. + OnStartServer(); + + // scene change needed? then change scene and spawn afterwards. + if (IsServerOnlineSceneChangeNeeded()) + { + ServerChangeScene(onlineScene); + } + // otherwise spawn directly + else + { + NetworkServer.SpawnObjects(); + } + } + + void SetupClient() + { + InitializeSingleton(); + + if (runInBackground) + Application.runInBackground = true; + + if (authenticator != null) + { + authenticator.OnStartClient(); + authenticator.OnClientAuthenticated.AddListener(OnClientAuthenticated); + } + + // NetworkClient.sendRate = clientSendRate; + } + + /// Starts the client, connects it to the server with networkAddress. + public void StartClient() + { + if (NetworkClient.active) + { + Debug.LogWarning("Client already started."); + return; + } + + mode = NetworkManagerMode.ClientOnly; + + SetupClient(); + + // In case this is a headless client... + ConfigureHeadlessFrameRate(); + + RegisterClientMessages(); + + if (string.IsNullOrWhiteSpace(networkAddress)) + { + Debug.LogError("Must set the Network Address field in the manager"); + return; + } + // Debug.Log($"NetworkManager StartClient address:{networkAddress}"); + + NetworkClient.Connect(networkAddress); + + OnStartClient(); + } + + /// Starts the client, connects it to the server via Uri + public void StartClient(Uri uri) + { + if (NetworkClient.active) + { + Debug.LogWarning("Client already started."); + return; + } + + mode = NetworkManagerMode.ClientOnly; + + SetupClient(); + + RegisterClientMessages(); + + // Debug.Log($"NetworkManager StartClient address:{uri}"); + networkAddress = uri.Host; + + NetworkClient.Connect(uri); + + OnStartClient(); + } + + /// Starts a network "host" - a server and client in the same application. + public void StartHost() + { + if (NetworkServer.active || NetworkClient.active) + { + Debug.LogWarning("Server or Client already started."); + return; + } + + mode = NetworkManagerMode.Host; + + // StartHost is inherently ASYNCHRONOUS (=doesn't finish immediately) + // + // Here is what it does: + // Listen + // ConnectHost + // if onlineScene: + // LoadSceneAsync + // ... + // FinishLoadSceneHost + // FinishStartHost + // SpawnObjects + // StartHostClient <= not guaranteed to happen after SpawnObjects if onlineScene is set! + // ClientAuth + // success: server sends changescene msg to client + // else: + // FinishStartHost + // + // there is NO WAY to make it synchronous because both LoadSceneAsync + // and LoadScene do not finish loading immediately. as long as we + // have the onlineScene feature, it will be asynchronous! + + // setup server first + SetupServer(); + + // scene change needed? then change scene and spawn afterwards. + // => BEFORE host client connects. if client auth succeeds then the + // server tells it to load 'onlineScene'. we can't do that if + // server is still in 'offlineScene'. so load on server first. + if (IsServerOnlineSceneChangeNeeded()) + { + // call FinishStartHost after changing scene. + finishStartHostPending = true; + ServerChangeScene(onlineScene); + } + // otherwise call FinishStartHost directly + else + { + FinishStartHost(); + } + } + + // This may be set true in StartHost and is evaluated in FinishStartHost + bool finishStartHostPending; + + // FinishStartHost is guaranteed to be called after the host server was + // fully started and all the asynchronous StartHost magic is finished + // (= scene loading), or immediately if there was no asynchronous magic. + // + // note: we don't really need FinishStartClient/FinishStartServer. the + // host version is enough. + void FinishStartHost() + { + // ConnectHost needs to be called BEFORE SpawnObjects: + // https://github.com/vis2k/Mirror/pull/1249/ + // -> this sets NetworkServer.localConnection. + // -> localConnection needs to be set before SpawnObjects because: + // -> SpawnObjects calls OnStartServer in all NetworkBehaviours + // -> OnStartServer might spawn an object and set [SyncVar(hook="OnColorChanged")] object.color = green; + // -> this calls SyncVar.set (generated by Weaver), which has + // a custom case for host mode (because host mode doesn't + // get OnDeserialize calls, where SyncVar hooks are usually + // called): + // + // if (!SyncVarEqual(value, ref color)) + // { + // if (NetworkServer.localClientActive && !getSyncVarHookGuard(1uL)) + // { + // setSyncVarHookGuard(1uL, value: true); + // OnColorChangedHook(value); + // setSyncVarHookGuard(1uL, value: false); + // } + // SetSyncVar(value, ref color, 1uL); + // } + // + // -> localClientActive needs to be true, otherwise the hook + // isn't called in host mode! + // + // TODO call this after spawnobjects and worry about the syncvar hook fix later? + NetworkClient.ConnectHost(); + + // invoke user callbacks AFTER ConnectHost has set .activeHost. + // this way initialization can properly handle host mode. + // + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3302 + // where [SyncVar] hooks wouldn't be called for objects spawned in + // NetworkManager.OnStartServer, because .activeHost was still false. + // + // TODO is there a risk of someone connecting between Listen() and FinishStartHost()? + OnStartServer(); + + // call OnStartHost AFTER SetupServer. this way we can use + // NetworkServer.Spawn etc. in there too. just like OnStartServer + // is called after the server is actually properly started. + OnStartHost(); + + // server scene was loaded. now spawn all the objects + NetworkServer.SpawnObjects(); + + // connect client and call OnStartClient AFTER server scene was + // loaded and all objects were spawned. + // DO NOT do this earlier. it would cause race conditions where a + // client will do things before the server is even fully started. + //Debug.Log("StartHostClient called"); + SetupClient(); + + networkAddress = "localhost"; + RegisterClientMessages(); + + // call OnConencted needs to be called AFTER RegisterClientMessages + // (https://github.com/vis2k/Mirror/pull/1249/) + HostMode.InvokeOnConnected(); + + OnStartClient(); + } + + /// This stops both the client and the server that the manager is using. + public void StopHost() + { + OnStopHost(); + StopClient(); + StopServer(); + } + + /// Stops the server from listening and simulating the game. + public void StopServer() + { + // return if already stopped to avoid recursion deadlock + if (!NetworkServer.active) + return; + + if (authenticator != null) + { + authenticator.OnServerAuthenticated.RemoveListener(OnServerAuthenticated); + authenticator.OnStopServer(); + } + + // Get Network Manager out of DDOL before going to offline scene + // to avoid collision and let a fresh Network Manager be created. + // IMPORTANT: .gameObject can be null if StopClient is called from + // OnApplicationQuit or from tests! + if (gameObject != null + && gameObject.scene.name == "DontDestroyOnLoad" + && !string.IsNullOrWhiteSpace(offlineScene) + && SceneManager.GetActiveScene().path != offlineScene) + SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene()); + + OnStopServer(); + + //Debug.Log("NetworkManager StopServer"); + NetworkServer.Shutdown(); + + // set offline mode BEFORE changing scene so that FinishStartScene + // doesn't think we need initialize anything. + mode = NetworkManagerMode.Offline; + + if (!string.IsNullOrWhiteSpace(offlineScene)) + { + ServerChangeScene(offlineScene); + } + + startPositionIndex = 0; + + networkSceneName = ""; + } + + /// Stops and disconnects the client. + public void StopClient() + { + if (mode == NetworkManagerMode.Offline) + return; + + // For Host client, call OnServerDisconnect before NetworkClient.Disconnect + // because we need NetworkServer.localConnection to not be null + // NetworkClient.Disconnect will set it null. + if (mode == NetworkManagerMode.Host) + OnServerDisconnect(NetworkServer.localConnection); + + // ask client -> transport to disconnect. + // handle voluntary and involuntary disconnects in OnClientDisconnect. + // + // StopClient + // NetworkClient.Disconnect + // Transport.Disconnect + // ... + // Transport.OnClientDisconnect + // NetworkClient.OnTransportDisconnect + // NetworkManager.OnClientDisconnect + NetworkClient.Disconnect(); + + // UNET invoked OnDisconnected cleanup immediately. + // let's keep it for now, in case any projects depend on it. + // TODO simply remove this in the future. + OnClientDisconnectInternal(); + } + + // called when quitting the application by closing the window / pressing + // stop in the editor. virtual so that inheriting classes' + // OnApplicationQuit() can call base.OnApplicationQuit() too + public virtual void OnApplicationQuit() + { + // stop client first + // (we want to send the quit packet to the server instead of waiting + // for a timeout) + if (NetworkClient.isConnected) + { + StopClient(); + //Debug.Log("OnApplicationQuit: stopped client"); + } + + // stop server after stopping client (for proper host mode stopping) + if (NetworkServer.active) + { + StopServer(); + //Debug.Log("OnApplicationQuit: stopped server"); + } + + // Call ResetStatics to reset statics and singleton + ResetStatics(); + } + + /// Set the frame rate for a headless builds. Override to disable or modify. + // useful for dedicated servers. + // useful for headless benchmark clients. + public virtual void ConfigureHeadlessFrameRate() + { +#if UNITY_SERVER + Application.targetFrameRate = sendRate; + // Debug.Log($"Server Tick Rate set to {Application.targetFrameRate} Hz."); +#endif + } + + bool InitializeSingleton() + { + if (singleton != null && singleton == this) + return true; + + if (dontDestroyOnLoad) + { + if (singleton != null) + { + Debug.LogWarning("Multiple NetworkManagers detected in the scene. Only one NetworkManager can exist at a time. The duplicate NetworkManager will be destroyed."); + Destroy(gameObject); + + // Return false to not allow collision-destroyed second instance to continue. + return false; + } + //Debug.Log("NetworkManager created singleton (DontDestroyOnLoad)"); + singleton = this; + if (Application.isPlaying) + { + // Force the object to scene root, in case user made it a child of something + // in the scene since DDOL is only allowed for scene root objects + transform.SetParent(null); + DontDestroyOnLoad(gameObject); + } + } + else + { + //Debug.Log("NetworkManager created singleton (ForScene)"); + singleton = this; + } + + // set active transport AFTER setting singleton. + // so only if we didn't destroy ourselves. + + // This tries to avoid missing transport errors and more clearly tells user what to fix. + if (transport == null) + if (TryGetComponent(out Transport newTransport)) + { + Debug.LogWarning($"No Transport assigned to Network Manager - Using {newTransport} found on same object."); + transport = newTransport; + } + else + { + Debug.LogError("No Transport on Network Manager...add a transport and assign it."); + return false; + } + + Transport.active = transport; + return true; + } + + void RegisterServerMessages() + { + NetworkServer.OnConnectedEvent = OnServerConnectInternal; + NetworkServer.OnDisconnectedEvent = OnServerDisconnect; + NetworkServer.OnErrorEvent = OnServerError; + NetworkServer.RegisterHandler(OnServerAddPlayerInternal); + + // Network Server initially registers its own handler for this, so we replace it here. + NetworkServer.ReplaceHandler(OnServerReadyMessageInternal); + } + + void RegisterClientMessages() + { + NetworkClient.OnConnectedEvent = OnClientConnectInternal; + NetworkClient.OnDisconnectedEvent = OnClientDisconnectInternal; + NetworkClient.OnErrorEvent = OnClientError; + NetworkClient.RegisterHandler(OnClientNotReadyMessageInternal); + NetworkClient.RegisterHandler(OnClientSceneInternal, false); + + if (playerPrefab != null) + NetworkClient.RegisterPrefab(playerPrefab); + + foreach (GameObject prefab in spawnPrefabs.Where(t => t != null)) + NetworkClient.RegisterPrefab(prefab); + } + + // This is the only way to clear the singleton, so another instance can be created. + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + public static void ResetStatics() + { + // call StopHost if we have a singleton + if (singleton) + singleton.StopHost(); + + // reset all statics + startPositions.Clear(); + startPositionIndex = 0; + clientReadyConnection = null; + loadingSceneAsync = null; + networkSceneName = string.Empty; + + // and finally (in case it isn't null already)... + singleton = null; + } + + // virtual so that inheriting classes' OnDestroy() can call base.OnDestroy() too + public virtual void OnDestroy() + { + //Debug.Log("NetworkManager destroyed"); + } + + /// The name of the current network scene. + // set by NetworkManager when changing the scene. + // new clients will automatically load this scene. + // Loading a scene manually won't set it. + public static string networkSceneName { get; protected set; } = ""; + + public static AsyncOperation loadingSceneAsync; + + /// Change the server scene and all client's scenes across the network. + // Called automatically if onlineScene or offlineScene are set, but it + // can be called from user code to switch scenes again while the game is + // in progress. This automatically sets clients to be not-ready during + // the change and ready again to participate in the new scene. + public virtual void ServerChangeScene(string newSceneName) + { + if (string.IsNullOrWhiteSpace(newSceneName)) + { + Debug.LogError("ServerChangeScene empty scene name"); + return; + } + + if (NetworkServer.isLoadingScene && newSceneName == networkSceneName) + { + Debug.LogError($"Scene change is already in progress for {newSceneName}"); + return; + } + + // Debug.Log($"ServerChangeScene {newSceneName}"); + NetworkServer.SetAllClientsNotReady(); + networkSceneName = newSceneName; + + // Let server prepare for scene change + OnServerChangeScene(newSceneName); + + // set server flag to stop processing messages while changing scenes + // it will be re-enabled in FinishLoadScene. + NetworkServer.isLoadingScene = true; + + loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); + + // ServerChangeScene can be called when stopping the server + // when this happens the server is not active so does not need to tell clients about the change + if (NetworkServer.active) + { + // notify all clients about the new scene + NetworkServer.SendToAll(new SceneMessage + { + sceneName = newSceneName + }); + } + + startPositionIndex = 0; + startPositions.Clear(); + } + + // This is only set in ClientChangeScene below...never on server. + // We need to check this in OnClientSceneChanged called from FinishLoadSceneClientOnly + // to prevent AddPlayer message after loading/unloading additive scenes + SceneOperation clientSceneOperation = SceneOperation.Normal; + + internal void ClientChangeScene(string newSceneName, SceneOperation sceneOperation = SceneOperation.Normal, bool customHandling = false) + { + if (string.IsNullOrWhiteSpace(newSceneName)) + { + Debug.LogError("ClientChangeScene empty scene name"); + return; + } + + //Debug.Log($"ClientChangeScene newSceneName: {newSceneName} networkSceneName{networkSceneName}"); + + // Let client prepare for scene change + OnClientChangeScene(newSceneName, sceneOperation, customHandling); + + // After calling OnClientChangeScene, exit if server since server is already doing + // the actual scene change, and we don't need to do it for the host client + if (NetworkServer.active) + return; + + // set client flag to stop processing messages while loading scenes. + // otherwise we would process messages and then lose all the state + // as soon as the load is finishing, causing all kinds of bugs + // because of missing state. + // (client may be null after StopClient etc.) + // Debug.Log("ClientChangeScene: pausing handlers while scene is loading to avoid data loss after scene was loaded."); + NetworkClient.isLoadingScene = true; + + // Cache sceneOperation so we know what was requested by the + // Scene message in OnClientChangeScene and OnClientSceneChanged + clientSceneOperation = sceneOperation; + + // scene handling will happen in overrides of OnClientChangeScene and/or OnClientSceneChanged + // Do not call FinishLoadScene here. Custom handler will assign loadingSceneAsync and we need + // to wait for that to finish. UpdateScene already checks for that to be not null and isDone. + if (customHandling) + return; + + switch (sceneOperation) + { + case SceneOperation.Normal: + loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName); + break; + case SceneOperation.LoadAdditive: + // Ensure additive scene is not already loaded on client by name or path + // since we don't know which was passed in the Scene message + if (!SceneManager.GetSceneByName(newSceneName).IsValid() && !SceneManager.GetSceneByPath(newSceneName).IsValid()) + loadingSceneAsync = SceneManager.LoadSceneAsync(newSceneName, LoadSceneMode.Additive); + else + { + Debug.LogWarning($"Scene {newSceneName} is already loaded"); + + // Reset the flag that we disabled before entering this switch + NetworkClient.isLoadingScene = false; + } + break; + case SceneOperation.UnloadAdditive: + // Ensure additive scene is actually loaded on client by name or path + // since we don't know which was passed in the Scene message + if (SceneManager.GetSceneByName(newSceneName).IsValid() || SceneManager.GetSceneByPath(newSceneName).IsValid()) + loadingSceneAsync = SceneManager.UnloadSceneAsync(newSceneName, UnloadSceneOptions.UnloadAllEmbeddedSceneObjects); + else + { + Debug.LogWarning($"Cannot unload {newSceneName} with UnloadAdditive operation"); + + // Reset the flag that we disabled before entering this switch + NetworkClient.isLoadingScene = false; + } + break; + } + + // don't change the client's current networkSceneName when loading additive scene content + if (sceneOperation == SceneOperation.Normal) + networkSceneName = newSceneName; + } + + // support additive scene loads: + // NetworkScenePostProcess disables all scene objects on load, and + // * NetworkServer.SpawnObjects enables them again on the server when + // calling OnStartServer + // * NetworkClient.PrepareToSpawnSceneObjects enables them again on the + // client after the server sends ObjectSpawnStartedMessage to client + // in SpawnObserversForConnection. this is only called when the + // client joins, so we need to rebuild scene objects manually again + // TODO merge this with FinishLoadScene()? + void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + if (mode == LoadSceneMode.Additive) + { + if (NetworkServer.active) + { + // TODO only respawn the server objects from that scene later! + NetworkServer.SpawnObjects(); + // Debug.Log($"Respawned Server objects after additive scene load: {scene.name}"); + } + if (NetworkClient.active) + { + NetworkClient.PrepareToSpawnSceneObjects(); + // Debug.Log($"Rebuild Client spawnableObjects after additive scene load: {scene.name}"); + } + } + } + + void UpdateScene() + { + if (loadingSceneAsync != null && loadingSceneAsync.isDone) + { + //Debug.Log($"ClientChangeScene done readyConn {clientReadyConnection}"); + + // try-finally to guarantee loadingSceneAsync being cleared. + // fixes https://github.com/vis2k/Mirror/issues/2517 where if + // FinishLoadScene throws an exception, loadingSceneAsync would + // never be cleared and this code would run every Update. + try + { + FinishLoadScene(); + } + finally + { + loadingSceneAsync.allowSceneActivation = true; + loadingSceneAsync = null; + } + } + } + + protected void FinishLoadScene() + { + // NOTE: this cannot use NetworkClient.allClients[0] - that client may be for a completely different purpose. + + // process queued messages that we received while loading the scene + //Debug.Log("FinishLoadScene: resuming handlers after scene was loading."); + NetworkServer.isLoadingScene = false; + NetworkClient.isLoadingScene = false; + + // host mode? + if (mode == NetworkManagerMode.Host) + { + FinishLoadSceneHost(); + } + // server-only mode? + else if (mode == NetworkManagerMode.ServerOnly) + { + FinishLoadSceneServerOnly(); + } + // client-only mode? + else if (mode == NetworkManagerMode.ClientOnly) + { + FinishLoadSceneClientOnly(); + } + // otherwise we called it after stopping when loading offline scene. + // do nothing then. + } + + // finish load scene part for host mode. makes code easier and is + // necessary for FinishStartHost later. + // (the 3 things have to happen in that exact order) + void FinishLoadSceneHost() + { + // debug message is very important. if we ever break anything then + // it's very obvious to notice. + //Debug.Log("Finished loading scene in host mode."); + + if (clientReadyConnection != null) + { + clientLoadedScene = true; + clientReadyConnection = null; + } + + // do we need to finish a StartHost() call? + // then call FinishStartHost and let it take care of spawning etc. + if (finishStartHostPending) + { + finishStartHostPending = false; + FinishStartHost(); + + // call OnServerSceneChanged + OnServerSceneChanged(networkSceneName); + + // DO NOT call OnClientSceneChanged here. + // the scene change happened because StartHost loaded the + // server's online scene. it has nothing to do with the client. + // this was not meant as a client scene load, so don't call it. + // + // otherwise AddPlayer would be called twice: + // -> once for client OnConnected + // -> once in OnClientSceneChanged + } + // otherwise we just changed a scene in host mode + else + { + // spawn server objects + NetworkServer.SpawnObjects(); + + // call OnServerSceneChanged + OnServerSceneChanged(networkSceneName); + + if (NetworkClient.isConnected) + OnClientSceneChanged(); + } + } + + // finish load scene part for server-only. . makes code easier and is + // necessary for FinishStartServer later. + void FinishLoadSceneServerOnly() + { + // debug message is very important. if we ever break anything then + // it's very obvious to notice. + //Debug.Log("Finished loading scene in server-only mode."); + + NetworkServer.SpawnObjects(); + OnServerSceneChanged(networkSceneName); + } + + // finish load scene part for client-only. makes code easier and is + // necessary for FinishStartClient later. + void FinishLoadSceneClientOnly() + { + // debug message is very important. if we ever break anything then + // it's very obvious to notice. + //Debug.Log("Finished loading scene in client-only mode."); + + if (clientReadyConnection != null) + { + clientLoadedScene = true; + clientReadyConnection = null; + } + + if (NetworkClient.isConnected) + OnClientSceneChanged(); + } + + /// + /// Registers the transform of a game object as a player spawn location. + /// This is done automatically by NetworkStartPosition components, but can be done manually from user script code. + /// + /// Transform to register. + // Static because it's called from NetworkStartPosition::Awake + // and singleton may not exist yet + public static void RegisterStartPosition(Transform start) + { + // Debug.Log($"RegisterStartPosition: {start.gameObject.name} {start.position}"); + startPositions.Add(start); + + // reorder the list so that round-robin spawning uses the start positions + // in hierarchy order. This assumes all objects with NetworkStartPosition + // component are siblings, either in the scene root or together as children + // under a single parent in the scene. + startPositions = startPositions.OrderBy(transform => transform.GetSiblingIndex()).ToList(); + } + + /// Unregister a Transform from start positions. + // Static because it's called from NetworkStartPosition::OnDestroy + // and singleton may not exist yet + public static void UnRegisterStartPosition(Transform start) + { + //Debug.Log($"UnRegisterStartPosition: {start.name} {start.position}"); + startPositions.Remove(start); + } + + /// Get the next NetworkStartPosition based on the selected PlayerSpawnMethod. + public virtual Transform GetStartPosition() + { + // first remove any dead transforms + startPositions.RemoveAll(t => t == null); + + if (startPositions.Count == 0) + return null; + + if (playerSpawnMethod == PlayerSpawnMethod.Random) + { + return startPositions[UnityEngine.Random.Range(0, startPositions.Count)]; + } + else + { + Transform startPosition = startPositions[startPositionIndex]; + startPositionIndex = (startPositionIndex + 1) % startPositions.Count; + return startPosition; + } + } + + void OnServerConnectInternal(NetworkConnectionToClient conn) + { + //Debug.Log("NetworkManager.OnServerConnectInternal"); + + if (authenticator != null) + { + // we have an authenticator - let it handle authentication + authenticator.OnServerAuthenticate(conn); + } + else + { + // authenticate immediately + OnServerAuthenticated(conn); + } + } + + // called after successful authentication + // TODO do the NetworkServer.OnAuthenticated thing from x branch + void OnServerAuthenticated(NetworkConnectionToClient conn) + { + //Debug.Log("NetworkManager.OnServerAuthenticated"); + + // set connection to authenticated + conn.isAuthenticated = true; + + // proceed with the login handshake by calling OnServerConnect + if (networkSceneName != "" && networkSceneName != offlineScene) + { + SceneMessage msg = new SceneMessage() + { + sceneName = networkSceneName + }; + conn.Send(msg); + } + + OnServerConnect(conn); + } + + void OnServerReadyMessageInternal(NetworkConnectionToClient conn, ReadyMessage msg) + { + //Debug.Log("NetworkManager.OnServerReadyMessageInternal"); + OnServerReady(conn); + } + + void OnServerAddPlayerInternal(NetworkConnectionToClient conn, AddPlayerMessage msg) + { + //Debug.Log("NetworkManager.OnServerAddPlayer"); + + if (autoCreatePlayer && playerPrefab == null) + { + Debug.LogError("The PlayerPrefab is empty on the NetworkManager. Please setup a PlayerPrefab object."); + return; + } + + if (autoCreatePlayer && !playerPrefab.TryGetComponent(out NetworkIdentity _)) + { + Debug.LogError("The PlayerPrefab does not have a NetworkIdentity. Please add a NetworkIdentity to the player prefab."); + return; + } + + if (conn.identity != null) + { + Debug.LogError("There is already a player for this connection."); + return; + } + + OnServerAddPlayer(conn); + } + + void OnClientConnectInternal() + { + //Debug.Log("NetworkManager.OnClientConnectInternal"); + + if (authenticator != null) + { + // we have an authenticator - let it handle authentication + authenticator.OnClientAuthenticate(); + } + else + { + // authenticate immediately + OnClientAuthenticated(); + } + } + + // called after successful authentication + void OnClientAuthenticated() + { + //Debug.Log("NetworkManager.OnClientAuthenticated"); + + // set connection to authenticated + NetworkClient.connection.isAuthenticated = true; + + // Set flag to wait for scene change? + if (string.IsNullOrWhiteSpace(onlineScene) || onlineScene == offlineScene || Utils.IsSceneActive(onlineScene)) + { + clientLoadedScene = false; + } + else + { + // Scene message expected from server. + clientLoadedScene = true; + clientReadyConnection = NetworkClient.connection; + } + + // Call virtual method regardless of whether a scene change is expected or not. + OnClientConnect(); + } + + // Transport callback, invoked after client fully disconnected. + // the call order should always be: + // Disconnect() -> ask Transport -> Transport.OnDisconnected -> Cleanup + void OnClientDisconnectInternal() + { + //Debug.Log("NetworkManager.OnClientDisconnectInternal"); + + // Only let this run once. StopClient in Host mode changes to ServerOnly + if (mode == NetworkManagerMode.ServerOnly || mode == NetworkManagerMode.Offline) + return; + + // user callback + OnClientDisconnect(); + + if (authenticator != null) + { + authenticator.OnClientAuthenticated.RemoveListener(OnClientAuthenticated); + authenticator.OnStopClient(); + } + + // set mode BEFORE changing scene so FinishStartScene doesn't re-initialize anything. + // set mode BEFORE NetworkClient.Disconnect so StopClient only runs once. + // set mode BEFORE OnStopClient so StopClient only runs once. + // If we got here from StopClient in Host mode, change to ServerOnly. + // - If StopHost was called, StopServer will put us in Offline mode. + if (mode == NetworkManagerMode.Host) + mode = NetworkManagerMode.ServerOnly; + else + mode = NetworkManagerMode.Offline; + + //Debug.Log("NetworkManager StopClient"); + OnStopClient(); + + // shutdown client + NetworkClient.Shutdown(); + + // Exit here if we're now in ServerOnly mode (StopClient called in Host mode). + if (mode == NetworkManagerMode.ServerOnly) return; + + // Get Network Manager out of DDOL before going to offline scene + // to avoid collision and let a fresh Network Manager be created. + // IMPORTANT: .gameObject can be null if StopClient is called from + // OnApplicationQuit or from tests! + if (gameObject != null + && gameObject.scene.name == "DontDestroyOnLoad" + && !string.IsNullOrWhiteSpace(offlineScene) + && SceneManager.GetActiveScene().path != offlineScene) + SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetActiveScene()); + + // If StopHost called in Host mode, StopServer will change scenes after this. + // Check loadingSceneAsync to ensure we don't double-invoke the scene change. + // Check if NetworkServer.active because we can get here via Disconnect before server has started to change scenes. + if (!string.IsNullOrWhiteSpace(offlineScene) && !Utils.IsSceneActive(offlineScene) && loadingSceneAsync == null && !NetworkServer.active) + { + ClientChangeScene(offlineScene, SceneOperation.Normal); + } + + networkSceneName = ""; + } + + void OnClientNotReadyMessageInternal(NotReadyMessage msg) + { + //Debug.Log("NetworkManager.OnClientNotReadyMessageInternal"); + NetworkClient.ready = false; + OnClientNotReady(); + + // NOTE: clientReadyConnection is not set here! don't want OnClientConnect to be invoked again after scene changes. + } + + void OnClientSceneInternal(SceneMessage msg) + { + //Debug.Log("NetworkManager.OnClientSceneInternal"); + + // This needs to run for host client too. NetworkServer.active is checked there + if (NetworkClient.isConnected) + { + ClientChangeScene(msg.sceneName, msg.sceneOperation, msg.customHandling); + } + } + + /// Called on the server when a new client connects. + public virtual void OnServerConnect(NetworkConnectionToClient conn) { } + + /// Called on the server when a client disconnects. + // Called by NetworkServer.OnTransportDisconnect! + public virtual void OnServerDisconnect(NetworkConnectionToClient conn) + { + // by default, this function destroys the connection's player. + // can be overwritten for cases like delayed logouts in MMOs to + // avoid players escaping from PvP situations by logging out. + NetworkServer.DestroyPlayerForConnection(conn); + //Debug.Log("OnServerDisconnect: Client disconnected."); + } + + /// Called on the server when a client is ready (= loaded the scene) + public virtual void OnServerReady(NetworkConnectionToClient conn) + { + if (conn.identity == null) + { + // this is now allowed (was not for a while) + //Debug.Log("Ready with no player object"); + } + NetworkServer.SetClientReady(conn); + } + + /// Called on server when a client requests to add the player. Adds playerPrefab by default. Can be overwritten. + // The default implementation for this function creates a new player object from the playerPrefab. + public virtual void OnServerAddPlayer(NetworkConnectionToClient conn) + { + Transform startPos = GetStartPosition(); + GameObject player = startPos != null + ? Instantiate(playerPrefab, startPos.position, startPos.rotation) + : Instantiate(playerPrefab); + + // instantiating a "Player" prefab gives it the name "Player(clone)" + // => appending the connectionId is WAY more useful for debugging! + player.name = $"{playerPrefab.name} [connId={conn.connectionId}]"; + NetworkServer.AddPlayerForConnection(conn, player); + } + + /// Called on server when transport raises an exception. NetworkConnection may be null. + public virtual void OnServerError(NetworkConnectionToClient conn, TransportError error, string reason) { } + + /// Called from ServerChangeScene immediately before SceneManager.LoadSceneAsync is executed + public virtual void OnServerChangeScene(string newSceneName) { } + + /// Called on server after a scene load with ServerChangeScene() is completed. + public virtual void OnServerSceneChanged(string sceneName) { } + + /// Called on the client when connected to a server. By default it sets client as ready and adds a player. + public virtual void OnClientConnect() + { + // OnClientConnect by default calls AddPlayer but it should not do + // that when we have online/offline scenes. so we need the + // clientLoadedScene flag to prevent it. + if (!clientLoadedScene) + { + // Ready/AddPlayer is usually triggered by a scene load completing. + // if no scene was loaded, then Ready/AddPlayer it here instead. + if (!NetworkClient.ready) + NetworkClient.Ready(); + + if (autoCreatePlayer) + NetworkClient.AddPlayer(); + } + } + + /// Called on clients when disconnected from a server. + public virtual void OnClientDisconnect() { } + + /// Called on client when transport raises an exception. + public virtual void OnClientError(TransportError error, string reason) { } + + /// Called on clients when a servers tells the client it is no longer ready, e.g. when switching scenes. + public virtual void OnClientNotReady() { } + + /// Called from ClientChangeScene immediately before SceneManager.LoadSceneAsync is executed + // customHandling: indicates if scene loading will be handled through overrides + public virtual void OnClientChangeScene(string newSceneName, SceneOperation sceneOperation, bool customHandling) { } + + /// Called on clients when a scene has completed loaded, when the scene load was initiated by the server. + // Scene changes can cause player objects to be destroyed. The default + // implementation of OnClientSceneChanged in the NetworkManager is to + // add a player object for the connection if no player object exists. + public virtual void OnClientSceneChanged() + { + // always become ready. + if (NetworkClient.connection.isAuthenticated && !NetworkClient.ready) NetworkClient.Ready(); + + // Only call AddPlayer for normal scene changes, not additive load/unload + if (NetworkClient.connection.isAuthenticated && clientSceneOperation == SceneOperation.Normal && autoCreatePlayer && NetworkClient.localPlayer == null) + { + // add player if existing one is null + NetworkClient.AddPlayer(); + } + } + + // Since there are multiple versions of StartServer, StartClient and + // StartHost, to reliably customize their functionality, users would + // need override all the versions. Instead these callbacks are invoked + // from all versions, so users only need to implement this one case. + + /// This is invoked when a host is started. + public virtual void OnStartHost() { } + + /// This is invoked when a server is started - including when a host is started. + public virtual void OnStartServer() { } + + /// This is invoked when the client is started. + public virtual void OnStartClient() { } + + /// This is called when a server is stopped - including when a host is stopped. + public virtual void OnStopServer() { } + + /// This is called when a client is stopped. + public virtual void OnStopClient() { } + + /// This is called when a host is stopped. + public virtual void OnStopHost() { } + + // keep OnGUI even in builds. useful to debug snap interp. + void OnGUI() + { + if (!timeInterpolationGui) return; + NetworkClient.OnGUI(); + } + } +} diff --git a/Assets/Mirror/Core/NetworkManager.cs.meta b/Assets/Mirror/Core/NetworkManager.cs.meta new file mode 100644 index 0000000..0a7564a --- /dev/null +++ b/Assets/Mirror/Core/NetworkManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8aab4c8111b7c411b9b92cf3dbc5bd4e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkManagerHUD.cs b/Assets/Mirror/Core/NetworkManagerHUD.cs new file mode 100644 index 0000000..0a267fb --- /dev/null +++ b/Assets/Mirror/Core/NetworkManagerHUD.cs @@ -0,0 +1,155 @@ +// vis2k: GUILayout instead of spacey += ...; removed Update hotkeys to avoid +// confusion if someone accidentally presses one. +using UnityEngine; + +namespace Mirror +{ + /// Shows NetworkManager controls in a GUI at runtime. + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Manager HUD")] + [RequireComponent(typeof(NetworkManager))] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-manager-hud")] + public class NetworkManagerHUD : MonoBehaviour + { + NetworkManager manager; + + public int offsetX; + public int offsetY; + + void Awake() + { + manager = GetComponent(); + } + + void OnGUI() + { + GUILayout.BeginArea(new Rect(10 + offsetX, 40 + offsetY, 250, 9999)); + if (!NetworkClient.isConnected && !NetworkServer.active) + { + StartButtons(); + } + else + { + StatusLabels(); + } + + // client ready + if (NetworkClient.isConnected && !NetworkClient.ready) + { + if (GUILayout.Button("Client Ready")) + { + NetworkClient.Ready(); + if (NetworkClient.localPlayer == null) + { + NetworkClient.AddPlayer(); + } + } + } + + StopButtons(); + + GUILayout.EndArea(); + } + + void StartButtons() + { + if (!NetworkClient.active) + { + // Server + Client + if (Application.platform != RuntimePlatform.WebGLPlayer) + { + if (GUILayout.Button("Host (Server + Client)")) + { + manager.StartHost(); + } + } + + // Client + IP + GUILayout.BeginHorizontal(); + if (GUILayout.Button("Client")) + { + manager.StartClient(); + } + // This updates networkAddress every frame from the TextField + manager.networkAddress = GUILayout.TextField(manager.networkAddress); + GUILayout.EndHorizontal(); + + // Server Only + if (Application.platform == RuntimePlatform.WebGLPlayer) + { + // cant be a server in webgl build + GUILayout.Box("( WebGL cannot be server )"); + } + else + { + if (GUILayout.Button("Server Only")) manager.StartServer(); + } + } + else + { + // Connecting + GUILayout.Label($"Connecting to {manager.networkAddress}.."); + if (GUILayout.Button("Cancel Connection Attempt")) + { + manager.StopClient(); + } + } + } + + void StatusLabels() + { + // host mode + // display separately because this always confused people: + // Server: ... + // Client: ... + if (NetworkServer.active && NetworkClient.active) + { + GUILayout.Label($"Host: running via {Transport.active}"); + } + // server only + else if (NetworkServer.active) + { + GUILayout.Label($"Server: running via {Transport.active}"); + } + // client only + else if (NetworkClient.isConnected) + { + GUILayout.Label($"Client: connected to {manager.networkAddress} via {Transport.active}"); + } + } + + void StopButtons() + { + // stop host if host mode + if (NetworkServer.active && NetworkClient.isConnected) + { + GUILayout.BeginHorizontal(); + if (GUILayout.Button("Stop Host")) + { + manager.StopHost(); + } + if (GUILayout.Button("Stop Client")) + { + manager.StopClient(); + } + GUILayout.EndHorizontal(); + } + // stop client if client-only + else if (NetworkClient.isConnected) + { + if (GUILayout.Button("Stop Client")) + { + manager.StopClient(); + } + } + // stop server if server-only + else if (NetworkServer.active) + { + if (GUILayout.Button("Stop Server")) + { + manager.StopServer(); + } + } + } + } +} diff --git a/Assets/Mirror/Core/NetworkManagerHUD.cs.meta b/Assets/Mirror/Core/NetworkManagerHUD.cs.meta new file mode 100644 index 0000000..a720b9c --- /dev/null +++ b/Assets/Mirror/Core/NetworkManagerHUD.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6442dc8070ceb41f094e44de0bf87274 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkMessage.cs b/Assets/Mirror/Core/NetworkMessage.cs new file mode 100644 index 0000000..7fc387a --- /dev/null +++ b/Assets/Mirror/Core/NetworkMessage.cs @@ -0,0 +1,4 @@ +namespace Mirror +{ + public interface NetworkMessage {} +} diff --git a/Assets/Mirror/Core/NetworkMessage.cs.meta b/Assets/Mirror/Core/NetworkMessage.cs.meta new file mode 100644 index 0000000..73d3d8f --- /dev/null +++ b/Assets/Mirror/Core/NetworkMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eb04e4848a2e4452aa2dbd7adb801c51 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkMessages.cs b/Assets/Mirror/Core/NetworkMessages.cs new file mode 100644 index 0000000..034e877 --- /dev/null +++ b/Assets/Mirror/Core/NetworkMessages.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Text; +using UnityEngine; + +namespace Mirror +{ + // for performance, we (ab)use c# generics to cache the message id in a static field + // this is significantly faster than doing the computation at runtime or looking up cached results via Dictionary + // generic classes have separate static fields per type specification + public static class NetworkMessageId where T : struct, NetworkMessage + { + // automated message id from type hash. + // platform independent via stable hashcode. + // => convenient so we don't need to track messageIds across projects + // => addons can work with each other without knowing their ids before + // => 2 bytes is enough to avoid collisions. + // registering a messageId twice will log a warning anyway. + public static readonly ushort Id = + (ushort)(typeof(T).FullName.GetStableHashCode()); + } + + // message packing all in one place, instead of constructing headers in all + // kinds of different places + // + // MsgType (2 bytes) + // Content (ContentSize bytes) + public static class NetworkMessages + { + // size of message id header in bytes + public const int IdSize = sizeof(ushort); + + // Id <> Type lookup for debugging, profiler, etc. + // important when debugging messageId errors! + public static readonly Dictionary Lookup = + new Dictionary(); + + // dump all types for debugging + public static void LogTypes() + { + StringBuilder builder = new StringBuilder(); + builder.AppendLine("NetworkMessageIds:"); + foreach (KeyValuePair kvp in Lookup) + { + builder.AppendLine($" Id={kvp.Key} = {kvp.Value}"); + } + Debug.Log(builder.ToString()); + } + + // max message content size (without header) calculation for convenience + // -> Transport.GetMaxPacketSize is the raw maximum + // -> Every message gets serialized into <> + // -> Every serialized message get put into a batch with one timestamp per batch + // -> Every message in a batch has a varuint size header. + // use the worst case VarUInt size for the largest possible + // message size = int.max. + public static int MaxContentSize(int channelId) + { + // calculate the max possible size that can fit in a batch + int transportMax = Transport.active.GetMaxPacketSize(channelId); + return transportMax - IdSize - Batcher.MaxMessageOverhead(transportMax); + } + + // max message size which includes header + content. + public static int MaxMessageSize(int channelId) => + MaxContentSize(channelId) + IdSize; + + // automated message id from type hash. + // platform independent via stable hashcode. + // => convenient so we don't need to track messageIds across projects + // => addons can work with each other without knowing their ids before + // => 2 bytes is enough to avoid collisions. + // registering a messageId twice will log a warning anyway. + // keep this for convenience. easier to use than NetworkMessageId.Id. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ushort GetId() where T : struct, NetworkMessage => + NetworkMessageId.Id; + + // pack message before sending + // -> NetworkWriter passed as arg so that we can use .ToArraySegment + // and do an allocation free send before recycling it. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Pack(T message, NetworkWriter writer) + where T : struct, NetworkMessage + { + writer.WriteUShort(NetworkMessageId.Id); + writer.Write(message); + } + + // read only the message id. + // common function in case we ever change the header size. + public static bool UnpackId(NetworkReader reader, out ushort messageId) + { + // read message type + try + { + messageId = reader.ReadUShort(); + return true; + } + catch (System.IO.EndOfStreamException) + { + messageId = 0; + return false; + } + } + + // version for handlers with channelId + // inline! only exists for 20-30 messages and they call it all the time. + internal static NetworkMessageDelegate WrapHandler(Action handler, bool requireAuthentication) + where T : struct, NetworkMessage + where C : NetworkConnection + => (conn, reader, channelId) => + { + // protect against DOS attacks if attackers try to send invalid + // data packets to crash the server/client. there are a thousand + // ways to cause an exception in data handling: + // - invalid headers + // - invalid message ids + // - invalid data causing exceptions + // - negative ReadBytesAndSize prefixes + // - invalid utf8 strings + // - etc. + // + // let's catch them all and then disconnect that connection to avoid + // further attacks. + T message = default; + // record start position for NetworkDiagnostics because reader might contain multiple messages if using batching + int startPos = reader.Position; + try + { + if (requireAuthentication && !conn.isAuthenticated) + { + // message requires authentication, but the connection was not authenticated + Debug.LogWarning($"Disconnecting connection: {conn}. Received message {typeof(T)} that required authentication, but the user has not authenticated yet"); + conn.Disconnect(); + return; + } + + //Debug.Log($"ConnectionRecv {conn} msgType:{typeof(T)} content:{BitConverter.ToString(reader.buffer.Array, reader.buffer.Offset, reader.buffer.Count)}"); + + // if it is a value type, just use default(T) + // otherwise allocate a new instance + message = reader.Read(); + } + catch (Exception exception) + { + Debug.LogError($"Disconnecting connection: {conn}. This can happen if the other side accidentally (or an attacker intentionally) sent invalid data. Reason: {exception}"); + conn.Disconnect(); + return; + } + finally + { + int endPos = reader.Position; + // TODO: Figure out the correct channel + NetworkDiagnostics.OnReceive(message, channelId, endPos - startPos); + } + + // user handler exception should not stop the whole server + try + { + // user implemented handler + handler((C)conn, message, channelId); + } + catch (Exception e) + { + Debug.LogError($"Disconnecting connId={conn.connectionId} to prevent exploits from an Exception in MessageHandler: {e.GetType().Name} {e.Message}\n{e.StackTrace}"); + conn.Disconnect(); + } + }; + + // version for handlers without channelId + // TODO obsolete this some day to always use the channelId version. + // all handlers in this version are wrapped with 1 extra action. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static NetworkMessageDelegate WrapHandler(Action handler, bool requireAuthentication) + where T : struct, NetworkMessage + where C : NetworkConnection + { + // wrap action as channelId version, call original + void Wrapped(C conn, T msg, int _) => handler(conn, msg); + return WrapHandler((Action)Wrapped, requireAuthentication); + } + } +} diff --git a/Assets/Mirror/Core/NetworkMessages.cs.meta b/Assets/Mirror/Core/NetworkMessages.cs.meta new file mode 100644 index 0000000..910b75c --- /dev/null +++ b/Assets/Mirror/Core/NetworkMessages.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2db134099f0df4d96a84ae7a0cd9b4bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkReader.cs b/Assets/Mirror/Core/NetworkReader.cs new file mode 100644 index 0000000..82fb7cd --- /dev/null +++ b/Assets/Mirror/Core/NetworkReader.cs @@ -0,0 +1,249 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text; +using Unity.Collections.LowLevel.Unsafe; +using UnityEngine; + +namespace Mirror +{ + /// Network Reader for most simple types like floats, ints, buffers, structs, etc. Use NetworkReaderPool.GetReader() to avoid allocations. + // Note: This class is intended to be extremely pedantic, + // and throw exceptions whenever stuff is going slightly wrong. + // The exceptions will be handled in NetworkServer/NetworkClient. + // + // Note that NetworkWriter can be passed in constructor thanks to implicit + // ArraySegment conversion: + // NetworkReader reader = new NetworkReader(writer); + public class NetworkReader + { + // internal buffer + // byte[] pointer would work, but we use ArraySegment to also support + // the ArraySegment constructor + internal ArraySegment buffer; + + /// Next position to read from the buffer + // 'int' is the best type for .Position. 'short' is too small if we send >32kb which would result in negative .Position + // -> converting long to int is fine until 2GB of data (MAX_INT), so we don't have to worry about overflows here + public int Position; + + /// Remaining bytes that can be read, for convenience. + public int Remaining => buffer.Count - Position; + + /// Total buffer capacity, independent of reader position. + public int Capacity => buffer.Count; + + // cache encoding for ReadString instead of creating it with each time + // 1000 readers before: 1MB GC, 30ms + // 1000 readers after: 0.8MB GC, 18ms + // member(!) to avoid static state. + // + // throwOnInvalidBytes is true. + // if false, it would silently ignore the invalid bytes but continue + // with the valid ones, creating strings like "a�������". + // instead, we want to catch it manually and return String.Empty. + // this is safer. see test: ReadString_InvalidUTF8(). + internal readonly UTF8Encoding encoding = new UTF8Encoding(false, true); + + // while allocation free ReadArraySegment is encouraged, + // some functions can allocate a new byte[], List, Texture, etc. + // we should keep a reasonable allocation size limit: + // -> server won't accidentally allocate 2GB on a mobile device + // -> client won't allocate 2GB on server for ClientToServer [SyncVar]s + // -> unlike max string length of 64 KB, we need a larger limit here. + // large enough to not break existing projects, + // small enough to reasonably limit allocation attacks. + // -> we don't know the exact size of ReadList etc. because is + // managed. instead, this is considered a 'collection length' limit. + public const int AllocationLimit = 1024 * 1024 * 16; // 16 MB * sizeof(T) + + public NetworkReader(ArraySegment segment) + { + buffer = segment; + } + +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have the implicit byte[] to segment conversion yet + public NetworkReader(byte[] bytes) + { + buffer = new ArraySegment(bytes, 0, bytes.Length); + } +#endif + + // sometimes it's useful to point a reader on another buffer instead of + // allocating a new reader (e.g. NetworkReaderPool) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetBuffer(ArraySegment segment) + { + buffer = segment; + Position = 0; + } + +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have the implicit byte[] to segment conversion yet + public void SetBuffer(byte[] bytes) + { + buffer = new ArraySegment(bytes, 0, bytes.Length); + Position = 0; + } +#endif + + // ReadBlittable from DOTSNET + // this is extremely fast, but only works for blittable types. + // => private to make sure nobody accidentally uses it for non-blittable + // + // Benchmark: see NetworkWriter.WriteBlittable! + // + // Note: + // ReadBlittable assumes same endianness for server & client. + // All Unity 2018+ platforms are little endian. + // + // This is not safe to expose to random structs. + // * StructLayout.Sequential is the default, which is safe. + // if the struct contains a reference type, it is converted to Auto. + // but since all structs here are unmanaged blittable, it's safe. + // see also: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.layoutkind?view=netframework-4.8#system-runtime-interopservices-layoutkind-sequential + // * StructLayout.Pack depends on CPU word size. + // this may be different 4 or 8 on some ARM systems, etc. + // this is not safe, and would cause bytes/shorts etc. to be padded. + // see also: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.structlayoutattribute.pack?view=net-6.0 + // * If we force pack all to '1', they would have no padding which is + // great for bandwidth. but on some android systems, CPU can't read + // unaligned memory. + // see also: https://github.com/vis2k/Mirror/issues/3044 + // * The only option would be to force explicit layout with multiples + // of word size. but this requires lots of weaver checking and is + // still questionable (IL2CPP etc.). + // + // Note: inlining ReadBlittable is enough. don't inline ReadInt etc. + // we don't want ReadBlittable to be copied in place everywhere. + internal unsafe T ReadBlittable() + where T : unmanaged + { + // check if blittable for safety +#if UNITY_EDITOR + if (!UnsafeUtility.IsBlittable(typeof(T))) + { + throw new ArgumentException($"{typeof(T)} is not blittable!"); + } +#endif + + // calculate size + // sizeof(T) gets the managed size at compile time. + // Marshal.SizeOf gets the unmanaged size at runtime (slow). + // => our 1mio writes benchmark is 6x slower with Marshal.SizeOf + // => for blittable types, sizeof(T) is even recommended: + // https://docs.microsoft.com/en-us/dotnet/standard/native-interop/best-practices + int size = sizeof(T); + + // ensure remaining + if (Remaining < size) + { + throw new EndOfStreamException($"ReadBlittable<{typeof(T)}> not enough data in buffer to read {size} bytes: {ToString()}"); + } + + // read blittable + T value; + fixed (byte* ptr = &buffer.Array[buffer.Offset + Position]) + { +#if UNITY_ANDROID + // on some android systems, reading *(T*)ptr throws a NRE if + // the ptr isn't aligned (i.e. if Position is 1,2,3,5, etc.). + // here we have to use memcpy. + // + // => we can't get a pointer of a struct in C# without + // marshalling allocations + // => instead, we stack allocate an array of type T and use that + // => stackalloc avoids GC and is very fast. it only works for + // value types, but all blittable types are anyway. + // + // this way, we can still support blittable reads on android. + // see also: https://github.com/vis2k/Mirror/issues/3044 + // (solution discovered by AIIO, FakeByte, mischa) + T* valueBuffer = stackalloc T[1]; + UnsafeUtility.MemCpy(valueBuffer, ptr, size); + value = valueBuffer[0]; +#else + // cast buffer to a T* pointer and then read from it. + value = *(T*)ptr; +#endif + } + Position += size; + return value; + } + + // blittable'?' template for code reuse + // note: bool isn't blittable. need to read as byte. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal T? ReadBlittableNullable() + where T : unmanaged => + ReadByte() != 0 ? ReadBlittable() : default(T?); + + public byte ReadByte() => ReadBlittable(); + + /// Read 'count' bytes into the bytes array + // NOTE: returns byte[] because all reader functions return something. + public byte[] ReadBytes(byte[] bytes, int count) + { + // user may call ReadBytes(ReadInt()). ensure positive count. + if (count < 0) throw new ArgumentOutOfRangeException("ReadBytes requires count >= 0"); + + // check if passed byte array is big enough + if (count > bytes.Length) + { + throw new EndOfStreamException($"ReadBytes can't read {count} + bytes because the passed byte[] only has length {bytes.Length}"); + } + // ensure remaining + if (Remaining < count) + { + throw new EndOfStreamException($"ReadBytesSegment can't read {count} bytes because it would read past the end of the stream. {ToString()}"); + } + + Array.Copy(buffer.Array, buffer.Offset + Position, bytes, 0, count); + Position += count; + return bytes; + } + + /// Read 'count' bytes allocation-free as ArraySegment that points to the internal array. + public ArraySegment ReadBytesSegment(int count) + { + // user may call ReadBytes(ReadInt()). ensure positive count. + if (count < 0) throw new ArgumentOutOfRangeException("ReadBytesSegment requires count >= 0"); + + // ensure remaining + if (Remaining < count) + { + throw new EndOfStreamException($"ReadBytesSegment can't read {count} bytes because it would read past the end of the stream. {ToString()}"); + } + + // return the segment + ArraySegment result = new ArraySegment(buffer.Array, buffer.Offset + Position, count); + Position += count; + return result; + } + + /// Reads any data type that mirror supports. Uses weaver populated Reader(T).read + public T Read() + { + Func readerDelegate = Reader.read; + if (readerDelegate == null) + { + Debug.LogError($"No reader found for {typeof(T)}. Use a type supported by Mirror or define a custom reader extension for {typeof(T)}."); + return default; + } + return readerDelegate(this); + } + + // print the full buffer with position / capacity. + public override string ToString() => + $"[{buffer.ToHexString()} @ {Position}/{Capacity}]"; + } + + /// Helper class that weaver populates with all reader types. + // Note that c# creates a different static variable for each type + // -> Weaver.ReaderWriterProcessor.InitializeReaderAndWriters() populates it + public static class Reader + { + public static Func read; + } +} diff --git a/Assets/Mirror/Core/NetworkReader.cs.meta b/Assets/Mirror/Core/NetworkReader.cs.meta new file mode 100644 index 0000000..65ad3f0 --- /dev/null +++ b/Assets/Mirror/Core/NetworkReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1610f05ec5bd14d6882e689f7372596a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkReaderExtensions.cs b/Assets/Mirror/Core/NetworkReaderExtensions.cs new file mode 100644 index 0000000..bb6ca31 --- /dev/null +++ b/Assets/Mirror/Core/NetworkReaderExtensions.cs @@ -0,0 +1,376 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; + +namespace Mirror +{ + // Mirror's Weaver automatically detects all NetworkReader function types, + // but they do all need to be extensions. + public static class NetworkReaderExtensions + { + public static byte ReadByte(this NetworkReader reader) => reader.ReadBlittable(); + public static byte? ReadByteNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static sbyte ReadSByte(this NetworkReader reader) => reader.ReadBlittable(); + public static sbyte? ReadSByteNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + // bool is not blittable. read as ushort. + public static char ReadChar(this NetworkReader reader) => (char)reader.ReadBlittable(); + public static char? ReadCharNullable(this NetworkReader reader) => (char?)reader.ReadBlittableNullable(); + + // bool is not blittable. read as byte. + public static bool ReadBool(this NetworkReader reader) => reader.ReadBlittable() != 0; + public static bool? ReadBoolNullable(this NetworkReader reader) + { + byte? value = reader.ReadBlittableNullable(); + return value.HasValue ? (value.Value != 0) : default(bool?); + } + + public static short ReadShort(this NetworkReader reader) => (short)reader.ReadUShort(); + public static short? ReadShortNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static ushort ReadUShort(this NetworkReader reader) => reader.ReadBlittable(); + public static ushort? ReadUShortNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static int ReadInt(this NetworkReader reader) => reader.ReadBlittable(); + public static int? ReadIntNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static uint ReadUInt(this NetworkReader reader) => reader.ReadBlittable(); + public static uint? ReadUIntNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static long ReadLong(this NetworkReader reader) => reader.ReadBlittable(); + public static long? ReadLongNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static ulong ReadULong(this NetworkReader reader) => reader.ReadBlittable(); + public static ulong? ReadULongNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static float ReadFloat(this NetworkReader reader) => reader.ReadBlittable(); + public static float? ReadFloatNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static double ReadDouble(this NetworkReader reader) => reader.ReadBlittable(); + public static double? ReadDoubleNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static decimal ReadDecimal(this NetworkReader reader) => reader.ReadBlittable(); + public static decimal? ReadDecimalNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + /// if an invalid utf8 string is sent + public static string ReadString(this NetworkReader reader) + { + // read number of bytes + ushort size = reader.ReadUShort(); + + // null support, see NetworkWriter + if (size == 0) + return null; + + ushort realSize = (ushort)(size - 1); + + // make sure it's within limits to avoid allocation attacks etc. + if (realSize > NetworkWriter.MaxStringLength) + throw new EndOfStreamException($"NetworkReader.ReadString - Value too long: {realSize} bytes. Limit is: {NetworkWriter.MaxStringLength} bytes"); + + ArraySegment data = reader.ReadBytesSegment(realSize); + + // convert directly from buffer to string via encoding + // throws in case of invalid utf8. + // see test: ReadString_InvalidUTF8() + return reader.encoding.GetString(data.Array, data.Offset, data.Count); + } + + /// if count is invalid + public static byte[] ReadBytesAndSize(this NetworkReader reader) + { + // count = 0 means the array was null + // otherwise count -1 is the length of the array + uint count = reader.ReadUInt(); + // Use checked() to force it to throw OverflowException if data is invalid + return count == 0 ? null : reader.ReadBytes(checked((int)(count - 1u))); + } + + public static byte[] ReadBytes(this NetworkReader reader, int count) + { + // prevent allocation attacks with a reasonable limit. + // server shouldn't allocate too much on client devices. + // client shouldn't allocate too much on server in ClientToServer [SyncVar]s. + if (count > NetworkReader.AllocationLimit) + { + // throw EndOfStream for consistency with ReadBlittable when out of data + throw new EndOfStreamException($"NetworkReader attempted to allocate {count} bytes, which is larger than the allowed limit of {NetworkReader.AllocationLimit} bytes."); + } + + byte[] bytes = new byte[count]; + reader.ReadBytes(bytes, count); + return bytes; + } + + /// if count is invalid + public static ArraySegment ReadBytesAndSizeSegment(this NetworkReader reader) + { + // count = 0 means the array was null + // otherwise count - 1 is the length of the array + uint count = reader.ReadUInt(); + // Use checked() to force it to throw OverflowException if data is invalid + return count == 0 ? default : reader.ReadBytesSegment(checked((int)(count - 1u))); + } + + public static Vector2 ReadVector2(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector2? ReadVector2Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Vector3 ReadVector3(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector3? ReadVector3Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Vector4 ReadVector4(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector4? ReadVector4Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Vector2Int ReadVector2Int(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector2Int? ReadVector2IntNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Vector3Int ReadVector3Int(this NetworkReader reader) => reader.ReadBlittable(); + public static Vector3Int? ReadVector3IntNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Color ReadColor(this NetworkReader reader) => reader.ReadBlittable(); + public static Color? ReadColorNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Color32 ReadColor32(this NetworkReader reader) => reader.ReadBlittable(); + public static Color32? ReadColor32Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Quaternion ReadQuaternion(this NetworkReader reader) => reader.ReadBlittable(); + public static Quaternion? ReadQuaternionNullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + // Rect is a struct with properties instead of fields + public static Rect ReadRect(this NetworkReader reader) => new Rect(reader.ReadVector2(), reader.ReadVector2()); + public static Rect? ReadRectNullable(this NetworkReader reader) => reader.ReadBool() ? ReadRect(reader) : default(Rect?); + + // Plane is a struct with properties instead of fields + public static Plane ReadPlane(this NetworkReader reader) => new Plane(reader.ReadVector3(), reader.ReadFloat()); + public static Plane? ReadPlaneNullable(this NetworkReader reader) => reader.ReadBool() ? ReadPlane(reader) : default(Plane?); + + // Ray is a struct with properties instead of fields + public static Ray ReadRay(this NetworkReader reader) => new Ray(reader.ReadVector3(), reader.ReadVector3()); + public static Ray? ReadRayNullable(this NetworkReader reader) => reader.ReadBool() ? ReadRay(reader) : default(Ray?); + + public static Matrix4x4 ReadMatrix4x4(this NetworkReader reader) => reader.ReadBlittable(); + public static Matrix4x4? ReadMatrix4x4Nullable(this NetworkReader reader) => reader.ReadBlittableNullable(); + + public static Guid ReadGuid(this NetworkReader reader) + { +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have Span yet + return new Guid(reader.ReadBytes(16)); +#else + // ReadBlittable(Guid) isn't safe. see ReadBlittable comments. + // Guid is Sequential, but we can't guarantee packing. + if (reader.Remaining >= 16) + { + ReadOnlySpan span = new ReadOnlySpan(reader.buffer.Array, reader.buffer.Offset + reader.Position, 16); + reader.Position += 16; + return new Guid(span); + } + throw new EndOfStreamException($"ReadGuid out of range: {reader}"); +#endif + } + public static Guid? ReadGuidNullable(this NetworkReader reader) => reader.ReadBool() ? ReadGuid(reader) : default(Guid?); + + public static NetworkIdentity ReadNetworkIdentity(this NetworkReader reader) + { + uint netId = reader.ReadUInt(); + if (netId == 0) + return null; + + // NOTE: a netId not being in spawned is common. + // for example, "[SyncVar] NetworkIdentity target" netId would not + // be known on client if the monster walks out of proximity for a + // moment. no need to log any error or warning here. + return Utils.GetSpawnedInServerOrClient(netId); + } + + public static NetworkBehaviour ReadNetworkBehaviour(this NetworkReader reader) + { + // read netId first. + // + // IMPORTANT: if netId != 0, writer always writes componentIndex. + // reusing ReadNetworkIdentity() might return a null NetworkIdentity + // even if netId was != 0 but the identity disappeared on the client, + // resulting in unequal amounts of data being written / read. + // https://github.com/vis2k/Mirror/issues/2972 + uint netId = reader.ReadUInt(); + if (netId == 0) + return null; + + // read component index in any case, BEFORE searching the spawned + // NetworkIdentity by netId. + byte componentIndex = reader.ReadByte(); + + // NOTE: a netId not being in spawned is common. + // for example, "[SyncVar] NetworkIdentity target" netId would not + // be known on client if the monster walks out of proximity for a + // moment. no need to log any error or warning here. + NetworkIdentity identity = Utils.GetSpawnedInServerOrClient(netId); + + return identity != null + ? identity.NetworkBehaviours[componentIndex] + : null; + } + + public static T ReadNetworkBehaviour(this NetworkReader reader) where T : NetworkBehaviour + { + return reader.ReadNetworkBehaviour() as T; + } + + public static NetworkBehaviourSyncVar ReadNetworkBehaviourSyncVar(this NetworkReader reader) + { + uint netId = reader.ReadUInt(); + byte componentIndex = default; + + // if netId is not 0, then index is also sent to read before returning + if (netId != 0) + { + componentIndex = reader.ReadByte(); + } + + return new NetworkBehaviourSyncVar(netId, componentIndex); + } + + public static Transform ReadTransform(this NetworkReader reader) + { + // Don't use null propagation here as it could lead to MissingReferenceException + NetworkIdentity networkIdentity = reader.ReadNetworkIdentity(); + return networkIdentity != null ? networkIdentity.transform : null; + } + + public static GameObject ReadGameObject(this NetworkReader reader) + { + // Don't use null propagation here as it could lead to MissingReferenceException + NetworkIdentity networkIdentity = reader.ReadNetworkIdentity(); + return networkIdentity != null ? networkIdentity.gameObject : null; + } + + // while SyncList is recommended for NetworkBehaviours, + // structs may have .List members which weaver needs to be able to + // fully serialize for NetworkMessages etc. + // note that Weaver/Readers/GenerateReader() handles this manually. + public static List ReadList(this NetworkReader reader) + { + int length = reader.ReadInt(); + + // 'null' is encoded as '-1' + if (length < 0) return null; + + // prevent allocation attacks with a reasonable limit. + // server shouldn't allocate too much on client devices. + // client shouldn't allocate too much on server in ClientToServer [SyncVar]s. + if (length > NetworkReader.AllocationLimit) + { + // throw EndOfStream for consistency with ReadBlittable when out of data + throw new EndOfStreamException($"NetworkReader attempted to allocate a List<{typeof(T)}> {length} elements, which is larger than the allowed limit of {NetworkReader.AllocationLimit}."); + } + + List result = new List(length); + for (int i = 0; i < length; i++) + { + result.Add(reader.Read()); + } + return result; + } + + // while SyncSet is recommended for NetworkBehaviours, + // structs may have .Set members which weaver needs to be able to + // fully serialize for NetworkMessages etc. + // note that Weaver/Readers/GenerateReader() handles this manually. + // TODO writer not found. need to adjust weaver first. see tests. + /* + public static HashSet ReadHashSet(this NetworkReader reader) + { + int length = reader.ReadInt(); + if (length < 0) + return null; + HashSet result = new HashSet(); + for (int i = 0; i < length; i++) + { + result.Add(reader.Read()); + } + return result; + } + */ + + public static T[] ReadArray(this NetworkReader reader) + { + int length = reader.ReadInt(); + + // 'null' is encoded as '-1' + if (length < 0) return null; + + // prevent allocation attacks with a reasonable limit. + // server shouldn't allocate too much on client devices. + // client shouldn't allocate too much on server in ClientToServer [SyncVar]s. + if (length > NetworkReader.AllocationLimit) + { + // throw EndOfStream for consistency with ReadBlittable when out of data + throw new EndOfStreamException($"NetworkReader attempted to allocate an Array<{typeof(T)}> with {length} elements, which is larger than the allowed limit of {NetworkReader.AllocationLimit}."); + } + + // we can't check if reader.Remaining < length, + // because we don't know sizeof(T) since it's a managed type. + // if (length > reader.Remaining) throw new EndOfStreamException($"Received array that is too large: {length}"); + + T[] result = new T[length]; + for (int i = 0; i < length; i++) + { + result[i] = reader.Read(); + } + return result; + } + + public static Uri ReadUri(this NetworkReader reader) + { + string uriString = reader.ReadString(); + return (string.IsNullOrWhiteSpace(uriString) ? null : new Uri(uriString)); + } + + public static Texture2D ReadTexture2D(this NetworkReader reader) + { + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 + short width = reader.ReadShort(); + if (width == -1) return null; + + // read height + short height = reader.ReadShort(); + + // prevent allocation attacks with a reasonable limit. + // server shouldn't allocate too much on client devices. + // client shouldn't allocate too much on server in ClientToServer [SyncVar]s. + // log an error and return default. + // we don't want attackers to be able to trigger exceptions. + int totalSize = width * height; + if (totalSize > NetworkReader.AllocationLimit) + { + Debug.LogWarning($"NetworkReader attempted to allocate a Texture2D with total size (width * height) of {totalSize}, which is larger than the allowed limit of {NetworkReader.AllocationLimit}."); + return null; + } + + Texture2D texture2D = new Texture2D(width, height); + + // read pixel content + Color32[] pixels = reader.ReadArray(); + texture2D.SetPixels32(pixels); + texture2D.Apply(); + return texture2D; + } + + public static Sprite ReadSprite(this NetworkReader reader) + { + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 + Texture2D texture = reader.ReadTexture2D(); + if (texture == null) return null; + + // otherwise create a valid sprite + return Sprite.Create(texture, reader.ReadRect(), reader.ReadVector2()); + } + + public static DateTime ReadDateTime(this NetworkReader reader) => DateTime.FromOADate(reader.ReadDouble()); + public static DateTime? ReadDateTimeNullable(this NetworkReader reader) => reader.ReadBool() ? ReadDateTime(reader) : default(DateTime?); + } +} diff --git a/Assets/Mirror/Core/NetworkReaderExtensions.cs.meta b/Assets/Mirror/Core/NetworkReaderExtensions.cs.meta new file mode 100644 index 0000000..66536c9 --- /dev/null +++ b/Assets/Mirror/Core/NetworkReaderExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 364a9f7ccd5541e19aa2ae0b81f0b3cf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkReaderPool.cs b/Assets/Mirror/Core/NetworkReaderPool.cs new file mode 100644 index 0000000..d50258a --- /dev/null +++ b/Assets/Mirror/Core/NetworkReaderPool.cs @@ -0,0 +1,45 @@ +// API consistent with Microsoft's ObjectPool. +using System; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + /// Pool of NetworkReaders to avoid allocations. + public static class NetworkReaderPool + { + // reuse Pool + // we still wrap it in NetworkReaderPool.Get/Recyle so we can reset the + // position and array before reusing. + static readonly Pool Pool = new Pool( + // byte[] will be assigned in GetReader + () => new NetworkReaderPooled(new byte[]{}), + // initial capacity to avoid allocations in the first few frames + 1000 + ); + + /// Get the next reader in the pool. If pool is empty, creates a new Reader + public static NetworkReaderPooled Get(byte[] bytes) + { + // grab from pool & set buffer + NetworkReaderPooled reader = Pool.Get(); + reader.SetBuffer(bytes); + return reader; + } + + /// Get the next reader in the pool. If pool is empty, creates a new Reader + public static NetworkReaderPooled Get(ArraySegment segment) + { + // grab from pool & set buffer + NetworkReaderPooled reader = Pool.Get(); + reader.SetBuffer(segment); + return reader; + } + + /// Returns a reader to the pool. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Return(NetworkReaderPooled reader) + { + Pool.Return(reader); + } + } +} diff --git a/Assets/Mirror/Core/NetworkReaderPool.cs.meta b/Assets/Mirror/Core/NetworkReaderPool.cs.meta new file mode 100644 index 0000000..2c94768 --- /dev/null +++ b/Assets/Mirror/Core/NetworkReaderPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2bacff63613ad634a98f9e4d15d29dbf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkReaderPooled.cs b/Assets/Mirror/Core/NetworkReaderPooled.cs new file mode 100644 index 0000000..5348904 --- /dev/null +++ b/Assets/Mirror/Core/NetworkReaderPooled.cs @@ -0,0 +1,15 @@ +// "NetworkReaderPooled" instead of "PooledNetworkReader" to group files, for +// easier IDE workflow and more elegant code. +using System; + +namespace Mirror +{ + /// Pooled NetworkReader, automatically returned to pool when using 'using' + // TODO make sealed again after removing obsolete NetworkReaderPooled! + public class NetworkReaderPooled : NetworkReader, IDisposable + { + internal NetworkReaderPooled(byte[] bytes) : base(bytes) {} + internal NetworkReaderPooled(ArraySegment segment) : base(segment) {} + public void Dispose() => NetworkReaderPool.Return(this); + } +} diff --git a/Assets/Mirror/Core/NetworkReaderPooled.cs.meta b/Assets/Mirror/Core/NetworkReaderPooled.cs.meta new file mode 100644 index 0000000..4eb6e9d --- /dev/null +++ b/Assets/Mirror/Core/NetworkReaderPooled.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: faafa97c32e44adf8e8888de817a370a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkServer.cs b/Assets/Mirror/Core/NetworkServer.cs new file mode 100644 index 0000000..b3acb46 --- /dev/null +++ b/Assets/Mirror/Core/NetworkServer.cs @@ -0,0 +1,1864 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Mirror.RemoteCalls; +using UnityEngine; + +namespace Mirror +{ + /// NetworkServer handles remote connections and has a local connection for a local client. + public static partial class NetworkServer + { + static bool initialized; + public static int maxConnections; + + /// Server Update frequency, per second. Use around 60Hz for fast paced games like Counter-Strike to minimize latency. Use around 30Hz for games like WoW to minimize computations. Use around 1-10Hz for slow paced games like EVE. + // overwritten by NetworkManager (if any) + public static int tickRate = 60; + + // tick rate is in Hz. + // convert to interval in seconds for convenience where needed. + // + // send interval is 1 / sendRate. + // but for tests we need a way to set it to exactly 0. + // 1 / int.max would not be exactly 0, so handel that manually. + public static float tickInterval => tickRate < int.MaxValue ? 1f / tickRate : 0; // for 30 Hz, that's 33ms + + // time & value snapshot interpolation are separate. + // -> time is interpolated globally on NetworkClient / NetworkConnection + // -> value is interpolated per-component, i.e. NetworkTransform. + // however, both need to be on the same send interval. + public static int sendRate => tickRate; + public static float sendInterval => sendRate < int.MaxValue ? 1f / sendRate : 0; // for 30 Hz, that's 33ms + static double lastSendTime; + + /// Connection to host mode client (if any) + public static LocalConnectionToClient localConnection { get; private set; } + + /// Dictionary of all server connections, with connectionId as key + public static Dictionary connections = + new Dictionary(); + + /// Message Handlers dictionary, with messageId as key + internal static Dictionary handlers = + new Dictionary(); + + /// All spawned NetworkIdentities by netId. + // server sees ALL spawned ones. + public static readonly Dictionary spawned = + new Dictionary(); + + /// Single player mode can use dontListen to not accept incoming connections + // see also: https://github.com/vis2k/Mirror/pull/2595 + public static bool dontListen; + + // Deprecated 2022-12-12 + [Obsolete("NetworkServer.localClientActive was renamed to .activeHost to be more obvious")] + public static bool localClientActive => activeHost; + + /// active checks if the server has been started either has standalone or as host server. + public static bool active { get; internal set; } + + /// active checks if the server has been started in host mode. + // naming consistent with NetworkClient.activeHost. + public static bool activeHost => localConnection != null; + + // scene loading + public static bool isLoadingScene; + + // interest management component (optional) + // by default, everyone observes everyone + public static InterestManagementBase aoi; + + // Mirror global disconnect inactive option, independent of Transport. + // not all Transports do this properly, and it's easiest to configure this just once. + // this is very useful for some projects, keep it. + public static bool disconnectInactiveConnections; + public static float disconnectInactiveTimeout = 60; + + // OnConnected / OnDisconnected used to be NetworkMessages that were + // invoked. this introduced a bug where external clients could send + // Connected/Disconnected messages over the network causing undefined + // behaviour. + // => public so that custom NetworkManagers can hook into it + public static Action OnConnectedEvent; + public static Action OnDisconnectedEvent; + public static Action OnErrorEvent; + + // keep track of actual achieved tick rate. + // might become lower under heavy load. + // very useful for profiling etc. + // measured over 1s each, same as frame rate. no EMA here. + public static int actualTickRate; + static double actualTickRateStart; // start time when counting + static int actualTickRateCounter; // current counter since start + + // profiling + // includes transport update time, because transport calls handlers etc. + // averaged over 1s by passing 'tickRate' to constructor. + public static TimeSample earlyUpdateDuration; + public static TimeSample lateUpdateDuration; + + // capture full Unity update time from before Early- to after LateUpdate + public static TimeSample fullUpdateDuration; + + /// Starts server and listens to incoming connections with max connections limit. + public static void Listen(int maxConns) + { + Initialize(); + maxConnections = maxConns; + + // only start server if we want to listen + if (!dontListen) + { + Transport.active.ServerStart(); + //Debug.Log("Server started listening"); + } + + active = true; + RegisterMessageHandlers(); + } + + // initialization / shutdown /////////////////////////////////////////// + static void Initialize() + { + if (initialized) + return; + + // safety: ensure Weaving succeded. + // if it silently failed, we would get lots of 'writer not found' + // and other random errors at runtime instead. this is cleaner. + if (!WeaverFuse.Weaved()) + { + // if it failed, throw an exception to early exit all Listen calls. + throw new Exception("NetworkServer won't start because Weaving failed or didn't run."); + } + + // Debug.Log($"NetworkServer Created version {Version.Current}"); + + //Make sure connections are cleared in case any old connections references exist from previous sessions + connections.Clear(); + + // reset Interest Management so that rebuild intervals + // start at 0 when starting again. + if (aoi != null) aoi.Reset(); + + // reset NetworkTime + NetworkTime.ResetStatics(); + + Debug.Assert(Transport.active != null, "There was no active transport when calling NetworkServer.Listen, If you are calling Listen manually then make sure to set 'Transport.active' first"); + AddTransportHandlers(); + + initialized = true; + + // profiling + earlyUpdateDuration = new TimeSample(sendRate); + lateUpdateDuration = new TimeSample(sendRate); + fullUpdateDuration = new TimeSample(sendRate); + } + + static void AddTransportHandlers() + { + // += so that other systems can also hook into it (i.e. statistics) + Transport.active.OnServerConnected += OnTransportConnected; + Transport.active.OnServerDataReceived += OnTransportData; + Transport.active.OnServerDisconnected += OnTransportDisconnected; + Transport.active.OnServerError += OnTransportError; + } + + /// Shuts down the server and disconnects all clients + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + public static void Shutdown() + { + if (initialized) + { + DisconnectAll(); + + // stop the server. + // we do NOT call Transport.Shutdown, because someone only + // called NetworkServer.Shutdown. we can't assume that the + // client is supposed to be shut down too! + // + // NOTE: stop no matter what, even if 'dontListen': + // someone might enabled dontListen at runtime. + // but we still need to stop the server. + // fixes https://github.com/vis2k/Mirror/issues/2536 + Transport.active.ServerStop(); + + // transport handlers are hooked into when initializing. + // so only remove them when shutting down. + RemoveTransportHandlers(); + + initialized = false; + } + + // Reset all statics here.... + dontListen = false; + isLoadingScene = false; + lastSendTime = 0; + actualTickRate = 0; + + localConnection = null; + + connections.Clear(); + connectionsCopy.Clear(); + handlers.Clear(); + + // destroy all spawned objects, _then_ set inactive. + // make sure .active is still true before calling this. + // otherwise modifying SyncLists in OnStopServer would throw + // because .IsWritable() check checks if NetworkServer.active. + // https://github.com/MirrorNetworking/Mirror/issues/3344 + CleanupSpawned(); + active = false; + + // sets nextNetworkId to 1 + // sets clientAuthorityCallback to null + // sets previousLocalPlayer to null + NetworkIdentity.ResetStatics(); + + // clear events. someone might have hooked into them before, but + // we don't want to use those hooks after Shutdown anymore. + OnConnectedEvent = null; + OnDisconnectedEvent = null; + OnErrorEvent = null; + + if (aoi != null) aoi.Reset(); + } + + static void RemoveTransportHandlers() + { + // -= so that other systems can also hook into it (i.e. statistics) + Transport.active.OnServerConnected -= OnTransportConnected; + Transport.active.OnServerDataReceived -= OnTransportData; + Transport.active.OnServerDisconnected -= OnTransportDisconnected; + Transport.active.OnServerError -= OnTransportError; + } + + // Note: NetworkClient.DestroyAllClientObjects does the same on client. + static void CleanupSpawned() + { + // iterate a COPY of spawned. + // DestroyObject removes them from the original collection. + // removing while iterating is not allowed. + foreach (NetworkIdentity identity in spawned.Values.ToList()) + { + if (identity != null) + { + // scene object + if (identity.sceneId != 0) + { + // spawned scene objects are unspawned and reset. + // afterwards we disable them again. + // (they always stay in the scene, we don't destroy them) + DestroyObject(identity, DestroyMode.Reset); + identity.gameObject.SetActive(false); + } + // spawned prefabs + else + { + // spawned prefabs are unspawned and destroyed. + DestroyObject(identity, DestroyMode.Destroy); + } + } + } + + spawned.Clear(); + } + + internal static void RegisterMessageHandlers() + { + RegisterHandler(OnClientReadyMessage); + RegisterHandler(OnCommandMessage); + RegisterHandler(NetworkTime.OnServerPing, false); + RegisterHandler(NetworkTime.OnServerPong, false); + RegisterHandler(OnEntityStateMessage, true); + RegisterHandler(OnTimeSnapshotMessage, true); + } + + // remote calls //////////////////////////////////////////////////////// + // Handle command from specific player, this could be one of multiple + // players on a single client + // default ready handler. + static void OnClientReadyMessage(NetworkConnectionToClient conn, ReadyMessage msg) + { + // Debug.Log($"Default handler for ready message from {conn}"); + SetClientReady(conn); + } + + static void OnCommandMessage(NetworkConnectionToClient conn, CommandMessage msg, int channelId) + { + if (!conn.isReady) + { + // Clients may be set NotReady due to scene change or other game logic by user, e.g. respawning. + // Ignore commands that may have been in flight before client received NotReadyMessage message. + // Unreliable messages may be out of order, so don't spam warnings for those. + if (channelId == Channels.Reliable) + Debug.LogWarning("Command received while client is not ready.\nThis may be ignored if client intentionally set NotReady."); + return; + } + + if (!spawned.TryGetValue(msg.netId, out NetworkIdentity identity)) + { + // over reliable channel, commands should always come after spawn. + // over unreliable, they might come in before the object was spawned. + // for example, NetworkTransform. + // let's not spam the console for unreliable out of order messages. + if (channelId == Channels.Reliable) + Debug.LogWarning($"Spawned object not found when handling Command message [netId={msg.netId}]"); + return; + } + + // Commands can be for player objects, OR other objects with client-authority + // -> so if this connection's controller has a different netId then + // only allow the command if clientAuthorityOwner + bool requiresAuthority = RemoteProcedureCalls.CommandRequiresAuthority(msg.functionHash); + if (requiresAuthority && identity.connectionToClient != conn) + { + Debug.LogWarning($"Command for object without authority [netId={msg.netId}]"); + return; + } + + // Debug.Log($"OnCommandMessage for netId:{msg.netId} conn:{conn}"); + + using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(msg.payload)) + identity.HandleRemoteCall(msg.componentIndex, msg.functionHash, RemoteCallType.Command, networkReader, conn); + } + + // client to server broadcast ////////////////////////////////////////// + // for client's owned ClientToServer components. + static void OnEntityStateMessage(NetworkConnectionToClient connection, EntityStateMessage message) + { + // need to validate permissions carefully. + // an attacker may attempt to modify a not-owned or not-ClientToServer component. + + // valid netId? + if (spawned.TryGetValue(message.netId, out NetworkIdentity identity) && identity != null) + { + // owned by the connection? + if (identity.connectionToClient == connection) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message.payload)) + { + // DeserializeServer checks permissions internally. + // failure to deserialize disconnects to prevent exploits. + if (!identity.DeserializeServer(reader)) + { + Debug.LogWarning($"Server failed to deserialize client state for {identity.name} with netId={identity.netId}, Disconnecting."); + connection.Disconnect(); + } + } + } + // An attacker may attempt to modify another connection's entity + // This could also be a race condition of message in flight when + // RemoveClientAuthority is called, so not malicious. + // Don't disconnect, just log the warning. + else + Debug.LogWarning($"EntityStateMessage from {connection} for {identity} without authority."); + } + // no warning. don't spam server logs. + // else Debug.LogWarning($"Did not find target for sync message for {message.netId} . Note: this can be completely normal because UDP messages may arrive out of order, so this message might have arrived after a Destroy message."); + } + + // client sends TimeSnapshotMessage every sendInterval. + // batching already includes the remoteTimestamp. + // we simply insert it on-message here. + // => only for reliable channel. unreliable would always arrive earlier. + static void OnTimeSnapshotMessage(NetworkConnectionToClient connection, TimeSnapshotMessage _) + { + // insert another snapshot for snapshot interpolation. + // before calling OnDeserialize so components can use + // NetworkTime.time and NetworkTime.timeStamp. + + // TODO validation? + // maybe we shouldn't allow timeline to deviate more than a certain %. + // for now, this is only used for client authority movement. + + // Unity 2019 doesn't have Time.timeAsDouble yet + // + // NetworkTime uses unscaled time and ignores Time.timeScale. + // fixes Time.timeScale getting server & client time out of sync: + // https://github.com/MirrorNetworking/Mirror/issues/3409 + connection.OnTimeSnapshot(new TimeSnapshot(connection.remoteTimeStamp, NetworkTime.localTime)); + } + + // connections ///////////////////////////////////////////////////////// + /// Add a connection and setup callbacks. Returns true if not added yet. + public static bool AddConnection(NetworkConnectionToClient conn) + { + if (!connections.ContainsKey(conn.connectionId)) + { + // connection cannot be null here or conn.connectionId + // would throw NRE + connections[conn.connectionId] = conn; + return true; + } + // already a connection with this id + return false; + } + + /// Removes a connection by connectionId. Returns true if removed. + public static bool RemoveConnection(int connectionId) => + connections.Remove(connectionId); + + // called by LocalClient to add itself. don't call directly. + // TODO consider internal setter instead? + internal static void SetLocalConnection(LocalConnectionToClient conn) + { + if (localConnection != null) + { + Debug.LogError("Local Connection already exists"); + return; + } + + localConnection = conn; + } + + // removes local connection to client + internal static void RemoveLocalConnection() + { + if (localConnection != null) + { + localConnection.Disconnect(); + localConnection = null; + } + RemoveConnection(0); + } + + /// True if we have external connections (that are not host) + public static bool HasExternalConnections() + { + // any connections? + if (connections.Count > 0) + { + // only host connection? + if (connections.Count == 1 && localConnection != null) + return false; + + // otherwise we have real external connections + return true; + } + return false; + } + + // send //////////////////////////////////////////////////////////////// + /// Send a message to all clients, even those that haven't joined the world yet (non ready) + public static void SendToAll(T message, int channelId = Channels.Reliable, bool sendToReadyOnly = false) + where T : struct, NetworkMessage + { + if (!active) + { + Debug.LogWarning("Can not send using NetworkServer.SendToAll(T msg) because NetworkServer is not active"); + return; + } + + // Debug.Log($"Server.SendToAll {typeof(T)}"); + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // pack message only once + NetworkMessages.Pack(message, writer); + ArraySegment segment = writer.ToArraySegment(); + + // filter and then send to all internet connections at once + // -> makes code more complicated, but is HIGHLY worth it to + // avoid allocations, allow for multicast, etc. + int count = 0; + foreach (NetworkConnectionToClient conn in connections.Values) + { + if (sendToReadyOnly && !conn.isReady) + continue; + + count++; + conn.Send(segment, channelId); + } + + NetworkDiagnostics.OnSend(message, channelId, segment.Count, count); + } + } + + /// Send a message to all clients which have joined the world (are ready). + // TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady! + public static void SendToReady(T message, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + if (!active) + { + Debug.LogWarning("Can not send using NetworkServer.SendToReady(T msg) because NetworkServer is not active"); + return; + } + + SendToAll(message, channelId, true); + } + + // this is like SendToReadyObservers - but it doesn't check the ready flag on the connection. + // this is used for ObjectDestroy messages. + static void SendToObservers(NetworkIdentity identity, T message, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + // Debug.Log($"Server.SendToObservers {typeof(T)}"); + if (identity == null || identity.observers.Count == 0) + return; + + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // pack message into byte[] once + NetworkMessages.Pack(message, writer); + ArraySegment segment = writer.ToArraySegment(); + + foreach (NetworkConnectionToClient conn in identity.observers.Values) + { + conn.Send(segment, channelId); + } + + NetworkDiagnostics.OnSend(message, channelId, segment.Count, identity.observers.Count); + } + } + + /// Send a message to only clients which are ready with option to include the owner of the object identity + // TODO obsolete this later. it's not used anymore + public static void SendToReadyObservers(NetworkIdentity identity, T message, bool includeOwner = true, int channelId = Channels.Reliable) + where T : struct, NetworkMessage + { + // Debug.Log($"Server.SendToReady {typeof(T)}"); + if (identity == null || identity.observers.Count == 0) + return; + + using (NetworkWriterPooled writer = NetworkWriterPool.Get()) + { + // pack message only once + NetworkMessages.Pack(message, writer); + ArraySegment segment = writer.ToArraySegment(); + + int count = 0; + foreach (NetworkConnectionToClient conn in identity.observers.Values) + { + bool isOwner = conn == identity.connectionToClient; + if ((!isOwner || includeOwner) && conn.isReady) + { + count++; + conn.Send(segment, channelId); + } + } + + NetworkDiagnostics.OnSend(message, channelId, segment.Count, count); + } + } + + /// Send a message to only clients which are ready including the owner of the NetworkIdentity + // TODO obsolete this later. it's not used anymore + public static void SendToReadyObservers(NetworkIdentity identity, T message, int channelId) + where T : struct, NetworkMessage + { + SendToReadyObservers(identity, message, true, channelId); + } + + // transport events //////////////////////////////////////////////////// + // called by transport + static void OnTransportConnected(int connectionId) + { + // Debug.Log($"Server accepted client:{connectionId}"); + + // connectionId needs to be != 0 because 0 is reserved for local player + // note that some transports like kcp generate connectionId by + // hashing which can be < 0 as well, so we need to allow < 0! + if (connectionId == 0) + { + Debug.LogError($"Server.HandleConnect: invalid connectionId: {connectionId} . Needs to be != 0, because 0 is reserved for local player."); + Transport.active.ServerDisconnect(connectionId); + return; + } + + // connectionId not in use yet? + if (connections.ContainsKey(connectionId)) + { + Transport.active.ServerDisconnect(connectionId); + // Debug.Log($"Server connectionId {connectionId} already in use...kicked client"); + return; + } + + // are more connections allowed? if not, kick + // (it's easier to handle this in Mirror, so Transports can have + // less code and third party transport might not do that anyway) + // (this way we could also send a custom 'tooFull' message later, + // Transport can't do that) + if (connections.Count < maxConnections) + { + // add connection + NetworkConnectionToClient conn = new NetworkConnectionToClient(connectionId); + OnConnected(conn); + } + else + { + // kick + Transport.active.ServerDisconnect(connectionId); + // Debug.Log($"Server full, kicked client {connectionId}"); + } + } + + internal static void OnConnected(NetworkConnectionToClient conn) + { + // Debug.Log($"Server accepted client:{conn}"); + + // add connection and invoke connected event + AddConnection(conn); + OnConnectedEvent?.Invoke(conn); + } + + static bool UnpackAndInvoke(NetworkConnectionToClient connection, NetworkReader reader, int channelId) + { + if (NetworkMessages.UnpackId(reader, out ushort msgType)) + { + // try to invoke the handler for that message + if (handlers.TryGetValue(msgType, out NetworkMessageDelegate handler)) + { + handler.Invoke(connection, reader, channelId); + connection.lastMessageTime = Time.time; + return true; + } + else + { + // message in a batch are NOT length prefixed to save bandwidth. + // every message needs to be handled and read until the end. + // otherwise it would overlap into the next message. + // => need to warn and disconnect to avoid undefined behaviour. + // => WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning($"Unknown message id: {msgType} for connection: {connection}. This can happen if no handler was registered for this message."); + // simply return false. caller is responsible for disconnecting. + //connection.Disconnect(); + return false; + } + } + else + { + // => WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning($"Invalid message header for connection: {connection}."); + // simply return false. caller is responsible for disconnecting. + //connection.Disconnect(); + return false; + } + } + + // called by transport + internal static void OnTransportData(int connectionId, ArraySegment data, int channelId) + { + if (connections.TryGetValue(connectionId, out NetworkConnectionToClient connection)) + { + // client might batch multiple messages into one packet. + // feed it to the Unbatcher. + // NOTE: we don't need to associate a channelId because we + // always process all messages in the batch. + if (!connection.unbatcher.AddBatch(data)) + { + Debug.LogWarning($"NetworkServer: received Message was too short (messages should start with message id)"); + connection.Disconnect(); + return; + } + + // process all messages in the batch. + // only while NOT loading a scene. + // if we get a scene change message, then we need to stop + // processing. otherwise we might apply them to the old scene. + // => fixes https://github.com/vis2k/Mirror/issues/2651 + // + // NOTE: if scene starts loading, then the rest of the batch + // would only be processed when OnTransportData is called + // the next time. + // => consider moving processing to NetworkEarlyUpdate. + while (!isLoadingScene && + connection.unbatcher.GetNextMessage(out ArraySegment message, out double remoteTimestamp)) + { + using (NetworkReaderPooled reader = NetworkReaderPool.Get(message)) + { + // enough to read at least header size? + if (reader.Remaining >= NetworkMessages.IdSize) + { + // make remoteTimeStamp available to the user + connection.remoteTimeStamp = remoteTimestamp; + + // handle message + if (!UnpackAndInvoke(connection, reader, channelId)) + { + // warn, disconnect and return if failed + // -> warning because attackers might send random data + // -> messages in a batch aren't length prefixed. + // failing to read one would cause undefined + // behaviour for every message afterwards. + // so we need to disconnect. + // -> return to avoid the below unbatches.count error. + // we already disconnected and handled it. + Debug.LogWarning($"NetworkServer: failed to unpack and invoke message. Disconnecting {connectionId}."); + connection.Disconnect(); + return; + } + } + // otherwise disconnect + else + { + // WARNING, not error. can happen if attacker sends random data. + Debug.LogWarning($"NetworkServer: received Message was too short (messages should start with message id). Disconnecting {connectionId}"); + connection.Disconnect(); + return; + } + } + } + + // if we weren't interrupted by a scene change, + // then all batched messages should have been processed now. + // otherwise batches would silently grow. + // we need to log an error to avoid debugging hell. + // + // EXAMPLE: https://github.com/vis2k/Mirror/issues/2882 + // -> UnpackAndInvoke silently returned because no handler for id + // -> Reader would never be read past the end + // -> Batch would never be retired because end is never reached + // + // NOTE: prefixing every message in a batch with a length would + // avoid ever not reading to the end. for extra bandwidth. + // + // IMPORTANT: always keep this check to detect memory leaks. + // this took half a day to debug last time. + if (!isLoadingScene && connection.unbatcher.BatchesCount > 0) + { + Debug.LogError($"Still had {connection.unbatcher.BatchesCount} batches remaining after processing, even though processing was not interrupted by a scene change. This should never happen, as it would cause ever growing batches.\nPossible reasons:\n* A message didn't deserialize as much as it serialized\n*There was no message handler for a message id, so the reader wasn't read until the end."); + } + } + else Debug.LogError($"HandleData Unknown connectionId:{connectionId}"); + } + + // called by transport + // IMPORTANT: often times when disconnecting, we call this from Mirror + // too because we want to remove the connection and handle + // the disconnect immediately. + // => which is fine as long as we guarantee it only runs once + // => which we do by removing the connection! + internal static void OnTransportDisconnected(int connectionId) + { + // Debug.Log($"Server disconnect client:{connectionId}"); + if (connections.TryGetValue(connectionId, out NetworkConnectionToClient conn)) + { + RemoveConnection(connectionId); + // Debug.Log($"Server lost client:{connectionId}"); + + // NetworkManager hooks into OnDisconnectedEvent to make + // DestroyPlayerForConnection(conn) optional, e.g. for PvP MMOs + // where players shouldn't be able to escape combat instantly. + if (OnDisconnectedEvent != null) + { + OnDisconnectedEvent.Invoke(conn); + } + // if nobody hooked into it, then simply call DestroyPlayerForConnection + else + { + DestroyPlayerForConnection(conn); + } + } + } + + // transport errors are forwarded to high level + static void OnTransportError(int connectionId, TransportError error, string reason) + { + // transport errors will happen. logging a warning is enough. + // make sure the user does not panic. + Debug.LogWarning($"Server Transport Error for connId={connectionId}: {error}: {reason}. This is fine."); + // try get connection. passes null otherwise. + connections.TryGetValue(connectionId, out NetworkConnectionToClient conn); + OnErrorEvent?.Invoke(conn, error, reason); + } + + /// Destroys all of the connection's owned objects on the server. + // This is used when a client disconnects, to remove the players for + // that client. This also destroys non-player objects that have client + // authority set for this connection. + public static void DestroyPlayerForConnection(NetworkConnectionToClient conn) + { + // destroy all objects owned by this connection, including the player object + conn.DestroyOwnedObjects(); + // remove connection from all of its observing entities observers + // fixes https://github.com/vis2k/Mirror/issues/2737 + // -> cleaning those up in NetworkConnection.Disconnect is NOT enough + // because voluntary disconnects from the other end don't call + // NetworkConnection.Disconnect() + conn.RemoveFromObservingsObservers(); + conn.identity = null; + } + + // message handlers //////////////////////////////////////////////////// + /// Register a handler for message type T. Most should require authentication. + // TODO obsolete this some day to always use the channelId version. + // all handlers in this version are wrapped with 1 extra action. + public static void RegisterHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + if (handlers.ContainsKey(msgType)) + { + Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning."); + } + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + handlers[msgType] = NetworkMessages.WrapHandler(handler, requireAuthentication); + } + + /// Register a handler for message type T. Most should require authentication. + // This version passes channelId to the handler. + public static void RegisterHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + if (handlers.ContainsKey(msgType)) + { + Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning."); + } + + // register Id <> Type in lookup for debugging. + NetworkMessages.Lookup[msgType] = typeof(T); + + handlers[msgType] = NetworkMessages.WrapHandler(handler, requireAuthentication); + } + + /// Replace a handler for message type T. Most should require authentication. + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ReplaceHandler((_, value) => { handler(value); }, requireAuthentication); + } + + /// Replace a handler for message type T. Most should require authentication. + public static void ReplaceHandler(Action handler, bool requireAuthentication = true) + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + handlers[msgType] = NetworkMessages.WrapHandler(handler, requireAuthentication); + } + + /// Unregister a handler for a message type T. + public static void UnregisterHandler() + where T : struct, NetworkMessage + { + ushort msgType = NetworkMessageId.Id; + handlers.Remove(msgType); + } + + /// Clears all registered message handlers. + public static void ClearHandlers() => handlers.Clear(); + + internal static bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity) + { + if (!go.TryGetComponent(out identity)) + { + Debug.LogError($"GameObject {go.name} doesn't have NetworkIdentity."); + return false; + } + return true; + } + + // disconnect ////////////////////////////////////////////////////////// + /// Disconnect all connections, including the local connection. + // synchronous: handles disconnect events and cleans up fully before returning! + public static void DisconnectAll() + { + // disconnect and remove all connections. + // we can not use foreach here because if + // conn.Disconnect -> Transport.ServerDisconnect calls + // OnDisconnect -> NetworkServer.OnDisconnect(connectionId) + // immediately then OnDisconnect would remove the connection while + // we are iterating here. + // see also: https://github.com/vis2k/Mirror/issues/2357 + // this whole process should be simplified some day. + // until then, let's copy .Values to avoid InvalidOperationException. + // note that this is only called when stopping the server, so the + // copy is no performance problem. + foreach (NetworkConnectionToClient conn in connections.Values.ToList()) + { + // disconnect via connection->transport + conn.Disconnect(); + + // we want this function to be synchronous: handle disconnect + // events and clean up fully before returning. + // -> OnTransportDisconnected can safely be called without + // waiting for the Transport's callback. + // -> it has checks to only run once. + + // call OnDisconnected unless local player in host mod + // TODO unnecessary check? + if (conn.connectionId != NetworkConnection.LocalConnectionId) + OnTransportDisconnected(conn.connectionId); + } + + // cleanup + connections.Clear(); + localConnection = null; + // this used to set active=false. + // however, then Shutdown can't properly destroy objects: + // https://github.com/MirrorNetworking/Mirror/issues/3344 + // "DisconnectAll" should only disconnect all, not set inactive. + // active = false; + } + + // add/remove/replace player /////////////////////////////////////////// + /// Called by server after AddPlayer message to add the player for the connection. + // When a player is added for a connection, the client for that + // connection is made ready automatically. The player object is + // automatically spawned, so you do not need to call NetworkServer.Spawn + // for that object. This function is used for "adding" a player, not for + // "replacing" the player on a connection. If there is already a player + // on this playerControllerId for this connection, this will fail. + public static bool AddPlayerForConnection(NetworkConnectionToClient conn, GameObject player, uint assetId) + { + if (GetNetworkIdentity(player, out NetworkIdentity identity)) + { + identity.assetId = assetId; + } + return AddPlayerForConnection(conn, player); + } + + /// Called by server after AddPlayer message to add the player for the connection. + // When a player is added for a connection, the client for that + // connection is made ready automatically. The player object is + // automatically spawned, so you do not need to call NetworkServer.Spawn + // for that object. This function is used for "adding" a player, not for + // "replacing" the player on a connection. If there is already a player + // on this playerControllerId for this connection, this will fail. + public static bool AddPlayerForConnection(NetworkConnectionToClient conn, GameObject player) + { + if (!player.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogWarning($"AddPlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}"); + return false; + } + + // cannot have a player object in "Add" version + if (conn.identity != null) + { + Debug.Log("AddPlayer: player object already exists"); + return false; + } + + // make sure we have a controller before we call SetClientReady + // because the observers will be rebuilt only if we have a controller + conn.identity = identity; + + // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients) + identity.SetClientOwner(conn); + + // special case, we are in host mode, set hasAuthority to true so that all overrides see it + if (conn is LocalConnectionToClient) + { + identity.isOwned = true; + NetworkClient.InternalAddPlayer(identity); + } + + // set ready if not set yet + SetClientReady(conn); + + // Debug.Log($"Adding new playerGameObject object netId: {identity.netId} asset ID: {identity.assetId}"); + + Respawn(identity); + return true; + } + + /// Replaces connection's player object. The old object is not destroyed. + // This does NOT change the ready state of the connection, so it can + // safely be used while changing scenes. + public static bool ReplacePlayerForConnection(NetworkConnectionToClient conn, GameObject player, bool keepAuthority = false) + { + if (!player.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"ReplacePlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}"); + return false; + } + + if (identity.connectionToClient != null && identity.connectionToClient != conn) + { + Debug.LogError($"Cannot replace player for connection. New player is already owned by a different connection{player}"); + return false; + } + + //NOTE: there can be an existing player + //Debug.Log("NetworkServer ReplacePlayer"); + + NetworkIdentity previousPlayer = conn.identity; + + conn.identity = identity; + + // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients) + identity.SetClientOwner(conn); + + // special case, we are in host mode, set hasAuthority to true so that all overrides see it + if (conn is LocalConnectionToClient) + { + identity.isOwned = true; + NetworkClient.InternalAddPlayer(identity); + } + + // add connection to observers AFTER the playerController was set. + // by definition, there is nothing to observe if there is no player + // controller. + // + // IMPORTANT: do this in AddPlayerForConnection & ReplacePlayerForConnection! + SpawnObserversForConnection(conn); + + //Debug.Log($"Replacing playerGameObject object netId:{player.GetComponent().netId} asset ID {player.GetComponent().assetId}"); + + Respawn(identity); + + if (keepAuthority) + { + // This needs to be sent to clear isLocalPlayer on + // client while keeping hasAuthority true + SendChangeOwnerMessage(previousPlayer, conn); + } + else + { + // This clears both isLocalPlayer and hasAuthority on client + previousPlayer.RemoveClientAuthority(); + } + + return true; + } + + /// Replaces connection's player object. The old object is not destroyed. + // This does NOT change the ready state of the connection, so it can + // safely be used while changing scenes. + public static bool ReplacePlayerForConnection(NetworkConnectionToClient conn, GameObject player, uint assetId, bool keepAuthority = false) + { + if (GetNetworkIdentity(player, out NetworkIdentity identity)) + { + identity.assetId = assetId; + } + return ReplacePlayerForConnection(conn, player, keepAuthority); + } + + /// Removes the player object from the connection + // destroyServerObject: Indicates whether the server object should be destroyed + public static void RemovePlayerForConnection(NetworkConnection conn, bool destroyServerObject) + { + if (conn.identity != null) + { + if (destroyServerObject) + Destroy(conn.identity.gameObject); + else + UnSpawn(conn.identity.gameObject); + + conn.identity = null; + } + //else Debug.Log($"Connection {conn} has no identity"); + } + + // ready /////////////////////////////////////////////////////////////// + /// Flags client connection as ready (=joined world). + // When a client has signaled that it is ready, this method tells the + // server that the client is ready to receive spawned objects and state + // synchronization updates. This is usually called in a handler for the + // SYSTEM_READY message. If there is not specific action a game needs to + // take for this message, relying on the default ready handler function + // is probably fine, so this call wont be needed. + public static void SetClientReady(NetworkConnectionToClient conn) + { + // Debug.Log($"SetClientReadyInternal for conn:{conn}"); + + // set ready + conn.isReady = true; + + // client is ready to start spawning objects + if (conn.identity != null) + SpawnObserversForConnection(conn); + } + + static void SpawnObserversForConnection(NetworkConnectionToClient conn) + { + //Debug.Log($"Spawning {spawned.Count} objects for conn {conn}"); + + if (!conn.isReady) + { + // client needs to finish initializing before we can spawn objects + // otherwise it would not find them. + return; + } + + // let connection know that we are about to start spawning... + conn.Send(new ObjectSpawnStartedMessage()); + + // add connection to each nearby NetworkIdentity's observers, which + // internally sends a spawn message for each one to the connection. + foreach (NetworkIdentity identity in spawned.Values) + { + // try with far away ones in ummorpg! + if (identity.gameObject.activeSelf) //TODO this is different + { + //Debug.Log($"Sending spawn message for current server objects name:{identity.name} netId:{identity.netId} sceneId:{identity.sceneId:X}"); + + // we need to support three cases: + // - legacy system (identity has .visibility) + // - new system (networkserver has .aoi) + // - default case: no .visibility and no .aoi means add all + // connections by default) + // + // ForceHidden/ForceShown overwrite all systems so check it + // first! + + // ForceShown: add no matter what + if (identity.visible == Visibility.ForceShown) + { + identity.AddObserver(conn); + } + // ForceHidden: don't show no matter what + else if (identity.visible == Visibility.ForceHidden) + { + // do nothing + } + // default: legacy system / new system / no system support + else if (identity.visible == Visibility.Default) + { + // aoi system + if (aoi != null) + { + // call OnCheckObserver + if (aoi.OnCheckObserver(identity, conn)) + identity.AddObserver(conn); + } + // no system: add all observers by default + else + { + identity.AddObserver(conn); + } + } + } + } + + // let connection know that we finished spawning, so it can call + // OnStartClient on each one (only after all were spawned, which + // is how Unity's Start() function works too) + conn.Send(new ObjectSpawnFinishedMessage()); + } + + /// Marks the client of the connection to be not-ready. + // Clients that are not ready do not receive spawned objects or state + // synchronization updates. They client can be made ready again by + // calling SetClientReady(). + public static void SetClientNotReady(NetworkConnectionToClient conn) + { + conn.isReady = false; + conn.RemoveFromObservingsObservers(); + conn.Send(new NotReadyMessage()); + } + + /// Marks all connected clients as no longer ready. + // All clients will no longer be sent state synchronization updates. The + // player's clients can call ClientManager.Ready() again to re-enter the + // ready state. This is useful when switching scenes. + public static void SetAllClientsNotReady() + { + foreach (NetworkConnectionToClient conn in connections.Values) + { + SetClientNotReady(conn); + } + } + + // show / hide for connection ////////////////////////////////////////// + internal static void ShowForConnection(NetworkIdentity identity, NetworkConnection conn) + { + if (conn.isReady) + SendSpawnMessage(identity, conn); + } + + internal static void HideForConnection(NetworkIdentity identity, NetworkConnection conn) + { + ObjectHideMessage msg = new ObjectHideMessage + { + netId = identity.netId + }; + conn.Send(msg); + } + + // spawning //////////////////////////////////////////////////////////// + internal static void SendSpawnMessage(NetworkIdentity identity, NetworkConnection conn) + { + if (identity.serverOnly) return; + + //Debug.Log($"Server SendSpawnMessage: name:{identity.name} sceneId:{identity.sceneId:X} netid:{identity.netId}"); + + // one writer for owner, one for observers + using (NetworkWriterPooled ownerWriter = NetworkWriterPool.Get(), observersWriter = NetworkWriterPool.Get()) + { + bool isOwner = identity.connectionToClient == conn; + ArraySegment payload = CreateSpawnMessagePayload(isOwner, identity, ownerWriter, observersWriter); + SpawnMessage message = new SpawnMessage + { + netId = identity.netId, + isLocalPlayer = conn.identity == identity, + isOwner = isOwner, + sceneId = identity.sceneId, + assetId = identity.assetId, + // use local values for VR support + position = identity.transform.localPosition, + rotation = identity.transform.localRotation, + scale = identity.transform.localScale, + payload = payload + }; + conn.Send(message); + } + } + + static ArraySegment CreateSpawnMessagePayload(bool isOwner, NetworkIdentity identity, NetworkWriterPooled ownerWriter, NetworkWriterPooled observersWriter) + { + // Only call SerializeAll if there are NetworkBehaviours + if (identity.NetworkBehaviours.Length == 0) + { + return default; + } + + // serialize all components with initialState = true + // (can be null if has none) + identity.SerializeServer(true, ownerWriter, observersWriter); + + // convert to ArraySegment to avoid reader allocations + // if nothing was written, .ToArraySegment returns an empty segment. + ArraySegment ownerSegment = ownerWriter.ToArraySegment(); + ArraySegment observersSegment = observersWriter.ToArraySegment(); + + // use owner segment if 'conn' owns this identity, otherwise + // use observers segment + ArraySegment payload = isOwner ? ownerSegment : observersSegment; + + return payload; + } + + internal static void SendChangeOwnerMessage(NetworkIdentity identity, NetworkConnectionToClient conn) + { + // Don't send if identity isn't spawned or only exists on server + if (identity.netId == 0 || identity.serverOnly) return; + + // Don't send if conn doesn't have the identity spawned yet + // May be excluded from the client by interest management + if (!conn.observing.Contains(identity)) return; + + //Debug.Log($"Server SendChangeOwnerMessage: name={identity.name} netid={identity.netId}"); + + conn.Send(new ChangeOwnerMessage + { + netId = identity.netId, + isOwner = identity.connectionToClient == conn, + isLocalPlayer = conn.identity == identity + }); + } + + // check NetworkIdentity parent before spawning it. + // - without parent, they are spawned + // - with parent, only if the parent is active in hierarchy + // + // note that active parents may have inactive parents of their own. + // we need to check .activeInHierarchy. + // + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3330 + // https://github.com/vis2k/Mirror/issues/2778 + static bool ValidParent(NetworkIdentity identity) => + identity.transform.parent == null || + identity.transform.parent.gameObject.activeInHierarchy; + + /// Spawns NetworkIdentities in the scene on the server. + // NetworkIdentity objects in a scene are disabled by default. Calling + // SpawnObjects() causes these scene objects to be enabled and spawned. + // It is like calling NetworkServer.Spawn() for each of them. + public static bool SpawnObjects() + { + // only if server active + if (!active) + return false; + + // find all NetworkIdentities in the scene. + // all of them are disabled because of NetworkScenePostProcess. + NetworkIdentity[] identities = Resources.FindObjectsOfTypeAll(); + + // first pass: activate all scene objects + foreach (NetworkIdentity identity in identities) + { + // only spawn scene objects which haven't been spawned yet. + // SpawnObjects may be called multiple times for additive scenes. + // https://github.com/MirrorNetworking/Mirror/issues/3318 + // + // note that we even activate objects under inactive parents. + // while they are not spawned, they do need to be activated + // in order to be spawned later. so here, we don't check parents. + // https://github.com/MirrorNetworking/Mirror/issues/3330 + if (Utils.IsSceneObject(identity) && identity.netId == 0) + { + // Debug.Log($"SpawnObjects sceneId:{identity.sceneId:X} name:{identity.gameObject.name}"); + identity.gameObject.SetActive(true); + } + } + + // second pass: spawn all scene objects + foreach (NetworkIdentity identity in identities) + { + // scene objects may be children of inactive parents. + // users would put them under disabled parents to 'deactivate' them. + // those should not be used by Mirror at all. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3330 + // https://github.com/vis2k/Mirror/issues/2778 + if (Utils.IsSceneObject(identity) && identity.netId == 0 && ValidParent(identity)) + { + // pass connection so that authority is not lost when server loads a scene + // https://github.com/vis2k/Mirror/pull/2987 + Spawn(identity.gameObject, identity.connectionToClient); + } + } + + return true; + } + + /// Spawns an object and also assigns Client Authority to the specified client. + // This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + public static void Spawn(GameObject obj, GameObject ownerPlayer) + { + if (!ownerPlayer.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError("Player object has no NetworkIdentity"); + return; + } + + if (identity.connectionToClient == null) + { + Debug.LogError("Player object is not a player."); + return; + } + + Spawn(obj, identity.connectionToClient); + } + + static void Respawn(NetworkIdentity identity) + { + if (identity.netId == 0) + { + // If the object has not been spawned, then do a full spawn and update observers + Spawn(identity.gameObject, identity.connectionToClient); + } + else + { + // otherwise just replace his data + SendSpawnMessage(identity, identity.connectionToClient); + } + } + + /// Spawn the given game object on all clients which are ready. + // This will cause a new object to be instantiated from the registered + // prefab, or from a custom spawn function. + public static void Spawn(GameObject obj, NetworkConnection ownerConnection = null) + { + SpawnObject(obj, ownerConnection); + } + + /// Spawns an object and also assigns Client Authority to the specified client. + // This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object. + public static void Spawn(GameObject obj, uint assetId, NetworkConnection ownerConnection = null) + { + if (GetNetworkIdentity(obj, out NetworkIdentity identity)) + { + identity.assetId = assetId; + } + SpawnObject(obj, ownerConnection); + } + + static void SpawnObject(GameObject obj, NetworkConnection ownerConnection) + { + // verify if we can spawn this + if (Utils.IsPrefab(obj)) + { + Debug.LogError($"GameObject {obj.name} is a prefab, it can't be spawned. Instantiate it first.", obj); + return; + } + + if (!active) + { + Debug.LogError($"SpawnObject for {obj}, NetworkServer is not active. Cannot spawn objects without an active server.", obj); + return; + } + + if (!obj.TryGetComponent(out NetworkIdentity identity)) + { + Debug.LogError($"SpawnObject {obj} has no NetworkIdentity. Please add a NetworkIdentity to {obj}", obj); + return; + } + + if (identity.SpawnedFromInstantiate) + { + // Using Instantiate on SceneObject is not allowed, so stop spawning here + // NetworkIdentity.Awake already logs error, no need to log a second error here + return; + } + + // Spawn should only be called once per netId. + // calling it twice would lead to undefined behaviour. + // https://github.com/MirrorNetworking/Mirror/pull/3205 + if (spawned.ContainsKey(identity.netId)) + { + Debug.LogWarning($"{identity} with netId={identity.netId} was already spawned.", identity.gameObject); + return; + } + + identity.connectionToClient = (NetworkConnectionToClient)ownerConnection; + + // special case to make sure hasAuthority is set + // on start server in host mode + if (ownerConnection is LocalConnectionToClient) + identity.isOwned = true; + + // only call OnStartServer if not spawned yet. + // check used to be in NetworkIdentity. may not be necessary anymore. + if (!identity.isServer && identity.netId == 0) + { + // configure NetworkIdentity + // this may be called in host mode, so we need to initialize + // isLocalPlayer/isClient flags too. + identity.isLocalPlayer = NetworkClient.localPlayer == identity; + identity.isClient = NetworkClient.active; + identity.isServer = true; + identity.netId = NetworkIdentity.GetNextNetworkId(); + + // add to spawned (after assigning netId) + spawned[identity.netId] = identity; + + // callback after all fields were set + identity.OnStartServer(); + } + + // Debug.Log($"SpawnObject instance ID {identity.netId} asset ID {identity.assetId}"); + + if (aoi) + { + // This calls user code which might throw exceptions + // We don't want this to leave us in bad state + try + { + aoi.OnSpawned(identity); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + + RebuildObservers(identity, true); + } + + /// This takes an object that has been spawned and un-spawns it. + // The object will be removed from clients that it was spawned on, or + // the custom spawn handler function on the client will be called for + // the object. + // Unlike when calling NetworkServer.Destroy(), on the server the object + // will NOT be destroyed. This allows the server to re-use the object, + // even spawn it again later. + public static void UnSpawn(GameObject obj) => DestroyObject(obj, DestroyMode.Reset); + + // destroy ///////////////////////////////////////////////////////////// + // sometimes we want to GameObject.Destroy it. + // sometimes we want to just unspawn on clients and .Reset() it on server. + // => 'bool destroy' isn't obvious enough. it's really destroy OR reset! + enum DestroyMode { Destroy, Reset } + + /// Destroys this object and corresponding objects on all clients. + // In some cases it is useful to remove an object but not delete it on + // the server. For that, use NetworkServer.UnSpawn() instead of + // NetworkServer.Destroy(). + public static void Destroy(GameObject obj) => DestroyObject(obj, DestroyMode.Destroy); + + static void DestroyObject(GameObject obj, DestroyMode mode) + { + if (obj == null) + { + Debug.Log("NetworkServer DestroyObject is null"); + return; + } + + if (GetNetworkIdentity(obj, out NetworkIdentity identity)) + { + DestroyObject(identity, mode); + } + } + + static void DestroyObject(NetworkIdentity identity, DestroyMode mode) + { + // Debug.Log($"DestroyObject instance:{identity.netId}"); + + // only call OnRebuildObservers while active, + // not while shutting down + // (https://github.com/vis2k/Mirror/issues/2977) + if (active && aoi) + { + // This calls user code which might throw exceptions + // We don't want this to leave us in bad state + try + { + aoi.OnDestroyed(identity); + } + catch (Exception e) + { + Debug.LogException(e); + } + } + + // remove from NetworkServer (this) dictionary + spawned.Remove(identity.netId); + + identity.connectionToClient?.RemoveOwnedObject(identity); + + // send object destroy message to all observers, clear observers + SendToObservers(identity, new ObjectDestroyMessage + { + netId = identity.netId + }); + identity.ClearObservers(); + + // in host mode, call OnStopClient/OnStopLocalPlayer manually + if (NetworkClient.active && activeHost) + { + if (identity.isLocalPlayer) + identity.OnStopLocalPlayer(); + + identity.OnStopClient(); + // The object may have been spawned with host client ownership, + // e.g. a pet so we need to clear hasAuthority and call + // NotifyAuthority which invokes OnStopAuthority if hasAuthority. + identity.isOwned = false; + identity.NotifyAuthority(); + + // remove from NetworkClient dictionary + NetworkClient.connection.owned.Remove(identity); + NetworkClient.spawned.Remove(identity.netId); + } + + // we are on the server. call OnStopServer. + identity.OnStopServer(); + + // are we supposed to GameObject.Destroy() it completely? + if (mode == DestroyMode.Destroy) + { + identity.destroyCalled = true; + + // Destroy if application is running + if (Application.isPlaying) + { + UnityEngine.Object.Destroy(identity.gameObject); + } + // Destroy can't be used in Editor during tests. use DestroyImmediate. + else + { + GameObject.DestroyImmediate(identity.gameObject); + } + } + // otherwise simply .Reset() and set inactive again + else if (mode == DestroyMode.Reset) + { + identity.Reset(); + } + } + + // interest management ///////////////////////////////////////////////// + + // Helper function to add all server connections as observers. + // This is used if none of the components provides their own + // OnRebuildObservers function. + // rebuild observers default method (no AOI) - adds all connections + static void RebuildObserversDefault(NetworkIdentity identity, bool initialize) + { + // only add all connections when rebuilding the first time. + // second time we just keep them without rebuilding anything. + if (initialize) + { + // not force hidden? + if (identity.visible != Visibility.ForceHidden) + { + AddAllReadyServerConnectionsToObservers(identity); + } + } + } + + internal static void AddAllReadyServerConnectionsToObservers(NetworkIdentity identity) + { + // add all server connections + foreach (NetworkConnectionToClient conn in connections.Values) + { + // only if authenticated (don't send to people during logins) + if (conn.isReady) + identity.AddObserver(conn); + } + + // add local host connection (if any) + if (localConnection != null && localConnection.isReady) + { + identity.AddObserver(localConnection); + } + } + + // RebuildObservers does a local rebuild for the NetworkIdentity. + // This causes the set of players that can see this object to be rebuild. + // + // IMPORTANT: + // => global rebuild would be more simple, BUT + // => local rebuild is way faster for spawn/despawn because we can + // simply rebuild a select NetworkIdentity only + // => having both .observers and .observing is necessary for local + // rebuilds + // + // in other words, this is the perfect solution even though it's not + // completely simple (due to .observers & .observing) + // + // Mirror maintains .observing automatically in the background. best of + // both worlds without any worrying now! + public static void RebuildObservers(NetworkIdentity identity, bool initialize) + { + // if there is no interest management system, + // or if 'force shown' then add all connections + if (aoi == null || identity.visible == Visibility.ForceShown) + { + RebuildObserversDefault(identity, initialize); + } + // otherwise let interest management system rebuild + else + { + aoi.Rebuild(identity, initialize); + } + } + + + // broadcasting //////////////////////////////////////////////////////// + // helper function to get the right serialization for a connection + static NetworkWriter SerializeForConnection(NetworkIdentity identity, NetworkConnectionToClient connection) + { + // get serialization for this entity (cached) + // IMPORTANT: int tick avoids floating point inaccuracy over days/weeks + NetworkIdentitySerialization serialization = identity.GetServerSerializationAtTick(Time.frameCount); + + // is this entity owned by this connection? + bool owned = identity.connectionToClient == connection; + + // send serialized data + // owner writer if owned + if (owned) + { + // was it dirty / did we actually serialize anything? + if (serialization.ownerWriter.Position > 0) + return serialization.ownerWriter; + } + // observers writer if not owned + else + { + // was it dirty / did we actually serialize anything? + if (serialization.observersWriter.Position > 0) + return serialization.observersWriter; + } + + // nothing was serialized + return null; + } + + // helper function to broadcast the world to a connection + static void BroadcastToConnection(NetworkConnectionToClient connection) + { + // for each entity that this connection is seeing + foreach (NetworkIdentity identity in connection.observing) + { + // make sure it's not null or destroyed. + // (which can happen if someone uses + // GameObject.Destroy instead of + // NetworkServer.Destroy) + if (identity != null) + { + // get serialization for this entity viewed by this connection + // (if anything was serialized this time) + NetworkWriter serialization = SerializeForConnection(identity, connection); + if (serialization != null) + { + EntityStateMessage message = new EntityStateMessage + { + netId = identity.netId, + payload = serialization.ToArraySegment() + }; + connection.Send(message); + } + } + // spawned list should have no null entries because we + // always call Remove in OnObjectDestroy everywhere. + // if it does have null then someone used + // GameObject.Destroy instead of NetworkServer.Destroy. + else Debug.LogWarning($"Found 'null' entry in observing list for connectionId={connection.connectionId}. Please call NetworkServer.Destroy to destroy networked objects. Don't use GameObject.Destroy."); + } + } + + // helper function to check a connection for inactivity and disconnect if necessary + // returns true if disconnected + static bool DisconnectIfInactive(NetworkConnectionToClient connection) + { + // check for inactivity + if (disconnectInactiveConnections && + !connection.IsAlive(disconnectInactiveTimeout)) + { + Debug.LogWarning($"Disconnecting {connection} for inactivity!"); + connection.Disconnect(); + return true; + } + return false; + } + + // NetworkLateUpdate called after any Update/FixedUpdate/LateUpdate + // (we add this to the UnityEngine in NetworkLoop) + // internal for tests + internal static readonly List connectionsCopy = + new List(); + + static void Broadcast() + { + // copy all connections into a helper collection so that + // OnTransportDisconnected can be called while iterating. + // -> OnTransportDisconnected removes from the collection + // -> which would throw 'can't modify while iterating' errors + // => see also: https://github.com/vis2k/Mirror/issues/2739 + // (copy nonalloc) + // TODO remove this when we move to 'lite' transports with only + // socket send/recv later. + connectionsCopy.Clear(); + connections.Values.CopyTo(connectionsCopy); + + // go through all connections + foreach (NetworkConnectionToClient connection in connectionsCopy) + { + // check for inactivity. disconnects if necessary. + if (DisconnectIfInactive(connection)) + continue; + + // has this connection joined the world yet? + // for each READY connection: + // pull in UpdateVarsMessage for each entity it observes + if (connection.isReady) + { + // send time for snapshot interpolation every sendInterval. + // BroadcastToConnection() may not send if nothing is new. + // + // sent over unreliable. + // NetworkTime / Transform both use unreliable. + // + // make sure Broadcast() is only called every sendInterval, + // even if targetFrameRate isn't set in host mode (!) + // (done via AccurateInterval) + connection.Send(new TimeSnapshotMessage(), Channels.Unreliable); + + // broadcast world state to this connection + BroadcastToConnection(connection); + } + + // update connection to flush out batched messages + connection.Update(); + } + + // TODO this is way too slow because we iterate ALL spawned :/ + // TODO this is way too complicated :/ + // to understand what this tries to prevent, consider this example: + // monster has health=100 + // we change health=200, dirty bit is set + // player comes in range, gets full serialization spawn packet. + // next Broadcast(), player gets the health=200 change because dirty bit was set. + // + // this code clears all dirty bits if no players are around to prevent it. + // BUT there are two issues: + // 1. what if a playerB was around the whole time? + // 2. why don't we handle broadcast and spawn packets both HERE? + // handling spawn separately is why we need this complex magic + // + // see test: DirtyBitsAreClearedForSpawnedWithoutObservers() + // see test: SyncObjectChanges_DontGrowWithoutObservers() + // + // PAUL: we also do this to avoid ever growing SyncList .changes + //ClearSpawnedDirtyBits(); + // + // this was moved to NetworkIdentity.AddObserver! + // same result, but no more O(N) loop in here! + // TODO remove this comment after moving spawning into Broadcast()! + } + + // update ////////////////////////////////////////////////////////////// + // NetworkEarlyUpdate called before any Update/FixedUpdate + // (we add this to the UnityEngine in NetworkLoop) + internal static void NetworkEarlyUpdate() + { + // measure update time for profiling. + if (active) + { + earlyUpdateDuration.Begin(); + fullUpdateDuration.Begin(); + } + + // process all incoming messages first before updating the world + if (Transport.active != null) + Transport.active.ServerEarlyUpdate(); + + // step each connection's local time interpolation in early update. + foreach (NetworkConnectionToClient connection in connections.Values) + connection.UpdateTimeInterpolation(); + + if (active) earlyUpdateDuration.End(); + } + + internal static void NetworkLateUpdate() + { + if (active) + { + // measure update time for profiling. + lateUpdateDuration.Begin(); + + // only broadcast world if active + // broadcast every sendInterval. + // AccurateInterval to avoid update frequency inaccuracy issues: + // https://github.com/vis2k/Mirror/pull/3153 + // + // for example, host mode server doesn't set .targetFrameRate. + // Broadcast() would be called every tick. + // snapshots might be sent way too often, etc. + // + // during tests, we always call Broadcast() though. + // + // also important for syncInterval=0 components like + // NetworkTransform, so they can sync on same interval as time + // snapshots _but_ not every single tick. + // Unity 2019 doesn't have Time.timeAsDouble yet + if (!Application.isPlaying || AccurateInterval.Elapsed(NetworkTime.localTime, sendInterval, ref lastSendTime)) + Broadcast(); + } + + // process all outgoing messages after updating the world + // (even if not active. still want to process disconnects etc.) + if (Transport.active != null) + Transport.active.ServerLateUpdate(); + + // measure actual tick rate every second. + if (active) + { + ++actualTickRateCounter; + + // NetworkTime.localTime has defines for 2019 / 2020 compatibility + if (NetworkTime.localTime >= actualTickRateStart + 1) + { + // calculate avg by exact elapsed time. + // assuming 1s wouldn't be accurate, usually a few more ms passed. + float elapsed = (float)(NetworkTime.localTime - actualTickRateStart); + actualTickRate = Mathf.RoundToInt(actualTickRateCounter / elapsed); + actualTickRateStart = NetworkTime.localTime; + actualTickRateCounter = 0; + } + + // measure total update time. including transport. + // because in early update, transport update calls handlers. + lateUpdateDuration.End(); + fullUpdateDuration.End(); + } + } + + // calls OnStartClient for all SERVER objects in host mode once. + // client doesn't get spawn messages for those, so need to call manually. + // Deprecated 2022-12-12 + [Obsolete("NetworkServer.ActivateHostScene was moved to HostMode.ActivateHostScene")] + public static void ActivateHostScene() => HostMode.ActivateHostScene(); + } +} diff --git a/Assets/Mirror/Core/NetworkServer.cs.meta b/Assets/Mirror/Core/NetworkServer.cs.meta new file mode 100644 index 0000000..9861342 --- /dev/null +++ b/Assets/Mirror/Core/NetworkServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5f5ec068f5604c32b160bc49ee97b75 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkStartPosition.cs b/Assets/Mirror/Core/NetworkStartPosition.cs new file mode 100644 index 0000000..e11029b --- /dev/null +++ b/Assets/Mirror/Core/NetworkStartPosition.cs @@ -0,0 +1,21 @@ +using UnityEngine; + +namespace Mirror +{ + /// Start position for player spawning, automatically registers itself in the NetworkManager. + [DisallowMultipleComponent] + [AddComponentMenu("Network/Network Start Position")] + [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-start-position")] + public class NetworkStartPosition : MonoBehaviour + { + public void Awake() + { + NetworkManager.RegisterStartPosition(transform); + } + + public void OnDestroy() + { + NetworkManager.UnRegisterStartPosition(transform); + } + } +} diff --git a/Assets/Mirror/Core/NetworkStartPosition.cs.meta b/Assets/Mirror/Core/NetworkStartPosition.cs.meta new file mode 100644 index 0000000..ae9ab89 --- /dev/null +++ b/Assets/Mirror/Core/NetworkStartPosition.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41f84591ce72545258ea98cb7518d8b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkTime.cs b/Assets/Mirror/Core/NetworkTime.cs new file mode 100644 index 0000000..bea4982 --- /dev/null +++ b/Assets/Mirror/Core/NetworkTime.cs @@ -0,0 +1,166 @@ +// NetworkTime now uses NetworkClient's snapshot interpolated timeline. +// this gives ideal results & ensures everything is on the same timeline. +// previously, NetworkTransforms were on separate timelines. +// +// however, some of the old NetworkTime code remains for ping time (rtt). +// some users may still be using that. +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +#if !UNITY_2020_3_OR_NEWER +using Stopwatch = System.Diagnostics.Stopwatch; +#endif + +namespace Mirror +{ + /// Synchronizes server time to clients. + public static class NetworkTime + { + /// Ping message interval, used to calculate network time and RTT + public static float PingInterval = 2; + + // DEPRECATED 2023-07-06 + [Obsolete("NetworkTime.PingFrequency was renamed to PingInterval, because we use it as seconds, not as Hz. Please rename all usages, but keep using it just as before.")] + public static float PingFrequency + { + get => PingInterval; + set => PingInterval = value; + } + + /// Average out the last few results from Ping + public static int PingWindowSize = 6; + + static double lastPingTime; + + static ExponentialMovingAverage _rtt = new ExponentialMovingAverage(PingWindowSize); + + /// Returns double precision clock time _in this system_, unaffected by the network. +#if UNITY_2020_3_OR_NEWER + public static double localTime + { + // NetworkTime uses unscaled time and ignores Time.timeScale. + // fixes Time.timeScale getting server & client time out of sync: + // https://github.com/MirrorNetworking/Mirror/issues/3409 + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Time.unscaledTimeAsDouble; + } +#else + // need stopwatch for older Unity versions, but it's quite slow. + // CAREFUL: unlike Time.time, this is not a FRAME time. + // it changes during the frame too. + static readonly Stopwatch stopwatch = new Stopwatch(); + static NetworkTime() => stopwatch.Start(); + public static double localTime => stopwatch.Elapsed.TotalSeconds; +#endif + + /// The time in seconds since the server started. + // via global NetworkClient snapshot interpolated timeline (if client). + // on server, this is simply Time.timeAsDouble. + // + // I measured the accuracy of float and I got this: + // for the same day, accuracy is better than 1 ms + // after 1 day, accuracy goes down to 7 ms + // after 10 days, accuracy is 61 ms + // after 30 days , accuracy is 238 ms + // after 60 days, accuracy is 454 ms + // in other words, if the server is running for 2 months, + // and you cast down to float, then the time will jump in 0.4s intervals. + public static double time + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => NetworkServer.active + ? localTime + : NetworkClient.localTimeline; + } + + /// Clock difference in seconds between the client and the server. Always 0 on server. + // original implementation used 'client - server' time. keep it this way. + // TODO obsolete later. people shouldn't worry about this. + public static double offset => localTime - time; + + /// Round trip time (in seconds) that it takes a message to go client->server->client. + public static double rtt => _rtt.Value; + + /// Round trip time variance aka jitter, in seconds. + // "rttVariance" instead of "rttVar" for consistency with older versions. + public static double rttVariance => _rtt.Variance; + + // RuntimeInitializeOnLoadMethod -> fast playmode without domain reload + [RuntimeInitializeOnLoadMethod] + public static void ResetStatics() + { + PingInterval = 2; + PingWindowSize = 6; + lastPingTime = 0; + _rtt = new ExponentialMovingAverage(PingWindowSize); +#if !UNITY_2020_3_OR_NEWER + stopwatch.Restart(); +#endif + } + + internal static void UpdateClient() + { + // localTime (double) instead of Time.time for accuracy over days + if (localTime >= lastPingTime + PingInterval) + { + NetworkPingMessage pingMessage = new NetworkPingMessage(localTime); + NetworkClient.Send(pingMessage, Channels.Unreliable); + lastPingTime = localTime; + } + } + + // client rtt calculation ////////////////////////////////////////////// + // executed at the server when we receive a ping message + // reply with a pong containing the time from the client + // and time from the server + internal static void OnServerPing(NetworkConnectionToClient conn, NetworkPingMessage message) + { + // Debug.Log($"OnServerPing conn:{conn}"); + NetworkPongMessage pongMessage = new NetworkPongMessage + { + localTime = message.localTime, + }; + conn.Send(pongMessage, Channels.Unreliable); + } + + // Executed at the client when we receive a Pong message + // find out how long it took since we sent the Ping + // and update time offset + internal static void OnClientPong(NetworkPongMessage message) + { + // prevent attackers from sending timestamps which are in the future + if (message.localTime > localTime) return; + + // how long did this message take to come back + double newRtt = localTime - message.localTime; + _rtt.Add(newRtt); + } + + // server rtt calculation ////////////////////////////////////////////// + // Executed at the client when we receive a ping message from the server. + // in other words, this is for server sided ping + rtt calculation. + // reply with a pong containing the time from the server + internal static void OnClientPing(NetworkPingMessage message) + { + // Debug.Log($"OnClientPing conn:{conn}"); + NetworkPongMessage pongMessage = new NetworkPongMessage + { + localTime = message.localTime, + }; + NetworkClient.Send(pongMessage, Channels.Unreliable); + } + + // Executed at the server when we receive a Pong message back. + // find out how long it took since we sent the Ping + // and update time offset + internal static void OnServerPong(NetworkConnectionToClient conn, NetworkPongMessage message) + { + // prevent attackers from sending timestamps which are in the future + if (message.localTime > localTime) return; + + // how long did this message take to come back + double newRtt = localTime - message.localTime; + conn._rtt.Add(newRtt); + } + } +} diff --git a/Assets/Mirror/Core/NetworkTime.cs.meta b/Assets/Mirror/Core/NetworkTime.cs.meta new file mode 100644 index 0000000..1dc9e0a --- /dev/null +++ b/Assets/Mirror/Core/NetworkTime.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09a0c241fc4a5496dbf4a0ab6e9a312c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkWriter.cs b/Assets/Mirror/Core/NetworkWriter.cs new file mode 100644 index 0000000..7ecf126 --- /dev/null +++ b/Assets/Mirror/Core/NetworkWriter.cs @@ -0,0 +1,249 @@ +using System; +using System.Runtime.CompilerServices; +using System.Text; +using Unity.Collections.LowLevel.Unsafe; +using UnityEngine; + +namespace Mirror +{ + /// Network Writer for most simple types like floats, ints, buffers, structs, etc. Use NetworkWriterPool.GetReader() to avoid allocations. + public class NetworkWriter + { + // the limit of ushort is so we can write string size prefix as only 2 bytes. + // -1 so we can still encode 'null' into it too. + public const ushort MaxStringLength = ushort.MaxValue - 1; + + // create writer immediately with it's own buffer so no one can mess with it and so that we can resize it. + // note: BinaryWriter allocates too much, so we only use a MemoryStream + // => 1500 bytes by default because on average, most packets will be <= MTU + public const int DefaultCapacity = 1500; + internal byte[] buffer = new byte[DefaultCapacity]; + + /// Next position to write to the buffer + public int Position; + + /// Current capacity. Automatically resized if necessary. + public int Capacity => buffer.Length; + + // cache encoding for WriteString instead of creating it each time. + // 1000 readers before: 1MB GC, 30ms + // 1000 readers after: 0.8MB GC, 18ms + // not(!) static for thread safety. + // + // throwOnInvalidBytes is true. + // writer should throw and user should fix if this ever happens. + // unlike reader, which needs to expect it to happen from attackers. + internal readonly UTF8Encoding encoding = new UTF8Encoding(false, true); + + /// Reset both the position and length of the stream + // Leaves the capacity the same so that we can reuse this writer without + // extra allocations + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Reset() + { + Position = 0; + } + + // NOTE that our runtime resizing comes at no extra cost because: + // 1. 'has space' checks are necessary even for fixed sized writers. + // 2. all writers will eventually be large enough to stop resizing. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void EnsureCapacity(int value) + { + if (buffer.Length < value) + { + int capacity = Math.Max(value, buffer.Length * 2); + Array.Resize(ref buffer, capacity); + } + } + + /// Copies buffer until 'Position' to a new array. + // Try to use ToArraySegment instead to avoid allocations! + public byte[] ToArray() + { + byte[] data = new byte[Position]; + Array.ConstrainedCopy(buffer, 0, data, 0, Position); + return data; + } + + /// Returns allocation-free ArraySegment until 'Position'. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ArraySegment ToArraySegment() => + new ArraySegment(buffer, 0, Position); + + // implicit conversion for convenience + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ArraySegment(NetworkWriter w) => + w.ToArraySegment(); + + // WriteBlittable from DOTSNET. + // this is extremely fast, but only works for blittable types. + // + // Benchmark: + // WriteQuaternion x 100k, Macbook Pro 2015 @ 2.2Ghz, Unity 2018 LTS (debug mode) + // + // | Median | Min | Max | Avg | Std | (ms) + // before | 30.35 | 29.86 | 48.99 | 32.54 | 4.93 | + // blittable* | 5.69 | 5.52 | 27.51 | 7.78 | 5.65 | + // + // * without IsBlittable check + // => 4-6x faster! + // + // WriteQuaternion x 100k, Macbook Pro 2015 @ 2.2Ghz, Unity 2020.1 (release mode) + // + // | Median | Min | Max | Avg | Std | (ms) + // before | 9.41 | 8.90 | 23.02 | 10.72 | 3.07 | + // blittable* | 1.48 | 1.40 | 16.03 | 2.60 | 2.71 | + // + // * without IsBlittable check + // => 6x faster! + // + // Note: + // WriteBlittable assumes same endianness for server & client. + // All Unity 2018+ platforms are little endian. + // => run NetworkWriterTests.BlittableOnThisPlatform() to verify! + // + // This is not safe to expose to random structs. + // * StructLayout.Sequential is the default, which is safe. + // if the struct contains a reference type, it is converted to Auto. + // but since all structs here are unmanaged blittable, it's safe. + // see also: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.layoutkind?view=netframework-4.8#system-runtime-interopservices-layoutkind-sequential + // * StructLayout.Pack depends on CPU word size. + // this may be different 4 or 8 on some ARM systems, etc. + // this is not safe, and would cause bytes/shorts etc. to be padded. + // see also: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.structlayoutattribute.pack?view=net-6.0 + // * If we force pack all to '1', they would have no padding which is + // great for bandwidth. but on some android systems, CPU can't read + // unaligned memory. + // see also: https://github.com/vis2k/Mirror/issues/3044 + // * The only option would be to force explicit layout with multiples + // of word size. but this requires lots of weaver checking and is + // still questionable (IL2CPP etc.). + // + // Note: inlining WriteBlittable is enough. don't inline WriteInt etc. + // we don't want WriteBlittable to be copied in place everywhere. + internal unsafe void WriteBlittable(T value) + where T : unmanaged + { + // check if blittable for safety +#if UNITY_EDITOR + if (!UnsafeUtility.IsBlittable(typeof(T))) + { + Debug.LogError($"{typeof(T)} is not blittable!"); + return; + } +#endif + // calculate size + // sizeof(T) gets the managed size at compile time. + // Marshal.SizeOf gets the unmanaged size at runtime (slow). + // => our 1mio writes benchmark is 6x slower with Marshal.SizeOf + // => for blittable types, sizeof(T) is even recommended: + // https://docs.microsoft.com/en-us/dotnet/standard/native-interop/best-practices + int size = sizeof(T); + + // ensure capacity + // NOTE that our runtime resizing comes at no extra cost because: + // 1. 'has space' checks are necessary even for fixed sized writers. + // 2. all writers will eventually be large enough to stop resizing. + EnsureCapacity(Position + size); + + // write blittable + fixed (byte* ptr = &buffer[Position]) + { +#if UNITY_ANDROID + // on some android systems, assigning *(T*)ptr throws a NRE if + // the ptr isn't aligned (i.e. if Position is 1,2,3,5, etc.). + // here we have to use memcpy. + // + // => we can't get a pointer of a struct in C# without + // marshalling allocations + // => instead, we stack allocate an array of type T and use that + // => stackalloc avoids GC and is very fast. it only works for + // value types, but all blittable types are anyway. + // + // this way, we can still support blittable reads on android. + // see also: https://github.com/vis2k/Mirror/issues/3044 + // (solution discovered by AIIO, FakeByte, mischa) + T* valueBuffer = stackalloc T[1]{value}; + UnsafeUtility.MemCpy(ptr, valueBuffer, size); +#else + // cast buffer to T* pointer, then assign value to the area + *(T*)ptr = value; +#endif + } + Position += size; + } + + // blittable'?' template for code reuse + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void WriteBlittableNullable(T? value) + where T : unmanaged + { + // bool isn't blittable. write as byte. + WriteByte((byte)(value.HasValue ? 0x01 : 0x00)); + + // only write value if exists. saves bandwidth. + if (value.HasValue) + WriteBlittable(value.Value); + } + + public void WriteByte(byte value) => WriteBlittable(value); + + // for byte arrays with consistent size, where the reader knows how many to read + // (like a packet opcode that's always the same) + public void WriteBytes(byte[] array, int offset, int count) + { + EnsureCapacity(Position + count); + Array.ConstrainedCopy(array, offset, this.buffer, Position, count); + Position += count; + } + // write an unsafe byte* array. + // useful for bit tree compression, etc. + public unsafe bool WriteBytes(byte* ptr, int offset, int size) + { + EnsureCapacity(Position + size); + + fixed (byte* destination = &buffer[Position]) + { + // write 'size' bytes at position + // 10 mio writes: 868ms + // Array.Copy(value.Array, value.Offset, buffer, Position, value.Count); + // 10 mio writes: 775ms + // Buffer.BlockCopy(value.Array, value.Offset, buffer, Position, value.Count); + // 10 mio writes: 637ms + UnsafeUtility.MemCpy(destination, ptr + offset, size); + } + + Position += size; + return true; + } + + /// Writes any type that mirror supports. Uses weaver populated Writer(T).write. + public void Write(T value) + { + Action writeDelegate = Writer.write; + if (writeDelegate == null) + { + Debug.LogError($"No writer found for {typeof(T)}. This happens either if you are missing a NetworkWriter extension for your custom type, or if weaving failed. Try to reimport a script to weave again."); + } + else + { + writeDelegate(this, value); + } + } + + // print with buffer content for easier debugging. + // [content, position / capacity]. + // showing "position / space" would be too confusing. + public override string ToString() => + $"[{ToArraySegment().ToHexString()} @ {Position}/{Capacity}]"; + } + + /// Helper class that weaver populates with all writer types. + // Note that c# creates a different static variable for each type + // -> Weaver.ReaderWriterProcessor.InitializeReaderAndWriters() populates it + public static class Writer + { + public static Action write; + } +} diff --git a/Assets/Mirror/Core/NetworkWriter.cs.meta b/Assets/Mirror/Core/NetworkWriter.cs.meta new file mode 100644 index 0000000..c938496 --- /dev/null +++ b/Assets/Mirror/Core/NetworkWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 48d2207bcef1f4477b624725f075f9bd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkWriterExtensions.cs b/Assets/Mirror/Core/NetworkWriterExtensions.cs new file mode 100644 index 0000000..c4de17c --- /dev/null +++ b/Assets/Mirror/Core/NetworkWriterExtensions.cs @@ -0,0 +1,415 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror +{ + // Mirror's Weaver automatically detects all NetworkWriter function types, + // but they do all need to be extensions. + public static class NetworkWriterExtensions + { + public static void WriteByte(this NetworkWriter writer, byte value) => writer.WriteBlittable(value); + public static void WriteByteNullable(this NetworkWriter writer, byte? value) => writer.WriteBlittableNullable(value); + + public static void WriteSByte(this NetworkWriter writer, sbyte value) => writer.WriteBlittable(value); + public static void WriteSByteNullable(this NetworkWriter writer, sbyte? value) => writer.WriteBlittableNullable(value); + + // char is not blittable. convert to ushort. + public static void WriteChar(this NetworkWriter writer, char value) => writer.WriteBlittable((ushort)value); + public static void WriteCharNullable(this NetworkWriter writer, char? value) => writer.WriteBlittableNullable((ushort?)value); + + // bool is not blittable. convert to byte. + public static void WriteBool(this NetworkWriter writer, bool value) => writer.WriteBlittable((byte)(value ? 1 : 0)); + public static void WriteBoolNullable(this NetworkWriter writer, bool? value) => writer.WriteBlittableNullable(value.HasValue ? ((byte)(value.Value ? 1 : 0)) : new byte?()); + + public static void WriteShort(this NetworkWriter writer, short value) => writer.WriteBlittable(value); + public static void WriteShortNullable(this NetworkWriter writer, short? value) => writer.WriteBlittableNullable(value); + + public static void WriteUShort(this NetworkWriter writer, ushort value) => writer.WriteBlittable(value); + public static void WriteUShortNullable(this NetworkWriter writer, ushort? value) => writer.WriteBlittableNullable(value); + + public static void WriteInt(this NetworkWriter writer, int value) => writer.WriteBlittable(value); + public static void WriteIntNullable(this NetworkWriter writer, int? value) => writer.WriteBlittableNullable(value); + + public static void WriteUInt(this NetworkWriter writer, uint value) => writer.WriteBlittable(value); + public static void WriteUIntNullable(this NetworkWriter writer, uint? value) => writer.WriteBlittableNullable(value); + + public static void WriteLong(this NetworkWriter writer, long value) => writer.WriteBlittable(value); + public static void WriteLongNullable(this NetworkWriter writer, long? value) => writer.WriteBlittableNullable(value); + + public static void WriteULong(this NetworkWriter writer, ulong value) => writer.WriteBlittable(value); + public static void WriteULongNullable(this NetworkWriter writer, ulong? value) => writer.WriteBlittableNullable(value); + + public static void WriteFloat(this NetworkWriter writer, float value) => writer.WriteBlittable(value); + public static void WriteFloatNullable(this NetworkWriter writer, float? value) => writer.WriteBlittableNullable(value); + + public static void WriteDouble(this NetworkWriter writer, double value) => writer.WriteBlittable(value); + public static void WriteDoubleNullable(this NetworkWriter writer, double? value) => writer.WriteBlittableNullable(value); + + public static void WriteDecimal(this NetworkWriter writer, decimal value) => writer.WriteBlittable(value); + public static void WriteDecimalNullable(this NetworkWriter writer, decimal? value) => writer.WriteBlittableNullable(value); + + public static void WriteString(this NetworkWriter writer, string value) + { + // write 0 for null support, increment real size by 1 + // (note: original HLAPI would write "" for null strings, but if a + // string is null on the server then it should also be null + // on the client) + if (value == null) + { + writer.WriteUShort(0); + return; + } + + // WriteString copies into the buffer manually. + // need to ensure capacity here first, manually. + int maxSize = writer.encoding.GetMaxByteCount(value.Length); + writer.EnsureCapacity(writer.Position + 2 + maxSize); // 2 bytes position + N bytes encoding + + // encode it into the buffer first. + // reserve 2 bytes for header after we know how much was written. + int written = writer.encoding.GetBytes(value, 0, value.Length, writer.buffer, writer.Position + 2); + + // check if within max size, otherwise Reader can't read it. + if (written > NetworkWriter.MaxStringLength) + throw new IndexOutOfRangeException($"NetworkWriter.WriteString - Value too long: {written} bytes. Limit: {NetworkWriter.MaxStringLength} bytes"); + + // .Position is unchanged, so fill in the size header now. + // we already ensured that max size fits into ushort.max-1. + writer.WriteUShort(checked((ushort)(written + 1))); // Position += 2 + + // now update position by what was written above + writer.Position += written; + } + + public static void WriteBytesAndSizeSegment(this NetworkWriter writer, ArraySegment buffer) + { + writer.WriteBytesAndSize(buffer.Array, buffer.Offset, buffer.Count); + } + + // Weaver needs a write function with just one byte[] parameter + // (we don't name it .Write(byte[]) because it's really a WriteBytesAndSize since we write size / null info too) + + public static void WriteBytesAndSize(this NetworkWriter writer, byte[] buffer) + { + // buffer might be null, so we can't use .Length in that case + writer.WriteBytesAndSize(buffer, 0, buffer != null ? buffer.Length : 0); + } + + // for byte arrays with dynamic size, where the reader doesn't know how many will come + // (like an inventory with different items etc.) + + public static void WriteBytesAndSize(this NetworkWriter writer, byte[] buffer, int offset, int count) + { + // null is supported because [SyncVar]s might be structs with null byte[] arrays + // write 0 for null array, increment normal size by 1 to save bandwidth + // (using size=-1 for null would limit max size to 32kb instead of 64kb) + if (buffer == null) + { + writer.WriteUInt(0u); + return; + } + writer.WriteUInt(checked((uint)count) + 1u); + writer.WriteBytes(buffer, offset, count); + } + + public static void WriteArraySegment(this NetworkWriter writer, ArraySegment segment) + { + int length = segment.Count; + writer.WriteInt(length); + for (int i = 0; i < length; i++) + { + writer.Write(segment.Array[segment.Offset + i]); + } + } + + public static void WriteVector2(this NetworkWriter writer, Vector2 value) => writer.WriteBlittable(value); + public static void WriteVector2Nullable(this NetworkWriter writer, Vector2? value) => writer.WriteBlittableNullable(value); + + public static void WriteVector3(this NetworkWriter writer, Vector3 value) => writer.WriteBlittable(value); + public static void WriteVector3Nullable(this NetworkWriter writer, Vector3? value) => writer.WriteBlittableNullable(value); + + public static void WriteVector4(this NetworkWriter writer, Vector4 value) => writer.WriteBlittable(value); + public static void WriteVector4Nullable(this NetworkWriter writer, Vector4? value) => writer.WriteBlittableNullable(value); + + public static void WriteVector2Int(this NetworkWriter writer, Vector2Int value) => writer.WriteBlittable(value); + public static void WriteVector2IntNullable(this NetworkWriter writer, Vector2Int? value) => writer.WriteBlittableNullable(value); + + public static void WriteVector3Int(this NetworkWriter writer, Vector3Int value) => writer.WriteBlittable(value); + public static void WriteVector3IntNullable(this NetworkWriter writer, Vector3Int? value) => writer.WriteBlittableNullable(value); + + public static void WriteColor(this NetworkWriter writer, Color value) => writer.WriteBlittable(value); + public static void WriteColorNullable(this NetworkWriter writer, Color? value) => writer.WriteBlittableNullable(value); + + public static void WriteColor32(this NetworkWriter writer, Color32 value) => writer.WriteBlittable(value); + public static void WriteColor32Nullable(this NetworkWriter writer, Color32? value) => writer.WriteBlittableNullable(value); + + public static void WriteQuaternion(this NetworkWriter writer, Quaternion value) => writer.WriteBlittable(value); + public static void WriteQuaternionNullable(this NetworkWriter writer, Quaternion? value) => writer.WriteBlittableNullable(value); + + // Rect is a struct with properties instead of fields + public static void WriteRect(this NetworkWriter writer, Rect value) + { + writer.WriteVector2(value.position); + writer.WriteVector2(value.size); + } + public static void WriteRectNullable(this NetworkWriter writer, Rect? value) + { + writer.WriteBool(value.HasValue); + if (value.HasValue) + writer.WriteRect(value.Value); + } + + // Plane is a struct with properties instead of fields + public static void WritePlane(this NetworkWriter writer, Plane value) + { + writer.WriteVector3(value.normal); + writer.WriteFloat(value.distance); + } + public static void WritePlaneNullable(this NetworkWriter writer, Plane? value) + { + writer.WriteBool(value.HasValue); + if (value.HasValue) + writer.WritePlane(value.Value); + } + + // Ray is a struct with properties instead of fields + public static void WriteRay(this NetworkWriter writer, Ray value) + { + writer.WriteVector3(value.origin); + writer.WriteVector3(value.direction); + } + public static void WriteRayNullable(this NetworkWriter writer, Ray? value) + { + writer.WriteBool(value.HasValue); + if (value.HasValue) + writer.WriteRay(value.Value); + } + + public static void WriteMatrix4x4(this NetworkWriter writer, Matrix4x4 value) => writer.WriteBlittable(value); + public static void WriteMatrix4x4Nullable(this NetworkWriter writer, Matrix4x4? value) => writer.WriteBlittableNullable(value); + + public static void WriteGuid(this NetworkWriter writer, Guid value) + { +#if !UNITY_2021_3_OR_NEWER + // Unity 2019 doesn't have Span yet + byte[] data = value.ToByteArray(); + writer.WriteBytes(data, 0, data.Length); +#else + // WriteBlittable(Guid) isn't safe. see WriteBlittable comments. + // Guid is Sequential, but we can't guarantee packing. + // TryWriteBytes is safe and allocation free. + writer.EnsureCapacity(writer.Position + 16); + value.TryWriteBytes(new Span(writer.buffer, writer.Position, 16)); + writer.Position += 16; +#endif + } + public static void WriteGuidNullable(this NetworkWriter writer, Guid? value) + { + writer.WriteBool(value.HasValue); + if (value.HasValue) + writer.WriteGuid(value.Value); + } + + public static void WriteNetworkIdentity(this NetworkWriter writer, NetworkIdentity value) + { + if (value == null) + { + writer.WriteUInt(0); + return; + } + + // users might try to use unspawned / prefab GameObjects in + // rpcs/cmds/syncvars/messages. they would be null on the other + // end, and it might not be obvious why. let's make it obvious. + // https://github.com/vis2k/Mirror/issues/2060 + // + // => warning (instead of exception) because we also use a warning + // if a GameObject doesn't have a NetworkIdentity component etc. + if (value.netId == 0) + Debug.LogWarning($"Attempted to serialize unspawned GameObject: {value.name}. Prefabs and unspawned GameObjects would always be null on the other side. Please spawn it before using it in [SyncVar]s/Rpcs/Cmds/NetworkMessages etc."); + + writer.WriteUInt(value.netId); + } + + public static void WriteNetworkBehaviour(this NetworkWriter writer, NetworkBehaviour value) + { + if (value == null) + { + writer.WriteUInt(0); + return; + } + + // users might try to use unspawned / prefab NetworkBehaviours in + // rpcs/cmds/syncvars/messages. they would be null on the other + // end, and it might not be obvious why. let's make it obvious. + // https://github.com/vis2k/Mirror/issues/2060 + // and more recently https://github.com/MirrorNetworking/Mirror/issues/3399 + // + // => warning (instead of exception) because we also use a warning + // when writing an unspawned NetworkIdentity + if (value.netId == 0) + { + Debug.LogWarning($"Attempted to serialize unspawned NetworkBehaviour: of type {value.GetType()} on GameObject {value.name}. Prefabs and unspawned GameObjects would always be null on the other side. Please spawn it before using it in [SyncVar]s/Rpcs/Cmds/NetworkMessages etc."); + writer.WriteUInt(0); + return; + } + + writer.WriteUInt(value.netId); + writer.WriteByte(value.ComponentIndex); + } + + public static void WriteTransform(this NetworkWriter writer, Transform value) + { + if (value == null) + { + writer.WriteUInt(0); + return; + } + if (value.TryGetComponent(out NetworkIdentity identity)) + { + writer.WriteUInt(identity.netId); + } + else + { + Debug.LogWarning($"NetworkWriter {value} has no NetworkIdentity"); + writer.WriteUInt(0); + } + } + + public static void WriteGameObject(this NetworkWriter writer, GameObject value) + { + if (value == null) + { + writer.WriteUInt(0); + return; + } + + // warn if the GameObject doesn't have a NetworkIdentity, + if (!value.TryGetComponent(out NetworkIdentity identity)) + Debug.LogWarning($"NetworkWriter {value} has no NetworkIdentity"); + + // serialize the correct amount of data in any case to make sure + // that the other end can read the expected amount of data too. + writer.WriteNetworkIdentity(identity); + } + + // while SyncList is recommended for NetworkBehaviours, + // structs may have .List members which weaver needs to be able to + // fully serialize for NetworkMessages etc. + // note that Weaver/Writers/GenerateWriter() handles this manually. + public static void WriteList(this NetworkWriter writer, List list) + { + // 'null' is encoded as '-1' + if (list is null) + { + writer.WriteInt(-1); + return; + } + + // check if within max size, otherwise Reader can't read it. + if (list.Count > NetworkReader.AllocationLimit) + throw new IndexOutOfRangeException($"NetworkWriter.WriteList - List<{typeof(T)}> too big: {list.Count} elements. Limit: {NetworkReader.AllocationLimit}"); + + writer.WriteInt(list.Count); + for (int i = 0; i < list.Count; i++) + writer.Write(list[i]); + } + + // while SyncSet is recommended for NetworkBehaviours, + // structs may have .Set members which weaver needs to be able to + // fully serialize for NetworkMessages etc. + // note that Weaver/Writers/GenerateWriter() handles this manually. + // TODO writer not found. need to adjust weaver first. see tests. + /* + public static void WriteHashSet(this NetworkWriter writer, HashSet hashSet) + { + if (hashSet is null) + { + writer.WriteInt(-1); + return; + } + writer.WriteInt(hashSet.Count); + foreach (T item in hashSet) + writer.Write(item); + } + */ + + public static void WriteArray(this NetworkWriter writer, T[] array) + { + // 'null' is encoded as '-1' + if (array is null) + { + writer.WriteInt(-1); + return; + } + + // check if within max size, otherwise Reader can't read it. + if (array.Length > NetworkReader.AllocationLimit) + throw new IndexOutOfRangeException($"NetworkWriter.WriteArray - Array<{typeof(T)}> too big: {array.Length} elements. Limit: {NetworkReader.AllocationLimit}"); + + writer.WriteInt(array.Length); + for (int i = 0; i < array.Length; i++) + writer.Write(array[i]); + } + + public static void WriteUri(this NetworkWriter writer, Uri uri) + { + writer.WriteString(uri?.ToString()); + } + + public static void WriteTexture2D(this NetworkWriter writer, Texture2D texture2D) + { + // TODO allocation protection when sending textures to server. + // currently can allocate 32k x 32k x 4 byte = 3.8 GB + + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 + // simply send -1 for width. + if (texture2D == null) + { + writer.WriteShort(-1); + return; + } + + // check if within max size, otherwise Reader can't read it. + int totalSize = texture2D.width * texture2D.height; + if (totalSize > NetworkReader.AllocationLimit) + throw new IndexOutOfRangeException($"NetworkWriter.WriteTexture2D - Texture2D total size (width*height) too big: {totalSize}. Limit: {NetworkReader.AllocationLimit}"); + + // write dimensions first so reader can create the texture with size + // 32k x 32k short is more than enough + writer.WriteShort((short)texture2D.width); + writer.WriteShort((short)texture2D.height); + writer.WriteArray(texture2D.GetPixels32()); + } + + public static void WriteSprite(this NetworkWriter writer, Sprite sprite) + { + // support 'null' textures for [SyncVar]s etc. + // https://github.com/vis2k/Mirror/issues/3144 + // simply send a 'null' for texture content. + if (sprite == null) + { + writer.WriteTexture2D(null); + return; + } + + writer.WriteTexture2D(sprite.texture); + writer.WriteRect(sprite.rect); + writer.WriteVector2(sprite.pivot); + } + + public static void WriteDateTime(this NetworkWriter writer, DateTime dateTime) + { + writer.WriteDouble(dateTime.ToOADate()); + } + + public static void WriteDateTimeNullable(this NetworkWriter writer, DateTime? dateTime) + { + writer.WriteBool(dateTime.HasValue); + if (dateTime.HasValue) + writer.WriteDouble(dateTime.Value.ToOADate()); + } + } +} diff --git a/Assets/Mirror/Core/NetworkWriterExtensions.cs.meta b/Assets/Mirror/Core/NetworkWriterExtensions.cs.meta new file mode 100644 index 0000000..9bbdaf0 --- /dev/null +++ b/Assets/Mirror/Core/NetworkWriterExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 94259792df2a404892c3e2377f58d0cb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkWriterPool.cs b/Assets/Mirror/Core/NetworkWriterPool.cs new file mode 100644 index 0000000..5eefa2a --- /dev/null +++ b/Assets/Mirror/Core/NetworkWriterPool.cs @@ -0,0 +1,37 @@ +// API consistent with Microsoft's ObjectPool. +using System.Runtime.CompilerServices; + +namespace Mirror +{ + /// Pool of NetworkWriters to avoid allocations. + public static class NetworkWriterPool + { + // reuse Pool + // we still wrap it in NetworkWriterPool.Get/Recycle so we can reset the + // position before reusing. + // this is also more consistent with NetworkReaderPool where we need to + // assign the internal buffer before reusing. + static readonly Pool Pool = new Pool( + () => new NetworkWriterPooled(), + // initial capacity to avoid allocations in the first few frames + // 1000 * 1200 bytes = around 1 MB. + 1000 + ); + + /// Get a writer from the pool. Creates new one if pool is empty. + public static NetworkWriterPooled Get() + { + // grab from pool & reset position + NetworkWriterPooled writer = Pool.Get(); + writer.Reset(); + return writer; + } + + /// Return a writer to the pool. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Return(NetworkWriterPooled writer) + { + Pool.Return(writer); + } + } +} diff --git a/Assets/Mirror/Core/NetworkWriterPool.cs.meta b/Assets/Mirror/Core/NetworkWriterPool.cs.meta new file mode 100644 index 0000000..19d2bb7 --- /dev/null +++ b/Assets/Mirror/Core/NetworkWriterPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3f34b53bea38e4f259eb8dc211e4fdb6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/NetworkWriterPooled.cs b/Assets/Mirror/Core/NetworkWriterPooled.cs new file mode 100644 index 0000000..5ac371d --- /dev/null +++ b/Assets/Mirror/Core/NetworkWriterPooled.cs @@ -0,0 +1,13 @@ +// "NetworkWriterPooled" instead of "PooledNetworkWriter" to group files, for +// easier IDE workflow and more elegant code. +using System; + +namespace Mirror +{ + /// Pooled NetworkWriter, automatically returned to pool when using 'using' + // TODO make sealed again after removing obsolete NetworkWriterPooled! + public class NetworkWriterPooled : NetworkWriter, IDisposable + { + public void Dispose() => NetworkWriterPool.Return(this); + } +} diff --git a/Assets/Mirror/Core/NetworkWriterPooled.cs.meta b/Assets/Mirror/Core/NetworkWriterPooled.cs.meta new file mode 100644 index 0000000..5571d6f --- /dev/null +++ b/Assets/Mirror/Core/NetworkWriterPooled.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a9fab936bf3c4716a452d94ad5ecbebe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/PortTransport.cs b/Assets/Mirror/Core/PortTransport.cs new file mode 100644 index 0000000..19a7dfd --- /dev/null +++ b/Assets/Mirror/Core/PortTransport.cs @@ -0,0 +1,13 @@ +// convenience interface for transports which use a port. +// useful for cases where someone wants to 'just set the port' independent of +// which transport it is. +// +// note that not all transports have ports, but most do. + +namespace Mirror +{ + public interface PortTransport + { + ushort Port { get; set; } + } +} diff --git a/Assets/Mirror/Core/PortTransport.cs.meta b/Assets/Mirror/Core/PortTransport.cs.meta new file mode 100644 index 0000000..3f96d30 --- /dev/null +++ b/Assets/Mirror/Core/PortTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f7c7c2820d7974cb28c7bfe9aae890a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/RemoteCalls.cs b/Assets/Mirror/Core/RemoteCalls.cs new file mode 100644 index 0000000..ffae3a0 --- /dev/null +++ b/Assets/Mirror/Core/RemoteCalls.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror.RemoteCalls +{ + // invoke type for Cmd/Rpc + public enum RemoteCallType { Command, ClientRpc } + + // remote call function delegate + public delegate void RemoteCallDelegate(NetworkBehaviour obj, NetworkReader reader, NetworkConnectionToClient senderConnection); + + class Invoker + { + // GameObjects might have multiple components of TypeA.CommandA(). + // when invoking, we check if 'TypeA' is an instance of the type. + // the hash itself isn't enough because we wouldn't know which component + // to invoke it on if there are multiple of the same type. + public Type componentType; + public RemoteCallType callType; + public RemoteCallDelegate function; + public bool cmdRequiresAuthority; + + public bool AreEqual(Type componentType, RemoteCallType remoteCallType, RemoteCallDelegate invokeFunction) => + this.componentType == componentType && + this.callType == remoteCallType && + this.function == invokeFunction; + } + + /// Used to help manage remote calls for NetworkBehaviours + public static class RemoteProcedureCalls + { + // one lookup for all remote calls. + // allows us to easily add more remote call types without duplicating code. + // note: do not clear those with [RuntimeInitializeOnLoad] + // + // IMPORTANT: cmd/rpc functions are identified via **HASHES**. + // an index would requires half the bandwidth, but introduces issues + // where static constructors are lazily called, so index order isn't + // guaranteed. keep hashes to avoid: + // https://github.com/vis2k/Mirror/pull/3135 + // https://github.com/vis2k/Mirror/issues/3138 + // BUT: 2 byte hash is enough if we check for collisions. that's what we + // do for NetworkMessage as well. + static readonly Dictionary remoteCallDelegates = new Dictionary(); + + static bool CheckIfDelegateExists(Type componentType, RemoteCallType remoteCallType, RemoteCallDelegate func, ushort functionHash) + { + if (remoteCallDelegates.ContainsKey(functionHash)) + { + // something already registered this hash. + // it's okay if it was the same function. + Invoker oldInvoker = remoteCallDelegates[functionHash]; + if (oldInvoker.AreEqual(componentType, remoteCallType, func)) + { + return true; + } + + // otherwise notify user. there is a rare chance of string + // hash collisions. + Debug.LogError($"Function {oldInvoker.componentType}.{oldInvoker.function.GetMethodName()} and {componentType}.{func.GetMethodName()} have the same hash. Please rename one of them. To save bandwidth, we only use 2 bytes for the hash, which has a small chance of collisions."); + } + + return false; + } + + // pass full function name to avoid ClassA.Func & ClassB.Func collisions + internal static ushort RegisterDelegate(Type componentType, string functionFullName, RemoteCallType remoteCallType, RemoteCallDelegate func, bool cmdRequiresAuthority = true) + { + // type+func so Inventory.RpcUse != Equipment.RpcUse + ushort hash = (ushort)(functionFullName.GetStableHashCode() & 0xFFFF); + + if (CheckIfDelegateExists(componentType, remoteCallType, func, hash)) + return hash; + + remoteCallDelegates[hash] = new Invoker + { + callType = remoteCallType, + componentType = componentType, + function = func, + cmdRequiresAuthority = cmdRequiresAuthority + }; + return hash; + } + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + // need to pass componentType to support invoking on GameObjects with + // multiple components of same type with same remote call. + public static void RegisterCommand(Type componentType, string functionFullName, RemoteCallDelegate func, bool requiresAuthority) => + RegisterDelegate(componentType, functionFullName, RemoteCallType.Command, func, requiresAuthority); + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + // need to pass componentType to support invoking on GameObjects with + // multiple components of same type with same remote call. + public static void RegisterRpc(Type componentType, string functionFullName, RemoteCallDelegate func) => + RegisterDelegate(componentType, functionFullName, RemoteCallType.ClientRpc, func); + + // to clean up tests + internal static void RemoveDelegate(ushort hash) => + remoteCallDelegates.Remove(hash); + + // note: no need to throw an error if not found. + // an attacker might just try to call a cmd with an rpc's hash etc. + // returning false is enough. + static bool GetInvokerForHash(ushort functionHash, RemoteCallType remoteCallType, out Invoker invoker) => + remoteCallDelegates.TryGetValue(functionHash, out invoker) && + invoker != null && + invoker.callType == remoteCallType; + + // InvokeCmd/Rpc Delegate can all use the same function here + internal static bool Invoke(ushort functionHash, RemoteCallType remoteCallType, NetworkReader reader, NetworkBehaviour component, NetworkConnectionToClient senderConnection = null) + { + // IMPORTANT: we check if the message's componentIndex component is + // actually of the right type. prevents attackers trying + // to invoke remote calls on wrong components. + if (GetInvokerForHash(functionHash, remoteCallType, out Invoker invoker) && + invoker.componentType.IsInstanceOfType(component)) + { + // invoke function on this component + invoker.function(component, reader, senderConnection); + return true; + } + return false; + } + + // check if the command 'requiresAuthority' which is set in the attribute + internal static bool CommandRequiresAuthority(ushort cmdHash) => + GetInvokerForHash(cmdHash, RemoteCallType.Command, out Invoker invoker) && + invoker.cmdRequiresAuthority; + + /// Gets the handler function by hash. Useful for profilers and debuggers. + public static RemoteCallDelegate GetDelegate(ushort functionHash) => + remoteCallDelegates.TryGetValue(functionHash, out Invoker invoker) + ? invoker.function + : null; + } +} + diff --git a/Assets/Mirror/Core/RemoteCalls.cs.meta b/Assets/Mirror/Core/RemoteCalls.cs.meta new file mode 100644 index 0000000..62b3288 --- /dev/null +++ b/Assets/Mirror/Core/RemoteCalls.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d2cdbcbd1e377d6408a91acbec31ba16 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/SnapshotInterpolation.meta b/Assets/Mirror/Core/SnapshotInterpolation.meta new file mode 100644 index 0000000..85ac9a9 --- /dev/null +++ b/Assets/Mirror/Core/SnapshotInterpolation.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4468e736f87964eaebb9d55fc3e132f7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/SnapshotInterpolation/Snapshot.cs b/Assets/Mirror/Core/SnapshotInterpolation/Snapshot.cs new file mode 100644 index 0000000..6b8ba8a --- /dev/null +++ b/Assets/Mirror/Core/SnapshotInterpolation/Snapshot.cs @@ -0,0 +1,17 @@ +// Snapshot interface so we can reuse it for all kinds of systems. +// for example, NetworkTransform, NetworkRigidbody, CharacterController etc. +// NOTE: we use '' and 'where T : Snapshot' to avoid boxing. +// List would cause allocations through boxing. +namespace Mirror +{ + public interface Snapshot + { + // the remote timestamp (when it was sent by the remote) + double remoteTime { get; set; } + + // the local timestamp (when it was received on our end) + // technically not needed for basic snapshot interpolation. + // only for dynamic buffer time adjustment. + double localTime { get; set; } + } +} diff --git a/Assets/Mirror/Core/SnapshotInterpolation/Snapshot.cs.meta b/Assets/Mirror/Core/SnapshotInterpolation/Snapshot.cs.meta new file mode 100644 index 0000000..24eedd7 --- /dev/null +++ b/Assets/Mirror/Core/SnapshotInterpolation/Snapshot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 12afea28fdb94154868a0a3b7a9df55b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs b/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs new file mode 100644 index 0000000..2d1a2fc --- /dev/null +++ b/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs @@ -0,0 +1,390 @@ +// snapshot interpolation V2 by mischa +// +// Unity independent to be engine agnostic & easy to test. +// boxing: in C#, uses does not box! passing the interface would box! +// +// credits: +// glenn fiedler: https://gafferongames.com/post/snapshot_interpolation/ +// fholm: netcode streams +// fakebyte: standard deviation for dynamic adjustment +// ninjakicka: math & debugging +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class SortedListExtensions + { + // removes the first 'amount' elements from the sorted list + public static void RemoveRange(this SortedList list, int amount) + { + // remove the first element 'amount' times. + // handles -1 and > count safely. + for (int i = 0; i < amount && i < list.Count; ++i) + list.RemoveAt(0); + } + } + + public static class SnapshotInterpolation + { + // calculate timescale for catch-up / slow-down + // note that negative threshold should be <0. + // caller should verify (i.e. Unity OnValidate). + // improves branch prediction. + public static double Timescale( + double drift, // how far we are off from bufferTime + double catchupSpeed, // in % [0,1] + double slowdownSpeed, // in % [0,1] + double absoluteCatchupNegativeThreshold, // in seconds (careful, we may run out of snapshots) + double absoluteCatchupPositiveThreshold) // in seconds + { + // if the drift time is too large, it means we are behind more time. + // so we need to speed up the timescale. + // note the threshold should be sendInterval * catchupThreshold. + if (drift > absoluteCatchupPositiveThreshold) + { + // localTimeline += 0.001; // too simple, this would ping pong + return 1 + catchupSpeed; // n% faster + } + + // if the drift time is too small, it means we are ahead of time. + // so we need to slow down the timescale. + // note the threshold should be sendInterval * catchupThreshold. + if (drift < absoluteCatchupNegativeThreshold) + { + // localTimeline -= 0.001; // too simple, this would ping pong + return 1 - slowdownSpeed; // n% slower + } + + // keep constant timescale while within threshold. + // this way we have perfectly smooth speed most of the time. + return 1; + } + + // calculate dynamic buffer time adjustment + public static double DynamicAdjustment( + double sendInterval, + double jitterStandardDeviation, + double dynamicAdjustmentTolerance) + { + // jitter is equal to delivery time standard variation. + // delivery time is made up of 'sendInterval+jitter'. + // .Average would be dampened by the constant sendInterval + // .StandardDeviation is the changes in 'jitter' that we want + // so add it to send interval again. + double intervalWithJitter = sendInterval + jitterStandardDeviation; + + // how many multiples of sendInterval is that? + // we want to convert to bufferTimeMultiplier later. + double multiples = intervalWithJitter / sendInterval; + + // add the tolerance + double safezone = multiples + dynamicAdjustmentTolerance; + // UnityEngine.Debug.Log($"sendInterval={sendInterval:F3} jitter std={jitterStandardDeviation:F3} => that is ~{multiples:F1} x sendInterval + {dynamicAdjustmentTolerance} => dynamic bufferTimeMultiplier={safezone}"); + return safezone; + } + + // helper function to insert a snapshot if it doesn't exist yet. + // extra function so we can use it for both cases: + // NetworkClient global timeline insertions & adjustments via Insert. + // NetworkBehaviour local insertion without any time adjustments. + public static bool InsertIfNotExists( + SortedList buffer, // snapshot buffer + int bufferLimit, // don't grow infinitely + T snapshot) // the newly received snapshot + where T : Snapshot + { + // slow clients may not be able to process incoming snapshots fast enough. + // infinitely growing snapshots would make it even worse. + // for example, run NetworkRigidbodyBenchmark while deep profiling client. + // the client just grows and reallocates the buffer forever. + if (buffer.Count >= bufferLimit) return false; + + // SortedList does not allow duplicates. + // we don't need to check ContainsKey (which is expensive). + // simply add and compare count before/after for the return value. + + //if (buffer.ContainsKey(snapshot.remoteTime)) return false; // too expensive + // buffer.Add(snapshot.remoteTime, snapshot); // throws if key exists + + int before = buffer.Count; + buffer[snapshot.remoteTime] = snapshot; // overwrites if key exists + return buffer.Count > before; + } + + // clamp timeline for cases where it gets too far behind. + // for example, a client app may go into the background and get updated + // with 1hz for a while. by the time it's back it's at least 30 frames + // behind, possibly more if the transport also queues up. In this + // scenario, at 1% catch up it took around 20+ seconds to finally catch + // up. For these kinds of scenarios it will be better to snap / clamp. + // + // to reproduce, try snapshot interpolation demo and press the button to + // simulate the client timeline at multiple seconds behind. it'll take + // a long time to catch up if the timeline is a long time behind. + public static double TimelineClamp( + double localTimeline, + double bufferTime, + double latestRemoteTime) + { + // we want local timeline to always be 'bufferTime' behind remote. + double targetTime = latestRemoteTime - bufferTime; + + // we define a boundary of 'bufferTime' around the target time. + // this is where catchup / slowdown will happen. + // outside of the area, we clamp. + double lowerBound = targetTime - bufferTime; // how far behind we can get + double upperBound = targetTime + bufferTime; // how far ahead we can get + return Mathd.Clamp(localTimeline, lowerBound, upperBound); + } + + // call this for every received snapshot. + // adds / inserts it to the list & initializes local time if needed. + public static void InsertAndAdjust( + SortedList buffer, // snapshot buffer + int bufferLimit, // don't grow infinitely + T snapshot, // the newly received snapshot + ref double localTimeline, // local interpolation time based on server time + ref double localTimescale, // timeline multiplier to apply catchup / slowdown over time + float sendInterval, // for debugging + double bufferTime, // offset for buffering + double catchupSpeed, // in % [0,1] + double slowdownSpeed, // in % [0,1] + ref ExponentialMovingAverage driftEma, // for catchup / slowdown + float catchupNegativeThreshold, // in % of sendInteral (careful, we may run out of snapshots) + float catchupPositiveThreshold, // in % of sendInterval + ref ExponentialMovingAverage deliveryTimeEma) // for dynamic buffer time adjustment + where T : Snapshot + { + // first snapshot? + // initialize local timeline. + // we want it to be behind by 'offset'. + // + // note that the first snapshot may be a lagging packet. + // so we would always be behind by that lag. + // this requires catchup later. + if (buffer.Count == 0) + localTimeline = snapshot.remoteTime - bufferTime; + + // insert into the buffer. + // + // note that we might insert it between our current interpolation + // which is fine, it adds another data point for accuracy. + // + // note that insert may be called twice for the same key. + // by default, this would throw. + // need to handle it silently. + if (InsertIfNotExists(buffer, bufferLimit, snapshot)) + { + // dynamic buffer adjustment needs delivery interval jitter + if (buffer.Count >= 2) + { + // note that this is not entirely accurate for scrambled inserts. + // + // we always use the last two, not what we just inserted + // even if we were to use the diff for what we just inserted, + // a scrambled insert would still not be 100% accurate: + // => assume a buffer of AC, with delivery time C-A + // => we then insert B, with delivery time B-A + // => but then technically the first C-A wasn't correct, + // as it would have to be C-B + // + // in practice, scramble is rare and won't make much difference + double previousLocalTime = buffer.Values[buffer.Count - 2].localTime; + double lastestLocalTime = buffer.Values[buffer.Count - 1].localTime; + + // this is the delivery time since last snapshot + double localDeliveryTime = lastestLocalTime - previousLocalTime; + + // feed the local delivery time to the EMA. + // this is what the original stream did too. + // our final dynamic buffer adjustment is different though. + // we use standard deviation instead of average. + deliveryTimeEma.Add(localDeliveryTime); + } + + // adjust timescale to catch up / slow down after each insertion + // because that is when we add new values to our EMA. + + // we want localTimeline to be about 'bufferTime' behind. + // for that, we need the delivery time EMA. + // snapshots may arrive out of order, we can not use last-timeline. + // we need to use the inserted snapshot's time - timeline. + double latestRemoteTime = snapshot.remoteTime; + + // ensure timeline stays within a reasonable bound behind/ahead. + localTimeline = TimelineClamp(localTimeline, bufferTime, latestRemoteTime); + + // calculate timediff after localTimeline override changes + double timeDiff = latestRemoteTime - localTimeline; + + // next, calculate average of a few seconds worth of timediffs. + // this gives smoother results. + // + // to calculate the average, we could simply loop through the + // last 'n' seconds worth of timediffs, but: + // - our buffer may only store a few snapshots (bufferTime) + // - looping through seconds worth of snapshots every time is + // expensive + // + // to solve this, we use an exponential moving average. + // https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average + // which is basically fancy math to do the same but faster. + // additionally, it allows us to look at more timeDiff values + // than we sould have access to in our buffer :) + driftEma.Add(timeDiff); + + // timescale depends on driftEma. + // driftEma only changes when inserting. + // therefore timescale only needs to be calculated when inserting. + // saves CPU cycles in Update. + + // next up, calculate how far we are currently away from bufferTime + double drift = driftEma.Value - bufferTime; + + // convert relative thresholds to absolute values based on sendInterval + double absoluteNegativeThreshold = sendInterval * catchupNegativeThreshold; + double absolutePositiveThreshold = sendInterval * catchupPositiveThreshold; + + // next, set localTimescale to catchup consistently in Update(). + // we quantize between default/catchup/slowdown, + // this way we have 'default' speed most of the time(!). + // and only catch up / slow down for a little bit occasionally. + // a consistent multiplier would never be exactly 1.0. + localTimescale = Timescale(drift, catchupSpeed, slowdownSpeed, absoluteNegativeThreshold, absolutePositiveThreshold); + + // debug logging + // UnityEngine.Debug.Log($"sendInterval={sendInterval:F3} bufferTime={bufferTime:F3} drift={drift:F3} driftEma={driftEma.Value:F3} timescale={localTimescale:F3} deliveryIntervalEma={deliveryTimeEma.Value:F3}"); + } + } + + // sample snapshot buffer to find the pair around the given time. + // returns indices so we can use it with RemoveRange to clear old snaps. + // make sure to use use buffer.Values[from/to], not buffer[from/to]. + // make sure to only call this is we have > 0 snapshots. + public static void Sample( + SortedList buffer, // snapshot buffer + double localTimeline, // local interpolation time based on server time + out int from, // the snapshot <= time + out int to, // the snapshot >= time + out double t) // interpolation factor + where T : Snapshot + { + from = -1; + to = -1; + t = 0; + + // sample from [0,count-1] so we always have two at 'i' and 'i+1'. + for (int i = 0; i < buffer.Count - 1; ++i) + { + // is local time between these two? + T first = buffer.Values[i]; + T second = buffer.Values[i + 1]; + if (localTimeline >= first.remoteTime && + localTimeline <= second.remoteTime) + { + // use these two snapshots + from = i; + to = i + 1; + t = Mathd.InverseLerp(first.remoteTime, second.remoteTime, localTimeline); + return; + } + } + + // didn't find two snapshots around local time. + // so pick either the first or last, depending on which is closer. + + // oldest snapshot ahead of local time? + if (buffer.Values[0].remoteTime > localTimeline) + { + from = to = 0; + t = 0; + } + // otherwise initialize both to the last one + else + { + from = to = buffer.Count - 1; + t = 0; + } + } + + // progress local timeline every update. + // + // ONLY CALL IF SNAPSHOTS.COUNT > 0! + // + // decoupled from Step for easier testing and so we can progress + // time only once in NetworkClient, while stepping for each component. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void StepTime( + double deltaTime, // engine delta time (unscaled) + ref double localTimeline, // local interpolation time based on server time + double localTimescale) // catchup / slowdown is applied to time every update) + { + // move local forward in time, scaled with catchup / slowdown applied + localTimeline += deltaTime * localTimescale; + } + + // sample, clear old. + // call this every update. + // + // ONLY CALL IF SNAPSHOTS.COUNT > 0! + // + // returns true if there is anything to apply (requires at least 1 snap) + // from/to/t are out parameters instead of an interpolated 'computed'. + // this allows us to store from/to/t globally (i.e. in NetworkClient) + // and have each component apply the interpolation manually. + // besides, passing "Func Interpolate" would allocate anyway. + public static void StepInterpolation( + SortedList buffer, // snapshot buffer + double localTimeline, // local interpolation time based on server time + out T fromSnapshot, // we interpolate 'from' this snapshot + out T toSnapshot, // 'to' this snapshot + out double t) // at ratio 't' [0,1] + where T : Snapshot + { + // check this in caller: + // nothing to do if there are no snapshots at all yet + // if (buffer.Count == 0) return false; + + // sample snapshot buffer at local interpolation time + Sample(buffer, localTimeline, out int from, out int to, out t); + + // save from/to + fromSnapshot = buffer.Values[from]; + toSnapshot = buffer.Values[to]; + + // remove older snapshots that we definitely don't need anymore. + // after(!) using the indices. + // + // if we have 3 snapshots and we are between 2nd and 3rd: + // from = 1, to = 2 + // then we need to remove the first one, which is exactly 'from'. + // because 'from-1' = 0 would remove none. + buffer.RemoveRange(from); + } + + // update time, sample, clear old. + // call this every update. + // + // ONLY CALL IF SNAPSHOTS.COUNT > 0! + // + // returns true if there is anything to apply (requires at least 1 snap) + // from/to/t are out parameters instead of an interpolated 'computed'. + // this allows us to store from/to/t globally (i.e. in NetworkClient) + // and have each component apply the interpolation manually. + // besides, passing "Func Interpolate" would allocate anyway. + public static void Step( + SortedList buffer, // snapshot buffer + double deltaTime, // engine delta time (unscaled) + ref double localTimeline, // local interpolation time based on server time + double localTimescale, // catchup / slowdown is applied to time every update + out T fromSnapshot, // we interpolate 'from' this snapshot + out T toSnapshot, // 'to' this snapshot + out double t) // at ratio 't' [0,1] + where T : Snapshot + { + StepTime(deltaTime, ref localTimeline, localTimescale); + StepInterpolation(buffer, localTimeline, out fromSnapshot, out toSnapshot, out t); + } + } +} diff --git a/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs.meta b/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs.meta new file mode 100644 index 0000000..244c5fb --- /dev/null +++ b/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 72c16070d85334011853813488ab1431 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs b/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs new file mode 100644 index 0000000..74feae4 --- /dev/null +++ b/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs @@ -0,0 +1,70 @@ +// snapshot interpolation settings struct. +// can easily be exposed in Unity inspectors. +using System; +using UnityEngine; + +namespace Mirror +{ + // class so we can define defaults easily + [Serializable] + public class SnapshotInterpolationSettings + { + // decrease bufferTime at runtime to see the catchup effect. + // increase to see slowdown. + // 'double' so we can have very precise dynamic adjustment without rounding + [Header("Buffering")] + [Tooltip("Local simulation is behind by sendInterval * multiplier seconds.\n\nThis guarantees that we always have enough snapshots in the buffer to mitigate lags & jitter.\n\nIncrease this if the simulation isn't smooth. By default, it should be around 2.")] + public double bufferTimeMultiplier = 2; + + [Tooltip("If a client can't process snapshots fast enough, don't store too many.")] + public int bufferLimit = 32; + + // catchup ///////////////////////////////////////////////////////////// + // catchup thresholds in 'frames'. + // half a frame might be too aggressive. + [Header("Catchup / Slowdown")] + [Tooltip("Slowdown begins when the local timeline is moving too fast towards remote time. Threshold is in frames worth of snapshots.\n\nThis needs to be negative.\n\nDon't modify unless you know what you are doing.")] + public float catchupNegativeThreshold = -1; // careful, don't want to run out of snapshots + + [Tooltip("Catchup begins when the local timeline is moving too slow and getting too far away from remote time. Threshold is in frames worth of snapshots.\n\nThis needs to be positive.\n\nDon't modify unless you know what you are doing.")] + public float catchupPositiveThreshold = 1; + + [Tooltip("Local timeline acceleration in % while catching up.")] + [Range(0, 1)] + public double catchupSpeed = 0.02f; // see snap interp demo. 1% is too slow. + + [Tooltip("Local timeline slowdown in % while slowing down.")] + [Range(0, 1)] + public double slowdownSpeed = 0.04f; // slow down a little faster so we don't encounter empty buffer (= jitter) + + [Tooltip("Catchup/Slowdown is adjusted over n-second exponential moving average.")] + public int driftEmaDuration = 1; // shouldn't need to modify this, but expose it anyway + + // dynamic buffer time adjustment ////////////////////////////////////// + // dynamically adjusts bufferTimeMultiplier for smooth results. + // to understand how this works, try this manually: + // + // - disable dynamic adjustment + // - set jitter = 0.2 (20% is a lot!) + // - notice some stuttering + // - disable interpolation to see just how much jitter this really is(!) + // - enable interpolation again + // - manually increase bufferTimeMultiplier to 3-4 + // ... the cube slows down (blue) until it's smooth + // - with dynamic adjustment enabled, it will set 4 automatically + // ... the cube slows down (blue) until it's smooth as well + // + // note that 20% jitter is extreme. + // for this to be perfectly smooth, set the safety tolerance to '2'. + // but realistically this is not necessary, and '1' is enough. + [Header("Dynamic Adjustment")] + [Tooltip("Automatically adjust bufferTimeMultiplier for smooth results.\nSets a low multiplier on stable connections, and a high multiplier on jittery connections.")] + public bool dynamicAdjustment = true; + + [Tooltip("Safety buffer that is always added to the dynamic bufferTimeMultiplier adjustment.")] + public float dynamicAdjustmentTolerance = 1; // 1 is realistically just fine, 2 is very very safe even for 20% jitter. can be half a frame too. (see above comments) + + [Tooltip("Dynamic adjustment is computed over n-second exponential moving average standard deviation.")] + public int deliveryTimeEmaDuration = 2; // 1-2s recommended to capture average delivery time + } +} diff --git a/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs.meta b/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs.meta new file mode 100644 index 0000000..5cc16e4 --- /dev/null +++ b/Assets/Mirror/Core/SnapshotInterpolation/SnapshotInterpolationSettings.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f955b76b7956417088c03992b3622dc9 +timeCreated: 1678507210 \ No newline at end of file diff --git a/Assets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs b/Assets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs new file mode 100644 index 0000000..5bfdd3a --- /dev/null +++ b/Assets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs @@ -0,0 +1,15 @@ +namespace Mirror +{ + // empty snapshot that is only used to progress client's local timeline. + public struct TimeSnapshot : Snapshot + { + public double remoteTime { get; set; } + public double localTime { get; set; } + + public TimeSnapshot(double remoteTime, double localTime) + { + this.remoteTime = remoteTime; + this.localTime = localTime; + } + } +} diff --git a/Assets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs.meta b/Assets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs.meta new file mode 100644 index 0000000..5e37981 --- /dev/null +++ b/Assets/Mirror/Core/SnapshotInterpolation/TimeSnapshot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: afe2b5ed49634971a2aec720ad74e5cd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/SyncDictionary.cs b/Assets/Mirror/Core/SyncDictionary.cs new file mode 100644 index 0000000..f0f0521 --- /dev/null +++ b/Assets/Mirror/Core/SyncDictionary.cs @@ -0,0 +1,326 @@ +using System.Collections; +using System.Collections.Generic; + +namespace Mirror +{ + public class SyncIDictionary : SyncObject, IDictionary, IReadOnlyDictionary + { + public delegate void SyncDictionaryChanged(Operation op, TKey key, TValue item); + + protected readonly IDictionary objects; + + public int Count => objects.Count; + public bool IsReadOnly => !IsWritable(); + public event SyncDictionaryChanged Callback; + + public enum Operation : byte + { + OP_ADD, + OP_CLEAR, + OP_REMOVE, + OP_SET + } + + struct Change + { + internal Operation operation; + internal TKey key; + internal TValue item; + } + + // list of changes. + // -> insert/delete/clear is only ONE change + // -> changing the same slot 10x caues 10 changes. + // -> note that this grows until next sync(!) + // TODO Dictionary to avoid ever growing changes / redundant changes! + readonly List changes = new List(); + + // how many changes we need to ignore + // this is needed because when we initialize the list, + // we might later receive changes that have already been applied + // so we need to skip them + int changesAhead; + + public override void Reset() + { + changes.Clear(); + changesAhead = 0; + objects.Clear(); + } + + public ICollection Keys => objects.Keys; + + public ICollection Values => objects.Values; + + IEnumerable IReadOnlyDictionary.Keys => objects.Keys; + + IEnumerable IReadOnlyDictionary.Values => objects.Values; + + // throw away all the changes + // this should be called after a successful sync + public override void ClearChanges() => changes.Clear(); + + public SyncIDictionary(IDictionary objects) + { + this.objects = objects; + } + + void AddOperation(Operation op, TKey key, TValue item, bool checkAccess) + { + if (checkAccess && IsReadOnly) + { + throw new System.InvalidOperationException("SyncDictionaries can only be modified by the owner."); + } + + Change change = new Change + { + operation = op, + key = key, + item = item + }; + + if (IsRecording()) + { + changes.Add(change); + OnDirty?.Invoke(); + } + + Callback?.Invoke(op, key, item); + } + + public override void OnSerializeAll(NetworkWriter writer) + { + // if init, write the full list content + writer.WriteUInt((uint)objects.Count); + + foreach (KeyValuePair syncItem in objects) + { + writer.Write(syncItem.Key); + writer.Write(syncItem.Value); + } + + // all changes have been applied already + // thus the client will need to skip all the pending changes + // or they would be applied again. + // So we write how many changes are pending + writer.WriteUInt((uint)changes.Count); + } + + public override void OnSerializeDelta(NetworkWriter writer) + { + // write all the queued up changes + writer.WriteUInt((uint)changes.Count); + + for (int i = 0; i < changes.Count; i++) + { + Change change = changes[i]; + writer.WriteByte((byte)change.operation); + + switch (change.operation) + { + case Operation.OP_ADD: + case Operation.OP_SET: + writer.Write(change.key); + writer.Write(change.item); + break; + case Operation.OP_REMOVE: + writer.Write(change.key); + break; + case Operation.OP_CLEAR: + break; + } + } + } + + public override void OnDeserializeAll(NetworkReader reader) + { + // if init, write the full list content + int count = (int)reader.ReadUInt(); + + objects.Clear(); + changes.Clear(); + + for (int i = 0; i < count; i++) + { + TKey key = reader.Read(); + TValue obj = reader.Read(); + objects.Add(key, obj); + } + + // We will need to skip all these changes + // the next time the list is synchronized + // because they have already been applied + changesAhead = (int)reader.ReadUInt(); + } + + public override void OnDeserializeDelta(NetworkReader reader) + { + int changesCount = (int)reader.ReadUInt(); + + for (int i = 0; i < changesCount; i++) + { + Operation operation = (Operation)reader.ReadByte(); + + // apply the operation only if it is a new change + // that we have not applied yet + bool apply = changesAhead == 0; + TKey key = default; + TValue item = default; + + switch (operation) + { + case Operation.OP_ADD: + case Operation.OP_SET: + key = reader.Read(); + item = reader.Read(); + if (apply) + { + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + if (ContainsKey(key)) + { + objects[key] = item; // assign after ContainsKey check + AddOperation(Operation.OP_SET, key, item, false); + } + else + { + objects[key] = item; // assign after ContainsKey check + AddOperation(Operation.OP_ADD, key, item, false); + } + } + break; + + case Operation.OP_CLEAR: + if (apply) + { + objects.Clear(); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_CLEAR, default, default, false); + } + break; + + case Operation.OP_REMOVE: + key = reader.Read(); + if (apply) + { + if (objects.TryGetValue(key, out item)) + { + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + objects.Remove(key); + AddOperation(Operation.OP_REMOVE, key, item, false); + } + } + break; + } + + if (!apply) + { + // we just skipped this change + changesAhead--; + } + } + } + + public void Clear() + { + objects.Clear(); + AddOperation(Operation.OP_CLEAR, default, default, true); + } + + public bool ContainsKey(TKey key) => objects.ContainsKey(key); + + public bool Remove(TKey key) + { + if (objects.TryGetValue(key, out TValue item) && objects.Remove(key)) + { + AddOperation(Operation.OP_REMOVE, key, item, true); + return true; + } + return false; + } + + public TValue this[TKey i] + { + get => objects[i]; + set + { + if (ContainsKey(i)) + { + objects[i] = value; + AddOperation(Operation.OP_SET, i, value, true); + } + else + { + objects[i] = value; + AddOperation(Operation.OP_ADD, i, value, true); + } + } + } + + public bool TryGetValue(TKey key, out TValue value) => objects.TryGetValue(key, out value); + + public void Add(TKey key, TValue value) + { + objects.Add(key, value); + AddOperation(Operation.OP_ADD, key, value, true); + } + + public void Add(KeyValuePair item) => Add(item.Key, item.Value); + + public bool Contains(KeyValuePair item) + { + return TryGetValue(item.Key, out TValue val) && EqualityComparer.Default.Equals(val, item.Value); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + if (arrayIndex < 0 || arrayIndex > array.Length) + { + throw new System.ArgumentOutOfRangeException(nameof(arrayIndex), "Array Index Out of Range"); + } + if (array.Length - arrayIndex < Count) + { + throw new System.ArgumentException("The number of items in the SyncDictionary is greater than the available space from arrayIndex to the end of the destination array"); + } + + int i = arrayIndex; + foreach (KeyValuePair item in objects) + { + array[i] = item; + i++; + } + } + + public bool Remove(KeyValuePair item) + { + bool result = objects.Remove(item.Key); + if (result) + { + AddOperation(Operation.OP_REMOVE, item.Key, item.Value, true); + } + return result; + } + + public IEnumerator> GetEnumerator() => objects.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => objects.GetEnumerator(); + } + + public class SyncDictionary : SyncIDictionary + { + public SyncDictionary() : base(new Dictionary()) {} + public SyncDictionary(IEqualityComparer eq) : base(new Dictionary(eq)) {} + public SyncDictionary(IDictionary d) : base(new Dictionary(d)) {} + public new Dictionary.ValueCollection Values => ((Dictionary)objects).Values; + public new Dictionary.KeyCollection Keys => ((Dictionary)objects).Keys; + public new Dictionary.Enumerator GetEnumerator() => ((Dictionary)objects).GetEnumerator(); + } +} diff --git a/Assets/Mirror/Core/SyncDictionary.cs.meta b/Assets/Mirror/Core/SyncDictionary.cs.meta new file mode 100644 index 0000000..1c20b57 --- /dev/null +++ b/Assets/Mirror/Core/SyncDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4b346c49cfdb668488a364c3023590e2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/SyncList.cs b/Assets/Mirror/Core/SyncList.cs new file mode 100644 index 0000000..8b70eed --- /dev/null +++ b/Assets/Mirror/Core/SyncList.cs @@ -0,0 +1,420 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Mirror +{ + public class SyncList : SyncObject, IList, IReadOnlyList + { + public delegate void SyncListChanged(Operation op, int itemIndex, T oldItem, T newItem); + + readonly IList objects; + readonly IEqualityComparer comparer; + + public int Count => objects.Count; + public bool IsReadOnly => !IsWritable(); + public event SyncListChanged Callback; + + public enum Operation : byte + { + OP_ADD, + OP_CLEAR, + OP_INSERT, + OP_REMOVEAT, + OP_SET + } + + struct Change + { + internal Operation operation; + internal int index; + internal T item; + } + + // list of changes. + // -> insert/delete/clear is only ONE change + // -> changing the same slot 10x caues 10 changes. + // -> note that this grows until next sync(!) + readonly List changes = new List(); + + // how many changes we need to ignore + // this is needed because when we initialize the list, + // we might later receive changes that have already been applied + // so we need to skip them + int changesAhead; + + public SyncList() : this(EqualityComparer.Default) {} + + public SyncList(IEqualityComparer comparer) + { + this.comparer = comparer ?? EqualityComparer.Default; + objects = new List(); + } + + public SyncList(IList objects, IEqualityComparer comparer = null) + { + this.comparer = comparer ?? EqualityComparer.Default; + this.objects = objects; + } + + // throw away all the changes + // this should be called after a successful sync + public override void ClearChanges() => changes.Clear(); + + public override void Reset() + { + changes.Clear(); + changesAhead = 0; + objects.Clear(); + } + + void AddOperation(Operation op, int itemIndex, T oldItem, T newItem, bool checkAccess) + { + if (checkAccess && IsReadOnly) + { + throw new InvalidOperationException("Synclists can only be modified by the owner."); + } + + Change change = new Change + { + operation = op, + index = itemIndex, + item = newItem + }; + + if (IsRecording()) + { + changes.Add(change); + OnDirty?.Invoke(); + } + + Callback?.Invoke(op, itemIndex, oldItem, newItem); + } + + public override void OnSerializeAll(NetworkWriter writer) + { + // if init, write the full list content + writer.WriteUInt((uint)objects.Count); + + for (int i = 0; i < objects.Count; i++) + { + T obj = objects[i]; + writer.Write(obj); + } + + // all changes have been applied already + // thus the client will need to skip all the pending changes + // or they would be applied again. + // So we write how many changes are pending + writer.WriteUInt((uint)changes.Count); + } + + public override void OnSerializeDelta(NetworkWriter writer) + { + // write all the queued up changes + writer.WriteUInt((uint)changes.Count); + + for (int i = 0; i < changes.Count; i++) + { + Change change = changes[i]; + writer.WriteByte((byte)change.operation); + + switch (change.operation) + { + case Operation.OP_ADD: + writer.Write(change.item); + break; + + case Operation.OP_CLEAR: + break; + + case Operation.OP_REMOVEAT: + writer.WriteUInt((uint)change.index); + break; + + case Operation.OP_INSERT: + case Operation.OP_SET: + writer.WriteUInt((uint)change.index); + writer.Write(change.item); + break; + } + } + } + + public override void OnDeserializeAll(NetworkReader reader) + { + // if init, write the full list content + int count = (int)reader.ReadUInt(); + + objects.Clear(); + changes.Clear(); + + for (int i = 0; i < count; i++) + { + T obj = reader.Read(); + objects.Add(obj); + } + + // We will need to skip all these changes + // the next time the list is synchronized + // because they have already been applied + changesAhead = (int)reader.ReadUInt(); + } + + public override void OnDeserializeDelta(NetworkReader reader) + { + int changesCount = (int)reader.ReadUInt(); + + for (int i = 0; i < changesCount; i++) + { + Operation operation = (Operation)reader.ReadByte(); + + // apply the operation only if it is a new change + // that we have not applied yet + bool apply = changesAhead == 0; + int index = 0; + T oldItem = default; + T newItem = default; + + switch (operation) + { + case Operation.OP_ADD: + newItem = reader.Read(); + if (apply) + { + index = objects.Count; + objects.Add(newItem); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_ADD, objects.Count - 1, default, newItem, false); + } + break; + + case Operation.OP_CLEAR: + if (apply) + { + objects.Clear(); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_CLEAR, 0, default, default, false); + } + break; + + case Operation.OP_INSERT: + index = (int)reader.ReadUInt(); + newItem = reader.Read(); + if (apply) + { + objects.Insert(index, newItem); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_INSERT, index, default, newItem, false); + } + break; + + case Operation.OP_REMOVEAT: + index = (int)reader.ReadUInt(); + if (apply) + { + oldItem = objects[index]; + objects.RemoveAt(index); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_REMOVEAT, index, oldItem, default, false); + } + break; + + case Operation.OP_SET: + index = (int)reader.ReadUInt(); + newItem = reader.Read(); + if (apply) + { + oldItem = objects[index]; + objects[index] = newItem; + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_SET, index, oldItem, newItem, false); + } + break; + } + + if (!apply) + { + // we just skipped this change + changesAhead--; + } + } + } + + public void Add(T item) + { + objects.Add(item); + AddOperation(Operation.OP_ADD, objects.Count - 1, default, item, true); + } + + public void AddRange(IEnumerable range) + { + foreach (T entry in range) + { + Add(entry); + } + } + + public void Clear() + { + objects.Clear(); + AddOperation(Operation.OP_CLEAR, 0, default, default, true); + } + + public bool Contains(T item) => IndexOf(item) >= 0; + + public void CopyTo(T[] array, int index) => objects.CopyTo(array, index); + + public int IndexOf(T item) + { + for (int i = 0; i < objects.Count; ++i) + if (comparer.Equals(item, objects[i])) + return i; + return -1; + } + + public int FindIndex(Predicate match) + { + for (int i = 0; i < objects.Count; ++i) + if (match(objects[i])) + return i; + return -1; + } + + public T Find(Predicate match) + { + int i = FindIndex(match); + return (i != -1) ? objects[i] : default; + } + + public List FindAll(Predicate match) + { + List results = new List(); + for (int i = 0; i < objects.Count; ++i) + if (match(objects[i])) + results.Add(objects[i]); + return results; + } + + public void Insert(int index, T item) + { + objects.Insert(index, item); + AddOperation(Operation.OP_INSERT, index, default, item, true); + } + + public void InsertRange(int index, IEnumerable range) + { + foreach (T entry in range) + { + Insert(index, entry); + index++; + } + } + + public bool Remove(T item) + { + int index = IndexOf(item); + bool result = index >= 0; + if (result) + { + RemoveAt(index); + } + return result; + } + + public void RemoveAt(int index) + { + T oldItem = objects[index]; + objects.RemoveAt(index); + AddOperation(Operation.OP_REMOVEAT, index, oldItem, default, true); + } + + public int RemoveAll(Predicate match) + { + List toRemove = new List(); + for (int i = 0; i < objects.Count; ++i) + if (match(objects[i])) + toRemove.Add(objects[i]); + + foreach (T entry in toRemove) + { + Remove(entry); + } + + return toRemove.Count; + } + + public T this[int i] + { + get => objects[i]; + set + { + if (!comparer.Equals(objects[i], value)) + { + T oldItem = objects[i]; + objects[i] = value; + AddOperation(Operation.OP_SET, i, oldItem, value, true); + } + } + } + + public Enumerator GetEnumerator() => new Enumerator(this); + + IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); + + IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); + + // default Enumerator allocates. we need a custom struct Enumerator to + // not allocate on the heap. + // (System.Collections.Generic.List source code does the same) + // + // benchmark: + // uMMORPG with 800 monsters, Skills.GetHealthBonus() which runs a + // foreach on skills SyncList: + // before: 81.2KB GC per frame + // after: 0KB GC per frame + // => this is extremely important for MMO scale networking + public struct Enumerator : IEnumerator + { + readonly SyncList list; + int index; + public T Current { get; private set; } + + public Enumerator(SyncList list) + { + this.list = list; + index = -1; + Current = default; + } + + public bool MoveNext() + { + if (++index >= list.Count) + { + return false; + } + Current = list[index]; + return true; + } + + public void Reset() => index = -1; + object IEnumerator.Current => Current; + public void Dispose() {} + } + } +} diff --git a/Assets/Mirror/Core/SyncList.cs.meta b/Assets/Mirror/Core/SyncList.cs.meta new file mode 100644 index 0000000..088ef1e --- /dev/null +++ b/Assets/Mirror/Core/SyncList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 744fc71f748fe40d5940e04bf42b29f3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/SyncObject.cs b/Assets/Mirror/Core/SyncObject.cs new file mode 100644 index 0000000..405e240 --- /dev/null +++ b/Assets/Mirror/Core/SyncObject.cs @@ -0,0 +1,53 @@ +using System; + +namespace Mirror +{ + /// SyncObjects sync state between server and client. E.g. SyncLists. + // SyncObject should be a class (instead of an interface) for a few reasons: + // * NetworkBehaviour stores SyncObjects in a list. structs would be a copy + // and OnSerialize would use the copy instead of the original struct. + // * Obsolete functions like Flush() don't need to be defined by each type + // * OnDirty/IsRecording etc. default functions can be defined once here + // for example, handling 'OnDirty wasn't initialized' with a default + // function that throws an exception will be useful for SyncVar + public abstract class SyncObject + { + /// Used internally to set owner NetworkBehaviour's dirty mask bit when changed. + public Action OnDirty; + + /// Used internally to check if we are currently tracking changes. + // prevents ever growing .changes lists: + // if a monster has no observers but we keep modifying a SyncObject, + // then the changes would never be flushed and keep growing, + // because OnSerialize isn't called without observers. + // => Func so we can set it to () => observers.Count > 0 + // without depending on NetworkComponent/NetworkIdentity here. + // => virtual so it simply always records by default + public Func IsRecording = () => true; + + // SyncList/Set/etc. shouldn't be modifiable if not owned. + // otherwise they would silently get out of sync. + // need a lambda because InitSyncObject is called in ctor, when + // 'isClient' etc. aren't initialized yet. + public Func IsWritable = () => true; + + /// Discard all the queued changes + // Consider the object fully synchronized with clients + public abstract void ClearChanges(); + + /// Write a full copy of the object + public abstract void OnSerializeAll(NetworkWriter writer); + + /// Write the changes made to the object since last sync + public abstract void OnSerializeDelta(NetworkWriter writer); + + /// Reads a full copy of the object + public abstract void OnDeserializeAll(NetworkReader reader); + + /// Reads the changes made to the object since last sync + public abstract void OnDeserializeDelta(NetworkReader reader); + + /// Resets the SyncObject so that it can be re-used + public abstract void Reset(); + } +} diff --git a/Assets/Mirror/Core/SyncObject.cs.meta b/Assets/Mirror/Core/SyncObject.cs.meta new file mode 100644 index 0000000..736c651 --- /dev/null +++ b/Assets/Mirror/Core/SyncObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae226d17a0c844041aa24cc2c023dd49 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/SyncSet.cs b/Assets/Mirror/Core/SyncSet.cs new file mode 100644 index 0000000..13d4302 --- /dev/null +++ b/Assets/Mirror/Core/SyncSet.cs @@ -0,0 +1,352 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Mirror +{ + public class SyncSet : SyncObject, ISet + { + public delegate void SyncSetChanged(Operation op, T item); + + protected readonly ISet objects; + + public int Count => objects.Count; + public bool IsReadOnly => !IsWritable(); + public event SyncSetChanged Callback; + + public enum Operation : byte + { + OP_ADD, + OP_CLEAR, + OP_REMOVE + } + + struct Change + { + internal Operation operation; + internal T item; + } + + // list of changes. + // -> insert/delete/clear is only ONE change + // -> changing the same slot 10x caues 10 changes. + // -> note that this grows until next sync(!) + // TODO Dictionary to avoid ever growing changes / redundant changes! + readonly List changes = new List(); + + // how many changes we need to ignore + // this is needed because when we initialize the list, + // we might later receive changes that have already been applied + // so we need to skip them + int changesAhead; + + public SyncSet(ISet objects) + { + this.objects = objects; + } + + public override void Reset() + { + changes.Clear(); + changesAhead = 0; + objects.Clear(); + } + + // throw away all the changes + // this should be called after a successful sync + public override void ClearChanges() => changes.Clear(); + + void AddOperation(Operation op, T item, bool checkAccess) + { + if (checkAccess && IsReadOnly) + { + throw new InvalidOperationException("SyncSets can only be modified by the owner."); + } + + Change change = new Change + { + operation = op, + item = item + }; + + if (IsRecording()) + { + changes.Add(change); + OnDirty?.Invoke(); + } + + Callback?.Invoke(op, item); + } + + void AddOperation(Operation op, bool checkAccess) => AddOperation(op, default, checkAccess); + + public override void OnSerializeAll(NetworkWriter writer) + { + // if init, write the full list content + writer.WriteUInt((uint)objects.Count); + + foreach (T obj in objects) + { + writer.Write(obj); + } + + // all changes have been applied already + // thus the client will need to skip all the pending changes + // or they would be applied again. + // So we write how many changes are pending + writer.WriteUInt((uint)changes.Count); + } + + public override void OnSerializeDelta(NetworkWriter writer) + { + // write all the queued up changes + writer.WriteUInt((uint)changes.Count); + + for (int i = 0; i < changes.Count; i++) + { + Change change = changes[i]; + writer.WriteByte((byte)change.operation); + + switch (change.operation) + { + case Operation.OP_ADD: + writer.Write(change.item); + break; + + case Operation.OP_CLEAR: + break; + + case Operation.OP_REMOVE: + writer.Write(change.item); + break; + } + } + } + + public override void OnDeserializeAll(NetworkReader reader) + { + // if init, write the full list content + int count = (int)reader.ReadUInt(); + + objects.Clear(); + changes.Clear(); + + for (int i = 0; i < count; i++) + { + T obj = reader.Read(); + objects.Add(obj); + } + + // We will need to skip all these changes + // the next time the list is synchronized + // because they have already been applied + changesAhead = (int)reader.ReadUInt(); + } + + public override void OnDeserializeDelta(NetworkReader reader) + { + int changesCount = (int)reader.ReadUInt(); + + for (int i = 0; i < changesCount; i++) + { + Operation operation = (Operation)reader.ReadByte(); + + // apply the operation only if it is a new change + // that we have not applied yet + bool apply = changesAhead == 0; + T item = default; + + switch (operation) + { + case Operation.OP_ADD: + item = reader.Read(); + if (apply) + { + objects.Add(item); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_ADD, item, false); + } + break; + + case Operation.OP_CLEAR: + if (apply) + { + objects.Clear(); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_CLEAR, false); + } + break; + + case Operation.OP_REMOVE: + item = reader.Read(); + if (apply) + { + objects.Remove(item); + // add dirty + changes. + // ClientToServer needs to set dirty in server OnDeserialize. + // no access check: server OnDeserialize can always + // write, even for ClientToServer (for broadcasting). + AddOperation(Operation.OP_REMOVE, item, false); + } + break; + } + + if (!apply) + { + // we just skipped this change + changesAhead--; + } + } + } + + public bool Add(T item) + { + if (objects.Add(item)) + { + AddOperation(Operation.OP_ADD, item, true); + return true; + } + return false; + } + + void ICollection.Add(T item) + { + if (objects.Add(item)) + { + AddOperation(Operation.OP_ADD, item, true); + } + } + + public void Clear() + { + objects.Clear(); + AddOperation(Operation.OP_CLEAR, true); + } + + public bool Contains(T item) => objects.Contains(item); + + public void CopyTo(T[] array, int index) => objects.CopyTo(array, index); + + public bool Remove(T item) + { + if (objects.Remove(item)) + { + AddOperation(Operation.OP_REMOVE, item, true); + return true; + } + return false; + } + + public IEnumerator GetEnumerator() => objects.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public void ExceptWith(IEnumerable other) + { + if (other == this) + { + Clear(); + return; + } + + // remove every element in other from this + foreach (T element in other) + { + Remove(element); + } + } + + public void IntersectWith(IEnumerable other) + { + if (other is ISet otherSet) + { + IntersectWithSet(otherSet); + } + else + { + HashSet otherAsSet = new HashSet(other); + IntersectWithSet(otherAsSet); + } + } + + void IntersectWithSet(ISet otherSet) + { + List elements = new List(objects); + + foreach (T element in elements) + { + if (!otherSet.Contains(element)) + { + Remove(element); + } + } + } + + public bool IsProperSubsetOf(IEnumerable other) => objects.IsProperSubsetOf(other); + + public bool IsProperSupersetOf(IEnumerable other) => objects.IsProperSupersetOf(other); + + public bool IsSubsetOf(IEnumerable other) => objects.IsSubsetOf(other); + + public bool IsSupersetOf(IEnumerable other) => objects.IsSupersetOf(other); + + public bool Overlaps(IEnumerable other) => objects.Overlaps(other); + + public bool SetEquals(IEnumerable other) => objects.SetEquals(other); + + // custom implementation so we can do our own Clear/Add/Remove for delta + public void SymmetricExceptWith(IEnumerable other) + { + if (other == this) + { + Clear(); + } + else + { + foreach (T element in other) + { + if (!Remove(element)) + { + Add(element); + } + } + } + } + + // custom implementation so we can do our own Clear/Add/Remove for delta + public void UnionWith(IEnumerable other) + { + if (other != this) + { + foreach (T element in other) + { + Add(element); + } + } + } + } + + public class SyncHashSet : SyncSet + { + public SyncHashSet() : this(EqualityComparer.Default) {} + public SyncHashSet(IEqualityComparer comparer) : base(new HashSet(comparer ?? EqualityComparer.Default)) {} + + // allocation free enumerator + public new HashSet.Enumerator GetEnumerator() => ((HashSet)objects).GetEnumerator(); + } + + public class SyncSortedSet : SyncSet + { + public SyncSortedSet() : this(Comparer.Default) {} + public SyncSortedSet(IComparer comparer) : base(new SortedSet(comparer ?? Comparer.Default)) {} + + // allocation free enumerator + public new SortedSet.Enumerator GetEnumerator() => ((SortedSet)objects).GetEnumerator(); + } +} diff --git a/Assets/Mirror/Core/SyncSet.cs.meta b/Assets/Mirror/Core/SyncSet.cs.meta new file mode 100644 index 0000000..6eeef1c --- /dev/null +++ b/Assets/Mirror/Core/SyncSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8a31599d9f9dd4ef9999f7b9707c832c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools.meta b/Assets/Mirror/Core/Tools.meta new file mode 100644 index 0000000..8319cae --- /dev/null +++ b/Assets/Mirror/Core/Tools.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d9c73cc2749d43268600b80df0b55c4d +timeCreated: 1667486812 \ No newline at end of file diff --git a/Assets/Mirror/Core/Tools/AccurateInterval.cs b/Assets/Mirror/Core/Tools/AccurateInterval.cs new file mode 100644 index 0000000..9d2ce0e --- /dev/null +++ b/Assets/Mirror/Core/Tools/AccurateInterval.cs @@ -0,0 +1,86 @@ +// accurate interval from Mirror II. +// for sync / send intervals where it matters. +// does not(!) do catch-up. +// +// first, let's understand the problem. +// say we need an interval of 10 Hz, so every 100ms in Update we do: +// if (Time.time >= lastTime + interval) +// { +// lastTime = Time.time; +// ... +// } +// +// this seems fine, but actually Time.time will always be a few ms beyond +// the interval. but since lastTime is reset to Time.time, the remainder +// is always ignored away. +// with fixed tickRate servers (say 30 Hz), the remainder is significant! +// +// in practice if we have a 30 Hz tickRate server with a 30 Hz sendRate, +// the above way to measure the interval would result in a 18-19 Hz sendRate! +// => this is not just a little off. this is _way_ off, by almost half. +// => displaying actual + target tick/send rate will show this very easily. +// +// we need an accurate way to measure intervals for where it matters. +// and it needs to be testable to guarantee results. +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class AccurateInterval + { + // static func instead of storing interval + lastTime struct. + // + don't need to initialize struct ctor with interval in Awake + // + allows for interval changes at runtime too + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Elapsed(double time, double interval, ref double lastTime) + { + // enough time elapsed? + if (time < lastTime + interval) + return false; + + // naive implementation: + //lastTime = time; + + // accurate but doesn't handle heavy load situations: + //lastTime += interval; + + // heavy load edge case: + // * interval is 100ms + // * server is under heavy load, Updates slow down to 1/s + // * Elapsed(1.000) returns true. + // technically 10 intervals have elapsed. + // * server recovers to normal, Updates are every 10ms again + // * Elapsed(1.010) should return false again until 1.100. + // + // increasing lastTime by interval would require 10 more calls + // to ever catch up again: + // lastTime += interval + // + // as result, the next 10 calls to Elapsed would return true. + // Elapsed(1.001) => true + // Elapsed(1.002) => true + // Elapsed(1.003) => true + // ... + // even though technically the delta was not >= interval. + // + // this would keep the server under heavy load, and it may never + // catch-up. this is not ideal for large virtual worlds. + // + // instead, we want to skip multiples of 'interval' and only + // keep the remainder. + // + // see also: AccurateIntervalTests.Slowdown() + + // easy to understand: + //double elapsed = time - lastTime; + //double remainder = elapsed % interval; + //lastTime = time - remainder; + + // easier: set to rounded multiples of interval (fholm). + // long to match double time. + long multiplier = (long)(time / interval); + lastTime = multiplier * interval; + return true; + } + } +} diff --git a/Assets/Mirror/Core/Tools/AccurateInterval.cs.meta b/Assets/Mirror/Core/Tools/AccurateInterval.cs.meta new file mode 100644 index 0000000..a58184d --- /dev/null +++ b/Assets/Mirror/Core/Tools/AccurateInterval.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c1b18064e25046f28b88db65a4012ec1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools/Compression.cs b/Assets/Mirror/Core/Tools/Compression.cs new file mode 100644 index 0000000..d04b566 --- /dev/null +++ b/Assets/Mirror/Core/Tools/Compression.cs @@ -0,0 +1,556 @@ +// Quaternion compression from DOTSNET +using System; +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Mirror +{ + /// Functions to Compress Quaternions and Floats + public static class Compression + { + // divide by precision (functions backported from Mirror II) + // for example, 0.1 cm precision converts '5.0f' float to '50' long. + // + // 'long' instead of 'int' to allow for large enough worlds. + // value / precision exceeds int.max range too easily. + // Convert.ToInt32/64 would throw. + // https://github.com/vis2k/DOTSNET/issues/59 + // + // 'long' and 'int' will result in the same bandwidth though. + // for example, ScaleToLong(10.5, 0.1) = 105. + // int: 0x00000069 + // long: 0x0000000000000069 + // delta compression will reduce both to 1 byte. + // + // returns + // 'true' if scaling was possible within 'long' bounds. + // 'false' if clamping was necessary. + // never throws. checking result is optional. + public static bool ScaleToLong(float value, float precision, out long result) + { + // user might try to pass precision = 0 to disable rounding. + // this is not supported. + // throw to make the user fix this immediately. + // otherwise we would have to reinterpret-cast if ==0 etc. + // this function should be kept simple. + // if rounding isn't wanted, this function shouldn't be called. + if (precision == 0) throw new DivideByZeroException($"ScaleToLong: precision=0 would cause null division. If rounding isn't wanted, don't call this function."); + + // catch OverflowException if value/precision > long.max. + // attackers should never be able to throw exceptions. + try + { + result = Convert.ToInt64(value / precision); + return true; + } + // clamp to .max/.min. + // returning '0' would make far away entities reset to origin. + // returning 'max' would keep them stuck at the end of the world. + // the latter is much easier to debug. + catch (OverflowException) + { + result = value > 0 ? long.MaxValue : long.MinValue; + return false; + } + } + + // returns + // 'true' if scaling was possible within 'long' bounds. + // 'false' if clamping was necessary. + // never throws. checking result is optional. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ScaleToLong(Vector3 value, float precision, out long x, out long y, out long z) + { + // attempt to convert every component. + // do not return early if one conversion returned 'false'. + // the return value is optional. always attempt to convert all. + bool result = true; + result &= ScaleToLong(value.x, precision, out x); + result &= ScaleToLong(value.y, precision, out y); + result &= ScaleToLong(value.z, precision, out z); + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ScaleToLong(Vector3 value, float precision, out Vector3Long quantized) + { + quantized = Vector3Long.zero; + return ScaleToLong(value, precision, out quantized.x, out quantized.y, out quantized.z); + } + + // multiple by precision. + // for example, 0.1 cm precision converts '50' long to '5.0f' float. + public static float ScaleToFloat(long value, float precision) + { + // user might try to pass precision = 0 to disable rounding. + // this is not supported. + // throw to make the user fix this immediately. + // otherwise we would have to reinterpret-cast if ==0 etc. + // this function should be kept simple. + // if rounding isn't wanted, this function shouldn't be called. + if (precision == 0) throw new DivideByZeroException($"ScaleToLong: precision=0 would cause null division. If rounding isn't wanted, don't call this function."); + + return value * precision; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 ScaleToFloat(long x, long y, long z, float precision) + { + Vector3 v; + v.x = ScaleToFloat(x, precision); + v.y = ScaleToFloat(y, precision); + v.z = ScaleToFloat(z, precision); + return v; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 ScaleToFloat(Vector3Long value, float precision) => + ScaleToFloat(value.x, value.y, value.z, precision); + + // scale a float within min/max range to an ushort between min/max range + // note: can also use this for byte range from byte.MinValue to byte.MaxValue + public static ushort ScaleFloatToUShort(float value, float minValue, float maxValue, ushort minTarget, ushort maxTarget) + { + // note: C# ushort - ushort => int, hence so many casts + // max ushort - min ushort only fits into something bigger + int targetRange = maxTarget - minTarget; + float valueRange = maxValue - minValue; + float valueRelative = value - minValue; + return (ushort)(minTarget + (ushort)(valueRelative / valueRange * targetRange)); + } + + // scale an ushort within min/max range to a float between min/max range + // note: can also use this for byte range from byte.MinValue to byte.MaxValue + public static float ScaleUShortToFloat(ushort value, ushort minValue, ushort maxValue, float minTarget, float maxTarget) + { + // note: C# ushort - ushort => int, hence so many casts + float targetRange = maxTarget - minTarget; + ushort valueRange = (ushort)(maxValue - minValue); + ushort valueRelative = (ushort)(value - minValue); + return minTarget + (valueRelative / (float)valueRange * targetRange); + } + + // quaternion compression ////////////////////////////////////////////// + // smallest three: https://gafferongames.com/post/snapshot_compression/ + // compresses 16 bytes quaternion into 4 bytes + + // helper function to find largest absolute element + // returns the index of the largest one + public static int LargestAbsoluteComponentIndex(Vector4 value, out float largestAbs, out Vector3 withoutLargest) + { + // convert to abs + Vector4 abs = new Vector4(Mathf.Abs(value.x), Mathf.Abs(value.y), Mathf.Abs(value.z), Mathf.Abs(value.w)); + + // set largest to first abs (x) + largestAbs = abs.x; + withoutLargest = new Vector3(value.y, value.z, value.w); + int largestIndex = 0; + + // compare to the others, starting at second value + // performance for 100k calls + // for-loop: 25ms + // manual checks: 22ms + if (abs.y > largestAbs) + { + largestIndex = 1; + largestAbs = abs.y; + withoutLargest = new Vector3(value.x, value.z, value.w); + } + if (abs.z > largestAbs) + { + largestIndex = 2; + largestAbs = abs.z; + withoutLargest = new Vector3(value.x, value.y, value.w); + } + if (abs.w > largestAbs) + { + largestIndex = 3; + largestAbs = abs.w; + withoutLargest = new Vector3(value.x, value.y, value.z); + } + + return largestIndex; + } + + const float QuaternionMinRange = -0.707107f; + const float QuaternionMaxRange = 0.707107f; + const ushort TenBitsMax = 0b11_1111_1111; + + // note: assumes normalized quaternions + public static uint CompressQuaternion(Quaternion q) + { + // note: assuming normalized quaternions is enough. no need to force + // normalize here. we already normalize when decompressing. + + // find the largest component index [0,3] + value + int largestIndex = LargestAbsoluteComponentIndex(new Vector4(q.x, q.y, q.z, q.w), out float _, out Vector3 withoutLargest); + + // from here on, we work with the 3 components without largest! + + // "You might think you need to send a sign bit for [largest] in + // case it is negative, but you don’t, because you can make + // [largest] always positive by negating the entire quaternion if + // [largest] is negative. in quaternion space (x,y,z,w) and + // (-x,-y,-z,-w) represent the same rotation." + if (q[largestIndex] < 0) + withoutLargest = -withoutLargest; + + // put index & three floats into one integer. + // => index is 2 bits (4 values require 2 bits to store them) + // => the three floats are between [-0.707107,+0.707107] because: + // "If v is the absolute value of the largest quaternion + // component, the next largest possible component value occurs + // when two components have the same absolute value and the + // other two components are zero. The length of that quaternion + // (v,v,0,0) is 1, therefore v^2 + v^2 = 1, 2v^2 = 1, + // v = 1/sqrt(2). This means you can encode the smallest three + // components in [-0.707107,+0.707107] instead of [-1,+1] giving + // you more precision with the same number of bits." + // => the article recommends storing each float in 9 bits + // => our uint has 32 bits, so we might as well store in (32-2)/3=10 + // 10 bits max value: 1023=0x3FF (use OSX calc to flip 10 bits) + ushort aScaled = ScaleFloatToUShort(withoutLargest.x, QuaternionMinRange, QuaternionMaxRange, 0, TenBitsMax); + ushort bScaled = ScaleFloatToUShort(withoutLargest.y, QuaternionMinRange, QuaternionMaxRange, 0, TenBitsMax); + ushort cScaled = ScaleFloatToUShort(withoutLargest.z, QuaternionMinRange, QuaternionMaxRange, 0, TenBitsMax); + + // now we just need to pack them into one integer + // -> index is 2 bit and needs to be shifted to 31..32 + // -> a is 10 bit and needs to be shifted 20..30 + // -> b is 10 bit and needs to be shifted 10..20 + // -> c is 10 bit and needs to be at 0..10 + return (uint)(largestIndex << 30 | aScaled << 20 | bScaled << 10 | cScaled); + } + + // Quaternion normalizeSAFE from ECS math.normalizesafe() + // => useful to produce valid quaternions even if client sends invalid + // data + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static Quaternion QuaternionNormalizeSafe(Quaternion value) + { + // The smallest positive normal number representable in a float. + const float FLT_MIN_NORMAL = 1.175494351e-38F; + + Vector4 v = new Vector4(value.x, value.y, value.z, value.w); + float length = Vector4.Dot(v, v); + return length > FLT_MIN_NORMAL + ? value.normalized + : Quaternion.identity; + } + + // note: gives normalized quaternions + public static Quaternion DecompressQuaternion(uint data) + { + // get cScaled which is at 0..10 and ignore the rest + ushort cScaled = (ushort)(data & TenBitsMax); + + // get bScaled which is at 10..20 and ignore the rest + ushort bScaled = (ushort)((data >> 10) & TenBitsMax); + + // get aScaled which is at 20..30 and ignore the rest + ushort aScaled = (ushort)((data >> 20) & TenBitsMax); + + // get 2 bit largest index, which is at 31..32 + int largestIndex = (int)(data >> 30); + + // scale back to floats + float a = ScaleUShortToFloat(aScaled, 0, TenBitsMax, QuaternionMinRange, QuaternionMaxRange); + float b = ScaleUShortToFloat(bScaled, 0, TenBitsMax, QuaternionMinRange, QuaternionMaxRange); + float c = ScaleUShortToFloat(cScaled, 0, TenBitsMax, QuaternionMinRange, QuaternionMaxRange); + + // calculate the omitted component based on a²+b²+c²+d²=1 + float d = Mathf.Sqrt(1 - a*a - b*b - c*c); + + // reconstruct based on largest index + Vector4 value; + switch (largestIndex) + { + case 0: value = new Vector4(d, a, b, c); break; + case 1: value = new Vector4(a, d, b, c); break; + case 2: value = new Vector4(a, b, d, c); break; + default: value = new Vector4(a, b, c, d); break; + } + + // ECS Rotation only works with normalized quaternions. + // make sure that's always the case here to avoid ECS bugs where + // everything stops moving if the quaternion isn't normalized. + // => NormalizeSafe returns a normalized quaternion even if we pass + // in NaN from deserializing invalid values! + return QuaternionNormalizeSafe(new Quaternion(value.x, value.y, value.z, value.w)); + } + + // varint compression ////////////////////////////////////////////////// + // helper function to predict varint size for a given number. + // useful when checking if a message + size header will fit, etc. + public static int VarUIntSize(ulong value) + { + if (value <= 240) + return 1; + if (value <= 2287) + return 2; + if (value <= 67823) + return 3; + if (value <= 16777215) + return 4; + if (value <= 4294967295) + return 5; + if (value <= 1099511627775) + return 6; + if (value <= 281474976710655) + return 7; + if (value <= 72057594037927935) + return 8; + return 9; + } + + // helper function to predict varint size for a given number. + // useful when checking if a message + size header will fit, etc. + public static int VarIntSize(long value) + { + // CompressVarInt zigzags it first + ulong zigzagged = (ulong)((value >> 63) ^ (value << 1)); + return VarUIntSize(zigzagged); + } + + // compress ulong varint. + // same result for ulong, uint, ushort and byte. only need one function. + // NOT an extension. otherwise weaver might accidentally use it. + public static void CompressVarUInt(NetworkWriter writer, ulong value) + { + // straight forward implementation: + // keep this for understanding & debugging. + /* + if (value <= 240) + { + writer.WriteByte((byte)value); + return; + } + if (value <= 2287) + { + writer.WriteByte((byte)(((value - 240) >> 8) + 241)); + writer.WriteByte((byte)((value - 240) & 0xFF)); + return; + } + if (value <= 67823) + { + writer.WriteByte((byte)249); + writer.WriteByte((byte)((value - 2288) >> 8)); + writer.WriteByte((byte)((value - 2288) & 0xFF)); + return; + } + if (value <= 16777215) + { + writer.WriteByte((byte)250); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + return; + } + if (value <= 4294967295) + { + writer.WriteByte((byte)251); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + return; + } + if (value <= 1099511627775) + { + writer.WriteByte((byte)252); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + writer.WriteByte((byte)((value >> 32) & 0xFF)); + return; + } + if (value <= 281474976710655) + { + writer.WriteByte((byte)253); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + writer.WriteByte((byte)((value >> 32) & 0xFF)); + writer.WriteByte((byte)((value >> 40) & 0xFF)); + return; + } + if (value <= 72057594037927935) + { + writer.WriteByte((byte)254); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + writer.WriteByte((byte)((value >> 32) & 0xFF)); + writer.WriteByte((byte)((value >> 40) & 0xFF)); + writer.WriteByte((byte)((value >> 48) & 0xFF)); + return; + } + + // all others + { + writer.WriteByte((byte)255); + writer.WriteByte((byte)(value & 0xFF)); + writer.WriteByte((byte)((value >> 8) & 0xFF)); + writer.WriteByte((byte)((value >> 16) & 0xFF)); + writer.WriteByte((byte)((value >> 24) & 0xFF)); + writer.WriteByte((byte)((value >> 32) & 0xFF)); + writer.WriteByte((byte)((value >> 40) & 0xFF)); + writer.WriteByte((byte)((value >> 48) & 0xFF)); + writer.WriteByte((byte)((value >> 56) & 0xFF)); + } + */ + + // faster implementation writes multiple bytes at once. + // avoids extra Space, WriteBlittable overhead. + // VarInt is in hot path, performance matters here. + if (value <= 240) + { + byte a = (byte)value; + writer.WriteByte(a); + return; + } + if (value <= 2287) + { + byte a = (byte)(((value - 240) >> 8) + 241); + byte b = (byte)((value - 240) & 0xFF); + writer.WriteUShort((ushort)(b << 8 | a)); + return; + } + if (value <= 67823) + { + byte a = (byte)249; + byte b = (byte)((value - 2288) >> 8); + byte c = (byte)((value - 2288) & 0xFF); + writer.WriteByte(a); + writer.WriteUShort((ushort)(c << 8 | b)); + return; + } + if (value <= 16777215) + { + byte a = (byte)250; + uint b = (uint)(value << 8); + writer.WriteUInt(b | a); + return; + } + if (value <= 4294967295) + { + byte a = (byte)251; + uint b = (uint)value; + writer.WriteByte(a); + writer.WriteUInt(b); + return; + } + if (value <= 1099511627775) + { + byte a = (byte)252; + byte b = (byte)(value & 0xFF); + uint c = (uint)(value >> 8); + writer.WriteUShort((ushort)(b << 8 | a)); + writer.WriteUInt(c); + return; + } + if (value <= 281474976710655) + { + byte a = (byte)253; + byte b = (byte)(value & 0xFF); + byte c = (byte)((value >> 8) & 0xFF); + uint d = (uint)(value >> 16); + writer.WriteByte(a); + writer.WriteUShort((ushort)(c << 8 | b)); + writer.WriteUInt(d); + return; + } + if (value <= 72057594037927935) + { + byte a = 254; + ulong b = value << 8; + writer.WriteULong(b | a); + return; + } + + // all others + { + writer.WriteByte(255); + writer.WriteULong(value); + } + } + + // zigzag encoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CompressVarInt(NetworkWriter writer, long i) + { + ulong zigzagged = (ulong)((i >> 63) ^ (i << 1)); + CompressVarUInt(writer, zigzagged); + } + + // NOT an extension. otherwise weaver might accidentally use it. + public static ulong DecompressVarUInt(NetworkReader reader) + { + byte a0 = reader.ReadByte(); + if (a0 < 241) + { + return a0; + } + + byte a1 = reader.ReadByte(); + if (a0 <= 248) + { + return 240 + ((a0 - (ulong)241) << 8) + a1; + } + + byte a2 = reader.ReadByte(); + if (a0 == 249) + { + return 2288 + ((ulong)a1 << 8) + a2; + } + + byte a3 = reader.ReadByte(); + if (a0 == 250) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16); + } + + byte a4 = reader.ReadByte(); + if (a0 == 251) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24); + } + + byte a5 = reader.ReadByte(); + if (a0 == 252) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32); + } + + byte a6 = reader.ReadByte(); + if (a0 == 253) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32) + (((ulong)a6) << 40); + } + + byte a7 = reader.ReadByte(); + if (a0 == 254) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32) + (((ulong)a6) << 40) + (((ulong)a7) << 48); + } + + byte a8 = reader.ReadByte(); + if (a0 == 255) + { + return a1 + (((ulong)a2) << 8) + (((ulong)a3) << 16) + (((ulong)a4) << 24) + (((ulong)a5) << 32) + (((ulong)a6) << 40) + (((ulong)a7) << 48) + (((ulong)a8) << 56); + } + + throw new IndexOutOfRangeException($"DecompressVarInt failure: {a0}"); + } + + // zigzag decoding https://gist.github.com/mfuerstenau/ba870a29e16536fdbaba + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long DecompressVarInt(NetworkReader reader) + { + ulong data = DecompressVarUInt(reader); + return ((long)(data >> 1)) ^ -((long)data & 1); + } + } +} diff --git a/Assets/Mirror/Core/Tools/Compression.cs.meta b/Assets/Mirror/Core/Tools/Compression.cs.meta new file mode 100644 index 0000000..e35474b --- /dev/null +++ b/Assets/Mirror/Core/Tools/Compression.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c28963f9c4b97e418252a55500fb91e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools/DeltaCompression.cs b/Assets/Mirror/Core/Tools/DeltaCompression.cs new file mode 100644 index 0000000..a59370a --- /dev/null +++ b/Assets/Mirror/Core/Tools/DeltaCompression.cs @@ -0,0 +1,38 @@ +// manual delta compression for some types. +// varint(b-a) +// Mirror can't use Mirror II's bit-tree delta compression. +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class DeltaCompression + { + // delta (usually small), then zigzag varint to support +- changes + // parameter order: (last, current) makes most sense (Q3 does this too). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Compress(NetworkWriter writer, long last, long current) => + Compression.CompressVarInt(writer, current - last); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long Decompress(NetworkReader reader, long last) => + last + Compression.DecompressVarInt(reader); + + // delta (usually small), then zigzag varint to support +- changes + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Compress(NetworkWriter writer, Vector3Long last, Vector3Long current) + { + Compress(writer, last.x, current.x); + Compress(writer, last.y, current.y); + Compress(writer, last.z, current.z); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long Decompress(NetworkReader reader, Vector3Long last) + { + long x = Decompress(reader, last.x); + long y = Decompress(reader, last.y); + long z = Decompress(reader, last.z); + return new Vector3Long(x, y, z); + } + } +} diff --git a/Assets/Mirror/Core/Tools/DeltaCompression.cs.meta b/Assets/Mirror/Core/Tools/DeltaCompression.cs.meta new file mode 100644 index 0000000..a7b2c8b --- /dev/null +++ b/Assets/Mirror/Core/Tools/DeltaCompression.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b8f3fffcb4754c15bc5ed4c33e2497b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools/ExponentialMovingAverage.cs b/Assets/Mirror/Core/Tools/ExponentialMovingAverage.cs new file mode 100644 index 0000000..674abb8 --- /dev/null +++ b/Assets/Mirror/Core/Tools/ExponentialMovingAverage.cs @@ -0,0 +1,53 @@ +// N-day EMA implementation from Mirror with a few changes (struct etc.) +// it calculates an exponential moving average roughly equivalent to the last n observations +// https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average +using System; + +namespace Mirror +{ + public struct ExponentialMovingAverage + { + readonly double alpha; + bool initialized; + + public double Value; + public double Variance; + public double StandardDeviation; // absolute value, see test + + public ExponentialMovingAverage(int n) + { + // standard N-day EMA alpha calculation + alpha = 2.0 / (n + 1); + initialized = false; + Value = 0; + Variance = 0; + StandardDeviation = 0; + } + + public void Add(double newValue) + { + // simple algorithm for EMA described here: + // https://en.wikipedia.org/wiki/Moving_average#Exponentially_weighted_moving_variance_and_standard_deviation + if (initialized) + { + double delta = newValue - Value; + Value += alpha * delta; + Variance = (1 - alpha) * (Variance + alpha * delta * delta); + StandardDeviation = Math.Sqrt(Variance); + } + else + { + Value = newValue; + initialized = true; + } + } + + public void Reset() + { + initialized = false; + Value = 0; + Variance = 0; + StandardDeviation = 0; + } + } +} diff --git a/Assets/Mirror/Core/Tools/ExponentialMovingAverage.cs.meta b/Assets/Mirror/Core/Tools/ExponentialMovingAverage.cs.meta new file mode 100644 index 0000000..d0d8210 --- /dev/null +++ b/Assets/Mirror/Core/Tools/ExponentialMovingAverage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 05e858cbaa54b4ce4a48c8c7f50c1914 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools/Extensions.cs b/Assets/Mirror/Core/Tools/Extensions.cs new file mode 100644 index 0000000..02407e0 --- /dev/null +++ b/Assets/Mirror/Core/Tools/Extensions.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class Extensions + { + public static string ToHexString(this ArraySegment segment) => + BitConverter.ToString(segment.Array, segment.Offset, segment.Count); + + // string.GetHashCode is not guaranteed to be the same on all + // machines, but we need one that is the same on all machines. + // NOTE: Do not call this from hot path because it's slow O(N) for long method names. + // - As of 2012-02-16 There are 2 design-time callers (weaver) and 1 runtime caller that caches. + public static int GetStableHashCode(this string text) + { + unchecked + { + int hash = 23; + foreach (char c in text) + hash = hash * 31 + c; + + //UnityEngine.Debug.Log($"Created stable hash {(ushort)hash} for {text}"); + return hash; + } + } + + // previously in DotnetCompatibility.cs + // leftover from the UNET days. supposedly for windows store? + internal static string GetMethodName(this Delegate func) + { +#if NETFX_CORE + return func.GetMethodInfo().Name; +#else + return func.Method.Name; +#endif + } + + // helper function to copy to List + // C# only provides CopyTo(T[]) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CopyTo(this IEnumerable source, List destination) + { + // foreach allocates. use AddRange. + destination.AddRange(source); + } + +#if !UNITY_2021_OR_NEWER + // Unity 2020 and earlier doesn't have Queue.TryDequeue which we need for batching. + public static bool TryDequeue(this Queue source, out T element) + { + if (source.Count > 0) + { + element = source.Dequeue(); + return true; + } + + element = default; + return false; + } +#endif + } +} diff --git a/Assets/Mirror/Core/Tools/Extensions.cs.meta b/Assets/Mirror/Core/Tools/Extensions.cs.meta new file mode 100644 index 0000000..c2a18b7 --- /dev/null +++ b/Assets/Mirror/Core/Tools/Extensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: decf32fd053744d18f35712b7a6f5116 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools/Mathd.cs b/Assets/Mirror/Core/Tools/Mathd.cs new file mode 100644 index 0000000..374471a --- /dev/null +++ b/Assets/Mirror/Core/Tools/Mathd.cs @@ -0,0 +1,32 @@ +// 'double' precision variants for some of Unity's Mathf functions. +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public static class Mathd + { + // Unity 2020 doesn't have Math.Clamp yet. + /// Clamps value between 0 and 1 and returns value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double Clamp(double value, double min, double max) + { + if (value < min) return min; + if (value > max) return max; + return value; + } + + /// Clamps value between 0 and 1 and returns value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double Clamp01(double value) => Clamp(value, 0, 1); + + /// Calculates the linear parameter t that produces the interpolant value within the range [a, b]. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double InverseLerp(double a, double b, double value) => + a != b ? Clamp01((value - a) / (b - a)) : 0; + + /// Linearly interpolates between a and b by t with no limit to t. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double LerpUnclamped(double a, double b, double t) => + a + (b - a) * t; + } +} diff --git a/Assets/Mirror/Core/Tools/Mathd.cs.meta b/Assets/Mirror/Core/Tools/Mathd.cs.meta new file mode 100644 index 0000000..927c55a --- /dev/null +++ b/Assets/Mirror/Core/Tools/Mathd.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f74084b91c74df2839b426c4a381373 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools/Pool.cs b/Assets/Mirror/Core/Tools/Pool.cs new file mode 100644 index 0000000..e204575 --- /dev/null +++ b/Assets/Mirror/Core/Tools/Pool.cs @@ -0,0 +1,40 @@ +// Pool to avoid allocations (from libuv2k) +// API consistent with Microsoft's ObjectPool. +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public class Pool + { + // Mirror is single threaded, no need for concurrent collections. + // stack increases the chance that a reused writer remains in cache. + readonly Stack objects = new Stack(); + + // some types might need additional parameters in their constructor, so + // we use a Func generator + readonly Func objectGenerator; + + public Pool(Func objectGenerator, int initialCapacity) + { + this.objectGenerator = objectGenerator; + + // allocate an initial pool so we have fewer (if any) + // allocations in the first few frames (or seconds). + for (int i = 0; i < initialCapacity; ++i) + objects.Push(objectGenerator()); + } + + // take an element from the pool, or create a new one if empty + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T Get() => objects.Count > 0 ? objects.Pop() : objectGenerator(); + + // return an element to the pool + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Return(T item) => objects.Push(item); + + // count to see how many objects are in the pool. useful for tests. + public int Count => objects.Count; + } +} diff --git a/Assets/Mirror/Core/Tools/Pool.cs.meta b/Assets/Mirror/Core/Tools/Pool.cs.meta new file mode 100644 index 0000000..7d12a20 --- /dev/null +++ b/Assets/Mirror/Core/Tools/Pool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 845bb05fa349344c3811022f4f15dfbc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools/Readme.txt b/Assets/Mirror/Core/Tools/Readme.txt new file mode 100644 index 0000000..09bd920 --- /dev/null +++ b/Assets/Mirror/Core/Tools/Readme.txt @@ -0,0 +1 @@ +Standalone algorithms & structs to help build Mirror. \ No newline at end of file diff --git a/Assets/Mirror/Core/Tools/Readme.txt.meta b/Assets/Mirror/Core/Tools/Readme.txt.meta new file mode 100644 index 0000000..5536ca7 --- /dev/null +++ b/Assets/Mirror/Core/Tools/Readme.txt.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: da033671de7d49e0838223a997c56bf1 +timeCreated: 1667486850 \ No newline at end of file diff --git a/Assets/Mirror/Core/Tools/TimeSample.cs b/Assets/Mirror/Core/Tools/TimeSample.cs new file mode 100644 index 0000000..111e971 --- /dev/null +++ b/Assets/Mirror/Core/Tools/TimeSample.cs @@ -0,0 +1,61 @@ +// TimeSample from Mirror II. +// simple profiling sample, averaged for display in statistics. +// usable in builds without unitiy profiler overhead etc. +// +// .average may safely be called from main thread while Begin/End is in another. +// i.e. worker threads, transport, etc. +using System.Diagnostics; +using System.Threading; + +namespace Mirror +{ + public struct TimeSample + { + // UnityEngine.Time isn't thread safe. use stopwatch instead. + readonly Stopwatch watch; + + // remember when Begin was called + double beginTime; + + // keep accumulating times over the given interval. + // (not readonly. we modify its contents.) + ExponentialMovingAverage ema; + + // average in seconds. + // code often runs in sub-millisecond time. float is more precise. + // + // set with Interlocked for thread safety. + // can be read from main thread while sampling happens in other thread. + public double average; // THREAD SAFE + + // average over N begin/end captures + public TimeSample(int n) + { + watch = new Stopwatch(); + watch.Start(); + ema = new ExponentialMovingAverage(n); + beginTime = 0; + average = 0; + } + + // begin is called before the code to be sampled + public void Begin() + { + // remember when Begin was called. + // keep StopWatch running so we can average over the given interval. + beginTime = watch.Elapsed.TotalSeconds; + // Debug.Log($"Begin @ {beginTime:F4}"); + } + + // end is called after the code to be sampled + public void End() + { + // add duration in seconds to accumulated durations + double elapsed = watch.Elapsed.TotalSeconds - beginTime; + ema.Add(elapsed); + + // expose new average thread safely + Interlocked.Exchange(ref average, ema.Value); + } + } +} diff --git a/Assets/Mirror/Core/Tools/TimeSample.cs.meta b/Assets/Mirror/Core/Tools/TimeSample.cs.meta new file mode 100644 index 0000000..83e5ede --- /dev/null +++ b/Assets/Mirror/Core/Tools/TimeSample.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 26c32f6429554546a88d800c846c74ed +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools/Utils.cs b/Assets/Mirror/Core/Tools/Utils.cs new file mode 100644 index 0000000..2ed8dff --- /dev/null +++ b/Assets/Mirror/Core/Tools/Utils.cs @@ -0,0 +1,188 @@ +using System; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace Mirror +{ + // Handles network messages on client and server + public delegate void NetworkMessageDelegate(NetworkConnection conn, NetworkReader reader, int channelId); + + // Handles requests to spawn objects on the client + public delegate GameObject SpawnDelegate(Vector3 position, uint assetId); + + public delegate GameObject SpawnHandlerDelegate(SpawnMessage msg); + + // Handles requests to unspawn objects on the client + public delegate void UnSpawnDelegate(GameObject spawned); + + // channels are const ints instead of an enum so people can add their own + // channels (can't extend an enum otherwise). + // + // note that Mirror is slowly moving towards quake style networking which + // will only require reliable for handshake, and unreliable for the rest. + // so eventually we can change this to an Enum and transports shouldn't + // add custom channels anymore. + public static class Channels + { + public const int Reliable = 0; // ordered + public const int Unreliable = 1; // unordered + } + + public static class Utils + { + public static uint GetTrueRandomUInt() + { + // use Crypto RNG to avoid having time based duplicates + using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) + { + byte[] bytes = new byte[4]; + rng.GetBytes(bytes); + return BitConverter.ToUInt32(bytes, 0); + } + } + + public static bool IsPrefab(GameObject obj) + { +#if UNITY_EDITOR + return UnityEditor.PrefabUtility.IsPartOfPrefabAsset(obj); +#else + return false; +#endif + } + + // simplified IsSceneObject check from Mirror II + public static bool IsSceneObject(NetworkIdentity identity) + { + // original UNET / Mirror still had the IsPersistent check. + // it never fires though. even for Prefabs dragged to the Scene. + // (see Scene Objects example scene.) + // #if UNITY_EDITOR + // if (UnityEditor.EditorUtility.IsPersistent(identity.gameObject)) + // return false; + // #endif + + return identity.gameObject.hideFlags != HideFlags.NotEditable && + identity.gameObject.hideFlags != HideFlags.HideAndDontSave && + identity.sceneId != 0; + } + + public static bool IsSceneObjectWithPrefabParent(GameObject gameObject, out GameObject prefab) + { + prefab = null; + +#if UNITY_EDITOR + if (!UnityEditor.PrefabUtility.IsPartOfPrefabInstance(gameObject)) + { + return false; + } + prefab = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject); +#endif + + if (prefab == null) + { + Debug.LogError($"Failed to find prefab parent for scene object [name:{gameObject.name}]"); + return false; + } + return true; + } + + // is a 2D point in screen? (from ummorpg) + // (if width = 1024, then indices from 0..1023 are valid (=1024 indices) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsPointInScreen(Vector2 point) => + 0 <= point.x && point.x < Screen.width && + 0 <= point.y && point.y < Screen.height; + + // pretty print bytes as KB/MB/GB/etc. from DOTSNET + // long to support > 2GB + // divides by floats to return "2.5MB" etc. + public static string PrettyBytes(long bytes) + { + // bytes + if (bytes < 1024) + return $"{bytes} B"; + // kilobytes + else if (bytes < 1024L * 1024L) + return $"{(bytes / 1024f):F2} KB"; + // megabytes + else if (bytes < 1024 * 1024L * 1024L) + return $"{(bytes / (1024f * 1024f)):F2} MB"; + // gigabytes + return $"{(bytes / (1024f * 1024f * 1024f)):F2} GB"; + } + + // pretty print seconds as hours:minutes:seconds(.milliseconds/100)s. + // double for long running servers. + public static string PrettySeconds(double seconds) + { + TimeSpan t = TimeSpan.FromSeconds(seconds); + string res = ""; + if (t.Days > 0) res += $"{t.Days}d"; + if (t.Hours > 0) res += $"{(res.Length > 0 ? " " : "")}{t.Hours}h"; + if (t.Minutes > 0) res += $"{(res.Length > 0 ? " " : "")}{t.Minutes}m"; + // 0.5s, 1.5s etc. if any milliseconds. 1s, 2s etc. if any seconds + if (t.Milliseconds > 0) res += $"{(res.Length > 0 ? " " : "")}{t.Seconds}.{(t.Milliseconds / 100)}s"; + else if (t.Seconds > 0) res += $"{(res.Length > 0 ? " " : "")}{t.Seconds}s"; + // if the string is still empty because the value was '0', then at least + // return the seconds instead of returning an empty string + return res != "" ? res : "0s"; + } + + // universal .spawned function + public static NetworkIdentity GetSpawnedInServerOrClient(uint netId) + { + // server / host mode: use the one from server. + // host mode has access to all spawned. + if (NetworkServer.active) + { + NetworkServer.spawned.TryGetValue(netId, out NetworkIdentity entry); + return entry; + } + + // client + if (NetworkClient.active) + { + NetworkClient.spawned.TryGetValue(netId, out NetworkIdentity entry); + return entry; + } + + return null; + } + + // keep a GUI window in screen. + // for example. if it's at x=1000 and screen is resized to w=500, + // it won't get lost in the invisible area etc. + public static Rect KeepInScreen(Rect rect) + { + // ensure min + rect.x = Math.Max(rect.x, 0); + rect.y = Math.Max(rect.y, 0); + + // ensure max + rect.x = Math.Min(rect.x, Screen.width - rect.width); + rect.y = Math.Min(rect.y, Screen.width - rect.height); + + return rect; + } + + // create local connections pair and connect them + public static void CreateLocalConnections( + out LocalConnectionToClient connectionToClient, + out LocalConnectionToServer connectionToServer) + { + connectionToServer = new LocalConnectionToServer(); + connectionToClient = new LocalConnectionToClient(); + connectionToServer.connectionToClient = connectionToClient; + connectionToClient.connectionToServer = connectionToServer; + } + + public static bool IsSceneActive(string scene) + { + Scene activeScene = SceneManager.GetActiveScene(); + return activeScene.path == scene || + activeScene.name == scene; + } + } +} diff --git a/Assets/Mirror/Core/Tools/Utils.cs.meta b/Assets/Mirror/Core/Tools/Utils.cs.meta new file mode 100644 index 0000000..7cf1557 --- /dev/null +++ b/Assets/Mirror/Core/Tools/Utils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b530ce39098b54374a29ad308c8e4554 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Tools/Vector3Long.cs b/Assets/Mirror/Core/Tools/Vector3Long.cs new file mode 100644 index 0000000..d54a46c --- /dev/null +++ b/Assets/Mirror/Core/Tools/Vector3Long.cs @@ -0,0 +1,125 @@ +#pragma warning disable CS0659 // 'Vector3Long' overrides Object.Equals(object o) but does not override Object.GetHashCode() +#pragma warning disable CS0661 // 'Vector3Long' defines operator == or operator != but does not override Object.GetHashCode() + +// Vector3Long by mischa (based on game engine project) +using System; +using System.Runtime.CompilerServices; + +namespace Mirror +{ + public struct Vector3Long + { + public long x; + public long y; + public long z; + + public static readonly Vector3Long zero = new Vector3Long(0, 0, 0); + public static readonly Vector3Long one = new Vector3Long(1, 1, 1); + public static readonly Vector3Long forward = new Vector3Long(0, 0, 1); + public static readonly Vector3Long back = new Vector3Long(0, 0, -1); + public static readonly Vector3Long left = new Vector3Long(-1, 0, 0); + public static readonly Vector3Long right = new Vector3Long(1, 0, 0); + public static readonly Vector3Long up = new Vector3Long(0, 1, 0); + public static readonly Vector3Long down = new Vector3Long(0, -1, 0); + + // constructor ///////////////////////////////////////////////////////// + public Vector3Long(long x, long y, long z) + { + this.x = x; + this.y = y; + this.z = z; + } + + // operators /////////////////////////////////////////////////////////// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator +(Vector3Long a, Vector3Long b) => + new Vector3Long(a.x + b.x, a.y + b.y, a.z + b.z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator -(Vector3Long a, Vector3Long b) => + new Vector3Long(a.x - b.x, a.y - b.y, a.z - b.z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator -(Vector3Long v) => + new Vector3Long(-v.x, -v.y, -v.z); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator *(Vector3Long a, long n) => + new Vector3Long(a.x * n, a.y * n, a.z * n); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3Long operator *(long n, Vector3Long a) => + new Vector3Long(a.x * n, a.y * n, a.z * n); + + // == returns true if approximately equal (with epsilon). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator ==(Vector3Long a, Vector3Long b) => + a.x == b.x && + a.y == b.y && + a.z == b.z; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool operator !=(Vector3Long a, Vector3Long b) => !(a == b); + + // NO IMPLICIT System.Numerics.Vector3Long conversion because double<->float + // would silently lose precision in large worlds. + + // [i] component index. useful for iterating all components etc. + public long this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + switch (index) + { + case 0: return x; + case 1: return y; + case 2: return z; + default: throw new IndexOutOfRangeException($"Vector3Long[{index}] out of range."); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + switch (index) + { + case 0: + x = value; + break; + case 1: + y = value; + break; + case 2: + z = value; + break; + default: throw new IndexOutOfRangeException($"Vector3Long[{index}] out of range."); + } + } + } + + // instance functions ////////////////////////////////////////////////// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override string ToString() => $"({x} {y} {z})"; + + // equality //////////////////////////////////////////////////////////// + // implement Equals & HashCode explicitly for performance. + // calling .Equals (instead of "==") checks for exact equality. + // (API compatibility) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(Vector3Long other) => + x == other.x && y == other.y && z == other.z; + + // Equals(object) can reuse Equals(Vector4) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool Equals(object other) => + other is Vector3Long vector4 && Equals(vector4); + +#if UNITY_2021_3_OR_NEWER + // Unity 2019/2020 don't have HashCode.Combine yet. + // this is only to avoid reflection. without defining, it works too. + // default generated by rider + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int GetHashCode() => HashCode.Combine(x, y, z); +#endif + } +} diff --git a/Assets/Mirror/Core/Tools/Vector3Long.cs.meta b/Assets/Mirror/Core/Tools/Vector3Long.cs.meta new file mode 100644 index 0000000..2239765 --- /dev/null +++ b/Assets/Mirror/Core/Tools/Vector3Long.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 18efa4e349254185ad257401dd24628b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/Transport.cs b/Assets/Mirror/Core/Transport.cs new file mode 100644 index 0000000..7e0716d --- /dev/null +++ b/Assets/Mirror/Core/Transport.cs @@ -0,0 +1,191 @@ +// For future reference, here is what Transports need to do in Mirror: +// +// Connecting: +// * Transports are responsible to call either OnConnected || OnDisconnected +// in a certain time after a Connect was called. It can not end in limbo. +// +// Disconnecting: +// * Connections might disconnect voluntarily by the other end. +// * Connections might be disconnect involuntarily by the server. +// * Either way, Transports need to detect it and call OnDisconnected. +// +// Timeouts: +// * Transports should expose a configurable timeout +// * Transports are responsible for calling OnDisconnected after a timeout +// +// Channels: +// * Default channel is Reliable, as in reliable ordered (OR DISCONNECT) +// * Where possible, Unreliable should be supported (unordered, no guarantee) +// +// Other: +// * Transports functions are all bound to the main thread. +// (Transports can use other threads in the background if they manage them) +// * Transports should only process messages while the component is enabled. +// +using System; +using UnityEngine; + +namespace Mirror +{ + /// Abstract transport layer component + public abstract class Transport : MonoBehaviour + { + /// The current transport used by Mirror. + public static Transport active; + + /// Is this transport available in the current platform? + public abstract bool Available(); + + // client ////////////////////////////////////////////////////////////// + /// Called by Transport when the client connected to the server. + public Action OnClientConnected; + + /// Called by Transport when the client received a message from the server. + public Action, int> OnClientDataReceived; + + /// Called by Transport when the client sent a message to the server. + // Transports are responsible for calling it because: + // - groups it together with OnReceived responsibility + // - allows transports to decide if anything was sent or not + // - allows transports to decide the actual used channel (i.e. tcp always sending reliable) + public Action, int> OnClientDataSent; + + /// Called by Transport when the client encountered an error. + public Action OnClientError; + + /// Called by Transport when the client disconnected from the server. + public Action OnClientDisconnected; + + // server ////////////////////////////////////////////////////////////// + /// Called by Transport when a new client connected to the server. + public Action OnServerConnected; + + /// Called by Transport when the server received a message from a client. + public Action, int> OnServerDataReceived; + + /// Called by Transport when the server sent a message to a client. + // Transports are responsible for calling it because: + // - groups it together with OnReceived responsibility + // - allows transports to decide if anything was sent or not + // - allows transports to decide the actual used channel (i.e. tcp always sending reliable) + public Action, int> OnServerDataSent; + + /// Called by Transport when a server's connection encountered a problem. + /// If a Disconnect will also be raised, raise the Error first. + public Action OnServerError; + + /// Called by Transport when a client disconnected from the server. + public Action OnServerDisconnected; + + // client functions //////////////////////////////////////////////////// + /// True if the client is currently connected to the server. + public abstract bool ClientConnected(); + + /// Connects the client to the server at the address. + public abstract void ClientConnect(string address); + + /// Connects the client to the server at the Uri. + public virtual void ClientConnect(Uri uri) + { + // By default, to keep backwards compatibility, just connect to the host + // in the uri + ClientConnect(uri.Host); + } + + /// Sends a message to the server over the given channel. + // The ArraySegment is only valid until returning. Copy if needed. + public abstract void ClientSend(ArraySegment segment, int channelId = Channels.Reliable); + + /// Disconnects the client from the server + public abstract void ClientDisconnect(); + + // server functions //////////////////////////////////////////////////// + /// Returns server address as Uri. + // Useful for NetworkDiscovery. + public abstract Uri ServerUri(); + + /// True if the server is currently listening for connections. + public abstract bool ServerActive(); + + /// Start listening for connections. + public abstract void ServerStart(); + + /// Send a message to a client over the given channel. + public abstract void ServerSend(int connectionId, ArraySegment segment, int channelId = Channels.Reliable); + + /// Disconnect a client from the server. + public abstract void ServerDisconnect(int connectionId); + + /// Get a client's address on the server. + // Can be useful for Game Master IP bans etc. + public abstract string ServerGetClientAddress(int connectionId); + + /// Stop listening and disconnect all connections. + public abstract void ServerStop(); + + /// Maximum message size for the given channel. + // Different channels often have different sizes, ranging from MTU to + // several megabytes. + // + // Needs to return a value at all times, even if the Transport isn't + // running or available because it's needed for initializations. + public abstract int GetMaxPacketSize(int channelId = Channels.Reliable); + + /// Recommended Batching threshold for this transport. + // Uses GetMaxPacketSize by default. + // Some transports like kcp support large max packet sizes which should + // not be used for batching all the time because they end up being too + // slow (head of line blocking etc.). + public virtual int GetBatchThreshold(int channelId = Channels.Reliable) + { + return GetMaxPacketSize(channelId); + } + + // block Update & LateUpdate to show warnings if Transports still use + // them instead of using + // Client/ServerEarlyUpdate: to process incoming messages + // Client/ServerLateUpdate: to process outgoing messages + // those are called by NetworkClient/Server at the right time. + // + // allows transports to implement the proper network update order of: + // process_incoming() + // update_world() + // process_outgoing() + // + // => see NetworkLoop.cs for detailed explanations! +#pragma warning disable UNT0001 // Empty Unity message + public void Update() {} + public void LateUpdate() {} +#pragma warning restore UNT0001 // Empty Unity message + + /// + /// NetworkLoop NetworkEarly/LateUpdate were added for a proper network + /// update order. the goal is to: + /// process_incoming() + /// update_world() + /// process_outgoing() + /// in order to avoid unnecessary latency and data races. + /// + // => split into client and server parts so that we can cleanly call + // them from NetworkClient/Server + // => VIRTUAL for now so we can take our time to convert transports + // without breaking anything. + public virtual void ClientEarlyUpdate() {} + public virtual void ServerEarlyUpdate() {} + public virtual void ClientLateUpdate() {} + public virtual void ServerLateUpdate() {} + + /// Shut down the transport, both as client and server + public abstract void Shutdown(); + + /// Called by Unity when quitting. Inheriting Transports should call base for proper Shutdown. + public virtual void OnApplicationQuit() + { + // stop transport (e.g. to shut down threads) + // (when pressing Stop in the Editor, Unity keeps threads alive + // until we press Start again. so if Transports use threads, we + // really want them to end now and not after next start) + Shutdown(); + } + } +} diff --git a/Assets/Mirror/Core/Transport.cs.meta b/Assets/Mirror/Core/Transport.cs.meta new file mode 100644 index 0000000..55072e1 --- /dev/null +++ b/Assets/Mirror/Core/Transport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cfffcac25d6d64ced9de620159e221b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/TransportError.cs b/Assets/Mirror/Core/TransportError.cs new file mode 100644 index 0000000..b452015 --- /dev/null +++ b/Assets/Mirror/Core/TransportError.cs @@ -0,0 +1,17 @@ +// Mirror transport error code enum. +// most transport implementations should use a subset of this, +// and then translate the transport error codes to mirror error codes. +namespace Mirror +{ + public enum TransportError : byte + { + DnsResolve, // failed to resolve a host name + Refused, // connection refused by other end. server full etc. + Timeout, // ping timeout or dead link + Congestion, // more messages than transport / network can process + InvalidReceive, // recv invalid packet (possibly intentional attack) + InvalidSend, // user tried to send invalid data + ConnectionClosed, // connection closed voluntarily or lost involuntarily + Unexpected // unexpected error / exception, requires fix. + } +} diff --git a/Assets/Mirror/Core/TransportError.cs.meta b/Assets/Mirror/Core/TransportError.cs.meta new file mode 100644 index 0000000..d1d0fa0 --- /dev/null +++ b/Assets/Mirror/Core/TransportError.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ce162bdedd704db9b8c35d163f0c1d54 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Core/WeaverFuse.cs b/Assets/Mirror/Core/WeaverFuse.cs new file mode 100644 index 0000000..f850323 --- /dev/null +++ b/Assets/Mirror/Core/WeaverFuse.cs @@ -0,0 +1,22 @@ +// safety fuse for weaver to flip. +// runtime can check this to ensure weaving succeded. +// otherwise running server/client would give lots of random 'writer not found' etc. errors. +// this is much cleaner. +// +// note that ILPostProcessor errors already block entering playmode. +// however, issues could still stop the weaving from running at all. +// WeaverFuse can check if it actually ran. +namespace Mirror +{ + public static class WeaverFuse + { + // this trick only works for ILPostProcessor. + // CompilationFinishedHook can't weaver Mirror.dll. + public static bool Weaved() => +#if UNITY_2020_3_OR_NEWER + false; +#else + true; +#endif + } +} diff --git a/Assets/Mirror/Core/WeaverFuse.cs.meta b/Assets/Mirror/Core/WeaverFuse.cs.meta new file mode 100644 index 0000000..282920a --- /dev/null +++ b/Assets/Mirror/Core/WeaverFuse.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4de3dfbcbd2e41fcac947c04bcac52c9 +timeCreated: 1686319660 \ No newline at end of file diff --git a/Assets/Mirror/Editor.meta b/Assets/Mirror/Editor.meta new file mode 100644 index 0000000..f679511 --- /dev/null +++ b/Assets/Mirror/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2539267b6934a4026a505690a1e1eda2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/AndroidManifestHelper.cs b/Assets/Mirror/Editor/AndroidManifestHelper.cs new file mode 100644 index 0000000..c76359a --- /dev/null +++ b/Assets/Mirror/Editor/AndroidManifestHelper.cs @@ -0,0 +1,113 @@ +// Android NetworkDiscovery Multicast fix +// https://github.com/vis2k/Mirror/pull/2887 +using UnityEditor; +using UnityEngine; +using UnityEditor.Build; +using UnityEditor.Build.Reporting; +using System.Xml; +using System.IO; +#if UNITY_ANDROID +using UnityEditor.Android; +#endif + + +[InitializeOnLoad] +public class AndroidManifestHelper : IPreprocessBuildWithReport, IPostprocessBuildWithReport +#if UNITY_ANDROID + , IPostGenerateGradleAndroidProject +#endif +{ + public int callbackOrder { get { return 99999; } } + +#if UNITY_ANDROID + public void OnPostGenerateGradleAndroidProject(string path) + { + string manifestFolder = Path.Combine(path, "src/main"); + string sourceFile = manifestFolder + "/AndroidManifest.xml"; + // Load android manifest file + XmlDocument doc = new XmlDocument(); + doc.Load(sourceFile); + + string androidNamepsaceURI; + XmlElement element = (XmlElement)doc.SelectSingleNode("/manifest"); + if (element == null) + { + UnityEngine.Debug.LogError("Could not find manifest tag in android manifest."); + return; + } + + // Get android namespace URI from the manifest + androidNamepsaceURI = element.GetAttribute("xmlns:android"); + if (string.IsNullOrEmpty(androidNamepsaceURI)) + { + UnityEngine.Debug.LogError("Could not find Android Namespace in manifest."); + return; + } + AddOrRemoveTag(doc, + androidNamepsaceURI, + "/manifest", + "uses-permission", + "android.permission.CHANGE_WIFI_MULTICAST_STATE", + true, + false); + AddOrRemoveTag(doc, + androidNamepsaceURI, + "/manifest", + "uses-permission", + "android.permission.INTERNET", + true, + false); + doc.Save(sourceFile); + } +#endif + + static void AddOrRemoveTag(XmlDocument doc, string @namespace, string path, string elementName, string name, bool required, bool modifyIfFound, params string[] attrs) // name, value pairs + { + var nodes = doc.SelectNodes(path + "/" + elementName); + XmlElement element = null; + foreach (XmlElement e in nodes) + { + if (name == null || name == e.GetAttribute("name", @namespace)) + { + element = e; + break; + } + } + + if (required) + { + if (element == null) + { + var parent = doc.SelectSingleNode(path); + element = doc.CreateElement(elementName); + element.SetAttribute("name", @namespace, name); + parent.AppendChild(element); + } + + for (int i = 0; i < attrs.Length; i += 2) + { + if (modifyIfFound || string.IsNullOrEmpty(element.GetAttribute(attrs[i], @namespace))) + { + if (attrs[i + 1] != null) + { + element.SetAttribute(attrs[i], @namespace, attrs[i + 1]); + } + else + { + element.RemoveAttribute(attrs[i], @namespace); + } + } + } + } + else + { + if (element != null && modifyIfFound) + { + element.ParentNode.RemoveChild(element); + } + } + } + + public void OnPostprocessBuild(BuildReport report) {} + public void OnPreprocessBuild(BuildReport report) {} +} diff --git a/Assets/Mirror/Editor/AndroidManifestHelper.cs.meta b/Assets/Mirror/Editor/AndroidManifestHelper.cs.meta new file mode 100644 index 0000000..1281aea --- /dev/null +++ b/Assets/Mirror/Editor/AndroidManifestHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 80cc70189403d7444bbffd185ca28462 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/EditorHelper.cs b/Assets/Mirror/Editor/EditorHelper.cs new file mode 100644 index 0000000..b10c7b0 --- /dev/null +++ b/Assets/Mirror/Editor/EditorHelper.cs @@ -0,0 +1,31 @@ +using System.IO; +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + public static class EditorHelper + { + public static string FindPath() + { + string typeName = typeof(T).Name; + + string[] guidsFound = AssetDatabase.FindAssets($"t:Script {typeName}"); + if (guidsFound.Length >= 1 && !string.IsNullOrWhiteSpace(guidsFound[0])) + { + if (guidsFound.Length > 1) + { + Debug.LogWarning($"Found more than one{typeName}"); + } + + string path = AssetDatabase.GUIDToAssetPath(guidsFound[0]); + return Path.GetDirectoryName(path); + } + else + { + Debug.LogError($"Could not find path of {typeName}"); + return string.Empty; + } + } + } +} diff --git a/Assets/Mirror/Editor/EditorHelper.cs.meta b/Assets/Mirror/Editor/EditorHelper.cs.meta new file mode 100644 index 0000000..a1cd814 --- /dev/null +++ b/Assets/Mirror/Editor/EditorHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dba787f167ff29c4288532af1ec3584c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty.meta b/Assets/Mirror/Editor/Empty.meta new file mode 100644 index 0000000..ee87976 --- /dev/null +++ b/Assets/Mirror/Editor/Empty.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 62c8dc5bb12bbc6428bb66ccbac57000 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs b/Assets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs new file mode 100644 index 0000000..18ab111 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs @@ -0,0 +1 @@ +// removed 2021-12-12 diff --git a/Assets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs.meta b/Assets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs.meta new file mode 100644 index 0000000..79a200d --- /dev/null +++ b/Assets/Mirror/Editor/Empty/EnterPlayModeSettingsCheck.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b15a0d2ca0909400eb53dd6fe894cddd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty/LogLevelWindow.cs b/Assets/Mirror/Editor/Empty/LogLevelWindow.cs new file mode 100644 index 0000000..82e5275 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/LogLevelWindow.cs @@ -0,0 +1 @@ +// File moved to Mirror/Editor/Logging/LogLevelWindow.cs \ No newline at end of file diff --git a/Assets/Mirror/Editor/Empty/LogLevelWindow.cs.meta b/Assets/Mirror/Editor/Empty/LogLevelWindow.cs.meta new file mode 100644 index 0000000..b8cbaeb --- /dev/null +++ b/Assets/Mirror/Editor/Empty/LogLevelWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f28def2148ed5194abe70af012a4e3e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty/Logging.meta b/Assets/Mirror/Editor/Empty/Logging.meta new file mode 100644 index 0000000..257467f --- /dev/null +++ b/Assets/Mirror/Editor/Empty/Logging.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4d97731cd74ac8b4b8aad808548ef9cd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs b/Assets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs.meta b/Assets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs.meta new file mode 100644 index 0000000..832876f --- /dev/null +++ b/Assets/Mirror/Editor/Empty/Logging/LogLevelWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c3dbf48190d77d243b87962a82c3b164 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs b/Assets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs.meta b/Assets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs.meta new file mode 100644 index 0000000..3214b08 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/Logging/LogLevelsGUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d6ce9d62a2d2ec4d8cef8a0d22b8dd2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs b/Assets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs.meta b/Assets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs.meta new file mode 100644 index 0000000..2c1fac4 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/Logging/LogSettingsEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f4ecb3d81ce9ff44b91f311ee46d4ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs b/Assets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs.meta b/Assets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs.meta new file mode 100644 index 0000000..b4c277d --- /dev/null +++ b/Assets/Mirror/Editor/Empty/Logging/NetworkLogSettingsEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 37fb96d5bbf965d47acfc5c8589a1b71 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty/ScriptableObjectUtility.cs b/Assets/Mirror/Editor/Empty/ScriptableObjectUtility.cs new file mode 100644 index 0000000..39b95f7 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/ScriptableObjectUtility.cs @@ -0,0 +1 @@ +// removed 2021-02-16 diff --git a/Assets/Mirror/Editor/Empty/ScriptableObjectUtility.cs.meta b/Assets/Mirror/Editor/Empty/ScriptableObjectUtility.cs.meta new file mode 100644 index 0000000..a1a0af3 --- /dev/null +++ b/Assets/Mirror/Editor/Empty/ScriptableObjectUtility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d54a29ddd5b52b4eaa07ed39c0e3e83 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Empty/SyncVarDrawer.cs b/Assets/Mirror/Editor/Empty/SyncVarDrawer.cs new file mode 100644 index 0000000..aaa3b9d --- /dev/null +++ b/Assets/Mirror/Editor/Empty/SyncVarDrawer.cs @@ -0,0 +1 @@ +// removed 2022-11-03 diff --git a/Assets/Mirror/Editor/Empty/SyncVarDrawer.cs.meta b/Assets/Mirror/Editor/Empty/SyncVarDrawer.cs.meta new file mode 100644 index 0000000..0ee91aa --- /dev/null +++ b/Assets/Mirror/Editor/Empty/SyncVarDrawer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 874812594431423b84f763b987ff9681 +timeCreated: 1632553007 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Icon.meta b/Assets/Mirror/Editor/Icon.meta new file mode 100644 index 0000000..7338187 --- /dev/null +++ b/Assets/Mirror/Editor/Icon.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b5f1356ad059a1243910a4e82cd68c5f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Icon/MirrorIcon.png b/Assets/Mirror/Editor/Icon/MirrorIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..1be896157a63edfe96735948eeb145381697d551 GIT binary patch literal 138247 zcmV(;K-<5GP)DP*7-ZbZ>KLZ*U+1wS zIWubl&Q%31NtvJmA*ETsC=CJK?JnEG+HSTj(#Ax$)3du{r?cak+42*vh>6AK$qG-F$t-cfv#E0^q)q^) zU9U_->Lk!R6~k+>IO+j_u7dQWa%`(y$XX@Us5-8UwflhW|G8$}=AzzOU}Z2fx)<08 ziPxqpxxGLiBu?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YBvo$-GGx4rwDUiOQc4BOrG1Jo2jAuk*F1#xyS6BXQ zP$)uFZ1ZKmo2*bV;%sDl@|Rm*+^KbY)R`skiUERS7dW~FzL1;e)I`jm#kSK_KOcbY zGVd(fDKa=sJ@hZWH(K{j4L@CWj#sb2I8*Uh3jvqC>;*B2)gKoh+gxl{r8-!d`I;W0 z^fpK$aifRvamc&V;lk6Z{W+oq%{H@lXuYuGX#h2-8eqTdS@LJMcYIf6yb6J|Ya`78 z`zFPap~Mr-%G}4foK-HPbnTD@?laNOlp)jNNV&q(ZoDdNf#MFus`!^J_{$j+JPu6M zWp8q3RP)wd!S@z?UrZjI`h}HVP^{0-(g5ksyFj$=bQPTYUQiItqvDLP&1>!giEusZ zc3zeOd*0sN-|drSo0{5?WEtC?nHGets all public and private fields for a type + // deepestBaseType: Stops at this base type (exclusive) + public static IEnumerable GetAllFields(Type type, Type deepestBaseType) + { + const BindingFlags publicFields = BindingFlags.Public | BindingFlags.Instance; + const BindingFlags privateFields = BindingFlags.NonPublic | BindingFlags.Instance; + + // get public fields (includes fields from base type) + FieldInfo[] allPublicFields = type.GetFields(publicFields); + foreach (FieldInfo field in allPublicFields) + { + yield return field; + } + + // get private fields in current type, then move to base type + while (type != null) + { + FieldInfo[] allPrivateFields = type.GetFields(privateFields); + foreach (FieldInfo field in allPrivateFields) + { + yield return field; + } + + type = type.BaseType; + + // stop early + if (type == deepestBaseType) + { + break; + } + } + } + + public static bool IsSyncVar(this FieldInfo field) + { + object[] fieldMarkers = field.GetCustomAttributes(typeof(SyncVarAttribute), true); + return fieldMarkers.Length > 0; + } + + public static bool IsSerializeField(this FieldInfo field) + { + object[] fieldMarkers = field.GetCustomAttributes(typeof(SerializeField), true); + return fieldMarkers.Length > 0; + } + + public static bool IsVisibleField(this FieldInfo field) + { + return field.IsPublic || IsSerializeField(field); + } + + public static bool ImplementsInterface(this FieldInfo field) + { + return typeof(T).IsAssignableFrom(field.FieldType); + } + + public static bool HasShowInInspector(this FieldInfo field) + { + object[] fieldMarkers = field.GetCustomAttributes(typeof(ShowInInspectorAttribute), true); + return fieldMarkers.Length > 0; + } + + // checks if SyncObject is public or has our custom [ShowInInspector] field + public static bool IsVisibleSyncObject(this FieldInfo field) + { + return field.IsPublic || HasShowInInspector(field); + } + } +} diff --git a/Assets/Mirror/Editor/InspectorHelper.cs.meta b/Assets/Mirror/Editor/InspectorHelper.cs.meta new file mode 100644 index 0000000..852ff71 --- /dev/null +++ b/Assets/Mirror/Editor/InspectorHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 047c894c2a5ccc1438b7e59302f62744 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Mirror.Editor.asmdef b/Assets/Mirror/Editor/Mirror.Editor.asmdef new file mode 100644 index 0000000..651b8fe --- /dev/null +++ b/Assets/Mirror/Editor/Mirror.Editor.asmdef @@ -0,0 +1,19 @@ +{ + "name": "Mirror.Editor", + "rootNamespace": "", + "references": [ + "GUID:30817c1a0e6d646d99c048fc403f5979", + "GUID:1d0b9d21c3ff546a4aa32399dfd33474" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Mirror/Editor/Mirror.Editor.asmdef.meta b/Assets/Mirror/Editor/Mirror.Editor.asmdef.meta new file mode 100644 index 0000000..e2e6f2a --- /dev/null +++ b/Assets/Mirror/Editor/Mirror.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1c7c33eb5480dd24c9e29a8250c1a775 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/NetworkBehaviourInspector.cs b/Assets/Mirror/Editor/NetworkBehaviourInspector.cs new file mode 100644 index 0000000..52c56d6 --- /dev/null +++ b/Assets/Mirror/Editor/NetworkBehaviourInspector.cs @@ -0,0 +1,104 @@ +using System; +using System.Reflection; +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + [CustomEditor(typeof(NetworkBehaviour), true)] + [CanEditMultipleObjects] + public class NetworkBehaviourInspector : Editor + { + bool syncsAnything; + SyncObjectCollectionsDrawer syncObjectCollectionsDrawer; + + // does this type sync anything? otherwise we don't need to show syncInterval + bool SyncsAnything(Type scriptClass) + { + // check for all SyncVar fields, they don't have to be visible + foreach (FieldInfo field in InspectorHelper.GetAllFields(scriptClass, typeof(NetworkBehaviour))) + { + if (field.IsSyncVar()) + { + return true; + } + } + + // has OnSerialize that is not in NetworkBehaviour? + // then it either has a syncvar or custom OnSerialize. either way + // this means we have something to sync. + MethodInfo method = scriptClass.GetMethod("OnSerialize"); + if (method != null && method.DeclaringType != typeof(NetworkBehaviour)) + { + return true; + } + + // SyncObjects are serialized in NetworkBehaviour.OnSerialize, which + // is always there even if we don't use SyncObjects. so we need to + // search for SyncObjects manually. + // Any SyncObject should be added to syncObjects when unity creates an + // object so we can check length of list so see if sync objects exists + return ((NetworkBehaviour)serializedObject.targetObject).HasSyncObjects(); + } + + void OnEnable() + { + // sometimes target is null. just return early. + if (target == null) return; + + // If target's base class is changed from NetworkBehaviour to MonoBehaviour + // then Unity temporarily keep using this Inspector causing things to break + if (!(target is NetworkBehaviour)) { return; } + + Type scriptClass = target.GetType(); + + syncObjectCollectionsDrawer = new SyncObjectCollectionsDrawer(serializedObject.targetObject); + + syncsAnything = SyncsAnything(scriptClass); + } + + public override void OnInspectorGUI() + { + DrawDefaultInspector(); + DrawSyncObjectCollections(); + DrawDefaultSyncSettings(); + } + + // Draws Sync Objects that are IEnumerable + protected void DrawSyncObjectCollections() + { + // Need this check in case OnEnable returns early + if (syncObjectCollectionsDrawer == null) return; + + syncObjectCollectionsDrawer.Draw(); + } + + // Draws SyncSettings if the NetworkBehaviour has anything to sync + protected void DrawDefaultSyncSettings() + { + // does it sync anything? then show extra properties + // (no need to show it if the class only has Cmds/Rpcs and no sync) + if (!syncsAnything) + { + return; + } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Sync Settings", EditorStyles.boldLabel); + + // sync direction + SerializedProperty syncDirection = serializedObject.FindProperty("syncDirection"); + EditorGUILayout.PropertyField(syncDirection); + + // sync mdoe: only show for ServerToClient components + if (syncDirection.enumValueIndex == (int)SyncDirection.ServerToClient) + EditorGUILayout.PropertyField(serializedObject.FindProperty("syncMode")); + + // sync interval + EditorGUILayout.PropertyField(serializedObject.FindProperty("syncInterval")); + + // apply + serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/Assets/Mirror/Editor/NetworkBehaviourInspector.cs.meta b/Assets/Mirror/Editor/NetworkBehaviourInspector.cs.meta new file mode 100644 index 0000000..78d9fa8 --- /dev/null +++ b/Assets/Mirror/Editor/NetworkBehaviourInspector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f02853db46b6346e4866594a96c3b0e7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/NetworkInformationPreview.cs b/Assets/Mirror/Editor/NetworkInformationPreview.cs new file mode 100644 index 0000000..ec0a01e --- /dev/null +++ b/Assets/Mirror/Editor/NetworkInformationPreview.cs @@ -0,0 +1,305 @@ +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + [CustomPreview(typeof(GameObject))] + class NetworkInformationPreview : ObjectPreview + { + struct NetworkIdentityInfo + { + public GUIContent name; + public GUIContent value; + } + + struct NetworkBehaviourInfo + { + // This is here just so we can check if it's enabled/disabled + public NetworkBehaviour behaviour; + public GUIContent name; + } + + class Styles + { + public GUIStyle labelStyle = new GUIStyle(EditorStyles.label); + public GUIStyle componentName = new GUIStyle(EditorStyles.boldLabel); + public GUIStyle disabledName = new GUIStyle(EditorStyles.miniLabel); + + public Styles() + { + Color fontColor = new Color(0.7f, 0.7f, 0.7f); + labelStyle.padding.right += 20; + labelStyle.normal.textColor = fontColor; + labelStyle.active.textColor = fontColor; + labelStyle.focused.textColor = fontColor; + labelStyle.hover.textColor = fontColor; + labelStyle.onNormal.textColor = fontColor; + labelStyle.onActive.textColor = fontColor; + labelStyle.onFocused.textColor = fontColor; + labelStyle.onHover.textColor = fontColor; + + componentName.normal.textColor = fontColor; + componentName.active.textColor = fontColor; + componentName.focused.textColor = fontColor; + componentName.hover.textColor = fontColor; + componentName.onNormal.textColor = fontColor; + componentName.onActive.textColor = fontColor; + componentName.onFocused.textColor = fontColor; + componentName.onHover.textColor = fontColor; + + disabledName.normal.textColor = fontColor; + disabledName.active.textColor = fontColor; + disabledName.focused.textColor = fontColor; + disabledName.hover.textColor = fontColor; + disabledName.onNormal.textColor = fontColor; + disabledName.onActive.textColor = fontColor; + disabledName.onFocused.textColor = fontColor; + disabledName.onHover.textColor = fontColor; + } + } + + GUIContent title; + Styles styles = new Styles(); + + public override GUIContent GetPreviewTitle() + { + if (title == null) + { + title = new GUIContent("Network Information"); + } + return title; + } + + public override bool HasPreviewGUI() + { + // need to check if target is null to stop MissingReferenceException + return target != null && target is GameObject gameObject && gameObject.GetComponent() != null; + } + + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (Event.current.type != EventType.Repaint) + return; + + if (target == null) + return; + + GameObject targetGameObject = target as GameObject; + + if (targetGameObject == null) + return; + + NetworkIdentity identity = targetGameObject.GetComponent(); + + if (identity == null) + return; + + if (styles == null) + styles = new Styles(); + + + // padding + RectOffset previewPadding = new RectOffset(-5, -5, -5, -5); + Rect paddedr = previewPadding.Add(r); + + //Centering + float initialX = paddedr.x + 10; + float Y = paddedr.y + 10; + + Y = DrawNetworkIdentityInfo(identity, initialX, Y); + + Y = DrawNetworkBehaviors(identity, initialX, Y); + + Y = DrawObservers(identity, initialX, Y); + + _ = DrawOwner(identity, initialX, Y); + + } + + float DrawNetworkIdentityInfo(NetworkIdentity identity, float initialX, float Y) + { + IEnumerable infos = GetNetworkIdentityInfo(identity); + // Get required label size for the names of the information values we're going to show + // There are two columns, one with label for the name of the info and the next for the value + Vector2 maxNameLabelSize = new Vector2(140, 16); + Vector2 maxValueLabelSize = GetMaxNameLabelSize(infos); + + Rect labelRect = new Rect(initialX, Y, maxNameLabelSize.x, maxNameLabelSize.y); + Rect idLabelRect = new Rect(maxNameLabelSize.x, Y, maxValueLabelSize.x, maxValueLabelSize.y); + + foreach (NetworkIdentityInfo info in infos) + { + GUI.Label(labelRect, info.name, styles.labelStyle); + GUI.Label(idLabelRect, info.value, styles.componentName); + labelRect.y += labelRect.height; + labelRect.x = initialX; + idLabelRect.y += idLabelRect.height; + } + + return labelRect.y; + } + + float DrawNetworkBehaviors(NetworkIdentity identity, float initialX, float Y) + { + IEnumerable behavioursInfo = GetNetworkBehaviorInfo(identity); + + // Show behaviours list in a different way than the name/value pairs above + Vector2 maxBehaviourLabelSize = GetMaxBehaviourLabelSize(behavioursInfo); + Rect behaviourRect = new Rect(initialX, Y + 10, maxBehaviourLabelSize.x, maxBehaviourLabelSize.y); + + GUI.Label(behaviourRect, new GUIContent("Network Behaviours"), styles.labelStyle); + // indent names + behaviourRect.x += 20; + behaviourRect.y += behaviourRect.height; + + foreach (NetworkBehaviourInfo info in behavioursInfo) + { + if (info.behaviour == null) + { + // could be the case in the editor after existing play mode. + continue; + } + + GUI.Label(behaviourRect, info.name, info.behaviour.enabled ? styles.componentName : styles.disabledName); + behaviourRect.y += behaviourRect.height; + Y = behaviourRect.y; + } + + return Y; + } + + float DrawObservers(NetworkIdentity identity, float initialX, float Y) + { + if (identity.observers.Count > 0) + { + Rect observerRect = new Rect(initialX, Y + 10, 200, 20); + + GUI.Label(observerRect, new GUIContent("Network observers"), styles.labelStyle); + // indent names + observerRect.x += 20; + observerRect.y += observerRect.height; + + foreach (KeyValuePair kvp in identity.observers) + { + GUI.Label(observerRect, $"{kvp.Value.address}:{kvp.Value}", styles.componentName); + observerRect.y += observerRect.height; + Y = observerRect.y; + } + } + + return Y; + } + + float DrawOwner(NetworkIdentity identity, float initialX, float Y) + { + if (identity.connectionToClient != null) + { + Rect ownerRect = new Rect(initialX, Y + 10, 400, 20); + GUI.Label(ownerRect, new GUIContent($"Client Authority: {identity.connectionToClient}"), styles.labelStyle); + Y += ownerRect.height; + } + return Y; + } + + // Get the maximum size used by the value of information items + Vector2 GetMaxNameLabelSize(IEnumerable infos) + { + Vector2 maxLabelSize = Vector2.zero; + foreach (NetworkIdentityInfo info in infos) + { + Vector2 labelSize = styles.labelStyle.CalcSize(info.value); + if (maxLabelSize.x < labelSize.x) + { + maxLabelSize.x = labelSize.x; + } + if (maxLabelSize.y < labelSize.y) + { + maxLabelSize.y = labelSize.y; + } + } + return maxLabelSize; + } + + Vector2 GetMaxBehaviourLabelSize(IEnumerable behavioursInfo) + { + Vector2 maxLabelSize = Vector2.zero; + foreach (NetworkBehaviourInfo behaviour in behavioursInfo) + { + Vector2 labelSize = styles.labelStyle.CalcSize(behaviour.name); + if (maxLabelSize.x < labelSize.x) + { + maxLabelSize.x = labelSize.x; + } + if (maxLabelSize.y < labelSize.y) + { + maxLabelSize.y = labelSize.y; + } + } + return maxLabelSize; + } + + IEnumerable GetNetworkIdentityInfo(NetworkIdentity identity) + { + List infos = new List + { + GetAssetId(identity), + GetString("Scene ID", identity.sceneId.ToString("X")) + }; + + if (Application.isPlaying) + { + infos.Add(GetString("Network ID", identity.netId.ToString())); + infos.Add(GetBoolean("Is Client", identity.isClient)); + infos.Add(GetBoolean("Is Server", identity.isServer)); + infos.Add(GetBoolean("Is Owned", identity.isOwned)); + infos.Add(GetBoolean("Is Local Player", identity.isLocalPlayer)); + } + return infos; + } + + IEnumerable GetNetworkBehaviorInfo(NetworkIdentity identity) + { + List behaviourInfos = new List(); + + NetworkBehaviour[] behaviours = identity.GetComponents(); + foreach (NetworkBehaviour behaviour in behaviours) + { + behaviourInfos.Add(new NetworkBehaviourInfo + { + name = new GUIContent(behaviour.GetType().FullName), + behaviour = behaviour + }); + } + return behaviourInfos; + } + + NetworkIdentityInfo GetAssetId(NetworkIdentity identity) + { + string assetId = identity.assetId.ToString(); + if (string.IsNullOrWhiteSpace(assetId)) + { + assetId = ""; + } + return GetString("Asset ID", assetId); + } + + static NetworkIdentityInfo GetString(string name, string value) + { + return new NetworkIdentityInfo + { + name = new GUIContent(name), + value = new GUIContent(value) + }; + } + + static NetworkIdentityInfo GetBoolean(string name, bool value) + { + return new NetworkIdentityInfo + { + name = new GUIContent(name), + value = new GUIContent((value ? "Yes" : "No")) + }; + } + } +} diff --git a/Assets/Mirror/Editor/NetworkInformationPreview.cs.meta b/Assets/Mirror/Editor/NetworkInformationPreview.cs.meta new file mode 100644 index 0000000..9bf2de4 --- /dev/null +++ b/Assets/Mirror/Editor/NetworkInformationPreview.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 51a99294efe134232932c34606737356 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/NetworkManagerEditor.cs b/Assets/Mirror/Editor/NetworkManagerEditor.cs new file mode 100644 index 0000000..94b0844 --- /dev/null +++ b/Assets/Mirror/Editor/NetworkManagerEditor.cs @@ -0,0 +1,108 @@ +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; + +namespace Mirror +{ + [CustomEditor(typeof(NetworkManager), true)] + [CanEditMultipleObjects] + public class NetworkManagerEditor : Editor + { + SerializedProperty spawnListProperty; + ReorderableList spawnList; + protected NetworkManager networkManager; + + protected void Init() + { + if (spawnList == null) + { + networkManager = target as NetworkManager; + spawnListProperty = serializedObject.FindProperty("spawnPrefabs"); + spawnList = new ReorderableList(serializedObject, spawnListProperty) + { + drawHeaderCallback = DrawHeader, + drawElementCallback = DrawChild, + onReorderCallback = Changed, + onRemoveCallback = RemoveButton, + onChangedCallback = Changed, + onAddCallback = AddButton, + // this uses a 16x16 icon. other sizes make it stretch. + elementHeight = 16 + }; + } + } + + public override void OnInspectorGUI() + { + Init(); + DrawDefaultInspector(); + EditorGUI.BeginChangeCheck(); + spawnList.DoLayoutList(); + if (EditorGUI.EndChangeCheck()) + { + serializedObject.ApplyModifiedProperties(); + } + } + + static void DrawHeader(Rect headerRect) + { + GUI.Label(headerRect, "Registered Spawnable Prefabs:"); + } + + internal void DrawChild(Rect r, int index, bool isActive, bool isFocused) + { + SerializedProperty prefab = spawnListProperty.GetArrayElementAtIndex(index); + GameObject go = (GameObject)prefab.objectReferenceValue; + + GUIContent label; + if (go == null) + { + label = new GUIContent("Empty", "Drag a prefab with a NetworkIdentity here"); + } + else + { + NetworkIdentity identity = go.GetComponent(); + label = new GUIContent(go.name, identity != null ? $"AssetId: [{identity.assetId}]" : "No Network Identity"); + } + + GameObject newGameObject = (GameObject)EditorGUI.ObjectField(r, label, go, typeof(GameObject), false); + + if (newGameObject != go) + { + if (newGameObject != null && !newGameObject.GetComponent()) + { + Debug.LogError($"Prefab {newGameObject} cannot be added as spawnable as it doesn't have a NetworkIdentity."); + return; + } + prefab.objectReferenceValue = newGameObject; + } + } + + internal void Changed(ReorderableList list) + { + EditorUtility.SetDirty(target); + } + + internal void AddButton(ReorderableList list) + { + spawnListProperty.arraySize += 1; + list.index = spawnListProperty.arraySize - 1; + + SerializedProperty obj = spawnListProperty.GetArrayElementAtIndex(spawnListProperty.arraySize - 1); + obj.objectReferenceValue = null; + + spawnList.index = spawnList.count - 1; + + Changed(list); + } + + internal void RemoveButton(ReorderableList list) + { + spawnListProperty.DeleteArrayElementAtIndex(spawnList.index); + if (list.index >= spawnListProperty.arraySize) + { + list.index = spawnListProperty.arraySize - 1; + } + } + } +} diff --git a/Assets/Mirror/Editor/NetworkManagerEditor.cs.meta b/Assets/Mirror/Editor/NetworkManagerEditor.cs.meta new file mode 100644 index 0000000..7fe8dbc --- /dev/null +++ b/Assets/Mirror/Editor/NetworkManagerEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 519712eb07f7a44039df57664811c2c5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/NetworkScenePostProcess.cs b/Assets/Mirror/Editor/NetworkScenePostProcess.cs new file mode 100644 index 0000000..2fa07d6 --- /dev/null +++ b/Assets/Mirror/Editor/NetworkScenePostProcess.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEditor.Callbacks; +using UnityEngine; + +namespace Mirror +{ + public class NetworkScenePostProcess : MonoBehaviour + { + [PostProcessScene] + public static void OnPostProcessScene() + { + // find all NetworkIdentities in all scenes + // => can't limit it to GetActiveScene() because that wouldn't work + // for additive scene loads (the additively loaded scene is never + // the active scene) + // => ignore DontDestroyOnLoad scene! this avoids weird situations + // like in NetworkZones when we destroy the local player and + // load another scene afterwards, yet the local player is still + // in the FindObjectsOfType result with scene=DontDestroyOnLoad + // for some reason + // => OfTypeAll so disabled objects are included too + // => Unity 2019 returns prefabs here too, so filter them out. + IEnumerable identities = Resources.FindObjectsOfTypeAll() + .Where(identity => identity.gameObject.hideFlags != HideFlags.NotEditable && + identity.gameObject.hideFlags != HideFlags.HideAndDontSave && + identity.gameObject.scene.name != "DontDestroyOnLoad" && + !Utils.IsPrefab(identity.gameObject)); + + foreach (NetworkIdentity identity in identities) + { + // if we had a [ConflictComponent] attribute that would be better than this check. + // also there is no context about which scene this is in. + if (identity.GetComponent() != null) + Debug.LogError("NetworkManager has a NetworkIdentity component. This will cause the NetworkManager object to be disabled, so it is not recommended."); + + // not spawned before? + // OnPostProcessScene is called after additive scene loads too, + // and we don't want to set main scene's objects inactive again + if (!identity.isClient && !identity.isServer) + { + // valid scene object? + // otherwise it might be an unopened scene that still has null + // sceneIds. builds are interrupted if they contain 0 sceneIds, + // but it's still possible that we call LoadScene in Editor + // for a previously unopened scene. + // (and only do SetActive if this was actually a scene object) + if (identity.sceneId != 0) + { + PrepareSceneObject(identity); + } + // throwing an exception would only show it for one object + // because this function would return afterwards. + else + { + // there are two cases where sceneId == 0: + // * if we have a prefab open in the prefab scene + // * if an unopened scene needs resaving + // show a proper error message in both cases so the user + // knows what to do. + string path = identity.gameObject.scene.path; + if (string.IsNullOrWhiteSpace(path)) + Debug.LogError($"{identity.name} is currently open in Prefab Edit Mode. Please open the actual scene before launching Mirror."); + else + Debug.LogError($"Scene {path} needs to be opened and resaved, because the scene object {identity.name} has no valid sceneId yet."); + + // either way we shouldn't continue. nothing good will + // happen when trying to launch with invalid sceneIds. + EditorApplication.isPlaying = false; + } + } + } + } + + static void PrepareSceneObject(NetworkIdentity identity) + { + // set scene hash + identity.SetSceneIdSceneHashPartInternal(); + + // spawnable scene objects are force disabled on scene load to + // ensure Start/Update/etc. aren't called until actually spawned. + // + // note: NetworkIdentity.OnDisable adds itself to the + // spawnableObjects dictionary (only if sceneId != 0) + identity.gameObject.SetActive(false); + + // safety check for prefabs with more than one NetworkIdentity + GameObject prefabGO = PrefabUtility.GetCorrespondingObjectFromSource(identity.gameObject); + if (prefabGO) + { + GameObject prefabRootGO = prefabGO.transform.root.gameObject; + if (prefabRootGO != null && prefabRootGO.GetComponentsInChildren().Length > 1) + Debug.LogWarning($"Prefab {prefabRootGO.name} has several NetworkIdentity components attached to itself or its children, this is not supported."); + } + } + } +} diff --git a/Assets/Mirror/Editor/NetworkScenePostProcess.cs.meta b/Assets/Mirror/Editor/NetworkScenePostProcess.cs.meta new file mode 100644 index 0000000..b567cc9 --- /dev/null +++ b/Assets/Mirror/Editor/NetworkScenePostProcess.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a3ec1c414d821444a9e77f18a2c130ea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/SceneDrawer.cs b/Assets/Mirror/Editor/SceneDrawer.cs new file mode 100644 index 0000000..f391684 --- /dev/null +++ b/Assets/Mirror/Editor/SceneDrawer.cs @@ -0,0 +1,47 @@ +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + [CustomPropertyDrawer(typeof(SceneAttribute))] + public class SceneDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + if (property.propertyType == SerializedPropertyType.String) + { + SceneAsset sceneObject = AssetDatabase.LoadAssetAtPath(property.stringValue); + + if (sceneObject == null && !string.IsNullOrWhiteSpace(property.stringValue)) + { + // try to load it from the build settings for legacy compatibility + sceneObject = GetBuildSettingsSceneObject(property.stringValue); + } + if (sceneObject == null && !string.IsNullOrWhiteSpace(property.stringValue)) + { + Debug.LogError($"Could not find scene {property.stringValue} in {property.propertyPath}, assign the proper scenes in your NetworkManager"); + } + SceneAsset scene = (SceneAsset)EditorGUI.ObjectField(position, label, sceneObject, typeof(SceneAsset), true); + + property.stringValue = AssetDatabase.GetAssetPath(scene); + } + else + { + EditorGUI.LabelField(position, label.text, "Use [Scene] with strings."); + } + } + + protected SceneAsset GetBuildSettingsSceneObject(string sceneName) + { + foreach (EditorBuildSettingsScene buildScene in EditorBuildSettings.scenes) + { + SceneAsset sceneAsset = AssetDatabase.LoadAssetAtPath(buildScene.path); + if (sceneAsset!= null && sceneAsset.name == sceneName) + { + return sceneAsset; + } + } + return null; + } + } +} diff --git a/Assets/Mirror/Editor/SceneDrawer.cs.meta b/Assets/Mirror/Editor/SceneDrawer.cs.meta new file mode 100644 index 0000000..6a996dc --- /dev/null +++ b/Assets/Mirror/Editor/SceneDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b24704a46211b4ea294aba8f58715cea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/SyncObjectCollectionsDrawer.cs b/Assets/Mirror/Editor/SyncObjectCollectionsDrawer.cs new file mode 100644 index 0000000..2c95bcf --- /dev/null +++ b/Assets/Mirror/Editor/SyncObjectCollectionsDrawer.cs @@ -0,0 +1,83 @@ +// helper class for NetworkBehaviourInspector to draw all enumerable SyncObjects +// (SyncList/Set/Dictionary) +// 'SyncObjectCollectionsDrawer' is a nicer name than 'IEnumerableSyncObjectsDrawer' +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using UnityEditor; + +namespace Mirror +{ + class SyncObjectCollectionField + { + public bool visible; + public readonly FieldInfo field; + public readonly string label; + + public SyncObjectCollectionField(FieldInfo field) + { + this.field = field; + visible = false; + label = $"{field.Name} [{field.FieldType.Name}]"; + } + } + + public class SyncObjectCollectionsDrawer + { + readonly UnityEngine.Object targetObject; + readonly List syncObjectCollectionFields; + + public SyncObjectCollectionsDrawer(UnityEngine.Object targetObject) + { + this.targetObject = targetObject; + syncObjectCollectionFields = new List(); + foreach (FieldInfo field in InspectorHelper.GetAllFields(targetObject.GetType(), typeof(NetworkBehaviour))) + { + // only draw SyncObjects that are IEnumerable (SyncList/Set/Dictionary) + if (field.IsVisibleSyncObject() && + field.ImplementsInterface() && + field.ImplementsInterface()) + { + syncObjectCollectionFields.Add(new SyncObjectCollectionField(field)); + } + } + } + + public void Draw() + { + if (syncObjectCollectionFields.Count == 0) { return; } + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Sync Collections", EditorStyles.boldLabel); + + for (int i = 0; i < syncObjectCollectionFields.Count; i++) + { + DrawSyncObjectCollection(syncObjectCollectionFields[i]); + } + } + + void DrawSyncObjectCollection(SyncObjectCollectionField syncObjectCollectionField) + { + syncObjectCollectionField.visible = EditorGUILayout.Foldout(syncObjectCollectionField.visible, syncObjectCollectionField.label); + if (syncObjectCollectionField.visible) + { + using (new EditorGUI.IndentLevelScope()) + { + object fieldValue = syncObjectCollectionField.field.GetValue(targetObject); + if (fieldValue is IEnumerable syncObject) + { + int index = 0; + foreach (object item in syncObject) + { + string itemValue = item != null ? item.ToString() : "NULL"; + string itemLabel = $"Element {index}"; + EditorGUILayout.LabelField(itemLabel, itemValue); + + index++; + } + } + } + } + } + } +} diff --git a/Assets/Mirror/Editor/SyncObjectCollectionsDrawer.cs.meta b/Assets/Mirror/Editor/SyncObjectCollectionsDrawer.cs.meta new file mode 100644 index 0000000..44ba75d --- /dev/null +++ b/Assets/Mirror/Editor/SyncObjectCollectionsDrawer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6f90afab12e04f0e945d83e9d38308a3 +timeCreated: 1632556645 \ No newline at end of file diff --git a/Assets/Mirror/Editor/SyncVarAttributeDrawer.cs b/Assets/Mirror/Editor/SyncVarAttributeDrawer.cs new file mode 100644 index 0000000..2356a5e --- /dev/null +++ b/Assets/Mirror/Editor/SyncVarAttributeDrawer.cs @@ -0,0 +1,28 @@ +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + [CustomPropertyDrawer(typeof(SyncVarAttribute))] + public class SyncVarAttributeDrawer : PropertyDrawer + { + static readonly GUIContent syncVarIndicatorContent = new GUIContent("SyncVar", "This variable has been marked with the [SyncVar] attribute."); + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + Vector2 syncVarIndicatorRect = EditorStyles.miniLabel.CalcSize(syncVarIndicatorContent); + float valueWidth = position.width - syncVarIndicatorRect.x; + + Rect valueRect = new Rect(position.x, position.y, valueWidth, position.height); + Rect labelRect = new Rect(position.x + valueWidth, position.y, syncVarIndicatorRect.x, position.height); + + EditorGUI.PropertyField(valueRect, property, label, true); + GUI.Label(labelRect, syncVarIndicatorContent, EditorStyles.miniLabel); + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return EditorGUI.GetPropertyHeight(property); + } + } +} diff --git a/Assets/Mirror/Editor/SyncVarAttributeDrawer.cs.meta b/Assets/Mirror/Editor/SyncVarAttributeDrawer.cs.meta new file mode 100644 index 0000000..6311f1d --- /dev/null +++ b/Assets/Mirror/Editor/SyncVarAttributeDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 27821afc81c4d064d8348fbeb00c0ce8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver.meta b/Assets/Mirror/Editor/Weaver.meta new file mode 100644 index 0000000..121fbf4 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d9f8e6274119b4ce29e498cfb8aca8a4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/AssemblyInfo.cs b/Assets/Mirror/Editor/Weaver/AssemblyInfo.cs new file mode 100644 index 0000000..08b43f5 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Mirror.Tests")] diff --git a/Assets/Mirror/Editor/Weaver/AssemblyInfo.cs.meta b/Assets/Mirror/Editor/Weaver/AssemblyInfo.cs.meta new file mode 100644 index 0000000..d356af8 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 929924d95663264478d4238d4910d22e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Empty.meta b/Assets/Mirror/Editor/Weaver/Empty.meta new file mode 100644 index 0000000..6e29ee7 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 30fc290f2ff9c29498f54f63de12ca6f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs b/Assets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs new file mode 100644 index 0000000..a88144a --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs @@ -0,0 +1 @@ +// Removed Oct 1 2020 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs.meta b/Assets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs.meta new file mode 100644 index 0000000..685f914 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/GenericArgumentResolver.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fd67b3f7c2d66074a9bc7a23787e2ffb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs b/Assets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs new file mode 100644 index 0000000..b38f171 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs @@ -0,0 +1 @@ +// removed Oct 5 2020 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs.meta new file mode 100644 index 0000000..cbea4d6 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/MessageClassProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e25c00c88fc134f6ea7ab00ae4db8083 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Empty/Program.cs b/Assets/Mirror/Editor/Weaver/Empty/Program.cs new file mode 100644 index 0000000..a214b81 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/Program.cs @@ -0,0 +1 @@ +// Removed 05/09/20 diff --git a/Assets/Mirror/Editor/Weaver/Empty/Program.cs.meta b/Assets/Mirror/Editor/Weaver/Empty/Program.cs.meta new file mode 100644 index 0000000..0a14018 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/Program.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0152994c9591626408fcfec96fcc7933 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs b/Assets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs new file mode 100644 index 0000000..a88144a --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs @@ -0,0 +1 @@ +// Removed Oct 1 2020 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs.meta new file mode 100644 index 0000000..0a7c2aa --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/SyncDictionaryProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 29e4a45f69822462ab0b15adda962a29 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs b/Assets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs new file mode 100644 index 0000000..2fdbc52 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs @@ -0,0 +1 @@ +// removed 2020-09 diff --git a/Assets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs.meta new file mode 100644 index 0000000..81b9576 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/SyncEventProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5d8b25543a624384944b599e5a832a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs b/Assets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs new file mode 100644 index 0000000..a88144a --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs @@ -0,0 +1 @@ +// Removed Oct 1 2020 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs.meta new file mode 100644 index 0000000..b73b047 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Empty/SyncListProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f3445268e45d437fac325837aff3246 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/EntryPoint.meta b/Assets/Mirror/Editor/Weaver/EntryPoint.meta new file mode 100644 index 0000000..81827c5 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPoint.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 251338e67afb4cefa38da924f8c50a6e +timeCreated: 1628851818 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs b/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs new file mode 100644 index 0000000..b5db851 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs @@ -0,0 +1,188 @@ +// for Unity 2020+ we use ILPostProcessor. +// only automatically invoke it for older versions. +#if !UNITY_2020_3_OR_NEWER +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Mono.CecilX; +using UnityEditor; +using UnityEditor.Compilation; +using UnityEngine; +using UnityAssembly = UnityEditor.Compilation.Assembly; + +namespace Mirror.Weaver +{ + public static class CompilationFinishedHook + { + // needs to be the same as Weaver.MirrorAssemblyName! + const string MirrorRuntimeAssemblyName = "Mirror"; + const string MirrorWeaverAssemblyName = "Mirror.Weaver"; + + // global weaver define so that tests can use it + internal static Weaver weaver; + + // delegate for subscription to Weaver warning messages + public static Action OnWeaverWarning; + // delete for subscription to Weaver error messages + public static Action OnWeaverError; + + // controls whether Weaver errors are reported direct to the Unity console (tests enable this) + public static bool UnityLogEnabled = true; + + [InitializeOnLoadMethod] + public static void OnInitializeOnLoad() + { + CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished; + + // We only need to run this once per session + // after that, all assemblies will be weaved by the event + if (!SessionState.GetBool("MIRROR_WEAVED", false)) + { + // reset session flag + SessionState.SetBool("MIRROR_WEAVED", true); + SessionState.SetBool("MIRROR_WEAVE_SUCCESS", true); + + WeaveExistingAssemblies(); + } + } + + public static void WeaveExistingAssemblies() + { + foreach (UnityAssembly assembly in CompilationPipeline.GetAssemblies()) + { + if (File.Exists(assembly.outputPath)) + { + OnCompilationFinished(assembly.outputPath, new CompilerMessage[0]); + } + } + + EditorUtility.RequestScriptReload(); + } + + static Assembly FindCompilationPipelineAssembly(string assemblyName) => + CompilationPipeline.GetAssemblies().First(assembly => assembly.name == assemblyName); + + static bool CompilerMessagesContainError(CompilerMessage[] messages) => + messages.Any(msg => msg.type == CompilerMessageType.Error); + + public static void OnCompilationFinished(string assemblyPath, CompilerMessage[] messages) + { + // Do nothing if there were compile errors on the target + if (CompilerMessagesContainError(messages)) + { + Debug.Log("Weaver: stop because compile errors on target"); + return; + } + + // Should not run on the editor only assemblies (test ones still need to be weaved) + if (assemblyPath.Contains("-Editor") || + (assemblyPath.Contains(".Editor") && !assemblyPath.Contains(".Tests"))) + { + return; + } + + // skip Mirror.dll because CompilationFinishedHook can't weave itself. + // this would cause a sharing violation. + // skip Mirror.Weaver.dll too. + string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath); + if (assemblyName == MirrorRuntimeAssemblyName || assemblyName == MirrorWeaverAssemblyName) + { + return; + } + + // find Mirror.dll + Assembly mirrorAssembly = FindCompilationPipelineAssembly(MirrorRuntimeAssemblyName); + if (mirrorAssembly == null) + { + Debug.LogError("Failed to find Mirror runtime assembly"); + return; + } + + string mirrorRuntimeDll = mirrorAssembly.outputPath; + if (!File.Exists(mirrorRuntimeDll)) + { + // this is normal, it happens with any assembly that is built before mirror + // such as unity packages or your own assemblies + // those don't need to be weaved + // if any assembly depends on mirror, then it will be built after + return; + } + + // find UnityEngine.CoreModule.dll + string unityEngineCoreModuleDLL = UnityEditorInternal.InternalEditorUtility.GetEngineCoreModuleAssemblyPath(); + if (string.IsNullOrEmpty(unityEngineCoreModuleDLL)) + { + Debug.LogError("Failed to find UnityEngine assembly"); + return; + } + + HashSet dependencyPaths = GetDependencyPaths(assemblyPath); + dependencyPaths.Add(Path.GetDirectoryName(mirrorRuntimeDll)); + dependencyPaths.Add(Path.GetDirectoryName(unityEngineCoreModuleDLL)); + + if (!WeaveFromFile(assemblyPath, dependencyPaths.ToArray())) + { + // Set false...will be checked in \Editor\EnterPlayModeSettingsCheck.CheckSuccessfulWeave() + SessionState.SetBool("MIRROR_WEAVE_SUCCESS", false); + if (UnityLogEnabled) Debug.LogError($"Weaving failed for {assemblyPath}"); + } + } + + static HashSet GetDependencyPaths(string assemblyPath) + { + // build directory list for later asm/symbol resolving using CompilationPipeline refs + HashSet dependencyPaths = new HashSet + { + Path.GetDirectoryName(assemblyPath) + }; + foreach (Assembly assembly in CompilationPipeline.GetAssemblies()) + { + if (assembly.outputPath == assemblyPath) + { + foreach (string reference in assembly.compiledAssemblyReferences) + { + dependencyPaths.Add(Path.GetDirectoryName(reference)); + } + } + } + + return dependencyPaths; + } + // helper function to invoke Weaver with an AssemblyDefinition from a + // file path, with dependencies added. + static bool WeaveFromFile(string assemblyPath, string[] dependencies) + { + // resolve assembly from stream + using (DefaultAssemblyResolver asmResolver = new DefaultAssemblyResolver()) + using (AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters{ ReadWrite = true, ReadSymbols = true, AssemblyResolver = asmResolver })) + { + // add this assembly's path and unity's assembly path + asmResolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath)); + asmResolver.AddSearchDirectory(Helpers.UnityEngineDllDirectoryName()); + + // add dependencies + if (dependencies != null) + { + foreach (string path in dependencies) + { + asmResolver.AddSearchDirectory(path); + } + } + + // create weaver with logger + weaver = new Weaver(new CompilationFinishedLogger()); + if (weaver.Weave(assembly, asmResolver, out bool modified)) + { + // write changes to file if modified + if (modified) + assembly.Write(new WriterParameters{WriteSymbols = true}); + + return true; + } + return false; + } + } + } +} +#endif diff --git a/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs.meta new file mode 100644 index 0000000..ed537ab --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedHook.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de2aeb2e8068f421a9a1febe408f7051 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs b/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs new file mode 100644 index 0000000..e053404 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs @@ -0,0 +1,31 @@ +// logger for compilation finished hook. +// where we need a callback and Debug.Log. +// for Unity 2020+ we use ILPostProcessor. +#if !UNITY_2020_3_OR_NEWER +using Mono.CecilX; +using UnityEngine; + +namespace Mirror.Weaver +{ + public class CompilationFinishedLogger : Logger + { + public void Warning(string message) => Warning(message, null); + public void Warning(string message, MemberReference mr) + { + if (mr != null) message = $"{message} (at {mr})"; + + if (CompilationFinishedHook.UnityLogEnabled) Debug.LogWarning(message); + CompilationFinishedHook.OnWeaverWarning?.Invoke(message); + } + + public void Error(string message) => Error(message, null); + public void Error(string message, MemberReference mr) + { + if (mr != null) message = $"{message} (at {mr})"; + + if (CompilationFinishedHook.UnityLogEnabled) Debug.LogError(message); + CompilationFinishedHook.OnWeaverError?.Invoke(message); + } + } +} +#endif diff --git a/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs.meta new file mode 100644 index 0000000..f8c7139 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPoint/CompilationFinishedLogger.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 47026732f0fa475c94bd1dd41f1de559 +timeCreated: 1629379868 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs b/Assets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs new file mode 100644 index 0000000..5dffa97 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs @@ -0,0 +1,44 @@ +#if !UNITY_2020_3_OR_NEWER +// make sure we weaved successfully when entering play mode. +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + public class EnterPlayModeSettingsCheck : MonoBehaviour + { + [InitializeOnLoadMethod] + static void OnInitializeOnLoad() + { + // Hook this event to see if we have a good weave every time + // user attempts to enter play mode or tries to do a build + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + } + + static void OnPlayModeStateChanged(PlayModeStateChange state) + { + // Per Unity docs, this fires "when exiting edit mode before the Editor is in play mode". + // This doesn't fire when closing the editor. + if (state == PlayModeStateChange.ExitingEditMode) + { + // Check if last weave result was successful + if (!SessionState.GetBool("MIRROR_WEAVE_SUCCESS", false)) + { + // Last weave result was a failure...try to weave again + // Faults will show in the console that may have been cleared by "Clear on Play" + SessionState.SetBool("MIRROR_WEAVE_SUCCESS", true); + Weaver.CompilationFinishedHook.WeaveExistingAssemblies(); + + // Did that clear things up for us? + if (!SessionState.GetBool("MIRROR_WEAVE_SUCCESS", false)) + { + // Nope, still failed, and console has the issues logged + Debug.LogError("Can't enter play mode until weaver issues are resolved."); + EditorApplication.isPlaying = false; + } + } + } + } + } +} +#endif diff --git a/Assets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs.meta new file mode 100644 index 0000000..eca31e3 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPoint/EnterPlayModeHook.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b73d0f106ba84aa983baa5142b08a0a9 +timeCreated: 1628851346 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor.meta b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor.meta new file mode 100644 index 0000000..6ef7bf3 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 09082db63d1d48d9ab91320165c1b684 +timeCreated: 1628859005 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs new file mode 100644 index 0000000..e4d9de2 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs @@ -0,0 +1,31 @@ +// tests use WeaveAssembler, which uses AssemblyBuilder to Build(). +// afterwards ILPostProcessor weaves the build. +// this works on windows, but build() does not run ILPP on mac atm. +// we need to manually invoke ILPP with an assembly from file. +// +// this is in Weaver folder becuase CompilationPipeline can only be accessed +// from assemblies with the name "Unity.*.CodeGen" +using System.IO; +using Unity.CompilationPipeline.Common.ILPostProcessing; + +namespace Mirror.Weaver +{ + public class CompiledAssemblyFromFile : ICompiledAssembly + { + readonly string assemblyPath; + + public string Name => Path.GetFileNameWithoutExtension(assemblyPath); + public string[] References { get; set; } + public string[] Defines { get; set; } + public InMemoryAssembly InMemoryAssembly { get; } + + public CompiledAssemblyFromFile(string assemblyPath) + { + this.assemblyPath = assemblyPath; + byte[] peData = File.ReadAllBytes(assemblyPath); + string pdbFileName = Path.GetFileNameWithoutExtension(assemblyPath) + ".pdb"; + byte[] pdbData = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(assemblyPath), pdbFileName)); + InMemoryAssembly = new InMemoryAssembly(peData, pdbData); + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs.meta new file mode 100644 index 0000000..1e5091e --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/CompiledAssemblyFromFile.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9009d1db4ed44f6694a92bf8ad7738e9 +timeCreated: 1630129423 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs new file mode 100644 index 0000000..2b6b325 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs @@ -0,0 +1,199 @@ +// based on paul's resolver from +// https://github.com/MirageNet/Mirage/commit/def64cd1db525398738f057b3d1eb1fe8afc540c?branch=def64cd1db525398738f057b3d1eb1fe8afc540c&diff=split +// +// an assembly resolver's job is to open an assembly in case we want to resolve +// a type from it. +// +// for example, while weaving MyGame.dll: if we want to resolve ArraySegment, +// then we need to open and resolve from another assembly (CoreLib). +// +// using DefaultAssemblyResolver with ILPostProcessor throws Exceptions in +// WeaverTypes.cs when resolving anything, for example: +// ArraySegment in Mirror.Tests.Dll. +// +// we need a custom resolver for ILPostProcessor. +#if UNITY_2020_3_OR_NEWER +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Linq; +using System.Threading; +using Mono.CecilX; +using Unity.CompilationPipeline.Common.ILPostProcessing; + +namespace Mirror.Weaver +{ + class ILPostProcessorAssemblyResolver : IAssemblyResolver + { + readonly string[] assemblyReferences; + + // originally we used Dictionary + lock. + // Resolve() is called thousands of times for large projects. + // ILPostProcessor is multithreaded, so best to use ConcurrentDictionary without the lock here. + readonly ConcurrentDictionary assemblyCache = + new ConcurrentDictionary(); + + // Resolve() calls FindFile() every time. + // thousands of times for String => mscorlib alone in large projects. + // cache the results! ILPostProcessor is multithreaded, so use a ConcurrentDictionary here. + readonly ConcurrentDictionary fileNameCache = + new ConcurrentDictionary(); + + readonly ICompiledAssembly compiledAssembly; + AssemblyDefinition selfAssembly; + + readonly Logger Log; + + public ILPostProcessorAssemblyResolver(ICompiledAssembly compiledAssembly, Logger Log) + { + this.compiledAssembly = compiledAssembly; + assemblyReferences = compiledAssembly.References; + this.Log = Log; + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + // Cleanup + } + + public AssemblyDefinition Resolve(AssemblyNameReference name) => + Resolve(name, new ReaderParameters(ReadingMode.Deferred)); + + // here is an example on when this is called: + // Player : NetworkBehaviour has a [SyncVar] of type String. + // Weaver's SyncObjectInitializer checks if ImplementsSyncObject() + // which needs to resolve the type 'String' from mscorlib. + // Resolve() lives in CecilX.MetadataResolver.Resolve() + // which calls assembly_resolver.Resolve(). + // which uses our ILPostProcessorAssemblyResolver here. + // + // for large projects, this is called thousands of times for mscorlib alone. + // initially ILPostProcessorAssemblyResolver took 30x longer than with CompilationFinishedHook. + // we need to cache and speed up everything we can here! + public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) + { + if (name.Name == compiledAssembly.Name) + return selfAssembly; + + // cache FindFile. + // in large projects, this is called thousands(!) of times for String=>mscorlib alone. + // reduces a single String=>mscorlib resolve from 0.771ms to 0.015ms. + // => 50x improvement in TypeReference.Resolve() speed! + // => 22x improvement in Weaver speed! + if (!fileNameCache.TryGetValue(name.Name, out string fileName)) + { + fileName = FindFile(name.Name); + fileNameCache.TryAdd(name.Name, fileName); + } + + if (fileName == null) + { + // returning null will throw exceptions in our weaver where. + // let's make it obvious why we returned null for easier debugging. + // NOTE: if this fails for "System.Private.CoreLib": + // ILPostProcessorReflectionImporter fixes it! + Log.Warning($"ILPostProcessorAssemblyResolver.Resolve: Failed to find file for {name}"); + return null; + } + + // try to get cached assembly by filename + writetime + DateTime lastWriteTime = File.GetLastWriteTime(fileName); + string cacheKey = fileName + lastWriteTime; + if (assemblyCache.TryGetValue(cacheKey, out AssemblyDefinition result)) + return result; + + // otherwise resolve and cache a new assembly + parameters.AssemblyResolver = this; + MemoryStream ms = MemoryStreamFor(fileName); + + string pdb = fileName + ".pdb"; + if (File.Exists(pdb)) + parameters.SymbolStream = MemoryStreamFor(pdb); + + AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(ms, parameters); + assemblyCache.TryAdd(cacheKey, assemblyDefinition); + return assemblyDefinition; + } + + // find assemblyname in assembly's references + string FindFile(string name) + { + // perhaps the type comes from a .dll or .exe + // check both in one call without Linq instead of iterating twice like originally + foreach (string r in assemblyReferences) + { + if (Path.GetFileNameWithoutExtension(r) == name) + return r; + } + + // this is called thousands(!) of times. + // constructing strings only once saves ~0.1ms per call for mscorlib. + string dllName = name + ".dll"; + + // Unfortunately the current ICompiledAssembly API only provides direct references. + // It is very much possible that a postprocessor ends up investigating a type in a directly + // referenced assembly, that contains a field that is not in a directly referenced assembly. + // if we don't do anything special for that situation, it will fail to resolve. We should fix this + // in the ILPostProcessing API. As a workaround, we rely on the fact here that the indirect references + // are always located next to direct references, so we search in all directories of direct references we + // got passed, and if we find the file in there, we resolve to it. + foreach (string parentDir in assemblyReferences.Select(Path.GetDirectoryName).Distinct()) + { + string candidate = Path.Combine(parentDir, dllName); + if (File.Exists(candidate)) + return candidate; + } + + return null; + } + + // open file as MemoryStream. + // ILPostProcessor is multithreaded. + // retry a few times in case another thread is still accessing the file. + static MemoryStream MemoryStreamFor(string fileName) + { + return Retry(10, TimeSpan.FromSeconds(1), () => + { + byte[] byteArray; + using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + byteArray = new byte[fs.Length]; + int readLength = fs.Read(byteArray, 0, (int)fs.Length); + if (readLength != fs.Length) + throw new InvalidOperationException("File read length is not full length of file."); + } + + return new MemoryStream(byteArray); + }); + } + + static MemoryStream Retry(int retryCount, TimeSpan waitTime, Func func) + { + try + { + return func(); + } + catch (IOException) + { + if (retryCount == 0) + throw; + Console.WriteLine($"Caught IO Exception, trying {retryCount} more times"); + Thread.Sleep(waitTime); + return Retry(retryCount - 1, waitTime, func); + } + } + + // if the CompiledAssembly's AssemblyDefinition is known, we can add it + public void SetAssemblyDefinitionForCompiledAssembly(AssemblyDefinition assemblyDefinition) + { + selfAssembly = assemblyDefinition; + } + } +} +#endif diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs.meta new file mode 100644 index 0000000..07289dd --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorAssemblyResolver.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0b3e94696e22440ead0b3a42411bbe14 +timeCreated: 1629693784 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs new file mode 100644 index 0000000..6a70641 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs @@ -0,0 +1,53 @@ +// helper function to use ILPostProcessor for an assembly from file. +// we keep this in Weaver folder because we can access CompilationPipleine here. +// in tests folder we can't, unless we rename to "Unity.*.CodeGen", +// but then tests wouldn't be weaved anymore. +#if UNITY_2020_3_OR_NEWER +using System; +using System.IO; +using Unity.CompilationPipeline.Common.Diagnostics; +using Unity.CompilationPipeline.Common.ILPostProcessing; + +namespace Mirror.Weaver +{ + public static class ILPostProcessorFromFile + { + // read, weave, write file via ILPostProcessor + public static void ILPostProcessFile(string assemblyPath, string[] references, Action OnWarning, Action OnError) + { + // we COULD Weave() with a test logger manually. + // but for test result consistency on all platforms, + // let's invoke the ILPostProcessor here too. + CompiledAssemblyFromFile assembly = new CompiledAssemblyFromFile(assemblyPath); + assembly.References = references; + + // create ILPP and check WillProcess like Unity would. + ILPostProcessorHook ilpp = new ILPostProcessorHook(); + if (ilpp.WillProcess(assembly)) + { + //Debug.Log($"Will Process: {assembly.Name}"); + + // process it like Unity would + ILPostProcessResult result = ilpp.Process(assembly); + + // handle the error messages like Unity would + foreach (DiagnosticMessage message in result.Diagnostics) + { + if (message.DiagnosticType == DiagnosticType.Warning) + { + OnWarning(message.MessageData); + } + else if (message.DiagnosticType == DiagnosticType.Error) + { + OnError(message.MessageData); + } + } + + // save the weaved assembly to file. + // some tests open it and check for certain IL code. + File.WriteAllBytes(assemblyPath, result.InMemoryAssembly.PeData); + } + } + } +} +#endif diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs.meta new file mode 100644 index 0000000..e06dfa7 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorFromFile.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2a4b115486b74d27a9540f3c39ae2d46 +timeCreated: 1630152191 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs new file mode 100644 index 0000000..0cfb433 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs @@ -0,0 +1,143 @@ +// hook via ILPostProcessor from Unity 2020.3+ +// (2020.1 has errors https://github.com/vis2k/Mirror/issues/2912) +#if UNITY_2020_3_OR_NEWER +// Unity.CompilationPipeline reference is only resolved if assembly name is +// Unity.*.CodeGen: +// https://forum.unity.com/threads/how-does-unity-do-codegen-and-why-cant-i-do-it-myself.853867/#post-5646937 +using System.IO; +using System.Linq; +// to use Mono.CecilX here, we need to 'override references' in the +// Unity.Mirror.CodeGen assembly definition file in the Editor, and add CecilX. +// otherwise we get a reflection exception with 'file not found: CecilX'. +using Mono.CecilX; +using Mono.CecilX.Cil; +using Unity.CompilationPipeline.Common.ILPostProcessing; +// IMPORTANT: 'using UnityEngine' does not work in here. +// Unity gives "(0,0): error System.Security.SecurityException: ECall methods must be packaged into a system module." +//using UnityEngine; + +namespace Mirror.Weaver +{ + public class ILPostProcessorHook : ILPostProcessor + { + // from CompilationFinishedHook + const string MirrorRuntimeAssemblyName = "Mirror"; + + // ILPostProcessor is invoked by Unity. + // we can not tell it to ignore certain assemblies before processing. + // add a 'ignore' define for convenience. + // => WeaverTests/WeaverAssembler need it to avoid Unity running it + public const string IgnoreDefine = "ILPP_IGNORE"; + + // we can't use Debug.Log in ILPP, so we need a custom logger + ILPostProcessorLogger Log = new ILPostProcessorLogger(); + + // ??? + public override ILPostProcessor GetInstance() => this; + + // check if assembly has the 'ignore' define + static bool HasDefine(ICompiledAssembly assembly, string define) => + assembly.Defines != null && + assembly.Defines.Contains(define); + + // process Mirror, or anything that references Mirror + public override bool WillProcess(ICompiledAssembly compiledAssembly) + { + // compiledAssembly.References are file paths: + // Library/Bee/artifacts/200b0aE.dag/Mirror.CompilerSymbols.dll + // Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.dll + // /Applications/Unity/Hub/Editor/2021.2.0b6_apple_silicon/Unity.app/Contents/NetStandard/ref/2.1.0/netstandard.dll + // + // log them to see: + // foreach (string reference in compiledAssembly.References) + // LogDiagnostics($"{compiledAssembly.Name} references {reference}"); + bool relevant = compiledAssembly.Name == MirrorRuntimeAssemblyName || + compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == MirrorRuntimeAssemblyName); + bool ignore = HasDefine(compiledAssembly, IgnoreDefine); + return relevant && !ignore; + } + + public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly) + { + //Log.Warning($"Processing {compiledAssembly.Name}"); + + // load the InMemoryAssembly peData into a MemoryStream + byte[] peData = compiledAssembly.InMemoryAssembly.PeData; + //LogDiagnostics($" peData.Length={peData.Length} bytes"); + using (MemoryStream stream = new MemoryStream(peData)) + using (ILPostProcessorAssemblyResolver asmResolver = new ILPostProcessorAssemblyResolver(compiledAssembly, Log)) + { + // we need to load symbols. otherwise we get: + // "(0,0): error Mono.CecilX.Cil.SymbolsNotFoundException: No symbol found for file: " + using (MemoryStream symbols = new MemoryStream(compiledAssembly.InMemoryAssembly.PdbData)) + { + ReaderParameters readerParameters = new ReaderParameters{ + SymbolStream = symbols, + ReadWrite = true, + ReadSymbols = true, + AssemblyResolver = asmResolver, + // custom reflection importer to fix System.Private.CoreLib + // not being found in custom assembly resolver above. + ReflectionImporterProvider = new ILPostProcessorReflectionImporterProvider() + }; + using (AssemblyDefinition asmDef = AssemblyDefinition.ReadAssembly(stream, readerParameters)) + { + // resolving a Mirror.dll type like NetworkServer while + // weaving Mirror.dll does not work. it throws a + // NullReferenceException in WeaverTypes.ctor + // when Resolve() is called on the first Mirror type. + // need to add the AssemblyDefinition itself to use. + asmResolver.SetAssemblyDefinitionForCompiledAssembly(asmDef); + + // weave this assembly. + Weaver weaver = new Weaver(Log); + if (weaver.Weave(asmDef, asmResolver, out bool modified)) + { + //Log.Warning($"Weaving succeeded for: {compiledAssembly.Name}"); + + // write if modified + if (modified) + { + // when weaving Mirror.dll with ILPostProcessor, + // Weave() -> WeaverTypes -> resolving the first + // type in Mirror.dll adds a reference to + // Mirror.dll even though we are in Mirror.dll. + // -> this would throw an exception: + // "Mirror references itself" and not compile + // -> need to detect and fix manually here + if (asmDef.MainModule.AssemblyReferences.Any(r => r.Name == asmDef.Name.Name)) + { + asmDef.MainModule.AssemblyReferences.Remove(asmDef.MainModule.AssemblyReferences.First(r => r.Name == asmDef.Name.Name)); + //Log.Warning($"fixed self referencing Assembly: {asmDef.Name.Name}"); + } + + MemoryStream peOut = new MemoryStream(); + MemoryStream pdbOut = new MemoryStream(); + WriterParameters writerParameters = new WriterParameters + { + SymbolWriterProvider = new PortablePdbWriterProvider(), + SymbolStream = pdbOut, + WriteSymbols = true + }; + + asmDef.Write(peOut, writerParameters); + + InMemoryAssembly inMemory = new InMemoryAssembly(peOut.ToArray(), pdbOut.ToArray()); + return new ILPostProcessResult(inMemory, Log.Logs); + } + } + // if anything during Weave() fails, we log an error. + // don't need to indicate 'weaving failed' again. + // in fact, this would break tests only expecting certain errors. + //else Log.Error($"Weaving failed for: {compiledAssembly.Name}"); + } + } + } + + // always return an ILPostProcessResult with Logs. + // otherwise we won't see Logs if weaving failed. + return new ILPostProcessResult(compiledAssembly.InMemoryAssembly, Log.Logs); + } + } +} +#endif diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs.meta new file mode 100644 index 0000000..9d7e0a2 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorHook.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5f113eb695b348b5b28cd85358c8959a +timeCreated: 1628859074 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs new file mode 100644 index 0000000..2c070cc --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using Mono.CecilX; +using Unity.CompilationPipeline.Common.Diagnostics; + +namespace Mirror.Weaver +{ + public class ILPostProcessorLogger : Logger + { + // can't Debug.Log in ILPostProcessor. need to add to this list. + internal List Logs = new List(); + + void Add(string message, DiagnosticType logType) + { + Logs.Add(new DiagnosticMessage + { + // TODO add file etc. for double click opening later? + DiagnosticType = logType, // doesn't have .Log + File = null, + Line = 0, + Column = 0, + MessageData = message + }); + } + + public void LogDiagnostics(string message, DiagnosticType logType = DiagnosticType.Warning) + { + // DiagnosticMessage can't display \n for some reason. + // it just cuts it off and we don't see any stack trace. + // so let's replace all line breaks so we get the stack trace. + // (Unity 2021.2.0b6 apple silicon) + //message = message.Replace("\n", "/"); + + // lets break it into several messages instead so it's easier readable + string[] lines = message.Split('\n'); + + // if it's just one line, simply log it + if (lines.Length == 1) + { + // tests assume exact message log. + // don't include 'Weaver: ...' or similar. + Add($"{message}", logType); + } + // for multiple lines, log each line separately with start/end indicators + else + { + // first line with Weaver: ... first + Add("----------------------------------------------", logType); + foreach (string line in lines) Add(line, logType); + Add("----------------------------------------------", logType); + } + } + + public void Warning(string message) => Warning(message, null); + public void Warning(string message, MemberReference mr) + { + if (mr != null) message = $"{message} (at {mr})"; + LogDiagnostics(message, DiagnosticType.Warning); + } + + public void Error(string message) => Error(message, null); + public void Error(string message, MemberReference mr) + { + if (mr != null) message = $"{message} (at {mr})"; + LogDiagnostics(message, DiagnosticType.Error); + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs.meta new file mode 100644 index 0000000..8bb72e0 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorLogger.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e7b56e7826664e34a415e4b70d958f2a +timeCreated: 1629533154 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs new file mode 100644 index 0000000..e15c103 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs @@ -0,0 +1,36 @@ +// based on paul's resolver from +// https://github.com/MirageNet/Mirage/commit/def64cd1db525398738f057b3d1eb1fe8afc540c?branch=def64cd1db525398738f057b3d1eb1fe8afc540c&diff=split +// +// ILPostProcessorAssemblyRESOLVER does not find the .dll file for: +// "System.Private.CoreLib" +// we need this custom reflection importer to fix that. +using System.Linq; +using System.Reflection; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + internal class ILPostProcessorReflectionImporter : DefaultReflectionImporter + { + const string SystemPrivateCoreLib = "System.Private.CoreLib"; + readonly AssemblyNameReference fixedCoreLib; + + public ILPostProcessorReflectionImporter(ModuleDefinition module) : base(module) + { + // find the correct library for "System.Private.CoreLib". + // either mscorlib or netstandard. + // defaults to System.Private.CoreLib if not found. + fixedCoreLib = module.AssemblyReferences.FirstOrDefault(a => a.Name == "mscorlib" || a.Name == "netstandard" || a.Name == SystemPrivateCoreLib); + } + + public override AssemblyNameReference ImportReference(AssemblyName name) + { + // System.Private.CoreLib? + if (name.Name == SystemPrivateCoreLib && fixedCoreLib != null) + return fixedCoreLib; + + // otherwise import as usual + return base.ImportReference(name); + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs.meta new file mode 100644 index 0000000..d361e21 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporter.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6403a7e3b3ae4e009ae282f111d266e0 +timeCreated: 1629709256 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs new file mode 100644 index 0000000..7358e1b --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs @@ -0,0 +1,16 @@ +// based on paul's resolver from +// https://github.com/MirageNet/Mirage/commit/def64cd1db525398738f057b3d1eb1fe8afc540c?branch=def64cd1db525398738f057b3d1eb1fe8afc540c&diff=split +// +// ILPostProcessorAssemblyRESOLVER does not find the .dll file for: +// "System.Private.CoreLib" +// we need this custom reflection importer to fix that. +using Mono.CecilX; + +namespace Mirror.Weaver +{ + internal class ILPostProcessorReflectionImporterProvider : IReflectionImporterProvider + { + public IReflectionImporter GetReflectionImporter(ModuleDefinition module) => + new ILPostProcessorReflectionImporter(module); + } +} diff --git a/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs.meta b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs.meta new file mode 100644 index 0000000..d9b6f6b --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/EntryPointILPostProcessor/ILPostProcessorReflectionImporterProvider.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a1003b568bad4e69b961c4c81d5afd96 +timeCreated: 1629709223 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/Extensions.cs b/Assets/Mirror/Editor/Weaver/Extensions.cs new file mode 100644 index 0000000..566a51a --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Extensions.cs @@ -0,0 +1,359 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + public static class Extensions + { + public static bool Is(this TypeReference td, Type type) => + type.IsGenericType + ? td.GetElementType().FullName == type.FullName + : td.FullName == type.FullName; + + // check if 'td' is exactly of type T. + // it does not check if any base type is of , only the specific type. + // for example: + // NetworkConnection Is NetworkConnection: true + // NetworkConnectionToClient Is NetworkConnection: false + public static bool Is(this TypeReference td) => Is(td, typeof(T)); + + // check if 'tr' is derived from T. + // it does not check if 'tr' is exactly T. + // for example: + // NetworkConnection IsDerivedFrom: false + // NetworkConnectionToClient IsDerivedFrom: true + public static bool IsDerivedFrom(this TypeReference tr) => IsDerivedFrom(tr, typeof(T)); + + public static bool IsDerivedFrom(this TypeReference tr, Type baseClass) + { + TypeDefinition td = tr.Resolve(); + if (!td.IsClass) + return false; + + // are ANY parent classes of baseClass? + TypeReference parent = td.BaseType; + + if (parent == null) + return false; + + if (parent.Is(baseClass)) + return true; + + if (parent.CanBeResolved()) + return IsDerivedFrom(parent.Resolve(), baseClass); + + return false; + } + + public static TypeReference GetEnumUnderlyingType(this TypeDefinition td) + { + foreach (FieldDefinition field in td.Fields) + { + if (!field.IsStatic) + return field.FieldType; + } + throw new ArgumentException($"Invalid enum {td.FullName}"); + } + + public static bool ImplementsInterface(this TypeDefinition td) + { + TypeDefinition typedef = td; + + while (typedef != null) + { + if (typedef.Interfaces.Any(iface => iface.InterfaceType.Is())) + return true; + + try + { + TypeReference parent = typedef.BaseType; + typedef = parent?.Resolve(); + } + catch (AssemblyResolutionException) + { + // this can happen for plugins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + + return false; + } + + public static bool IsMultidimensionalArray(this TypeReference tr) => + tr is ArrayType arrayType && arrayType.Rank > 1; + + // Does type use netId as backing field + public static bool IsNetworkIdentityField(this TypeReference tr) => + tr.Is() || + tr.Is() || + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + tr.IsDerivedFrom() || + tr.Is(); + + public static bool CanBeResolved(this TypeReference parent) + { + while (parent != null) + { + if (parent.Scope.Name == "Windows") + { + return false; + } + + if (parent.Scope.Name == "mscorlib") + { + TypeDefinition resolved = parent.Resolve(); + return resolved != null; + } + + try + { + parent = parent.Resolve().BaseType; + } + catch + { + return false; + } + } + return true; + } + + // Makes T => Variable and imports function + public static MethodReference MakeGeneric(this MethodReference generic, ModuleDefinition module, TypeReference variableReference) + { + GenericInstanceMethod instance = new GenericInstanceMethod(generic); + instance.GenericArguments.Add(variableReference); + + MethodReference readFunc = module.ImportReference(instance); + return readFunc; + } + + // Given a method of a generic class such as ArraySegment`T.get_Count, + // and a generic instance such as ArraySegment`int + // Creates a reference to the specialized method ArraySegment`int`.get_Count + // Note that calling ArraySegment`T.get_Count directly gives an invalid IL error + public static MethodReference MakeHostInstanceGeneric(this MethodReference self, ModuleDefinition module, GenericInstanceType instanceType) + { + MethodReference reference = new MethodReference(self.Name, self.ReturnType, instanceType) + { + CallingConvention = self.CallingConvention, + HasThis = self.HasThis, + ExplicitThis = self.ExplicitThis + }; + + foreach (ParameterDefinition parameter in self.Parameters) + reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType)); + + foreach (GenericParameter generic_parameter in self.GenericParameters) + reference.GenericParameters.Add(new GenericParameter(generic_parameter.Name, reference)); + + return module.ImportReference(reference); + } + + // needed for NetworkBehaviour support + // https://github.com/vis2k/Mirror/pull/3073/ + public static FieldReference MakeHostInstanceGeneric(this FieldReference self) + { + var declaringType = new GenericInstanceType(self.DeclaringType); + foreach (var parameter in self.DeclaringType.GenericParameters) + { + declaringType.GenericArguments.Add(parameter); + } + return new FieldReference(self.Name, self.FieldType, declaringType); + } + + // Given a field of a generic class such as Writer.write, + // and a generic instance such as ArraySegment`int + // Creates a reference to the specialized method ArraySegment`int`.get_Count + // Note that calling ArraySegment`T.get_Count directly gives an invalid IL error + public static FieldReference SpecializeField(this FieldReference self, ModuleDefinition module, GenericInstanceType instanceType) + { + FieldReference reference = new FieldReference(self.Name, self.FieldType, instanceType); + return module.ImportReference(reference); + } + + public static CustomAttribute GetCustomAttribute(this ICustomAttributeProvider method) + { + return method.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.Is()); + } + + public static bool HasCustomAttribute(this ICustomAttributeProvider attributeProvider) + { + return attributeProvider.CustomAttributes.Any(attr => attr.AttributeType.Is()); + } + + public static T GetField(this CustomAttribute ca, string field, T defaultValue) + { + foreach (CustomAttributeNamedArgument customField in ca.Fields) + if (customField.Name == field) + return (T)customField.Argument.Value; + return defaultValue; + } + + public static MethodDefinition GetMethod(this TypeDefinition td, string methodName) + { + return td.Methods.FirstOrDefault(method => method.Name == methodName); + } + + public static List GetMethods(this TypeDefinition td, string methodName) + { + return td.Methods.Where(method => method.Name == methodName).ToList(); + } + + public static MethodDefinition GetMethodInBaseType(this TypeDefinition td, string methodName) + { + TypeDefinition typedef = td; + while (typedef != null) + { + foreach (MethodDefinition md in typedef.Methods) + { + if (md.Name == methodName) + return md; + } + + try + { + TypeReference parent = typedef.BaseType; + typedef = parent?.Resolve(); + } + catch (AssemblyResolutionException) + { + // this can happen for plugins. + break; + } + } + + return null; + } + + // Finds public fields in type and base type + public static IEnumerable FindAllPublicFields(this TypeReference variable) + { + return FindAllPublicFields(variable.Resolve()); + } + + // Finds public fields in type and base type + public static IEnumerable FindAllPublicFields(this TypeDefinition typeDefinition) + { + while (typeDefinition != null) + { + foreach (FieldDefinition field in typeDefinition.Fields) + { + // ignore static, private, protected fields + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3485 + // credit: James Frowen + if (field.IsStatic || field.IsPrivate || field.IsFamily) + continue; + + // also ignore internal fields + // we dont want to create different writers for this type if they are in current dll or another dll + // so we have to ignore internal in all cases + if (field.IsAssembly) + continue; + + if (field.IsNotSerialized) + continue; + + yield return field; + } + + try + { + typeDefinition = typeDefinition.BaseType?.Resolve(); + } + catch (AssemblyResolutionException) + { + break; + } + } + } + + public static bool ContainsClass(this ModuleDefinition module, string nameSpace, string className) => + module.GetTypes().Any(td => td.Namespace == nameSpace && + td.Name == className); + + + public static AssemblyNameReference FindReference(this ModuleDefinition module, string referenceName) + { + foreach (AssemblyNameReference reference in module.AssemblyReferences) + { + if (reference.Name == referenceName) + return reference; + } + return null; + } + + // Takes generic arguments from child class and applies them to parent reference, if possible + // eg makes `Base` in Child : Base have `int` instead of `T` + // Originally by James-Frowen under MIT + // https://github.com/MirageNet/Mirage/commit/cf91e1d54796866d2cf87f8e919bb5c681977e45 + public static TypeReference ApplyGenericParameters(this TypeReference parentReference, + TypeReference childReference) + { + // If the parent is not generic, we got nothing to apply + if (!parentReference.IsGenericInstance) + return parentReference; + + GenericInstanceType parentGeneric = (GenericInstanceType)parentReference; + // make new type so we can replace the args on it + // resolve it so we have non-generic instance (eg just instance with instead of ) + // if we don't cecil will make it double generic (eg INVALID IL) + GenericInstanceType generic = new GenericInstanceType(parentReference.Resolve()); + foreach (TypeReference arg in parentGeneric.GenericArguments) + generic.GenericArguments.Add(arg); + + for (int i = 0; i < generic.GenericArguments.Count; i++) + { + // if arg is not generic + // eg List would be int so not generic. + // But List would be T so is generic + if (!generic.GenericArguments[i].IsGenericParameter) + continue; + + // get the generic name, eg T + string name = generic.GenericArguments[i].Name; + // find what type T is, eg turn it into `int` if `List` + TypeReference arg = FindMatchingGenericArgument(childReference, name); + + // import just to be safe + TypeReference imported = parentReference.Module.ImportReference(arg); + // set arg on generic, parent ref will be Base instead of just Base + generic.GenericArguments[i] = imported; + } + + return generic; + } + + // Finds the type reference for a generic parameter with the provided name in the child reference + // Originally by James-Frowen under MIT + // https://github.com/MirageNet/Mirage/commit/cf91e1d54796866d2cf87f8e919bb5c681977e45 + static TypeReference FindMatchingGenericArgument(TypeReference childReference, string paramName) + { + TypeDefinition def = childReference.Resolve(); + // child class must be generic if we are in this part of the code + // eg Child : Base <--- child must have generic if Base has T + // vs Child : Base <--- wont be here if Base has int (we check if T exists before calling this) + if (!def.HasGenericParameters) + throw new InvalidOperationException( + "Base class had generic parameters, but could not find them in child class"); + + // go through parameters in child class, and find the generic that matches the name + for (int i = 0; i < def.GenericParameters.Count; i++) + { + GenericParameter param = def.GenericParameters[i]; + if (param.Name == paramName) + { + GenericInstanceType generic = (GenericInstanceType)childReference; + // return generic arg with same index + return generic.GenericArguments[i]; + } + } + + // this should never happen, if it does it means that this code is bugged + throw new InvalidOperationException("Did not find matching generic"); + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Extensions.cs.meta b/Assets/Mirror/Editor/Weaver/Extensions.cs.meta new file mode 100644 index 0000000..78660f9 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Extensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 562a5cf0254cc45738e9aa549a7100b2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Helpers.cs b/Assets/Mirror/Editor/Weaver/Helpers.cs new file mode 100644 index 0000000..56b7385 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Helpers.cs @@ -0,0 +1,26 @@ +using System.IO; +using System.Linq; +using System.Reflection; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + static class Helpers + { + // This code is taken from SerializationWeaver + public static string UnityEngineDllDirectoryName() + { + string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); + return directoryName?.Replace(@"file:\", ""); + } + + public static bool IsEditorAssembly(AssemblyDefinition currentAssembly) + { + // we want to add the [InitializeOnLoad] attribute if it's available + // -> usually either 'UnityEditor' or 'UnityEditor.CoreModule' + return currentAssembly.MainModule.AssemblyReferences.Any(assemblyReference => + assemblyReference.Name.StartsWith(nameof(UnityEditor)) + ); + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Helpers.cs.meta b/Assets/Mirror/Editor/Weaver/Helpers.cs.meta new file mode 100644 index 0000000..231f539 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Helpers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c4ed76daf48547c5abb7c58f8d20886 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Logger.cs b/Assets/Mirror/Editor/Weaver/Logger.cs new file mode 100644 index 0000000..8be978f --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Logger.cs @@ -0,0 +1,13 @@ +using Mono.CecilX; + +namespace Mirror.Weaver +{ + // not static, because ILPostProcessor is multithreaded + public interface Logger + { + void Warning(string message); + void Warning(string message, MemberReference mr); + void Error(string message); + void Error(string message, MemberReference mr); + } +} diff --git a/Assets/Mirror/Editor/Weaver/Logger.cs.meta b/Assets/Mirror/Editor/Weaver/Logger.cs.meta new file mode 100644 index 0000000..3f62978 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Logger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2a21c60c40a4c4d679c2b71a7c40882e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors.meta b/Assets/Mirror/Editor/Weaver/Processors.meta new file mode 100644 index 0000000..eb719b4 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e538d627280d2471b8c72fdea822ca49 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs new file mode 100644 index 0000000..0c05318 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs @@ -0,0 +1,130 @@ +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + // Processes [Command] methods in NetworkBehaviour + public static class CommandProcessor + { + /* + // generates code like: + public void CmdThrust(float thrusting, int spin) + { + NetworkWriterPooled writer = NetworkWriterPool.Get(); + writer.Write(thrusting); + writer.WritePackedUInt32((uint)spin); + base.SendCommandInternal(cmdName, cmdHash, writer, channel); + NetworkWriterPool.Return(writer); + } + + public void CallCmdThrust(float thrusting, int spin) + { + // whatever the user was doing before + } + + Originally HLAPI put the send message code inside the Call function + and then proceeded to replace every call to CmdTrust with CallCmdTrust + + This method moves all the user's code into the "CallCmd" method + and replaces the body of the original method with the send message code. + This way we do not need to modify the code anywhere else, and this works + correctly in dependent assemblies + */ + public static MethodDefinition ProcessCommandCall(WeaverTypes weaverTypes, Writers writers, Logger Log, TypeDefinition td, MethodDefinition md, CustomAttribute commandAttr, ref bool WeavingFailed) + { + MethodDefinition cmd = MethodProcessor.SubstituteMethod(Log, td, md, ref WeavingFailed); + + ILProcessor worker = md.Body.GetILProcessor(); + + NetworkBehaviourProcessor.WriteSetupLocals(worker, weaverTypes); + + // NetworkWriter writer = new NetworkWriter(); + NetworkBehaviourProcessor.WriteGetWriter(worker, weaverTypes); + + // write all the arguments that the user passed to the Cmd call + if (!NetworkBehaviourProcessor.WriteArguments(worker, writers, Log, md, RemoteCallType.Command, ref WeavingFailed)) + return null; + + int channel = commandAttr.GetField("channel", 0); + bool requiresAuthority = commandAttr.GetField("requiresAuthority", true); + + // invoke internal send and return + // load 'base.' to call the SendCommand function with + worker.Emit(OpCodes.Ldarg_0); + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + worker.Emit(OpCodes.Ldstr, md.FullName); + // pass the function hash so we don't have to compute it at runtime + // otherwise each GetStableHash call requires O(N) complexity. + // noticeable for long function names: + // https://github.com/MirrorNetworking/Mirror/issues/3375 + worker.Emit(OpCodes.Ldc_I4, md.FullName.GetStableHashCode()); + // writer + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Ldc_I4, channel); + // requiresAuthority ? 1 : 0 + worker.Emit(requiresAuthority ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + worker.Emit(OpCodes.Call, weaverTypes.sendCommandInternal); + + NetworkBehaviourProcessor.WriteReturnWriter(worker, weaverTypes); + + worker.Emit(OpCodes.Ret); + return cmd; + } + + /* + // generates code like: + protected static void InvokeCmdCmdThrust(NetworkBehaviour obj, NetworkReader reader, NetworkConnection senderConnection) + { + if (!NetworkServer.active) + { + return; + } + ((ShipControl)obj).CmdThrust(reader.ReadSingle(), (int)reader.ReadPackedUInt32()); + } + */ + public static MethodDefinition ProcessCommandInvoke(WeaverTypes weaverTypes, Readers readers, Logger Log, TypeDefinition td, MethodDefinition method, MethodDefinition cmdCallFunc, ref bool WeavingFailed) + { + string cmdName = Weaver.GenerateMethodName(Weaver.InvokeRpcPrefix, method); + + MethodDefinition cmd = new MethodDefinition(cmdName, + MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig, + weaverTypes.Import(typeof(void))); + + ILProcessor worker = cmd.Body.GetILProcessor(); + Instruction label = worker.Create(OpCodes.Nop); + + NetworkBehaviourProcessor.WriteServerActiveCheck(worker, weaverTypes, method.Name, label, "Command"); + + // setup for reader + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Castclass, td); + + if (!NetworkBehaviourProcessor.ReadArguments(method, readers, Log, worker, RemoteCallType.Command, ref WeavingFailed)) + return null; + + AddSenderConnection(method, worker); + + // invoke actual command function + worker.Emit(OpCodes.Callvirt, cmdCallFunc); + worker.Emit(OpCodes.Ret); + + NetworkBehaviourProcessor.AddInvokeParameters(weaverTypes, cmd.Parameters); + + td.Methods.Add(cmd); + return cmd; + } + + static void AddSenderConnection(MethodDefinition method, ILProcessor worker) + { + foreach (ParameterDefinition param in method.Parameters) + { + if (NetworkBehaviourProcessor.IsSenderConnection(param, RemoteCallType.Command)) + { + // NetworkConnection is 3nd arg (arg0 is "obj" not "this" because method is static) + // example: static void InvokeCmdCmdSendCommand(NetworkBehaviour obj, NetworkReader reader, NetworkConnection connection) + worker.Emit(OpCodes.Ldarg_2); + } + } + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta new file mode 100644 index 0000000..20c3e15 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 73f6c9cdbb9e54f65b3a0a35cc8e55c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs new file mode 100644 index 0000000..8a4c581 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs @@ -0,0 +1,139 @@ +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class MethodProcessor + { + const string RpcPrefix = "UserCode_"; + + // For a function like + // [ClientRpc] void RpcTest(int value), + // Weaver substitutes the method and moves the code to a new method: + // UserCode_RpcTest(int value) <- contains original code + // RpcTest(int value) <- serializes parameters, sends the message + // + // Note that all the calls to the method remain untouched. + // FixRemoteCallToBaseMethod replaces them afterwards. + public static MethodDefinition SubstituteMethod(Logger Log, TypeDefinition td, MethodDefinition md, ref bool WeavingFailed) + { + string newName = Weaver.GenerateMethodName(RpcPrefix, md); + + MethodDefinition cmd = new MethodDefinition(newName, md.Attributes, md.ReturnType); + + // force the substitute method to be protected. + // -> public would show in the Inspector for UnityEvents as + // User_CmdUsePotion() etc. but the user shouldn't use those. + // -> private would not allow inheriting classes to call it, see + // OverrideVirtualWithBaseCallsBothVirtualAndBase test. + // -> IL has no concept of 'protected', it's called IsFamily there. + cmd.IsPublic = false; + cmd.IsFamily = true; + + // add parameters + foreach (ParameterDefinition pd in md.Parameters) + { + cmd.Parameters.Add(new ParameterDefinition(pd.Name, ParameterAttributes.None, pd.ParameterType)); + } + + // swap bodies + (cmd.Body, md.Body) = (md.Body, cmd.Body); + + // Move over all the debugging information + foreach (SequencePoint sequencePoint in md.DebugInformation.SequencePoints) + cmd.DebugInformation.SequencePoints.Add(sequencePoint); + md.DebugInformation.SequencePoints.Clear(); + + foreach (CustomDebugInformation customInfo in md.CustomDebugInformations) + cmd.CustomDebugInformations.Add(customInfo); + md.CustomDebugInformations.Clear(); + + (md.DebugInformation.Scope, cmd.DebugInformation.Scope) = (cmd.DebugInformation.Scope, md.DebugInformation.Scope); + + td.Methods.Add(cmd); + + FixRemoteCallToBaseMethod(Log, td, cmd, ref WeavingFailed); + return cmd; + } + + // For a function like + // [ClientRpc] void RpcTest(int value), + // Weaver substitutes the method and moves the code to a new method: + // UserCode_RpcTest(int value) <- contains original code + // RpcTest(int value) <- serializes parameters, sends the message + // + // FixRemoteCallToBaseMethod replaces all calls to + // RpcTest(value) + // with + // UserCode_RpcTest(value) + public static void FixRemoteCallToBaseMethod(Logger Log, TypeDefinition type, MethodDefinition method, ref bool WeavingFailed) + { + string callName = method.Name; + + // Cmd/rpc start with Weaver.RpcPrefix + // e.g. CallCmdDoSomething + if (!callName.StartsWith(RpcPrefix)) + return; + + // e.g. CmdDoSomething + string baseRemoteCallName = method.Name.Substring(RpcPrefix.Length); + + foreach (Instruction instruction in method.Body.Instructions) + { + // is this instruction a Call to a method? + // if yes, output the method so we can check it. + if (IsCallToMethod(instruction, out MethodDefinition calledMethod)) + { + // when considering if 'calledMethod' is a call to 'method', + // we originally compared .Name. + // + // to fix IL2CPP build bugs with overloaded Rpcs, we need to + // generated rpc names like + // RpcTest(string value) => RpcTestString(strig value) + // RpcTest(int value) => RpcTestInt(int value) + // to make them unique. + // + // calledMethod.Name is still "RpcTest", so we need to + // convert this to the generated name as well before comparing. + string calledMethodName_Generated = Weaver.GenerateMethodName("", calledMethod); + if (calledMethodName_Generated == baseRemoteCallName) + { + TypeDefinition baseType = type.BaseType.Resolve(); + MethodDefinition baseMethod = baseType.GetMethodInBaseType(callName); + + if (baseMethod == null) + { + Log.Error($"Could not find base method for {callName}", method); + WeavingFailed = true; + return; + } + + if (!baseMethod.IsVirtual) + { + Log.Error($"Could not find base method that was virtual {callName}", method); + WeavingFailed = true; + return; + } + + instruction.Operand = baseMethod; + } + } + } + } + + static bool IsCallToMethod(Instruction instruction, out MethodDefinition calledMethod) + { + if (instruction.OpCode == OpCodes.Call && + instruction.Operand is MethodDefinition method) + { + calledMethod = method; + return true; + } + else + { + calledMethod = null; + return false; + } + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs.meta new file mode 100644 index 0000000..3c81894 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/MethodProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 661e1af528e3441f79e1552fb5ec4e0e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs new file mode 100644 index 0000000..e88c5d6 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs @@ -0,0 +1,56 @@ +using Mono.CecilX; + +namespace Mirror.Weaver +{ + // only shows warnings in case we use SyncVars etc. for MonoBehaviour. + static class MonoBehaviourProcessor + { + public static void Process(Logger Log, TypeDefinition td, ref bool WeavingFailed) + { + ProcessSyncVars(Log, td, ref WeavingFailed); + ProcessMethods(Log, td, ref WeavingFailed); + } + + static void ProcessSyncVars(Logger Log, TypeDefinition td, ref bool WeavingFailed) + { + // find syncvars + foreach (FieldDefinition fd in td.Fields) + { + if (fd.HasCustomAttribute()) + { + Log.Error($"SyncVar {fd.Name} must be inside a NetworkBehaviour. {td.Name} is not a NetworkBehaviour", fd); + WeavingFailed = true; + } + + if (SyncObjectInitializer.ImplementsSyncObject(fd.FieldType)) + { + Log.Error($"{fd.Name} is a SyncObject and must be inside a NetworkBehaviour. {td.Name} is not a NetworkBehaviour", fd); + WeavingFailed = true; + } + } + } + + static void ProcessMethods(Logger Log, TypeDefinition td, ref bool WeavingFailed) + { + // find command and RPC functions + foreach (MethodDefinition md in td.Methods) + { + if (md.HasCustomAttribute()) + { + Log.Error($"Command {md.Name} must be declared inside a NetworkBehaviour", md); + WeavingFailed = true; + } + if (md.HasCustomAttribute()) + { + Log.Error($"ClientRpc {md.Name} must be declared inside a NetworkBehaviour", md); + WeavingFailed = true; + } + if (md.HasCustomAttribute()) + { + Log.Error($"TargetRpc {md.Name} must be declared inside a NetworkBehaviour", md); + WeavingFailed = true; + } + } + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta new file mode 100644 index 0000000..ef3f5f4 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/MonoBehaviourProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35c16722912b64af894e4f6668f2e54c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs new file mode 100644 index 0000000..901fc96 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs @@ -0,0 +1,1041 @@ +using System.Collections.Generic; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public enum RemoteCallType + { + Command, + ClientRpc, + TargetRpc + } + + // processes SyncVars, Cmds, Rpcs, etc. of NetworkBehaviours + class NetworkBehaviourProcessor + { + AssemblyDefinition assembly; + WeaverTypes weaverTypes; + SyncVarAccessLists syncVarAccessLists; + SyncVarAttributeProcessor syncVarAttributeProcessor; + Writers writers; + Readers readers; + Logger Log; + + List syncVars = new List(); + List syncObjects = new List(); + // + Dictionary syncVarNetIds = new Dictionary(); + readonly List commands = new List(); + readonly List clientRpcs = new List(); + readonly List targetRpcs = new List(); + readonly List commandInvocationFuncs = new List(); + readonly List clientRpcInvocationFuncs = new List(); + readonly List targetRpcInvocationFuncs = new List(); + + readonly TypeDefinition netBehaviourSubclass; + + public struct CmdResult + { + public MethodDefinition method; + public bool requiresAuthority; + } + + public struct ClientRpcResult + { + public MethodDefinition method; + public bool includeOwner; + } + + public NetworkBehaviourProcessor(AssemblyDefinition assembly, WeaverTypes weaverTypes, SyncVarAccessLists syncVarAccessLists, Writers writers, Readers readers, Logger Log, TypeDefinition td) + { + this.assembly = assembly; + this.weaverTypes = weaverTypes; + this.syncVarAccessLists = syncVarAccessLists; + this.writers = writers; + this.readers = readers; + this.Log = Log; + syncVarAttributeProcessor = new SyncVarAttributeProcessor(assembly, weaverTypes, syncVarAccessLists, Log); + netBehaviourSubclass = td; + } + + // return true if modified + public bool Process(ref bool WeavingFailed) + { + // only process once + if (WasProcessed(netBehaviourSubclass)) + { + return false; + } + + MarkAsProcessed(netBehaviourSubclass); + + // deconstruct tuple and set fields + (syncVars, syncVarNetIds) = syncVarAttributeProcessor.ProcessSyncVars(netBehaviourSubclass, ref WeavingFailed); + + syncObjects = SyncObjectProcessor.FindSyncObjectsFields(writers, readers, Log, netBehaviourSubclass, ref WeavingFailed); + + ProcessMethods(ref WeavingFailed); + if (WeavingFailed) + { + // originally Process returned true in every case, except if already processed. + // maybe return false here in the future. + return true; + } + + // inject initializations into static & instance constructor + InjectIntoStaticConstructor(ref WeavingFailed); + InjectIntoInstanceConstructor(ref WeavingFailed); + + GenerateSerialization(ref WeavingFailed); + if (WeavingFailed) + { + // originally Process returned true in every case, except if already processed. + // maybe return false here in the future. + return true; + } + + GenerateDeSerialization(ref WeavingFailed); + return true; + } + + /* + generates code like: + if (!NetworkClient.active) + Debug.LogError((object) "Command function CmdRespawn called on server."); + + which is used in InvokeCmd, InvokeRpc, etc. + */ + public static void WriteClientActiveCheck(ILProcessor worker, WeaverTypes weaverTypes, string mdName, Instruction label, string errString) + { + // client active check + worker.Emit(OpCodes.Call, weaverTypes.NetworkClientGetActive); + worker.Emit(OpCodes.Brtrue, label); + + worker.Emit(OpCodes.Ldstr, $"{errString} {mdName} called on server."); + worker.Emit(OpCodes.Call, weaverTypes.logErrorReference); + worker.Emit(OpCodes.Ret); + worker.Append(label); + } + /* + generates code like: + if (!NetworkServer.active) + Debug.LogError((object) "Command CmdMsgWhisper called on client."); + */ + public static void WriteServerActiveCheck(ILProcessor worker, WeaverTypes weaverTypes, string mdName, Instruction label, string errString) + { + // server active check + worker.Emit(OpCodes.Call, weaverTypes.NetworkServerGetActive); + worker.Emit(OpCodes.Brtrue, label); + + worker.Emit(OpCodes.Ldstr, $"{errString} {mdName} called on client."); + worker.Emit(OpCodes.Call, weaverTypes.logErrorReference); + worker.Emit(OpCodes.Ret); + worker.Append(label); + } + + public static void WriteSetupLocals(ILProcessor worker, WeaverTypes weaverTypes) + { + worker.Body.InitLocals = true; + worker.Body.Variables.Add(new VariableDefinition(weaverTypes.Import())); + } + + public static void WriteGetWriter(ILProcessor worker, WeaverTypes weaverTypes) + { + // create writer + worker.Emit(OpCodes.Call, weaverTypes.GetWriterReference); + worker.Emit(OpCodes.Stloc_0); + } + + public static void WriteReturnWriter(ILProcessor worker, WeaverTypes weaverTypes) + { + // NetworkWriterPool.Recycle(writer); + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Call, weaverTypes.ReturnWriterReference); + } + + public static bool WriteArguments(ILProcessor worker, Writers writers, Logger Log, MethodDefinition method, RemoteCallType callType, ref bool WeavingFailed) + { + // write each argument + // example result + /* + writer.WritePackedInt32(someNumber); + writer.WriteNetworkIdentity(someTarget); + */ + + bool skipFirst = callType == RemoteCallType.TargetRpc + && TargetRpcProcessor.HasNetworkConnectionParameter(method); + + // arg of calling function, arg 0 is "this" so start counting at 1 + int argNum = 1; + foreach (ParameterDefinition param in method.Parameters) + { + // NetworkConnection is not sent via the NetworkWriter so skip it here + // skip first for NetworkConnection in TargetRpc + if (argNum == 1 && skipFirst) + { + argNum += 1; + continue; + } + // skip SenderConnection in Command + if (IsSenderConnection(param, callType)) + { + argNum += 1; + continue; + } + + MethodReference writeFunc = writers.GetWriteFunc(param.ParameterType, ref WeavingFailed); + if (writeFunc == null) + { + Log.Error($"{method.Name} has invalid parameter {param}", method); + WeavingFailed = true; + return false; + } + + // use built-in writer func on writer object + // NetworkWriter object + worker.Emit(OpCodes.Ldloc_0); + // add argument to call + worker.Emit(OpCodes.Ldarg, argNum); + // call writer extension method + worker.Emit(OpCodes.Call, writeFunc); + argNum += 1; + } + return true; + } + + #region mark / check type as processed + public const string ProcessedFunctionName = "Weaved"; + + // check if the type has a "Weaved" function already + public static bool WasProcessed(TypeDefinition td) + { + return td.GetMethod(ProcessedFunctionName) != null; + } + + // add the Weaved() function which returns true. + // can be called at runtime and from tests to check if weaving succeeded. + public void MarkAsProcessed(TypeDefinition td) + { + if (!WasProcessed(td)) + { + // add a function: + // public override bool MirrorProcessed() { return true; } + // ReuseSlot means 'override'. + MethodDefinition versionMethod = new MethodDefinition( + ProcessedFunctionName, + MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.ReuseSlot, + weaverTypes.Import(typeof(bool))); + ILProcessor worker = versionMethod.Body.GetILProcessor(); + worker.Emit(OpCodes.Ldc_I4_1); + worker.Emit(OpCodes.Ret); + td.Methods.Add(versionMethod); + } + } + #endregion + + // helper function to remove 'Ret' from the end of the method if 'Ret' + // is the last instruction. + // returns false if there was an issue + static bool RemoveFinalRetInstruction(MethodDefinition method) + { + // remove the return opcode from end of function. will add our own later. + if (method.Body.Instructions.Count != 0) + { + Instruction retInstr = method.Body.Instructions[method.Body.Instructions.Count - 1]; + if (retInstr.OpCode == OpCodes.Ret) + { + method.Body.Instructions.RemoveAt(method.Body.Instructions.Count - 1); + return true; + } + return false; + } + + // we did nothing, but there was no error. + return true; + } + + // we need to inject several initializations into NetworkBehaviour cctor + void InjectIntoStaticConstructor(ref bool WeavingFailed) + { + if (commands.Count == 0 && clientRpcs.Count == 0 && targetRpcs.Count == 0) + return; + + // find static constructor + MethodDefinition cctor = netBehaviourSubclass.GetMethod(".cctor"); + bool cctorFound = cctor != null; + if (cctor != null) + { + // remove the return opcode from end of function. will add our own later. + if (!RemoveFinalRetInstruction(cctor)) + { + Log.Error($"{netBehaviourSubclass.Name} has invalid class constructor", cctor); + WeavingFailed = true; + return; + } + } + else + { + // make one! + cctor = new MethodDefinition(".cctor", MethodAttributes.Private | + MethodAttributes.HideBySig | + MethodAttributes.SpecialName | + MethodAttributes.RTSpecialName | + MethodAttributes.Static, + weaverTypes.Import(typeof(void))); + } + + ILProcessor cctorWorker = cctor.Body.GetILProcessor(); + + // register all commands in cctor + for (int i = 0; i < commands.Count; ++i) + { + CmdResult cmdResult = commands[i]; + GenerateRegisterCommandDelegate(cctorWorker, weaverTypes.registerCommandReference, commandInvocationFuncs[i], cmdResult); + } + + // register all client rpcs in cctor + for (int i = 0; i < clientRpcs.Count; ++i) + { + ClientRpcResult clientRpcResult = clientRpcs[i]; + GenerateRegisterRemoteDelegate(cctorWorker, weaverTypes.registerRpcReference, clientRpcInvocationFuncs[i], clientRpcResult.method.FullName); + } + + // register all target rpcs in cctor + for (int i = 0; i < targetRpcs.Count; ++i) + { + GenerateRegisterRemoteDelegate(cctorWorker, weaverTypes.registerRpcReference, targetRpcInvocationFuncs[i], targetRpcs[i].FullName); + } + + // add final 'Ret' instruction to cctor + cctorWorker.Append(cctorWorker.Create(OpCodes.Ret)); + if (!cctorFound) + { + netBehaviourSubclass.Methods.Add(cctor); + } + + // in case class had no cctor, it might have BeforeFieldInit, so injected cctor would be called too late + netBehaviourSubclass.Attributes &= ~TypeAttributes.BeforeFieldInit; + } + + // we need to inject several initializations into NetworkBehaviour ctor + void InjectIntoInstanceConstructor(ref bool WeavingFailed) + { + if (syncObjects.Count == 0) + return; + + // find instance constructor + MethodDefinition ctor = netBehaviourSubclass.GetMethod(".ctor"); + if (ctor == null) + { + Log.Error($"{netBehaviourSubclass.Name} has invalid constructor", netBehaviourSubclass); + WeavingFailed = true; + return; + } + + // remove the return opcode from end of function. will add our own later. + if (!RemoveFinalRetInstruction(ctor)) + { + Log.Error($"{netBehaviourSubclass.Name} has invalid constructor", ctor); + WeavingFailed = true; + return; + } + + ILProcessor ctorWorker = ctor.Body.GetILProcessor(); + + // initialize all sync objects in ctor + foreach (FieldDefinition fd in syncObjects) + { + SyncObjectInitializer.GenerateSyncObjectInitializer(ctorWorker, weaverTypes, fd); + } + + // add final 'Ret' instruction to ctor + ctorWorker.Append(ctorWorker.Create(OpCodes.Ret)); + } + + /* + // This generates code like: + NetworkBehaviour.RegisterCommandDelegate(base.GetType(), "CmdThrust", new NetworkBehaviour.CmdDelegate(ShipControl.InvokeCmdCmdThrust)); + */ + + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + void GenerateRegisterRemoteDelegate(ILProcessor worker, MethodReference registerMethod, MethodDefinition func, string functionFullName) + { + worker.Emit(OpCodes.Ldtoken, netBehaviourSubclass); + worker.Emit(OpCodes.Call, weaverTypes.getTypeFromHandleReference); + worker.Emit(OpCodes.Ldstr, functionFullName); + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ldftn, func); + + worker.Emit(OpCodes.Newobj, weaverTypes.RemoteCallDelegateConstructor); + // + worker.Emit(OpCodes.Call, registerMethod); + } + + void GenerateRegisterCommandDelegate(ILProcessor worker, MethodReference registerMethod, MethodDefinition func, CmdResult cmdResult) + { + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + string cmdName = cmdResult.method.FullName; + bool requiresAuthority = cmdResult.requiresAuthority; + + worker.Emit(OpCodes.Ldtoken, netBehaviourSubclass); + worker.Emit(OpCodes.Call, weaverTypes.getTypeFromHandleReference); + worker.Emit(OpCodes.Ldstr, cmdName); + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ldftn, func); + + worker.Emit(OpCodes.Newobj, weaverTypes.RemoteCallDelegateConstructor); + + // requiresAuthority ? 1 : 0 + worker.Emit(requiresAuthority ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + + worker.Emit(OpCodes.Call, registerMethod); + } + + void GenerateSerialization(ref bool WeavingFailed) + { + const string SerializeMethodName = "SerializeSyncVars"; + if (netBehaviourSubclass.GetMethod(SerializeMethodName) != null) + return; + + if (syncVars.Count == 0) + { + // no synvars, no need for custom OnSerialize + return; + } + + MethodDefinition serialize = new MethodDefinition(SerializeMethodName, + MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, + weaverTypes.Import(typeof(void))); + + serialize.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, weaverTypes.Import())); + serialize.Parameters.Add(new ParameterDefinition("forceAll", ParameterAttributes.None, weaverTypes.Import())); + ILProcessor worker = serialize.Body.GetILProcessor(); + + serialize.Body.InitLocals = true; + + // base.SerializeSyncVars(writer, forceAll); + MethodReference baseSerialize = Resolvers.TryResolveMethodInParents(netBehaviourSubclass.BaseType, assembly, SerializeMethodName); + if (baseSerialize != null) + { + // base + worker.Emit(OpCodes.Ldarg_0); + // writer + worker.Emit(OpCodes.Ldarg_1); + // forceAll + worker.Emit(OpCodes.Ldarg_2); + worker.Emit(OpCodes.Call, baseSerialize); + } + + // Generates: + // if (forceAll) + // { + // writer.WriteInt(health); + // ... + // } + Instruction initialStateLabel = worker.Create(OpCodes.Nop); + // forceAll + worker.Emit(OpCodes.Ldarg_2); // load 'forceAll' flag + worker.Emit(OpCodes.Brfalse, initialStateLabel); // start the 'if forceAll' branch + + // generates write.Write(syncVar) for each SyncVar in forceAll case + foreach (FieldDefinition syncVarDef in syncVars) + { + FieldReference syncVar = syncVarDef; + if (netBehaviourSubclass.HasGenericParameters) + { + syncVar = syncVarDef.MakeHostInstanceGeneric(); + } + // Generates a writer call for each sync variable + // writer + worker.Emit(OpCodes.Ldarg_1); + // this + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, syncVar); + MethodReference writeFunc; + // For NBs we always need to use the default NetworkBehaviour write func + // since the reader counter part uses that exact layout which is not easy to change + // without introducing more edge cases + // effectively this disallows custom NB-type writers/readers on SyncVars + // see: https://github.com/MirrorNetworking/Mirror/issues/2680 + if (syncVar.FieldType.IsDerivedFrom()) + { + writeFunc = writers.GetWriteFunc(weaverTypes.Import(), ref WeavingFailed); + } + else + { + writeFunc = writers.GetWriteFunc(syncVar.FieldType, ref WeavingFailed); + } + + if (writeFunc != null) + { + worker.Emit(OpCodes.Call, writeFunc); + } + else + { + Log.Error($"{syncVar.Name} has unsupported type. Use a supported Mirror type instead", syncVar); + WeavingFailed = true; + return; + } + } + + // if (forceAll) then always return at the end of the 'if' case + worker.Emit(OpCodes.Ret); + + // end the 'if' case for "if (forceAll)" + worker.Append(initialStateLabel); + + //////////////////////////////////////////////////////////////////// + + // write dirty bits before the data fields + // Generates: writer.WritePackedUInt64 (base.get_syncVarDirtyBits ()); + // writer + worker.Emit(OpCodes.Ldarg_1); + // base + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Call, weaverTypes.NetworkBehaviourDirtyBitsReference); + MethodReference writeUint64Func = writers.GetWriteFunc(weaverTypes.Import(), ref WeavingFailed); + worker.Emit(OpCodes.Call, writeUint64Func); + + // generate a writer call for any dirty variable in this class + + // start at number of syncvars in parent + int dirtyBit = syncVarAccessLists.GetSyncVarStart(netBehaviourSubclass.BaseType.FullName); + foreach (FieldDefinition syncVarDef in syncVars) + { + FieldReference syncVar = syncVarDef; + if (netBehaviourSubclass.HasGenericParameters) + { + syncVar = syncVarDef.MakeHostInstanceGeneric(); + } + Instruction varLabel = worker.Create(OpCodes.Nop); + + // Generates: if ((base.get_syncVarDirtyBits() & 1uL) != 0uL) + // base + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Call, weaverTypes.NetworkBehaviourDirtyBitsReference); + // 8 bytes = long + worker.Emit(OpCodes.Ldc_I8, 1L << dirtyBit); + worker.Emit(OpCodes.And); + worker.Emit(OpCodes.Brfalse, varLabel); + + // Generates a call to the writer for that field + // writer + worker.Emit(OpCodes.Ldarg_1); + // base + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, syncVar); + + MethodReference writeFunc; + // For NBs we always need to use the default NetworkBehaviour write func + // since the reader counter part uses that exact layout which is not easy to change + // without introducing more edge cases + // effectively this disallows custom NB-type writers/readers on SyncVars + // see: https://github.com/MirrorNetworking/Mirror/issues/2680 + if (syncVar.FieldType.IsDerivedFrom()) + { + writeFunc = writers.GetWriteFunc(weaverTypes.Import(), ref WeavingFailed); + } + else + { + writeFunc = writers.GetWriteFunc(syncVar.FieldType, ref WeavingFailed); + } + + if (writeFunc != null) + { + worker.Emit(OpCodes.Call, writeFunc); + } + else + { + Log.Error($"{syncVar.Name} has unsupported type. Use a supported Mirror type instead", syncVar); + WeavingFailed = true; + return; + } + + worker.Append(varLabel); + dirtyBit += 1; + } + + // add a log message if needed for debugging + //worker.Emit(OpCodes.Ldstr, $"Injected Serialize {netBehaviourSubclass.Name}"); + //worker.Emit(OpCodes.Call, WeaverTypes.logErrorReference); + + // generate: return + worker.Emit(OpCodes.Ret); + netBehaviourSubclass.Methods.Add(serialize); + } + + void DeserializeField(FieldDefinition syncVar, ILProcessor worker, ref bool WeavingFailed) + { + // put 'this.' onto stack for 'this.syncvar' below + worker.Append(worker.Create(OpCodes.Ldarg_0)); + + // push 'ref T this.field' + worker.Emit(OpCodes.Ldarg_0); + // if the netbehaviour class is generic, we need to make the field reference generic as well for correct IL + if (netBehaviourSubclass.HasGenericParameters) + { + worker.Emit(OpCodes.Ldflda, syncVar.MakeHostInstanceGeneric()); + } + else + { + worker.Emit(OpCodes.Ldflda, syncVar); + } + + // hook? then push 'new Action(Hook)' onto stack + MethodDefinition hookMethod = syncVarAttributeProcessor.GetHookMethod(netBehaviourSubclass, syncVar, ref WeavingFailed); + if (hookMethod != null) + { + syncVarAttributeProcessor.GenerateNewActionFromHookMethod(syncVar, worker, hookMethod); + } + // otherwise push 'null' as hook + else + { + worker.Emit(OpCodes.Ldnull); + } + + // call GeneratedSyncVarDeserialize. + // special cases for GameObject/NetworkIdentity/NetworkBehaviour + // passing netId too for persistence. + if (syncVar.FieldType.Is()) + { + // reader + worker.Emit(OpCodes.Ldarg_1); + + // GameObject setter needs one more parameter: netId field ref + FieldDefinition netIdField = syncVarNetIds[syncVar]; + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdField); + worker.Emit(OpCodes.Call, weaverTypes.generatedSyncVarDeserialize_GameObject); + } + else if (syncVar.FieldType.Is()) + { + // reader + worker.Emit(OpCodes.Ldarg_1); + + // NetworkIdentity deserialize needs one more parameter: netId field ref + FieldDefinition netIdField = syncVarNetIds[syncVar]; + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdField); + worker.Emit(OpCodes.Call, weaverTypes.generatedSyncVarDeserialize_NetworkIdentity); + } + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + else if (syncVar.FieldType.IsDerivedFrom() || syncVar.FieldType.Is()) + { + // reader + worker.Emit(OpCodes.Ldarg_1); + + // NetworkIdentity deserialize needs one more parameter: netId field ref + // (actually its a NetworkBehaviourSyncVar type) + FieldDefinition netIdField = syncVarNetIds[syncVar]; + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdField); + // make generic version of GeneratedSyncVarSetter_NetworkBehaviour + MethodReference getFunc = weaverTypes.generatedSyncVarDeserialize_NetworkBehaviour_T.MakeGeneric(assembly.MainModule, syncVar.FieldType); + worker.Emit(OpCodes.Call, getFunc); + } + else + { + // T value = reader.ReadT(); + // this is still in IL because otherwise weaver generated + // readers/writers don't seem to work in tests. + // besides, this also avoids reader.Read overhead. + MethodReference readFunc = readers.GetReadFunc(syncVar.FieldType, ref WeavingFailed); + if (readFunc == null) + { + Log.Error($"{syncVar.Name} has unsupported type. Use a supported Mirror type instead", syncVar); + WeavingFailed = true; + return; + } + // reader. for 'reader.Read()' below + worker.Emit(OpCodes.Ldarg_1); + // reader.Read() + worker.Emit(OpCodes.Call, readFunc); + + // make generic version of GeneratedSyncVarDeserialize + MethodReference generic = weaverTypes.generatedSyncVarDeserialize.MakeGeneric(assembly.MainModule, syncVar.FieldType); + worker.Emit(OpCodes.Call, generic); + } + } + + void GenerateDeSerialization(ref bool WeavingFailed) + { + const string DeserializeMethodName = "DeserializeSyncVars"; + if (netBehaviourSubclass.GetMethod(DeserializeMethodName) != null) + return; + + if (syncVars.Count == 0) + { + // no synvars, no need for custom OnDeserialize + return; + } + + MethodDefinition serialize = new MethodDefinition(DeserializeMethodName, + MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, + weaverTypes.Import(typeof(void))); + + serialize.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, weaverTypes.Import())); + serialize.Parameters.Add(new ParameterDefinition("initialState", ParameterAttributes.None, weaverTypes.Import())); + ILProcessor serWorker = serialize.Body.GetILProcessor(); + // setup local for dirty bits + serialize.Body.InitLocals = true; + VariableDefinition dirtyBitsLocal = new VariableDefinition(weaverTypes.Import()); + serialize.Body.Variables.Add(dirtyBitsLocal); + + MethodReference baseDeserialize = Resolvers.TryResolveMethodInParents(netBehaviourSubclass.BaseType, assembly, DeserializeMethodName); + if (baseDeserialize != null) + { + // base + serWorker.Append(serWorker.Create(OpCodes.Ldarg_0)); + // reader + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + // initialState + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); + serWorker.Append(serWorker.Create(OpCodes.Call, baseDeserialize)); + } + + // Generates: if (initialState); + Instruction initialStateLabel = serWorker.Create(OpCodes.Nop); + + serWorker.Append(serWorker.Create(OpCodes.Ldarg_2)); + serWorker.Append(serWorker.Create(OpCodes.Brfalse, initialStateLabel)); + + foreach (FieldDefinition syncVar in syncVars) + { + DeserializeField(syncVar, serWorker, ref WeavingFailed); + } + + serWorker.Append(serWorker.Create(OpCodes.Ret)); + + // Generates: end if (initialState); + serWorker.Append(initialStateLabel); + + // get dirty bits + serWorker.Append(serWorker.Create(OpCodes.Ldarg_1)); + serWorker.Append(serWorker.Create(OpCodes.Call, readers.GetReadFunc(weaverTypes.Import(), ref WeavingFailed))); + serWorker.Append(serWorker.Create(OpCodes.Stloc_0)); + + // conditionally read each syncvar + // start at number of syncvars in parent + int dirtyBit = syncVarAccessLists.GetSyncVarStart(netBehaviourSubclass.BaseType.FullName); + foreach (FieldDefinition syncVar in syncVars) + { + Instruction varLabel = serWorker.Create(OpCodes.Nop); + + // check if dirty bit is set + serWorker.Append(serWorker.Create(OpCodes.Ldloc_0)); + serWorker.Append(serWorker.Create(OpCodes.Ldc_I8, 1L << dirtyBit)); + serWorker.Append(serWorker.Create(OpCodes.And)); + serWorker.Append(serWorker.Create(OpCodes.Brfalse, varLabel)); + + DeserializeField(syncVar, serWorker, ref WeavingFailed); + + serWorker.Append(varLabel); + dirtyBit += 1; + } + + // add a log message if needed for debugging + //serWorker.Append(serWorker.Create(OpCodes.Ldstr, $"Injected Deserialize {netBehaviourSubclass.Name}")); + //serWorker.Append(serWorker.Create(OpCodes.Call, WeaverTypes.logErrorReference)); + + serWorker.Append(serWorker.Create(OpCodes.Ret)); + netBehaviourSubclass.Methods.Add(serialize); + } + + public static bool ReadArguments(MethodDefinition method, Readers readers, Logger Log, ILProcessor worker, RemoteCallType callType, ref bool WeavingFailed) + { + // read each argument + // example result + /* + CallCmdDoSomething(reader.ReadPackedInt32(), reader.ReadNetworkIdentity()); + */ + + bool skipFirst = callType == RemoteCallType.TargetRpc + && TargetRpcProcessor.HasNetworkConnectionParameter(method); + + // arg of calling function, arg 0 is "this" so start counting at 1 + int argNum = 1; + foreach (ParameterDefinition param in method.Parameters) + { + // NetworkConnection is not sent via the NetworkWriter so skip it here + // skip first for NetworkConnection in TargetRpc + if (argNum == 1 && skipFirst) + { + argNum += 1; + continue; + } + // skip SenderConnection in Command + if (IsSenderConnection(param, callType)) + { + argNum += 1; + continue; + } + + + MethodReference readFunc = readers.GetReadFunc(param.ParameterType, ref WeavingFailed); + + if (readFunc == null) + { + Log.Error($"{method.Name} has invalid parameter {param}. Unsupported type {param.ParameterType}, use a supported Mirror type instead", method); + WeavingFailed = true; + return false; + } + + worker.Emit(OpCodes.Ldarg_1); + worker.Emit(OpCodes.Call, readFunc); + + // conversion.. is this needed? + if (param.ParameterType.Is()) + { + worker.Emit(OpCodes.Conv_R4); + } + else if (param.ParameterType.Is()) + { + worker.Emit(OpCodes.Conv_R8); + } + } + return true; + } + + public static void AddInvokeParameters(WeaverTypes weaverTypes, ICollection collection) + { + collection.Add(new ParameterDefinition("obj", ParameterAttributes.None, weaverTypes.Import())); + collection.Add(new ParameterDefinition("reader", ParameterAttributes.None, weaverTypes.Import())); + // senderConnection is only used for commands but NetworkBehaviour.CmdDelegate is used for all remote calls + collection.Add(new ParameterDefinition("senderConnection", ParameterAttributes.None, weaverTypes.Import())); + } + + // check if a Command/TargetRpc/Rpc function & parameters are valid for weaving + public bool ValidateRemoteCallAndParameters(MethodDefinition method, RemoteCallType callType, ref bool WeavingFailed) + { + if (method.IsStatic) + { + Log.Error($"{method.Name} must not be static", method); + WeavingFailed = true; + return false; + } + + return ValidateFunction(method, ref WeavingFailed) && + ValidateParameters(method, callType, ref WeavingFailed); + } + + // check if a Command/TargetRpc/Rpc function is valid for weaving + bool ValidateFunction(MethodReference md, ref bool WeavingFailed) + { + if (md.ReturnType.Is()) + { + Log.Error($"{md.Name} cannot be a coroutine", md); + WeavingFailed = true; + return false; + } + if (!md.ReturnType.Is(typeof(void))) + { + Log.Error($"{md.Name} cannot return a value. Make it void instead", md); + WeavingFailed = true; + return false; + } + if (md.HasGenericParameters) + { + Log.Error($"{md.Name} cannot have generic parameters", md); + WeavingFailed = true; + return false; + } + return true; + } + + // check if all Command/TargetRpc/Rpc function's parameters are valid for weaving + bool ValidateParameters(MethodReference method, RemoteCallType callType, ref bool WeavingFailed) + { + for (int i = 0; i < method.Parameters.Count; ++i) + { + ParameterDefinition param = method.Parameters[i]; + if (!ValidateParameter(method, param, callType, i == 0, ref WeavingFailed)) + { + return false; + } + } + return true; + } + + // validate parameters for a remote function call like Rpc/Cmd + bool ValidateParameter(MethodReference method, ParameterDefinition param, RemoteCallType callType, bool firstParam, ref bool WeavingFailed) + { + // need to check this before any type lookups since those will fail since generic types don't resolve + if (param.ParameterType.IsGenericParameter) + { + Log.Error($"{method.Name} cannot have generic parameters", method); + WeavingFailed = true; + return false; + } + + bool isNetworkConnection = param.ParameterType.Is(); + bool isSenderConnection = IsSenderConnection(param, callType); + + if (param.IsOut) + { + Log.Error($"{method.Name} cannot have out parameters", method); + WeavingFailed = true; + return false; + } + + // if not SenderConnection And not TargetRpc NetworkConnection first param + if (!isSenderConnection && isNetworkConnection && !(callType == RemoteCallType.TargetRpc && firstParam)) + { + if (callType == RemoteCallType.Command) + { + Log.Error($"{method.Name} has invalid parameter {param}, Cannot pass NetworkConnections. Instead use 'NetworkConnectionToClient conn = null' to get the sender's connection on the server", method); + } + else + { + Log.Error($"{method.Name} has invalid parameter {param}. Cannot pass NetworkConnections", method); + } + WeavingFailed = true; + return false; + } + + // sender connection can be optional + if (param.IsOptional && !isSenderConnection) + { + Log.Error($"{method.Name} cannot have optional parameters", method); + WeavingFailed = true; + return false; + } + + return true; + } + + public static bool IsSenderConnection(ParameterDefinition param, RemoteCallType callType) + { + if (callType != RemoteCallType.Command) + { + return false; + } + + TypeReference type = param.ParameterType; + + return type.Is() + || type.Resolve().IsDerivedFrom(); + } + + void ProcessMethods(ref bool WeavingFailed) + { + HashSet names = new HashSet(); + + // copy the list of methods because we will be adding methods in the loop + List methods = new List(netBehaviourSubclass.Methods); + // find command and RPC functions + foreach (MethodDefinition md in methods) + { + foreach (CustomAttribute ca in md.CustomAttributes) + { + if (ca.AttributeType.Is()) + { + ProcessCommand(names, md, ca, ref WeavingFailed); + break; + } + + if (ca.AttributeType.Is()) + { + ProcessTargetRpc(names, md, ca, ref WeavingFailed); + break; + } + + if (ca.AttributeType.Is()) + { + ProcessClientRpc(names, md, ca, ref WeavingFailed); + break; + } + } + } + } + + void ProcessClientRpc(HashSet names, MethodDefinition md, CustomAttribute clientRpcAttr, ref bool WeavingFailed) + { + if (md.IsAbstract) + { + Log.Error("Abstract ClientRpc are currently not supported, use virtual method instead", md); + WeavingFailed = true; + return; + } + + if (!ValidateRemoteCallAndParameters(md, RemoteCallType.ClientRpc, ref WeavingFailed)) + { + return; + } + + bool includeOwner = clientRpcAttr.GetField("includeOwner", true); + + names.Add(md.Name); + clientRpcs.Add(new ClientRpcResult + { + method = md, + includeOwner = includeOwner + }); + + MethodDefinition rpcCallFunc = RpcProcessor.ProcessRpcCall(weaverTypes, writers, Log, netBehaviourSubclass, md, clientRpcAttr, ref WeavingFailed); + // need null check here because ProcessRpcCall returns null if it can't write all the args + if (rpcCallFunc == null) { return; } + + MethodDefinition rpcFunc = RpcProcessor.ProcessRpcInvoke(weaverTypes, writers, readers, Log, netBehaviourSubclass, md, rpcCallFunc, ref WeavingFailed); + if (rpcFunc != null) + { + clientRpcInvocationFuncs.Add(rpcFunc); + } + } + + void ProcessTargetRpc(HashSet names, MethodDefinition md, CustomAttribute targetRpcAttr, ref bool WeavingFailed) + { + if (md.IsAbstract) + { + Log.Error("Abstract TargetRpc are currently not supported, use virtual method instead", md); + WeavingFailed = true; + return; + } + + if (!ValidateRemoteCallAndParameters(md, RemoteCallType.TargetRpc, ref WeavingFailed)) + return; + + names.Add(md.Name); + targetRpcs.Add(md); + + MethodDefinition rpcCallFunc = TargetRpcProcessor.ProcessTargetRpcCall(weaverTypes, writers, Log, netBehaviourSubclass, md, targetRpcAttr, ref WeavingFailed); + + MethodDefinition rpcFunc = TargetRpcProcessor.ProcessTargetRpcInvoke(weaverTypes, readers, Log, netBehaviourSubclass, md, rpcCallFunc, ref WeavingFailed); + if (rpcFunc != null) + { + targetRpcInvocationFuncs.Add(rpcFunc); + } + } + + void ProcessCommand(HashSet names, MethodDefinition md, CustomAttribute commandAttr, ref bool WeavingFailed) + { + if (md.IsAbstract) + { + Log.Error("Abstract Commands are currently not supported, use virtual method instead", md); + WeavingFailed = true; + return; + } + + if (!ValidateRemoteCallAndParameters(md, RemoteCallType.Command, ref WeavingFailed)) + return; + + bool requiresAuthority = commandAttr.GetField("requiresAuthority", true); + + names.Add(md.Name); + commands.Add(new CmdResult + { + method = md, + requiresAuthority = requiresAuthority + }); + + MethodDefinition cmdCallFunc = CommandProcessor.ProcessCommandCall(weaverTypes, writers, Log, netBehaviourSubclass, md, commandAttr, ref WeavingFailed); + + MethodDefinition cmdFunc = CommandProcessor.ProcessCommandInvoke(weaverTypes, readers, Log, netBehaviourSubclass, md, cmdCallFunc, ref WeavingFailed); + if (cmdFunc != null) + { + commandInvocationFuncs.Add(cmdFunc); + } + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta new file mode 100644 index 0000000..67c27dc --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8118d606be3214e5d99943ec39530dd8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs new file mode 100644 index 0000000..280240c --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs @@ -0,0 +1,216 @@ +// finds all readers and writers and register them +using System.Linq; +using Mono.CecilX; +using Mono.CecilX.Cil; +using Mono.CecilX.Rocks; +using UnityEngine; + +namespace Mirror.Weaver +{ + public static class ReaderWriterProcessor + { + public static bool Process(AssemblyDefinition CurrentAssembly, IAssemblyResolver resolver, Logger Log, Writers writers, Readers readers, ref bool WeavingFailed) + { + // find NetworkReader/Writer extensions from Mirror.dll first. + // and NetworkMessage custom writer/reader extensions. + // NOTE: do not include this result in our 'modified' return value, + // otherwise Unity crashes when running tests + ProcessMirrorAssemblyClasses(CurrentAssembly, resolver, Log, writers, readers, ref WeavingFailed); + + // find readers/writers in the assembly we are in right now. + return ProcessAssemblyClasses(CurrentAssembly, CurrentAssembly, writers, readers, ref WeavingFailed); + } + + static void ProcessMirrorAssemblyClasses(AssemblyDefinition CurrentAssembly, IAssemblyResolver resolver, Logger Log, Writers writers, Readers readers, ref bool WeavingFailed) + { + // find Mirror.dll in assembly's references. + // those are guaranteed to be resolvable and correct. + // after all, it references them :) + AssemblyNameReference mirrorAssemblyReference = CurrentAssembly.MainModule.FindReference(Weaver.MirrorAssemblyName); + if (mirrorAssemblyReference != null) + { + // resolve the assembly to load the AssemblyDefinition. + // we need to search all types in it. + // if we only were to resolve one known type like in WeaverTypes, + // then we wouldn't need it. + AssemblyDefinition mirrorAssembly = resolver.Resolve(mirrorAssemblyReference); + if (mirrorAssembly != null) + { + ProcessAssemblyClasses(CurrentAssembly, mirrorAssembly, writers, readers, ref WeavingFailed); + } + else Log.Error($"Failed to resolve {mirrorAssemblyReference}"); + } + else Log.Error("Failed to find Mirror AssemblyNameReference. Can't register Mirror.dll readers/writers."); + } + + static bool ProcessAssemblyClasses(AssemblyDefinition CurrentAssembly, AssemblyDefinition assembly, Writers writers, Readers readers, ref bool WeavingFailed) + { + bool modified = false; + foreach (TypeDefinition klass in assembly.MainModule.Types) + { + // extension methods only live in static classes + // static classes are represented as sealed and abstract + if (klass.IsAbstract && klass.IsSealed) + { + // if assembly has any declared writers then it is "modified" + modified |= LoadDeclaredWriters(CurrentAssembly, klass, writers); + modified |= LoadDeclaredReaders(CurrentAssembly, klass, readers); + } + } + + foreach (TypeDefinition klass in assembly.MainModule.Types) + { + // if assembly has any network message then it is modified + modified |= LoadMessageReadWriter(CurrentAssembly.MainModule, writers, readers, klass, ref WeavingFailed); + } + return modified; + } + + static bool LoadMessageReadWriter(ModuleDefinition module, Writers writers, Readers readers, TypeDefinition klass, ref bool WeavingFailed) + { + bool modified = false; + if (!klass.IsAbstract && !klass.IsInterface && klass.ImplementsInterface()) + { + readers.GetReadFunc(module.ImportReference(klass), ref WeavingFailed); + writers.GetWriteFunc(module.ImportReference(klass), ref WeavingFailed); + modified = true; + } + + foreach (TypeDefinition td in klass.NestedTypes) + { + modified |= LoadMessageReadWriter(module, writers, readers, td, ref WeavingFailed); + } + return modified; + } + + static bool LoadDeclaredWriters(AssemblyDefinition currentAssembly, TypeDefinition klass, Writers writers) + { + // register all the writers in this class. Skip the ones with wrong signature + bool modified = false; + foreach (MethodDefinition method in klass.Methods) + { + if (method.Parameters.Count != 2) + continue; + + if (!method.Parameters[0].ParameterType.Is()) + continue; + + if (!method.ReturnType.Is(typeof(void))) + continue; + + if (!method.HasCustomAttribute()) + continue; + + if (method.HasGenericParameters) + continue; + + TypeReference dataType = method.Parameters[1].ParameterType; + writers.Register(dataType, currentAssembly.MainModule.ImportReference(method)); + modified = true; + } + return modified; + } + + static bool LoadDeclaredReaders(AssemblyDefinition currentAssembly, TypeDefinition klass, Readers readers) + { + // register all the reader in this class. Skip the ones with wrong signature + bool modified = false; + foreach (MethodDefinition method in klass.Methods) + { + if (method.Parameters.Count != 1) + continue; + + if (!method.Parameters[0].ParameterType.Is()) + continue; + + if (method.ReturnType.Is(typeof(void))) + continue; + + if (!method.HasCustomAttribute()) + continue; + + if (method.HasGenericParameters) + continue; + + readers.Register(method.ReturnType, currentAssembly.MainModule.ImportReference(method)); + modified = true; + } + return modified; + } + + // helper function to add [RuntimeInitializeOnLoad] attribute to method + static void AddRuntimeInitializeOnLoadAttribute(AssemblyDefinition assembly, WeaverTypes weaverTypes, MethodDefinition method) + { + // NOTE: previously we used reflection because according paul, + // 'weaving Mirror.dll caused unity to rebuild all dlls but in wrong + // order, which breaks rewired' + // it's not obvious why importing an attribute via reflection instead + // of cecil would break anything. let's use cecil. + + // to add a CustomAttribute, we need the attribute's constructor. + // in this case, there are two: empty, and RuntimeInitializeOnLoadType. + // we want the last one, with the type parameter. + MethodDefinition ctor = weaverTypes.runtimeInitializeOnLoadMethodAttribute.GetConstructors().Last(); + //MethodDefinition ctor = weaverTypes.runtimeInitializeOnLoadMethodAttribute.GetConstructors().First(); + // using ctor directly throws: ArgumentException: Member 'System.Void UnityEditor.InitializeOnLoadMethodAttribute::.ctor()' is declared in another module and needs to be imported + // we need to import it first. + CustomAttribute attribute = new CustomAttribute(assembly.MainModule.ImportReference(ctor)); + // add the RuntimeInitializeLoadType.BeforeSceneLoad argument to ctor + attribute.ConstructorArguments.Add(new CustomAttributeArgument(weaverTypes.Import(), RuntimeInitializeLoadType.BeforeSceneLoad)); + method.CustomAttributes.Add(attribute); + } + + // helper function to add [InitializeOnLoad] attribute to method + // (only works in Editor assemblies. check IsEditorAssembly first.) + static void AddInitializeOnLoadAttribute(AssemblyDefinition assembly, WeaverTypes weaverTypes, MethodDefinition method) + { + // NOTE: previously we used reflection because according paul, + // 'weaving Mirror.dll caused unity to rebuild all dlls but in wrong + // order, which breaks rewired' + // it's not obvious why importing an attribute via reflection instead + // of cecil would break anything. let's use cecil. + + // to add a CustomAttribute, we need the attribute's constructor. + // in this case, there's only one - and it's an empty constructor. + MethodDefinition ctor = weaverTypes.initializeOnLoadMethodAttribute.GetConstructors().First(); + // using ctor directly throws: ArgumentException: Member 'System.Void UnityEditor.InitializeOnLoadMethodAttribute::.ctor()' is declared in another module and needs to be imported + // we need to import it first. + CustomAttribute attribute = new CustomAttribute(assembly.MainModule.ImportReference(ctor)); + method.CustomAttributes.Add(attribute); + } + + // adds Mirror.GeneratedNetworkCode.InitReadWriters() method that + // registers all generated writers into Mirror.Writer static class. + // -> uses [RuntimeInitializeOnLoad] attribute so it's invoke at runtime + // -> uses [InitializeOnLoad] if UnityEditor is referenced so it works + // in Editor and in tests too + // + // use ILSpy to see the result (it's in the DLL's 'Mirror' namespace) + public static void InitializeReaderAndWriters(AssemblyDefinition currentAssembly, WeaverTypes weaverTypes, Writers writers, Readers readers, TypeDefinition GeneratedCodeClass) + { + MethodDefinition initReadWriters = new MethodDefinition("InitReadWriters", MethodAttributes.Public | + MethodAttributes.Static, + weaverTypes.Import(typeof(void))); + + // add [RuntimeInitializeOnLoad] in any case + AddRuntimeInitializeOnLoadAttribute(currentAssembly, weaverTypes, initReadWriters); + + // add [InitializeOnLoad] if UnityEditor is referenced + if (Helpers.IsEditorAssembly(currentAssembly)) + { + AddInitializeOnLoadAttribute(currentAssembly, weaverTypes, initReadWriters); + } + + // fill function body with reader/writer initializers + ILProcessor worker = initReadWriters.Body.GetILProcessor(); + // for debugging: add a log to see if initialized on load + //worker.Emit(OpCodes.Ldstr, $"[InitReadWriters] called!"); + //worker.Emit(OpCodes.Call, Weaver.weaverTypes.logWarningReference); + writers.InitializeWriters(worker); + readers.InitializeReaders(worker); + worker.Emit(OpCodes.Ret); + + GeneratedCodeClass.Methods.Add(initReadWriters); + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta new file mode 100644 index 0000000..c14d6fa --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f3263602f0a374ecd8d08588b1fc2f76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs new file mode 100644 index 0000000..6c341e7 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs @@ -0,0 +1,104 @@ +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + // Processes [Rpc] methods in NetworkBehaviour + public static class RpcProcessor + { + public static MethodDefinition ProcessRpcInvoke(WeaverTypes weaverTypes, Writers writers, Readers readers, Logger Log, TypeDefinition td, MethodDefinition md, MethodDefinition rpcCallFunc, ref bool WeavingFailed) + { + string rpcName = Weaver.GenerateMethodName(Weaver.InvokeRpcPrefix, md); + + MethodDefinition rpc = new MethodDefinition(rpcName, MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig, + weaverTypes.Import(typeof(void))); + + ILProcessor worker = rpc.Body.GetILProcessor(); + Instruction label = worker.Create(OpCodes.Nop); + + NetworkBehaviourProcessor.WriteClientActiveCheck(worker, weaverTypes, md.Name, label, "RPC"); + + // setup for reader + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Castclass, td); + + if (!NetworkBehaviourProcessor.ReadArguments(md, readers, Log, worker, RemoteCallType.ClientRpc, ref WeavingFailed)) + return null; + + // invoke actual command function + worker.Emit(OpCodes.Callvirt, rpcCallFunc); + worker.Emit(OpCodes.Ret); + + NetworkBehaviourProcessor.AddInvokeParameters(weaverTypes, rpc.Parameters); + td.Methods.Add(rpc); + return rpc; + } + + /* + * generates code like: + + public void RpcTest (int param) + { + NetworkWriter writer = new NetworkWriter (); + writer.WritePackedUInt32((uint)param); + base.SendRPCInternal(typeof(class),"RpcTest", writer, 0); + } + public void CallRpcTest (int param) + { + // whatever the user did before + } + + Originally HLAPI put the send message code inside the Call function + and then proceeded to replace every call to RpcTest with CallRpcTest + + This method moves all the user's code into the "CallRpc" method + and replaces the body of the original method with the send message code. + This way we do not need to modify the code anywhere else, and this works + correctly in dependent assemblies + */ + public static MethodDefinition ProcessRpcCall(WeaverTypes weaverTypes, Writers writers, Logger Log, TypeDefinition td, MethodDefinition md, CustomAttribute clientRpcAttr, ref bool WeavingFailed) + { + MethodDefinition rpc = MethodProcessor.SubstituteMethod(Log, td, md, ref WeavingFailed); + + ILProcessor worker = md.Body.GetILProcessor(); + + NetworkBehaviourProcessor.WriteSetupLocals(worker, weaverTypes); + + // add a log message if needed for debugging + //worker.Emit(OpCodes.Ldstr, $"Call ClientRpc function {md.Name}"); + //worker.Emit(OpCodes.Call, WeaverTypes.logErrorReference); + + NetworkBehaviourProcessor.WriteGetWriter(worker, weaverTypes); + + // write all the arguments that the user passed to the Rpc call + if (!NetworkBehaviourProcessor.WriteArguments(worker, writers, Log, md, RemoteCallType.ClientRpc, ref WeavingFailed)) + return null; + + int channel = clientRpcAttr.GetField("channel", 0); + bool includeOwner = clientRpcAttr.GetField("includeOwner", true); + + // invoke SendInternal and return + // this + worker.Emit(OpCodes.Ldarg_0); + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + worker.Emit(OpCodes.Ldstr, md.FullName); + // pass the function hash so we don't have to compute it at runtime + // otherwise each GetStableHash call requires O(N) complexity. + // noticeable for long function names: + // https://github.com/MirrorNetworking/Mirror/issues/3375 + worker.Emit(OpCodes.Ldc_I4, md.FullName.GetStableHashCode()); + // writer + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Ldc_I4, channel); + // includeOwner ? 1 : 0 + worker.Emit(includeOwner ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + worker.Emit(OpCodes.Callvirt, weaverTypes.sendRpcInternal); + + NetworkBehaviourProcessor.WriteReturnWriter(worker, weaverTypes); + + worker.Emit(OpCodes.Ret); + + return rpc; + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta new file mode 100644 index 0000000..22375ba --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a3cb7051ff41947e59bba58bdd2b73fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs new file mode 100644 index 0000000..6bb95ee --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs @@ -0,0 +1,163 @@ +// Injects server/client active checks for [Server/Client] attributes +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + static class ServerClientAttributeProcessor + { + public static bool Process(WeaverTypes weaverTypes, Logger Log, TypeDefinition td, ref bool WeavingFailed) + { + bool modified = false; + foreach (MethodDefinition md in td.Methods) + { + modified |= ProcessSiteMethod(weaverTypes, Log, md, ref WeavingFailed); + } + + foreach (TypeDefinition nested in td.NestedTypes) + { + modified |= Process(weaverTypes, Log, nested, ref WeavingFailed); + } + return modified; + } + + static bool ProcessSiteMethod(WeaverTypes weaverTypes, Logger Log, MethodDefinition md, ref bool WeavingFailed) + { + if (md.Name == ".cctor" || + md.Name == NetworkBehaviourProcessor.ProcessedFunctionName || + md.Name.StartsWith(Weaver.InvokeRpcPrefix)) + return false; + + if (md.IsAbstract) + { + if (HasServerClientAttribute(md)) + { + Log.Error("Server or Client Attributes can't be added to abstract method. Server and Client Attributes are not inherited so they need to be applied to the override methods instead.", md); + WeavingFailed = true; + } + return false; + } + + if (md.Body != null && md.Body.Instructions != null) + { + return ProcessMethodAttributes(weaverTypes, md); + } + return false; + } + + public static bool HasServerClientAttribute(MethodDefinition md) + { + foreach (CustomAttribute attr in md.CustomAttributes) + { + switch (attr.Constructor.DeclaringType.ToString()) + { + case "Mirror.ServerAttribute": + case "Mirror.ServerCallbackAttribute": + case "Mirror.ClientAttribute": + case "Mirror.ClientCallbackAttribute": + return true; + default: + break; + } + } + return false; + } + + public static bool ProcessMethodAttributes(WeaverTypes weaverTypes, MethodDefinition md) + { + if (md.HasCustomAttribute()) + InjectServerGuard(weaverTypes, md, true); + else if (md.HasCustomAttribute()) + InjectServerGuard(weaverTypes, md, false); + else if (md.HasCustomAttribute()) + InjectClientGuard(weaverTypes, md, true); + else if (md.HasCustomAttribute()) + InjectClientGuard(weaverTypes, md, false); + else + return false; + + return true; + } + + static void InjectServerGuard(WeaverTypes weaverTypes, MethodDefinition md, bool logWarning) + { + ILProcessor worker = md.Body.GetILProcessor(); + Instruction top = md.Body.Instructions[0]; + + worker.InsertBefore(top, worker.Create(OpCodes.Call, weaverTypes.NetworkServerGetActive)); + worker.InsertBefore(top, worker.Create(OpCodes.Brtrue, top)); + if (logWarning) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldstr, $"[Server] function '{md.FullName}' called when server was not active")); + worker.InsertBefore(top, worker.Create(OpCodes.Call, weaverTypes.logWarningReference)); + } + InjectGuardParameters(md, worker, top); + InjectGuardReturnValue(md, worker, top); + worker.InsertBefore(top, worker.Create(OpCodes.Ret)); + } + + static void InjectClientGuard(WeaverTypes weaverTypes, MethodDefinition md, bool logWarning) + { + ILProcessor worker = md.Body.GetILProcessor(); + Instruction top = md.Body.Instructions[0]; + + worker.InsertBefore(top, worker.Create(OpCodes.Call, weaverTypes.NetworkClientGetActive)); + worker.InsertBefore(top, worker.Create(OpCodes.Brtrue, top)); + if (logWarning) + { + worker.InsertBefore(top, worker.Create(OpCodes.Ldstr, $"[Client] function '{md.FullName}' called when client was not active")); + worker.InsertBefore(top, worker.Create(OpCodes.Call, weaverTypes.logWarningReference)); + } + + InjectGuardParameters(md, worker, top); + InjectGuardReturnValue(md, worker, top); + worker.InsertBefore(top, worker.Create(OpCodes.Ret)); + } + + // this is required to early-out from a function with "ref" or "out" parameters + static void InjectGuardParameters(MethodDefinition md, ILProcessor worker, Instruction top) + { + int offset = md.Resolve().IsStatic ? 0 : 1; + for (int index = 0; index < md.Parameters.Count; index++) + { + ParameterDefinition param = md.Parameters[index]; + if (param.IsOut) + { + // this causes IL2CPP build issues with generic out parameters: + // https://github.com/MirrorNetworking/Mirror/issues/3482 + // TypeReference elementType = param.ParameterType.GetElementType(); + // + // instead we need to use ElementType not GetElementType() + // GetElementType() will get the element type of the inner elementType + // which will return wrong type for arrays and generic + // credit: JamesFrowen + ByReferenceType byRefType = (ByReferenceType)param.ParameterType; + TypeReference elementType = byRefType.ElementType; + + md.Body.Variables.Add(new VariableDefinition(elementType)); + md.Body.InitLocals = true; + + worker.InsertBefore(top, worker.Create(OpCodes.Ldarg, index + offset)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldloca_S, (byte)(md.Body.Variables.Count - 1))); + worker.InsertBefore(top, worker.Create(OpCodes.Initobj, elementType)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldloc, md.Body.Variables.Count - 1)); + worker.InsertBefore(top, worker.Create(OpCodes.Stobj, elementType)); + } + } + } + + // this is required to early-out from a function with a return value. + static void InjectGuardReturnValue(MethodDefinition md, ILProcessor worker, Instruction top) + { + if (!md.ReturnType.Is(typeof(void))) + { + md.Body.Variables.Add(new VariableDefinition(md.ReturnType)); + md.Body.InitLocals = true; + + worker.InsertBefore(top, worker.Create(OpCodes.Ldloca_S, (byte)(md.Body.Variables.Count - 1))); + worker.InsertBefore(top, worker.Create(OpCodes.Initobj, md.ReturnType)); + worker.InsertBefore(top, worker.Create(OpCodes.Ldloc, md.Body.Variables.Count - 1)); + } + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs.meta new file mode 100644 index 0000000..5a5451d --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/ServerClientAttributeProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 024f251bf693bb345b90b9177892d534 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs b/Assets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs new file mode 100644 index 0000000..a174403 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs @@ -0,0 +1,39 @@ +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class SyncObjectInitializer + { + // generates code like: + // this.InitSyncObject(m_sizes); + public static void GenerateSyncObjectInitializer(ILProcessor worker, WeaverTypes weaverTypes, FieldDefinition fd) + { + // register syncobject in network behaviour + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, fd); + worker.Emit(OpCodes.Call, weaverTypes.InitSyncObjectReference); + } + + public static bool ImplementsSyncObject(TypeReference typeRef) + { + try + { + // value types cant inherit from SyncObject + if (typeRef.IsValueType) + { + return false; + } + + return typeRef.Resolve().IsDerivedFrom(); + } + catch + { + // sometimes this will fail if we reference a weird library that can't be resolved, so we just swallow that exception and return false + } + + return false; + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta new file mode 100644 index 0000000..22f976e --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/SyncObjectInitializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d02219b00b3674e59a2151f41e791688 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs new file mode 100644 index 0000000..8143e86 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs @@ -0,0 +1,90 @@ +using System.Collections.Generic; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + public static class SyncObjectProcessor + { + // ulong = 64 bytes + const int SyncObjectsLimit = 64; + + // Finds SyncObjects fields in a type + // Type should be a NetworkBehaviour + public static List FindSyncObjectsFields(Writers writers, Readers readers, Logger Log, TypeDefinition td, ref bool WeavingFailed) + { + List syncObjects = new List(); + + foreach (FieldDefinition fd in td.Fields) + { + if (fd.FieldType.IsGenericParameter || fd.ContainsGenericParameter) + { + // can't call .Resolve on generic ones + continue; + } + + if (fd.FieldType.Resolve().IsDerivedFrom()) + { + if (fd.IsStatic) + { + Log.Error($"{fd.Name} cannot be static", fd); + WeavingFailed = true; + continue; + } + + // SyncObjects always needs to be readonly to guarantee. + // Weaver calls InitSyncObject on them for dirty bits etc. + // Reassigning at runtime would cause undefined behaviour. + // (C# 'readonly' is called 'initonly' in IL code.) + // + // NOTE: instead of forcing readonly, we could also scan all + // instructions for SyncObject assignments. this would + // make unit tests very difficult though. + if (!fd.IsInitOnly) + { + // just a warning for now. + // many people might still use non-readonly SyncObjects. + Log.Warning($"{fd.Name} should have a 'readonly' keyword in front of the variable because {typeof(SyncObject)}s always need to be initialized by the Weaver.", fd); + + // only log, but keep weaving. no need to break projects. + //WeavingFailed = true; + } + + GenerateReadersAndWriters(writers, readers, fd.FieldType, ref WeavingFailed); + + syncObjects.Add(fd); + } + } + + // SyncObjects dirty mask is 64 bit. can't sync more than 64. + if (syncObjects.Count > 64) + { + Log.Error($"{td.Name} has > {SyncObjectsLimit} SyncObjects (SyncLists etc). Consider refactoring your class into multiple components", td); + WeavingFailed = true; + } + + + return syncObjects; + } + + // Generates serialization methods for synclists + static void GenerateReadersAndWriters(Writers writers, Readers readers, TypeReference tr, ref bool WeavingFailed) + { + if (tr is GenericInstanceType genericInstance) + { + foreach (TypeReference argument in genericInstance.GenericArguments) + { + if (!argument.IsGenericParameter) + { + readers.GetReadFunc(argument, ref WeavingFailed); + writers.GetWriteFunc(argument, ref WeavingFailed); + } + } + } + + if (tr != null) + { + GenerateReadersAndWriters(writers, readers, tr.Resolve().BaseType, ref WeavingFailed); + } + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta new file mode 100644 index 0000000..0efe434 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/SyncObjectProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 78f71efc83cde4917b7d21efa90bcc9a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs b/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs new file mode 100644 index 0000000..da7b825 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs @@ -0,0 +1,206 @@ +// [SyncVar] int health; +// is replaced with: +// public int Networkhealth { get; set; } properties. +// this class processes all access to 'health' and replaces it with 'Networkhealth' +using System; +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + public static class SyncVarAttributeAccessReplacer + { + // process the module + public static void Process(Logger Log, ModuleDefinition moduleDef, SyncVarAccessLists syncVarAccessLists) + { + DateTime startTime = DateTime.Now; + + // process all classes in this module + foreach (TypeDefinition td in moduleDef.Types) + { + if (td.IsClass) + { + ProcessClass(Log, syncVarAccessLists, td); + } + } + + Console.WriteLine($" ProcessSitesModule {moduleDef.Name} elapsed time:{(DateTime.Now - startTime)}"); + } + + static void ProcessClass(Logger Log, SyncVarAccessLists syncVarAccessLists, TypeDefinition td) + { + //Console.WriteLine($" ProcessClass {td}"); + + // process all methods in this class + foreach (MethodDefinition md in td.Methods) + { + ProcessMethod(Log, syncVarAccessLists, md); + } + + // processes all nested classes in this class recursively + foreach (TypeDefinition nested in td.NestedTypes) + { + ProcessClass(Log, syncVarAccessLists, nested); + } + } + + static void ProcessMethod(Logger Log, SyncVarAccessLists syncVarAccessLists, MethodDefinition md) + { + // process all references to replaced members with properties + //Log.Warning($" ProcessSiteMethod {md}"); + + // skip static constructor, "MirrorProcessed", "InvokeUserCode_" + if (md.Name == ".cctor" || + md.Name == NetworkBehaviourProcessor.ProcessedFunctionName || + md.Name.StartsWith(Weaver.InvokeRpcPrefix)) + return; + + // skip abstract + if (md.IsAbstract) + { + return; + } + + // go through all instructions of this method + if (md.Body != null && md.Body.Instructions != null) + { + for (int i = 0; i < md.Body.Instructions.Count;) + { + Instruction instr = md.Body.Instructions[i]; + i += ProcessInstruction(Log, syncVarAccessLists, md, instr, i); + } + } + } + + static int ProcessInstruction(Logger Log, SyncVarAccessLists syncVarAccessLists, MethodDefinition md, Instruction instr, int iCount) + { + // stfld (sets value of a field)? + if (instr.OpCode == OpCodes.Stfld) + { + // operand is a FieldDefinition in the same assembly? + if (instr.Operand is FieldDefinition opFieldst) + { + ProcessSetInstruction(syncVarAccessLists, md, instr, opFieldst); + } + // operand is a FieldReference in another assembly? + // this is not supported just yet. + // compilation error is better than silently failing SyncVar serialization at runtime. + // https://github.com/MirrorNetworking/Mirror/issues/3525 + else if (instr.Operand is FieldReference opFieldstRef) + { + // resolve it from the other assembly + FieldDefinition field = opFieldstRef.Resolve(); + + // [SyncVar]? + if (field.HasCustomAttribute()) + { + // ILPostProcessor would need to Process() the assembly's + // references before processing this one. + // we can not control the order. + // instead, Log an error to suggest adding a SetSyncVar(value) function. + // this is a very easy solution for a very rare edge case. + Log.Error($"'[SyncVar] {opFieldstRef.Name}' in '{md.Module.Name}' is modified by '{md.FullName}' in '{field.Module.Name}'. Modifying a [SyncVar] from another assembly is not supported. Please add a: 'public void Set{opFieldstRef.Name}(value) {{ this.{opFieldstRef.Name} = value; }}' function in '{opFieldstRef.DeclaringType.Name}' and call this function from '{md.FullName}' instead."); + } + } + } + + // ldfld (load value of a field)? + if (instr.OpCode == OpCodes.Ldfld) + { + // operand is a FieldDefinition in the same assembly? + if (instr.Operand is FieldDefinition opFieldld) + { + // this instruction gets the value of a field. cache the field reference. + ProcessGetInstruction(syncVarAccessLists, md, instr, opFieldld); + } + } + + // ldflda (load field address aka reference) + if (instr.OpCode == OpCodes.Ldflda) + { + // operand is a FieldDefinition in the same assembly? + if (instr.Operand is FieldDefinition opFieldlda) + { + // watch out for initobj instruction + // see https://github.com/vis2k/Mirror/issues/696 + return ProcessLoadAddressInstruction(syncVarAccessLists, md, instr, opFieldlda, iCount); + } + } + + // we processed one instruction (instr) + return 1; + } + + // replaces syncvar write access with the NetworkXYZ.set property calls + static void ProcessSetInstruction(SyncVarAccessLists syncVarAccessLists, MethodDefinition md, Instruction i, FieldDefinition opField) + { + // don't replace property call sites in constructors + if (md.Name == ".ctor") + return; + + // does it set a field that we replaced? + if (syncVarAccessLists.replacementSetterProperties.TryGetValue(opField, out MethodDefinition replacement)) + { + //replace with property + //Log.Warning($" replacing {md.Name}:{i}", opField); + i.OpCode = OpCodes.Call; + i.Operand = replacement; + //Log.Warning($" replaced {md.Name}:{i}", opField); + } + } + + // replaces syncvar read access with the NetworkXYZ.get property calls + static void ProcessGetInstruction(SyncVarAccessLists syncVarAccessLists, MethodDefinition md, Instruction i, FieldDefinition opField) + { + // don't replace property call sites in constructors + if (md.Name == ".ctor") + return; + + // does it set a field that we replaced? + if (syncVarAccessLists.replacementGetterProperties.TryGetValue(opField, out MethodDefinition replacement)) + { + //replace with property + //Log.Warning($" replacing {md.Name}:{i}"); + i.OpCode = OpCodes.Call; + i.Operand = replacement; + //Log.Warning($" replaced {md.Name}:{i}"); + } + } + + static int ProcessLoadAddressInstruction(SyncVarAccessLists syncVarAccessLists, MethodDefinition md, Instruction instr, FieldDefinition opField, int iCount) + { + // don't replace property call sites in constructors + if (md.Name == ".ctor") + return 1; + + // does it set a field that we replaced? + if (syncVarAccessLists.replacementSetterProperties.TryGetValue(opField, out MethodDefinition replacement)) + { + // we have a replacement for this property + // is the next instruction a initobj? + Instruction nextInstr = md.Body.Instructions[iCount + 1]; + + if (nextInstr.OpCode == OpCodes.Initobj) + { + // we need to replace this code with: + // var tmp = new MyStruct(); + // this.set_Networkxxxx(tmp); + ILProcessor worker = md.Body.GetILProcessor(); + VariableDefinition tmpVariable = new VariableDefinition(opField.FieldType); + md.Body.Variables.Add(tmpVariable); + + worker.InsertBefore(instr, worker.Create(OpCodes.Ldloca, tmpVariable)); + worker.InsertBefore(instr, worker.Create(OpCodes.Initobj, opField.FieldType)); + worker.InsertBefore(instr, worker.Create(OpCodes.Ldloc, tmpVariable)); + worker.InsertBefore(instr, worker.Create(OpCodes.Call, replacement)); + + worker.Remove(instr); + worker.Remove(nextInstr); + return 4; + } + } + + return 1; + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs.meta new file mode 100644 index 0000000..e8c2500 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeAccessReplacer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d48f1ab125e9940a995603796bccc59e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs new file mode 100644 index 0000000..4d0e7b8 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs @@ -0,0 +1,490 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Mono.CecilX; +using Mono.CecilX.Cil; +using Mono.CecilX.Rocks; + +namespace Mirror.Weaver +{ + // Processes [SyncVar] attribute fields in NetworkBehaviour + // not static, because ILPostProcessor is multithreaded + public class SyncVarAttributeProcessor + { + // ulong = 64 bytes + const int SyncVarLimit = 64; + + AssemblyDefinition assembly; + WeaverTypes weaverTypes; + SyncVarAccessLists syncVarAccessLists; + Logger Log; + + string HookParameterMessage(string hookName, TypeReference ValueType) => + $"void {hookName}({ValueType} oldValue, {ValueType} newValue)"; + + public SyncVarAttributeProcessor(AssemblyDefinition assembly, WeaverTypes weaverTypes, SyncVarAccessLists syncVarAccessLists, Logger Log) + { + this.assembly = assembly; + this.weaverTypes = weaverTypes; + this.syncVarAccessLists = syncVarAccessLists; + this.Log = Log; + } + + // Get hook method if any + public MethodDefinition GetHookMethod(TypeDefinition td, FieldDefinition syncVar, ref bool WeavingFailed) + { + CustomAttribute syncVarAttr = syncVar.GetCustomAttribute(); + + if (syncVarAttr == null) + return null; + + string hookFunctionName = syncVarAttr.GetField("hook", null); + + if (hookFunctionName == null) + return null; + + return FindHookMethod(td, syncVar, hookFunctionName, ref WeavingFailed); + } + + // push hook from GetHookMethod() onto the stack as a new Action. + // allows for reuse without handling static/virtual cases every time. + public void GenerateNewActionFromHookMethod(FieldDefinition syncVar, ILProcessor worker, MethodDefinition hookMethod) + { + // IL_000a: ldarg.0 + // IL_000b: ldftn instance void Mirror.Examples.Tanks.Tank::ExampleHook(int32, int32) + // IL_0011: newobj instance void class [netstandard]System.Action`2::.ctor(object, native int) + + // we support static hook sand instance hooks. + if (hookMethod.IsStatic) + { + // for static hooks, we need to push 'null' first. + // we can't just push nothing. + // stack would get out of balance because we already pushed + // other stuff above. + worker.Emit(OpCodes.Ldnull); + } + else + { + // for instance hooks, we need to push 'this.' first. + worker.Emit(OpCodes.Ldarg_0); + } + + MethodReference hookMethodReference; + // if the network behaviour class is generic, we need to make the method reference generic for correct IL + if (hookMethod.DeclaringType.HasGenericParameters) + { + hookMethodReference = hookMethod.MakeHostInstanceGeneric(hookMethod.Module, hookMethod.DeclaringType.MakeGenericInstanceType(hookMethod.DeclaringType.GenericParameters.ToArray())); + } + else + { + hookMethodReference = hookMethod; + } + + // we support regular and virtual hook functions. + if (hookMethod.IsVirtual) + { + // for virtual / overwritten hooks, we need different IL. + // this is from simply testing Action = VirtualHook; in C#. + worker.Emit(OpCodes.Dup); + worker.Emit(OpCodes.Ldvirtftn, hookMethodReference); + } + else + { + worker.Emit(OpCodes.Ldftn, hookMethodReference); + } + + // call 'new Action()' constructor to convert the function to an action + // we need to make an instance of the generic Action. + // + // TODO this allocates a new 'Action' for every SyncVar hook call. + // we should allocate it once and store it somewhere in the future. + // hooks are only called on the client though, so it's not too bad for now. + TypeReference actionRef = assembly.MainModule.ImportReference(typeof(Action<,>)); + GenericInstanceType genericInstance = actionRef.MakeGenericInstanceType(syncVar.FieldType, syncVar.FieldType); + worker.Emit(OpCodes.Newobj, weaverTypes.ActionT_T.MakeHostInstanceGeneric(assembly.MainModule, genericInstance)); + } + + MethodDefinition FindHookMethod(TypeDefinition td, FieldDefinition syncVar, string hookFunctionName, ref bool WeavingFailed) + { + List methods = td.GetMethods(hookFunctionName); + + List methodsWith2Param = new List(methods.Where(m => m.Parameters.Count == 2)); + + if (methodsWith2Param.Count == 0) + { + Log.Error($"Could not find hook for '{syncVar.Name}', hook name '{hookFunctionName}'. " + + $"Method signature should be {HookParameterMessage(hookFunctionName, syncVar.FieldType)}", + syncVar); + WeavingFailed = true; + + return null; + } + + foreach (MethodDefinition method in methodsWith2Param) + { + if (MatchesParameters(syncVar, method)) + { + return method; + } + } + + Log.Error($"Wrong type for Parameter in hook for '{syncVar.Name}', hook name '{hookFunctionName}'. " + + $"Method signature should be {HookParameterMessage(hookFunctionName, syncVar.FieldType)}", + syncVar); + WeavingFailed = true; + + return null; + } + + bool MatchesParameters(FieldDefinition syncVar, MethodDefinition method) + { + // matches void onValueChange(T oldValue, T newValue) + return method.Parameters[0].ParameterType.FullName == syncVar.FieldType.FullName && + method.Parameters[1].ParameterType.FullName == syncVar.FieldType.FullName; + } + + public MethodDefinition GenerateSyncVarGetter(FieldDefinition fd, string originalName, FieldDefinition netFieldId) + { + //Create the get method + MethodDefinition get = new MethodDefinition( + $"get_Network{originalName}", MethodAttributes.Public | + MethodAttributes.SpecialName | + MethodAttributes.HideBySig, + fd.FieldType); + + ILProcessor worker = get.Body.GetILProcessor(); + + FieldReference fr; + if (fd.DeclaringType.HasGenericParameters) + { + fr = fd.MakeHostInstanceGeneric(); + } + else + { + fr = fd; + } + + FieldReference netIdFieldReference = null; + if (netFieldId != null) + { + if (netFieldId.DeclaringType.HasGenericParameters) + { + netIdFieldReference = netFieldId.MakeHostInstanceGeneric(); + } + else + { + netIdFieldReference = netFieldId; + } + } + + // [SyncVar] GameObject? + if (fd.FieldType.Is()) + { + // return this.GetSyncVarGameObject(ref field, uint netId); + // this. + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, netIdFieldReference); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, fr); + worker.Emit(OpCodes.Call, weaverTypes.getSyncVarGameObjectReference); + worker.Emit(OpCodes.Ret); + } + // [SyncVar] NetworkIdentity? + else if (fd.FieldType.Is()) + { + // return this.GetSyncVarNetworkIdentity(ref field, uint netId); + // this. + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, netIdFieldReference); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, fr); + worker.Emit(OpCodes.Call, weaverTypes.getSyncVarNetworkIdentityReference); + worker.Emit(OpCodes.Ret); + } + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + else if (fd.FieldType.IsDerivedFrom() || fd.FieldType.Is()) + { + // return this.GetSyncVarNetworkBehaviour(ref field, uint netId); + // this. + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, netIdFieldReference); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, fr); + MethodReference getFunc = weaverTypes.getSyncVarNetworkBehaviourReference.MakeGeneric(assembly.MainModule, fd.FieldType); + worker.Emit(OpCodes.Call, getFunc); + worker.Emit(OpCodes.Ret); + } + // [SyncVar] int, string, etc. + else + { + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldfld, fr); + worker.Emit(OpCodes.Ret); + } + + get.Body.Variables.Add(new VariableDefinition(fd.FieldType)); + get.Body.InitLocals = true; + get.SemanticsAttributes = MethodSemanticsAttributes.Getter; + + return get; + } + + // for [SyncVar] health, weaver generates + // + // NetworkHealth + // { + // get => health; + // set => GeneratedSyncVarSetter(...) + // } + // + // the setter used to be manually IL generated, but we moved it to C# :) + public MethodDefinition GenerateSyncVarSetter(TypeDefinition td, FieldDefinition fd, string originalName, long dirtyBit, FieldDefinition netFieldId, ref bool WeavingFailed) + { + //Create the set method + MethodDefinition set = new MethodDefinition($"set_Network{originalName}", MethodAttributes.Public | + MethodAttributes.SpecialName | + MethodAttributes.HideBySig, + weaverTypes.Import(typeof(void))); + + ILProcessor worker = set.Body.GetILProcessor(); + FieldReference fr; + if (fd.DeclaringType.HasGenericParameters) + { + fr = fd.MakeHostInstanceGeneric(); + } + else + { + fr = fd; + } + + FieldReference netIdFieldReference = null; + if (netFieldId != null) + { + if (netFieldId.DeclaringType.HasGenericParameters) + { + netIdFieldReference = netFieldId.MakeHostInstanceGeneric(); + } + else + { + netIdFieldReference = netFieldId; + } + } + + // if (!SyncVarEqual(value, ref playerData)) + Instruction endOfMethod = worker.Create(OpCodes.Nop); + + // NOTE: SyncVar...Equal functions are static. + // don't Emit Ldarg_0 aka 'this'. + + // call WeaverSyncVarSetter(T value, ref T field, ulong dirtyBit, Action OnChanged = null) + // IL_0000: ldarg.0 + // IL_0001: ldarg.1 + // IL_0002: ldarg.0 + // IL_0003: ldflda int32 Mirror.Examples.Tanks.Tank::health + // IL_0008: ldc.i4.1 + // IL_0009: conv.i8 + // IL_000a: ldnull + // IL_000b: call instance void [Mirror]Mirror.NetworkBehaviour::GeneratedSyncVarSetter(!!0, !!0&, uint64, class [netstandard]System.Action`2) + // IL_0010: ret + + // 'this.' for the call + worker.Emit(OpCodes.Ldarg_0); + + // first push 'value' + worker.Emit(OpCodes.Ldarg_1); + + // push 'ref T this.field' + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, fr); + + // push the dirty bit for this SyncVar + worker.Emit(OpCodes.Ldc_I8, dirtyBit); + + // hook? then push 'new Action(Hook)' onto stack + MethodDefinition hookMethod = GetHookMethod(td, fd, ref WeavingFailed); + if (hookMethod != null) + { + GenerateNewActionFromHookMethod(fd, worker, hookMethod); + } + // otherwise push 'null' as hook + else + { + worker.Emit(OpCodes.Ldnull); + } + + // call GeneratedSyncVarSetter. + // special cases for GameObject/NetworkIdentity/NetworkBehaviour + // passing netId too for persistence. + if (fd.FieldType.Is()) + { + // GameObject setter needs one more parameter: netId field ref + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdFieldReference); + worker.Emit(OpCodes.Call, weaverTypes.generatedSyncVarSetter_GameObject); + } + else if (fd.FieldType.Is()) + { + // NetworkIdentity setter needs one more parameter: netId field ref + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdFieldReference); + worker.Emit(OpCodes.Call, weaverTypes.generatedSyncVarSetter_NetworkIdentity); + } + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + else if (fd.FieldType.IsDerivedFrom() || fd.FieldType.Is()) + { + // NetworkIdentity setter needs one more parameter: netId field ref + // (actually its a NetworkBehaviourSyncVar type) + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldflda, netIdFieldReference); + // make generic version of GeneratedSyncVarSetter_NetworkBehaviour + MethodReference getFunc = weaverTypes.generatedSyncVarSetter_NetworkBehaviour_T.MakeGeneric(assembly.MainModule, fd.FieldType); + worker.Emit(OpCodes.Call, getFunc); + } + else + { + // make generic version of GeneratedSyncVarSetter + MethodReference generic = weaverTypes.generatedSyncVarSetter.MakeGeneric(assembly.MainModule, fd.FieldType); + worker.Emit(OpCodes.Call, generic); + } + + worker.Append(endOfMethod); + + worker.Emit(OpCodes.Ret); + + set.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.In, fd.FieldType)); + set.SemanticsAttributes = MethodSemanticsAttributes.Setter; + + return set; + } + + public void ProcessSyncVar(TypeDefinition td, FieldDefinition fd, Dictionary syncVarNetIds, long dirtyBit, ref bool WeavingFailed) + { + string originalName = fd.Name; + + // GameObject/NetworkIdentity SyncVars have a new field for netId + FieldDefinition netIdField = null; + // NetworkBehaviour has different field type than other NetworkIdentityFields + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + if (fd.FieldType.IsDerivedFrom() || fd.FieldType.Is()) + { + netIdField = new FieldDefinition($"___{fd.Name}NetId", + FieldAttributes.Family, // needs to be protected for generic classes, otherwise access isn't allowed + weaverTypes.Import()); + netIdField.DeclaringType = td; + + syncVarNetIds[fd] = netIdField; + } + else if (fd.FieldType.IsNetworkIdentityField()) + { + netIdField = new FieldDefinition($"___{fd.Name}NetId", + FieldAttributes.Family, // needs to be protected for generic classes, otherwise access isn't allowed + weaverTypes.Import()); + netIdField.DeclaringType = td; + + syncVarNetIds[fd] = netIdField; + } + + MethodDefinition get = GenerateSyncVarGetter(fd, originalName, netIdField); + MethodDefinition set = GenerateSyncVarSetter(td, fd, originalName, dirtyBit, netIdField, ref WeavingFailed); + + //NOTE: is property even needed? Could just use a setter function? + //create the property + PropertyDefinition propertyDefinition = new PropertyDefinition($"Network{originalName}", PropertyAttributes.None, fd.FieldType) + { + GetMethod = get, + SetMethod = set + }; + + //add the methods and property to the type. + td.Methods.Add(get); + td.Methods.Add(set); + td.Properties.Add(propertyDefinition); + syncVarAccessLists.replacementSetterProperties[fd] = set; + + // replace getter field if GameObject/NetworkIdentity so it uses + // netId instead + // -> only for GameObjects, otherwise an int syncvar's getter would + // end up in recursion. + if (fd.FieldType.IsNetworkIdentityField()) + { + syncVarAccessLists.replacementGetterProperties[fd] = get; + } + } + + public (List syncVars, Dictionary syncVarNetIds) ProcessSyncVars(TypeDefinition td, ref bool WeavingFailed) + { + List syncVars = new List(); + Dictionary syncVarNetIds = new Dictionary(); + + // the mapping of dirtybits to sync-vars is implicit in the order of the fields here. this order is recorded in m_replacementProperties. + // start assigning syncvars at the place the base class stopped, if any + int dirtyBitCounter = syncVarAccessLists.GetSyncVarStart(td.BaseType.FullName); + + // find syncvars + foreach (FieldDefinition fd in td.Fields) + { + if (fd.HasCustomAttribute()) + { + if ((fd.Attributes & FieldAttributes.Static) != 0) + { + Log.Error($"{fd.Name} cannot be static", fd); + WeavingFailed = true; + continue; + } + + if (fd.FieldType.IsGenericParameter) + { + Log.Error($"{fd.Name} has generic type. Generic SyncVars are not supported", fd); + WeavingFailed = true; + continue; + } + + if (fd.FieldType.IsArray) + { + Log.Error($"{fd.Name} has invalid type. Use SyncLists instead of arrays", fd); + WeavingFailed = true; + continue; + } + + if (SyncObjectInitializer.ImplementsSyncObject(fd.FieldType)) + { + Log.Warning($"{fd.Name} has [SyncVar] attribute. SyncLists should not be marked with SyncVar", fd); + } + else + { + syncVars.Add(fd); + + ProcessSyncVar(td, fd, syncVarNetIds, 1L << dirtyBitCounter, ref WeavingFailed); + dirtyBitCounter += 1; + + if (dirtyBitCounter > SyncVarLimit) + { + Log.Error($"{td.Name} has > {SyncVarLimit} SyncVars. Consider refactoring your class into multiple components", td); + WeavingFailed = true; + continue; + } + } + } + } + + // add all the new SyncVar __netId fields + foreach (FieldDefinition fd in syncVarNetIds.Values) + { + td.Fields.Add(fd); + } + + // include parent class syncvars + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3457 + int parentSyncVarCount = syncVarAccessLists.GetSyncVarStart(td.BaseType.FullName); + syncVarAccessLists.SetNumSyncVars(td.FullName, parentSyncVarCount + syncVars.Count); + + return (syncVars, syncVarNetIds); + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs.meta new file mode 100644 index 0000000..982f768 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/SyncVarAttributeProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f52c39bddd95d42b88f9cd554dfd9198 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs new file mode 100644 index 0000000..cbc1e5d --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs @@ -0,0 +1,159 @@ +using Mono.CecilX; +using Mono.CecilX.Cil; + +namespace Mirror.Weaver +{ + // Processes [TargetRpc] methods in NetworkBehaviour + public static class TargetRpcProcessor + { + // helper functions to check if the method has a NetworkConnection parameter + public static bool HasNetworkConnectionParameter(MethodDefinition md) + { + if (md.Parameters.Count > 0) + { + // we need to allow both NetworkConnection, and inheriting types. + // NetworkBehaviour.SendTargetRpc takes a NetworkConnection parameter. + // fixes https://github.com/vis2k/Mirror/issues/3290 + TypeReference type = md.Parameters[0].ParameterType; + return type.Is() || + type.IsDerivedFrom(); + } + return false; + } + + public static MethodDefinition ProcessTargetRpcInvoke(WeaverTypes weaverTypes, Readers readers, Logger Log, TypeDefinition td, MethodDefinition md, MethodDefinition rpcCallFunc, ref bool WeavingFailed) + { + string trgName = Weaver.GenerateMethodName(Weaver.InvokeRpcPrefix, md); + + MethodDefinition rpc = new MethodDefinition(trgName, MethodAttributes.Family | + MethodAttributes.Static | + MethodAttributes.HideBySig, + weaverTypes.Import(typeof(void))); + + ILProcessor worker = rpc.Body.GetILProcessor(); + Instruction label = worker.Create(OpCodes.Nop); + + NetworkBehaviourProcessor.WriteClientActiveCheck(worker, weaverTypes, md.Name, label, "TargetRPC"); + + // setup for reader + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Castclass, td); + + // NetworkConnection parameter is optional + if (HasNetworkConnectionParameter(md)) + { + // TargetRpcs are sent from server to client. + // on server, we currently support two types: + // TargetRpc(NetworkConnection) + // TargetRpc(NetworkConnectionToClient) + // however, it's always a connection to client. + // in the future, only NetworkConnectionToClient will be supported. + // explicit typing helps catch issues at compile time. + // + // on client, InvokeTargetRpc calls the original code. + // we need to fill in the NetworkConnection parameter. + // NetworkClient.connection is always a connection to server. + // + // we used to pass NetworkClient.connection as the TargetRpc parameter. + // which caused: https://github.com/MirrorNetworking/Mirror/issues/3455 + // when the parameter is defined as a NetworkConnectionToClient. + // + // a client's connection never fits into a NetworkConnectionToClient. + // we need to always pass null here. + worker.Emit(OpCodes.Ldnull); + } + + // process reader parameters and skip first one if first one is NetworkConnection + if (!NetworkBehaviourProcessor.ReadArguments(md, readers, Log, worker, RemoteCallType.TargetRpc, ref WeavingFailed)) + return null; + + // invoke actual command function + worker.Emit(OpCodes.Callvirt, rpcCallFunc); + worker.Emit(OpCodes.Ret); + + NetworkBehaviourProcessor.AddInvokeParameters(weaverTypes, rpc.Parameters); + td.Methods.Add(rpc); + return rpc; + } + + /* generates code like: + public void TargetTest (NetworkConnection conn, int param) + { + NetworkWriter writer = new NetworkWriter (); + writer.WritePackedUInt32 ((uint)param); + base.SendTargetRPCInternal (conn, typeof(class), "TargetTest", val); + } + public void CallTargetTest (NetworkConnection conn, int param) + { + // whatever the user did before + } + + or if optional: + public void TargetTest (int param) + { + NetworkWriter writer = new NetworkWriter (); + writer.WritePackedUInt32 ((uint)param); + base.SendTargetRPCInternal (null, typeof(class), "TargetTest", val); + } + public void CallTargetTest (int param) + { + // whatever the user did before + } + + Originally HLAPI put the send message code inside the Call function + and then proceeded to replace every call to TargetTest with CallTargetTest + + This method moves all the user's code into the "CallTargetRpc" method + and replaces the body of the original method with the send message code. + This way we do not need to modify the code anywhere else, and this works + correctly in dependent assemblies + + */ + public static MethodDefinition ProcessTargetRpcCall(WeaverTypes weaverTypes, Writers writers, Logger Log, TypeDefinition td, MethodDefinition md, CustomAttribute targetRpcAttr, ref bool WeavingFailed) + { + MethodDefinition rpc = MethodProcessor.SubstituteMethod(Log, td, md, ref WeavingFailed); + + ILProcessor worker = md.Body.GetILProcessor(); + + NetworkBehaviourProcessor.WriteSetupLocals(worker, weaverTypes); + + NetworkBehaviourProcessor.WriteGetWriter(worker, weaverTypes); + + // write all the arguments that the user passed to the TargetRpc call + // (skip first one if first one is NetworkConnection) + if (!NetworkBehaviourProcessor.WriteArguments(worker, writers, Log, md, RemoteCallType.TargetRpc, ref WeavingFailed)) + return null; + + // invoke SendInternal and return + // this + worker.Emit(OpCodes.Ldarg_0); + if (HasNetworkConnectionParameter(md)) + { + // connection + worker.Emit(OpCodes.Ldarg_1); + } + else + { + // null + worker.Emit(OpCodes.Ldnull); + } + // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions + worker.Emit(OpCodes.Ldstr, md.FullName); + // pass the function hash so we don't have to compute it at runtime + // otherwise each GetStableHash call requires O(N) complexity. + // noticeable for long function names: + // https://github.com/MirrorNetworking/Mirror/issues/3375 + worker.Emit(OpCodes.Ldc_I4, md.FullName.GetStableHashCode()); + // writer + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Ldc_I4, targetRpcAttr.GetField("channel", 0)); + worker.Emit(OpCodes.Callvirt, weaverTypes.sendTargetRpcInternal); + + NetworkBehaviourProcessor.WriteReturnWriter(worker, weaverTypes); + + worker.Emit(OpCodes.Ret); + + return rpc; + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta b/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta new file mode 100644 index 0000000..0ff7cc5 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb3ce6c6f3f2942ae88178b86f5a8282 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Readers.cs b/Assets/Mirror/Editor/Weaver/Readers.cs new file mode 100644 index 0000000..33941d9 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Readers.cs @@ -0,0 +1,385 @@ +using System; +using System.Collections.Generic; +using Mono.CecilX; +using Mono.CecilX.Cil; +// to use Mono.CecilX.Rocks here, we need to 'override references' in the +// Unity.Mirror.CodeGen assembly definition file in the Editor, and add CecilX.Rocks. +// otherwise we get an unknown import exception. +using Mono.CecilX.Rocks; + +namespace Mirror.Weaver +{ + // not static, because ILPostProcessor is multithreaded + public class Readers + { + // Readers are only for this assembly. + // can't be used from another assembly, otherwise we will get: + // "System.ArgumentException: Member ... is declared in another module and needs to be imported" + AssemblyDefinition assembly; + WeaverTypes weaverTypes; + TypeDefinition GeneratedCodeClass; + Logger Log; + + Dictionary readFuncs = + new Dictionary(new TypeReferenceComparer()); + + public Readers(AssemblyDefinition assembly, WeaverTypes weaverTypes, TypeDefinition GeneratedCodeClass, Logger Log) + { + this.assembly = assembly; + this.weaverTypes = weaverTypes; + this.GeneratedCodeClass = GeneratedCodeClass; + this.Log = Log; + } + + internal void Register(TypeReference dataType, MethodReference methodReference) + { + if (readFuncs.ContainsKey(dataType)) + { + // TODO enable this again later. + // Reader has some obsolete functions that were renamed. + // Don't want weaver warnings for all of them. + //Log.Warning($"Registering a Read method for {dataType.FullName} when one already exists", methodReference); + } + + // we need to import type when we Initialize Readers so import here in case it is used anywhere else + TypeReference imported = assembly.MainModule.ImportReference(dataType); + readFuncs[imported] = methodReference; + } + + void RegisterReadFunc(TypeReference typeReference, MethodDefinition newReaderFunc) + { + Register(typeReference, newReaderFunc); + GeneratedCodeClass.Methods.Add(newReaderFunc); + } + + // Finds existing reader for type, if non exists trys to create one + public MethodReference GetReadFunc(TypeReference variable, ref bool WeavingFailed) + { + if (readFuncs.TryGetValue(variable, out MethodReference foundFunc)) + return foundFunc; + + TypeReference importedVariable = assembly.MainModule.ImportReference(variable); + return GenerateReader(importedVariable, ref WeavingFailed); + } + + MethodReference GenerateReader(TypeReference variableReference, ref bool WeavingFailed) + { + // Arrays are special, if we resolve them, we get the element type, + // so the following ifs might choke on it for scriptable objects + // or other objects that require a custom serializer + // thus check if it is an array and skip all the checks. + if (variableReference.IsArray) + { + if (variableReference.IsMultidimensionalArray()) + { + Log.Error($"{variableReference.Name} is an unsupported type. Multidimensional arrays are not supported", variableReference); + WeavingFailed = true; + return null; + } + + return GenerateReadCollection(variableReference, variableReference.GetElementType(), nameof(NetworkReaderExtensions.ReadArray), ref WeavingFailed); + } + + TypeDefinition variableDefinition = variableReference.Resolve(); + + // check if the type is completely invalid + if (variableDefinition == null) + { + Log.Error($"{variableReference.Name} is not a supported type", variableReference); + WeavingFailed = true; + return null; + } + else if (variableReference.IsByReference) + { + // error?? + Log.Error($"Cannot pass type {variableReference.Name} by reference", variableReference); + WeavingFailed = true; + return null; + } + + // use existing func for known types + if (variableDefinition.IsEnum) + { + return GenerateEnumReadFunc(variableReference, ref WeavingFailed); + } + else if (variableDefinition.Is(typeof(ArraySegment<>))) + { + return GenerateArraySegmentReadFunc(variableReference, ref WeavingFailed); + } + else if (variableDefinition.Is(typeof(List<>))) + { + GenericInstanceType genericInstance = (GenericInstanceType)variableReference; + TypeReference elementType = genericInstance.GenericArguments[0]; + + return GenerateReadCollection(variableReference, elementType, nameof(NetworkReaderExtensions.ReadList), ref WeavingFailed); + } + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + else if (variableReference.IsDerivedFrom() || variableReference.Is()) + { + return GetNetworkBehaviourReader(variableReference); + } + + // check if reader generation is applicable on this type + if (variableDefinition.IsDerivedFrom()) + { + Log.Error($"Cannot generate reader for component type {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; + return null; + } + if (variableReference.Is()) + { + Log.Error($"Cannot generate reader for {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; + return null; + } + if (variableReference.Is()) + { + Log.Error($"Cannot generate reader for {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; + return null; + } + if (variableDefinition.HasGenericParameters) + { + Log.Error($"Cannot generate reader for generic variable {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; + return null; + } + if (variableDefinition.IsInterface) + { + Log.Error($"Cannot generate reader for interface {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; + return null; + } + if (variableDefinition.IsAbstract) + { + Log.Error($"Cannot generate reader for abstract class {variableReference.Name}. Use a supported type or provide a custom reader", variableReference); + WeavingFailed = true; + return null; + } + + return GenerateClassOrStructReadFunction(variableReference, ref WeavingFailed); + } + + MethodReference GetNetworkBehaviourReader(TypeReference variableReference) + { + // uses generic ReadNetworkBehaviour rather than having weaver create one for each NB + MethodReference generic = weaverTypes.readNetworkBehaviourGeneric; + + MethodReference readFunc = generic.MakeGeneric(assembly.MainModule, variableReference); + + // register function so it is added to Reader + // use Register instead of RegisterWriteFunc because this is not a generated function + Register(variableReference, readFunc); + + return readFunc; + } + + MethodDefinition GenerateEnumReadFunc(TypeReference variable, ref bool WeavingFailed) + { + MethodDefinition readerFunc = GenerateReaderFunction(variable); + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + worker.Emit(OpCodes.Ldarg_0); + + TypeReference underlyingType = variable.Resolve().GetEnumUnderlyingType(); + MethodReference underlyingFunc = GetReadFunc(underlyingType, ref WeavingFailed); + + worker.Emit(OpCodes.Call, underlyingFunc); + worker.Emit(OpCodes.Ret); + return readerFunc; + } + + MethodDefinition GenerateArraySegmentReadFunc(TypeReference variable, ref bool WeavingFailed) + { + GenericInstanceType genericInstance = (GenericInstanceType)variable; + TypeReference elementType = genericInstance.GenericArguments[0]; + + MethodDefinition readerFunc = GenerateReaderFunction(variable); + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + // $array = reader.Read<[T]>() + ArrayType arrayType = elementType.MakeArrayType(); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Call, GetReadFunc(arrayType, ref WeavingFailed)); + + // return new ArraySegment($array); + worker.Emit(OpCodes.Newobj, weaverTypes.ArraySegmentConstructorReference.MakeHostInstanceGeneric(assembly.MainModule, genericInstance)); + worker.Emit(OpCodes.Ret); + return readerFunc; + } + + MethodDefinition GenerateReaderFunction(TypeReference variable) + { + string functionName = $"_Read_{variable.FullName}"; + + // create new reader for this type + MethodDefinition readerFunc = new MethodDefinition(functionName, + MethodAttributes.Public | + MethodAttributes.Static | + MethodAttributes.HideBySig, + variable); + + readerFunc.Parameters.Add(new ParameterDefinition("reader", ParameterAttributes.None, weaverTypes.Import())); + readerFunc.Body.InitLocals = true; + RegisterReadFunc(variable, readerFunc); + + return readerFunc; + } + + MethodDefinition GenerateReadCollection(TypeReference variable, TypeReference elementType, string readerFunction, ref bool WeavingFailed) + { + MethodDefinition readerFunc = GenerateReaderFunction(variable); + // generate readers for the element + GetReadFunc(elementType, ref WeavingFailed); + + ModuleDefinition module = assembly.MainModule; + TypeReference readerExtensions = module.ImportReference(typeof(NetworkReaderExtensions)); + MethodReference listReader = Resolvers.ResolveMethod(readerExtensions, assembly, Log, readerFunction, ref WeavingFailed); + + GenericInstanceMethod methodRef = new GenericInstanceMethod(listReader); + methodRef.GenericArguments.Add(elementType); + + // generates + // return reader.ReadList(); + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + worker.Emit(OpCodes.Ldarg_0); // reader + worker.Emit(OpCodes.Call, methodRef); // Read + + worker.Emit(OpCodes.Ret); + + return readerFunc; + } + + MethodDefinition GenerateClassOrStructReadFunction(TypeReference variable, ref bool WeavingFailed) + { + MethodDefinition readerFunc = GenerateReaderFunction(variable); + + // create local for return value + readerFunc.Body.Variables.Add(new VariableDefinition(variable)); + + ILProcessor worker = readerFunc.Body.GetILProcessor(); + + TypeDefinition td = variable.Resolve(); + + if (!td.IsValueType) + GenerateNullCheck(worker, ref WeavingFailed); + + CreateNew(variable, worker, td, ref WeavingFailed); + ReadAllFields(variable, worker, ref WeavingFailed); + + worker.Emit(OpCodes.Ldloc_0); + worker.Emit(OpCodes.Ret); + return readerFunc; + } + + void GenerateNullCheck(ILProcessor worker, ref bool WeavingFailed) + { + // if (!reader.ReadBoolean()) { + // return null; + // } + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Call, GetReadFunc(weaverTypes.Import(), ref WeavingFailed)); + + Instruction labelEmptyArray = worker.Create(OpCodes.Nop); + worker.Emit(OpCodes.Brtrue, labelEmptyArray); + // return null + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ret); + worker.Append(labelEmptyArray); + } + + // Initialize the local variable with a new instance + void CreateNew(TypeReference variable, ILProcessor worker, TypeDefinition td, ref bool WeavingFailed) + { + if (variable.IsValueType) + { + // structs are created with Initobj + worker.Emit(OpCodes.Ldloca, 0); + worker.Emit(OpCodes.Initobj, variable); + } + else if (td.IsDerivedFrom()) + { + GenericInstanceMethod genericInstanceMethod = new GenericInstanceMethod(weaverTypes.ScriptableObjectCreateInstanceMethod); + genericInstanceMethod.GenericArguments.Add(variable); + worker.Emit(OpCodes.Call, genericInstanceMethod); + worker.Emit(OpCodes.Stloc_0); + } + else + { + // classes are created with their constructor + MethodDefinition ctor = Resolvers.ResolveDefaultPublicCtor(variable); + if (ctor == null) + { + Log.Error($"{variable.Name} can't be deserialized because it has no default constructor. Don't use {variable.Name} in [SyncVar]s, Rpcs, Cmds, etc.", variable); + WeavingFailed = true; + return; + } + + MethodReference ctorRef = assembly.MainModule.ImportReference(ctor); + + worker.Emit(OpCodes.Newobj, ctorRef); + worker.Emit(OpCodes.Stloc_0); + } + } + + void ReadAllFields(TypeReference variable, ILProcessor worker, ref bool WeavingFailed) + { + foreach (FieldDefinition field in variable.FindAllPublicFields()) + { + // mismatched ldloca/ldloc for struct/class combinations is invalid IL, which causes crash at runtime + OpCode opcode = variable.IsValueType ? OpCodes.Ldloca : OpCodes.Ldloc; + worker.Emit(opcode, 0); + MethodReference readFunc = GetReadFunc(field.FieldType, ref WeavingFailed); + if (readFunc != null) + { + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Call, readFunc); + } + else + { + Log.Error($"{field.Name} has an unsupported type", field); + WeavingFailed = true; + } + FieldReference fieldRef = assembly.MainModule.ImportReference(field); + + worker.Emit(OpCodes.Stfld, fieldRef); + } + } + + // Save a delegate for each one of the readers into Reader.read + internal void InitializeReaders(ILProcessor worker) + { + ModuleDefinition module = assembly.MainModule; + + TypeReference genericReaderClassRef = module.ImportReference(typeof(Reader<>)); + + System.Reflection.FieldInfo fieldInfo = typeof(Reader<>).GetField(nameof(Reader.read)); + FieldReference fieldRef = module.ImportReference(fieldInfo); + TypeReference networkReaderRef = module.ImportReference(typeof(NetworkReader)); + TypeReference funcRef = module.ImportReference(typeof(Func<,>)); + MethodReference funcConstructorRef = module.ImportReference(typeof(Func<,>).GetConstructors()[0]); + + foreach (KeyValuePair kvp in readFuncs) + { + TypeReference targetType = kvp.Key; + MethodReference readFunc = kvp.Value; + + // create a Func delegate + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ldftn, readFunc); + GenericInstanceType funcGenericInstance = funcRef.MakeGenericInstanceType(networkReaderRef, targetType); + MethodReference funcConstructorInstance = funcConstructorRef.MakeHostInstanceGeneric(assembly.MainModule, funcGenericInstance); + worker.Emit(OpCodes.Newobj, funcConstructorInstance); + + // save it in Reader.read + GenericInstanceType genericInstance = genericReaderClassRef.MakeGenericInstanceType(targetType); + FieldReference specializedField = fieldRef.SpecializeField(assembly.MainModule, genericInstance); + worker.Emit(OpCodes.Stsfld, specializedField); + } + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Readers.cs.meta b/Assets/Mirror/Editor/Weaver/Readers.cs.meta new file mode 100644 index 0000000..838ff59 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Readers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be40277098a024539bf63d0205cae824 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Resolvers.cs b/Assets/Mirror/Editor/Weaver/Resolvers.cs new file mode 100644 index 0000000..a9d551b --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Resolvers.cs @@ -0,0 +1,94 @@ +// all the resolve functions for the weaver +// NOTE: these functions should be made extensions, but right now they still +// make heavy use of Weaver.fail and we'd have to check each one's return +// value for null otherwise. +// (original FieldType.Resolve returns null if not found too, so +// exceptions would be a bit inconsistent here) +using Mono.CecilX; + +namespace Mirror.Weaver +{ + public static class Resolvers + { + public static MethodReference ResolveMethod(TypeReference tr, AssemblyDefinition assembly, Logger Log, string name, ref bool WeavingFailed) + { + if (tr == null) + { + Log.Error($"Cannot resolve method {name} without a class"); + WeavingFailed = true; + return null; + } + MethodReference method = ResolveMethod(tr, assembly, Log, m => m.Name == name, ref WeavingFailed); + if (method == null) + { + Log.Error($"Method not found with name {name} in type {tr.Name}", tr); + WeavingFailed = true; + } + return method; + } + + public static MethodReference ResolveMethod(TypeReference t, AssemblyDefinition assembly, Logger Log, System.Func predicate, ref bool WeavingFailed) + { + foreach (MethodDefinition methodRef in t.Resolve().Methods) + { + if (predicate(methodRef)) + { + return assembly.MainModule.ImportReference(methodRef); + } + } + + Log.Error($"Method not found in type {t.Name}", t); + WeavingFailed = true; + return null; + } + + public static MethodReference TryResolveMethodInParents(TypeReference tr, AssemblyDefinition assembly, string name) + { + if (tr == null) + { + return null; + } + foreach (MethodDefinition methodDef in tr.Resolve().Methods) + { + if (methodDef.Name == name) + { + MethodReference methodRef = methodDef; + if (tr.IsGenericInstance) + { + methodRef = methodRef.MakeHostInstanceGeneric(tr.Module, (GenericInstanceType)tr); + } + return assembly.MainModule.ImportReference(methodRef); + } + } + + // Could not find the method in this class, try the parent + return TryResolveMethodInParents(tr.Resolve().BaseType.ApplyGenericParameters(tr), assembly, name); + } + + public static MethodDefinition ResolveDefaultPublicCtor(TypeReference variable) + { + foreach (MethodDefinition methodRef in variable.Resolve().Methods) + { + if (methodRef.Name == ".ctor" && + methodRef.Resolve().IsPublic && + methodRef.Parameters.Count == 0) + { + return methodRef; + } + } + return null; + } + + public static MethodReference ResolveProperty(TypeReference tr, AssemblyDefinition assembly, string name) + { + foreach (PropertyDefinition pd in tr.Resolve().Properties) + { + if (pd.Name == name) + { + return assembly.MainModule.ImportReference(pd.GetMethod); + } + } + return null; + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Resolvers.cs.meta b/Assets/Mirror/Editor/Weaver/Resolvers.cs.meta new file mode 100644 index 0000000..f4f6602 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Resolvers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3039a59c76aec43c797ad66930430367 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/SyncVarAccessLists.cs b/Assets/Mirror/Editor/Weaver/SyncVarAccessLists.cs new file mode 100644 index 0000000..fa7a682 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/SyncVarAccessLists.cs @@ -0,0 +1,32 @@ +// tracks SyncVar read/write access when processing NetworkBehaviour, +// to later be replaced by SyncVarAccessReplacer. +using System.Collections.Generic; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + // This data is flushed each time - if we are run multiple times in the same process/domain + public class SyncVarAccessLists + { + // setter functions that replace [SyncVar] member variable references. dict + public Dictionary replacementSetterProperties = + new Dictionary(); + + // getter functions that replace [SyncVar] member variable references. dict + public Dictionary replacementGetterProperties = + new Dictionary(); + + // amount of SyncVars per class. dict + // necessary for SyncVar dirty bits, where inheriting classes start + // their dirty bits at base class SyncVar amount. + public Dictionary numSyncVars = new Dictionary(); + + public int GetSyncVarStart(string className) => + numSyncVars.TryGetValue(className, out int value) ? value : 0; + + public void SetNumSyncVars(string className, int num) + { + numSyncVars[className] = num; + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/SyncVarAccessLists.cs.meta b/Assets/Mirror/Editor/Weaver/SyncVarAccessLists.cs.meta new file mode 100644 index 0000000..9a4da44 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/SyncVarAccessLists.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6905230c3c4c4e158760065a93380e83 +timeCreated: 1629348618 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/TypeReferenceComparer.cs b/Assets/Mirror/Editor/Weaver/TypeReferenceComparer.cs new file mode 100644 index 0000000..e3c31d5 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/TypeReferenceComparer.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + // Compares TypeReference using FullName + public class TypeReferenceComparer : IEqualityComparer + { + public bool Equals(TypeReference x, TypeReference y) => + x.FullName == y.FullName; + + public int GetHashCode(TypeReference obj) => + obj.FullName.GetHashCode(); + } +} diff --git a/Assets/Mirror/Editor/Weaver/TypeReferenceComparer.cs.meta b/Assets/Mirror/Editor/Weaver/TypeReferenceComparer.cs.meta new file mode 100644 index 0000000..890b4dc --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/TypeReferenceComparer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 55eb9eb8794946f4da7ad39788c9920b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef b/Assets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef new file mode 100644 index 0000000..987382c --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef @@ -0,0 +1,21 @@ +{ + "name": "Unity.Mirror.CodeGen", + "rootNamespace": "", + "references": [ + "GUID:30817c1a0e6d646d99c048fc403f5979" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": true, + "precompiledReferences": [ + "Mono.CecilX.dll", + "Mono.CecilX.Rocks.dll" + ], + "autoReferenced": false, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef.meta b/Assets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef.meta new file mode 100644 index 0000000..b65a0cd --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Unity.Mirror.CodeGen.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1d0b9d21c3ff546a4aa32399dfd33474 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/Weaver.cs b/Assets/Mirror/Editor/Weaver/Weaver.cs new file mode 100644 index 0000000..4bff720 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Weaver.cs @@ -0,0 +1,269 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using Mono.CecilX; +using Mono.CecilX.Cil; +using Mono.CecilX.Rocks; + +namespace Mirror.Weaver +{ + // not static, because ILPostProcessor is multithreaded + internal class Weaver + { + public const string InvokeRpcPrefix = "InvokeUserCode_"; + + // generated code class + public const string GeneratedCodeNamespace = "Mirror"; + public const string GeneratedCodeClassName = "GeneratedNetworkCode"; + TypeDefinition GeneratedCodeClass; + + // for resolving Mirror.dll in ReaderWriterProcessor, we need to know + // Mirror.dll name + public const string MirrorAssemblyName = "Mirror"; + + WeaverTypes weaverTypes; + SyncVarAccessLists syncVarAccessLists; + AssemblyDefinition CurrentAssembly; + Writers writers; + Readers readers; + + // in case of weaver errors, we don't stop immediately. + // we log all errors and then eventually return false if + // weaving has failed. + // this way the user can fix multiple errors at once, instead of having + // to fix -> recompile -> fix -> recompile for one error at a time. + bool WeavingFailed; + + // logger functions can be set from the outside. + // for example, Debug.Log or ILPostProcessor Diagnostics log for + // multi threaded logging. + public Logger Log; + + // remote actions now support overloads, + // -> but IL2CPP doesnt like it when two generated methods + // -> have the same signature, + // -> so, append the signature to the generated method name, + // -> to create a unique name + // Example: + // RpcTeleport(Vector3 position) -> InvokeUserCode_RpcTeleport__Vector3() + // RpcTeleport(Vector3 position, Quaternion rotation) -> InvokeUserCode_RpcTeleport__Vector3Quaternion() + // fixes https://github.com/vis2k/Mirror/issues/3060 + public static string GenerateMethodName(string initialPrefix, MethodDefinition md) + { + initialPrefix += md.Name; + + for (int i = 0; i < md.Parameters.Count; ++i) + { + // with __ so it's more obvious that this is the parameter suffix. + // otherwise RpcTest(int) => RpcTestInt(int) which is not obvious. + initialPrefix += $"__{md.Parameters[i].ParameterType.Name}"; + } + + return initialPrefix; + } + + public Weaver(Logger Log) + { + this.Log = Log; + } + + // returns 'true' if modified (=if we did anything) + bool WeaveNetworkBehavior(TypeDefinition td) + { + if (!td.IsClass) + return false; + + if (!td.IsDerivedFrom()) + { + if (td.IsDerivedFrom()) + MonoBehaviourProcessor.Process(Log, td, ref WeavingFailed); + return false; + } + + // process this and base classes from parent to child order + + List behaviourClasses = new List(); + + TypeDefinition parent = td; + while (parent != null) + { + if (parent.Is()) + { + break; + } + + try + { + behaviourClasses.Insert(0, parent); + parent = parent.BaseType.Resolve(); + } + catch (AssemblyResolutionException) + { + // this can happen for plugins. + //Console.WriteLine("AssemblyResolutionException: "+ ex.ToString()); + break; + } + } + + bool modified = false; + foreach (TypeDefinition behaviour in behaviourClasses) + { + modified |= new NetworkBehaviourProcessor(CurrentAssembly, weaverTypes, syncVarAccessLists, writers, readers, Log, behaviour).Process(ref WeavingFailed); + } + return modified; + } + + bool WeaveModule(ModuleDefinition moduleDefinition) + { + bool modified = false; + + Stopwatch watch = Stopwatch.StartNew(); + watch.Start(); + + // ModuleDefinition.Types only finds top level types. + // GetAllTypes recursively finds all nested types as well. + // fixes nested types not being weaved, for example: + // class Parent { // ModuleDefinition.Types finds this + // class Child { // .Types.NestedTypes finds this + // class GrandChild {} // only GetAllTypes finds this too + // } + // } + // note this is not about inheritance, only about type definitions. + // see test: NetworkBehaviourTests.DeeplyNested() + foreach (TypeDefinition td in moduleDefinition.GetAllTypes()) + { + if (td.IsClass && td.BaseType.CanBeResolved()) + { + modified |= WeaveNetworkBehavior(td); + modified |= ServerClientAttributeProcessor.Process(weaverTypes, Log, td, ref WeavingFailed); + } + } + + watch.Stop(); + Console.WriteLine($"Weave behaviours and messages took {watch.ElapsedMilliseconds} milliseconds"); + + return modified; + } + + void CreateGeneratedCodeClass() + { + // create "Mirror.GeneratedNetworkCode" class which holds all + // Readers and Writers + GeneratedCodeClass = new TypeDefinition(GeneratedCodeNamespace, GeneratedCodeClassName, + TypeAttributes.BeforeFieldInit | TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.Abstract | TypeAttributes.Sealed, + weaverTypes.Import()); + } + + void ToggleWeaverFuse() + { + // // find Weaved() function + MethodDefinition func = weaverTypes.weaverFuseMethod.Resolve(); + // // change return 0 to return 1 + + ILProcessor worker = func.Body.GetILProcessor(); + func.Body.Instructions[0] = worker.Create(OpCodes.Ldc_I4_1); + } + + // Weave takes an AssemblyDefinition to be compatible with both old and + // new weavers: + // * old takes a filepath, new takes a in-memory byte[] + // * old uses DefaultAssemblyResolver with added dependencies paths, + // new uses ...? + // + // => assembly: the one we are currently weaving (MyGame.dll) + // => resolver: useful in case we need to resolve any of the assembly's + // assembly.MainModule.AssemblyReferences. + // -> we can resolve ANY of them given that the resolver + // works properly (need custom one for ILPostProcessor) + // -> IMPORTANT: .Resolve() takes an AssemblyNameReference. + // those from assembly.MainModule.AssemblyReferences are + // guaranteed to be resolve-able. + // Parsing from a string for Library/.../Mirror.dll + // would not be guaranteed to be resolve-able because + // for ILPostProcessor we can't assume where Mirror.dll + // is etc. + public bool Weave(AssemblyDefinition assembly, IAssemblyResolver resolver, out bool modified) + { + WeavingFailed = false; + modified = false; + try + { + CurrentAssembly = assembly; + + // fix "No writer found for ..." error + // https://github.com/vis2k/Mirror/issues/2579 + // -> when restarting Unity, weaver would try to weave a DLL + // again + // -> resulting in two GeneratedNetworkCode classes (see ILSpy) + // -> the second one wouldn't have all the writer types setup + if (CurrentAssembly.MainModule.ContainsClass(GeneratedCodeNamespace, GeneratedCodeClassName)) + { + //Log.Warning($"Weaver: skipping {CurrentAssembly.Name} because already weaved"); + return true; + } + + weaverTypes = new WeaverTypes(CurrentAssembly, Log, ref WeavingFailed); + + // weaverTypes are needed for CreateGeneratedCodeClass + CreateGeneratedCodeClass(); + + // WeaverList depends on WeaverTypes setup because it uses Import + syncVarAccessLists = new SyncVarAccessLists(); + + // initialize readers & writers with this assembly. + // we need to do this in every Process() call. + // otherwise we would get + // "System.ArgumentException: Member ... is declared in another module and needs to be imported" + // errors when still using the previous module's reader/writer funcs. + writers = new Writers(CurrentAssembly, weaverTypes, GeneratedCodeClass, Log); + readers = new Readers(CurrentAssembly, weaverTypes, GeneratedCodeClass, Log); + + Stopwatch rwstopwatch = Stopwatch.StartNew(); + // Need to track modified from ReaderWriterProcessor too because it could find custom read/write functions or create functions for NetworkMessages + modified = ReaderWriterProcessor.Process(CurrentAssembly, resolver, Log, writers, readers, ref WeavingFailed); + rwstopwatch.Stop(); + Console.WriteLine($"Find all reader and writers took {rwstopwatch.ElapsedMilliseconds} milliseconds"); + + ModuleDefinition moduleDefinition = CurrentAssembly.MainModule; + Console.WriteLine($"Script Module: {moduleDefinition.Name}"); + + modified |= WeaveModule(moduleDefinition); + + if (WeavingFailed) + { + return false; + } + + if (modified) + { + SyncVarAttributeAccessReplacer.Process(Log, moduleDefinition, syncVarAccessLists); + + // add class that holds read/write functions + moduleDefinition.Types.Add(GeneratedCodeClass); + + ReaderWriterProcessor.InitializeReaderAndWriters(CurrentAssembly, weaverTypes, writers, readers, GeneratedCodeClass); + + // DO NOT WRITE here. + // CompilationFinishedHook writes to the file. + // ILPostProcessor writes to in-memory assembly. + // it depends on the caller. + //CurrentAssembly.Write(new WriterParameters{ WriteSymbols = true }); + } + + // if weaving succeeded, switch on the Weaver Fuse in Mirror.dll + if (CurrentAssembly.Name.Name == MirrorAssemblyName) + { + ToggleWeaverFuse(); + } + + return true; + } + catch (Exception e) + { + Log.Error($"Exception :{e}"); + WeavingFailed = true; + return false; + } + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Weaver.cs.meta b/Assets/Mirror/Editor/Weaver/Weaver.cs.meta new file mode 100644 index 0000000..0ea2dfe --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Weaver.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de160f52931054064852f2afd7e7a86f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/WeaverExceptions.cs b/Assets/Mirror/Editor/Weaver/WeaverExceptions.cs new file mode 100644 index 0000000..efedd27 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/WeaverExceptions.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.Serialization; +using Mono.CecilX; + +namespace Mirror.Weaver +{ + [Serializable] + public abstract class WeaverException : Exception + { + public MemberReference MemberReference { get; } + + protected WeaverException(string message, MemberReference member) : base(message) + { + MemberReference = member; + } + + protected WeaverException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) {} + } + + [Serializable] + public class GenerateWriterException : WeaverException + { + public GenerateWriterException(string message, MemberReference member) : base(message, member) {} + protected GenerateWriterException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) {} + } +} diff --git a/Assets/Mirror/Editor/Weaver/WeaverExceptions.cs.meta b/Assets/Mirror/Editor/Weaver/WeaverExceptions.cs.meta new file mode 100644 index 0000000..68643b2 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/WeaverExceptions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8aaaf6193bad7424492677f8e81f1b30 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Weaver/WeaverTypes.cs b/Assets/Mirror/Editor/Weaver/WeaverTypes.cs new file mode 100644 index 0000000..5a988a1 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/WeaverTypes.cs @@ -0,0 +1,171 @@ +using System; +using Mono.CecilX; +using UnityEditor; +using UnityEngine; + +namespace Mirror.Weaver +{ + // not static, because ILPostProcessor is multithreaded + public class WeaverTypes + { + public MethodReference ScriptableObjectCreateInstanceMethod; + + public MethodReference NetworkBehaviourDirtyBitsReference; + public MethodReference GetWriterReference; + public MethodReference ReturnWriterReference; + + public MethodReference NetworkClientConnectionReference; + + public MethodReference RemoteCallDelegateConstructor; + + public MethodReference NetworkServerGetActive; + public MethodReference NetworkClientGetActive; + + // custom attribute types + public MethodReference InitSyncObjectReference; + + // array segment + public MethodReference ArraySegmentConstructorReference; + + // Action for SyncVar Hooks + public MethodReference ActionT_T; + + // syncvar + public MethodReference generatedSyncVarSetter; + public MethodReference generatedSyncVarSetter_GameObject; + public MethodReference generatedSyncVarSetter_NetworkIdentity; + public MethodReference generatedSyncVarSetter_NetworkBehaviour_T; + public MethodReference generatedSyncVarDeserialize; + public MethodReference generatedSyncVarDeserialize_GameObject; + public MethodReference generatedSyncVarDeserialize_NetworkIdentity; + public MethodReference generatedSyncVarDeserialize_NetworkBehaviour_T; + public MethodReference getSyncVarGameObjectReference; + public MethodReference getSyncVarNetworkIdentityReference; + public MethodReference getSyncVarNetworkBehaviourReference; + public MethodReference registerCommandReference; + public MethodReference registerRpcReference; + public MethodReference getTypeFromHandleReference; + public MethodReference logErrorReference; + public MethodReference logWarningReference; + public MethodReference sendCommandInternal; + public MethodReference sendRpcInternal; + public MethodReference sendTargetRpcInternal; + + public MethodReference readNetworkBehaviourGeneric; + + public TypeReference weaverFuseType; + public MethodReference weaverFuseMethod; + + // attributes + public TypeDefinition initializeOnLoadMethodAttribute; + public TypeDefinition runtimeInitializeOnLoadMethodAttribute; + + AssemblyDefinition assembly; + + public TypeReference Import() => Import(typeof(T)); + + public TypeReference Import(Type t) => assembly.MainModule.ImportReference(t); + + // constructor resolves the types and stores them in fields + public WeaverTypes(AssemblyDefinition assembly, Logger Log, ref bool WeavingFailed) + { + // system types + this.assembly = assembly; + + TypeReference ArraySegmentType = Import(typeof(ArraySegment<>)); + ArraySegmentConstructorReference = Resolvers.ResolveMethod(ArraySegmentType, assembly, Log, ".ctor", ref WeavingFailed); + + TypeReference ActionType = Import(typeof(Action<,>)); + ActionT_T = Resolvers.ResolveMethod(ActionType, assembly, Log, ".ctor", ref WeavingFailed); + + weaverFuseType = Import(typeof(WeaverFuse)); + weaverFuseMethod = Resolvers.ResolveMethod(weaverFuseType, assembly, Log, "Weaved", ref WeavingFailed); + + TypeReference NetworkServerType = Import(typeof(NetworkServer)); + NetworkServerGetActive = Resolvers.ResolveMethod(NetworkServerType, assembly, Log, "get_active", ref WeavingFailed); + + TypeReference NetworkClientType = Import(typeof(NetworkClient)); + NetworkClientGetActive = Resolvers.ResolveMethod(NetworkClientType, assembly, Log, "get_active", ref WeavingFailed); + NetworkClientConnectionReference = Resolvers.ResolveMethod(NetworkClientType, assembly, Log, "get_connection", ref WeavingFailed); + + TypeReference NetworkBehaviourType = Import(); + + NetworkBehaviourDirtyBitsReference = Resolvers.ResolveProperty(NetworkBehaviourType, assembly, "syncVarDirtyBits"); + + generatedSyncVarSetter = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarSetter", ref WeavingFailed); + generatedSyncVarSetter_GameObject = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarSetter_GameObject", ref WeavingFailed); + generatedSyncVarSetter_NetworkIdentity = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarSetter_NetworkIdentity", ref WeavingFailed); + generatedSyncVarSetter_NetworkBehaviour_T = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarSetter_NetworkBehaviour", ref WeavingFailed); + + generatedSyncVarDeserialize_GameObject = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarDeserialize_GameObject", ref WeavingFailed); + generatedSyncVarDeserialize = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarDeserialize", ref WeavingFailed); + generatedSyncVarDeserialize_NetworkIdentity = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarDeserialize_NetworkIdentity", ref WeavingFailed); + generatedSyncVarDeserialize_NetworkBehaviour_T = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GeneratedSyncVarDeserialize_NetworkBehaviour", ref WeavingFailed); + + getSyncVarGameObjectReference = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GetSyncVarGameObject", ref WeavingFailed); + getSyncVarNetworkIdentityReference = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GetSyncVarNetworkIdentity", ref WeavingFailed); + getSyncVarNetworkBehaviourReference = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "GetSyncVarNetworkBehaviour", ref WeavingFailed); + + sendCommandInternal = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "SendCommandInternal", ref WeavingFailed); + sendRpcInternal = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "SendRPCInternal", ref WeavingFailed); + sendTargetRpcInternal = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "SendTargetRPCInternal", ref WeavingFailed); + + InitSyncObjectReference = Resolvers.ResolveMethod(NetworkBehaviourType, assembly, Log, "InitSyncObject", ref WeavingFailed); + + TypeReference RemoteProcedureCallsType = Import(typeof(RemoteCalls.RemoteProcedureCalls)); + registerCommandReference = Resolvers.ResolveMethod(RemoteProcedureCallsType, assembly, Log, "RegisterCommand", ref WeavingFailed); + registerRpcReference = Resolvers.ResolveMethod(RemoteProcedureCallsType, assembly, Log, "RegisterRpc", ref WeavingFailed); + + TypeReference RemoteCallDelegateType = Import(); + RemoteCallDelegateConstructor = Resolvers.ResolveMethod(RemoteCallDelegateType, assembly, Log, ".ctor", ref WeavingFailed); + + TypeReference ScriptableObjectType = Import(); + ScriptableObjectCreateInstanceMethod = Resolvers.ResolveMethod( + ScriptableObjectType, assembly, Log, + md => md.Name == "CreateInstance" && md.HasGenericParameters, + ref WeavingFailed); + + TypeReference unityDebug = Import(typeof(UnityEngine.Debug)); + // these have multiple methods with same name, so need to check parameters too + logErrorReference = Resolvers.ResolveMethod(unityDebug, assembly, Log, md => + md.Name == "LogError" && + md.Parameters.Count == 1 && + md.Parameters[0].ParameterType.FullName == typeof(object).FullName, + ref WeavingFailed); + + logWarningReference = Resolvers.ResolveMethod(unityDebug, assembly, Log, md => + md.Name == "LogWarning" && + md.Parameters.Count == 1 && + md.Parameters[0].ParameterType.FullName == typeof(object).FullName, + ref WeavingFailed); + + TypeReference typeType = Import(typeof(Type)); + getTypeFromHandleReference = Resolvers.ResolveMethod(typeType, assembly, Log, "GetTypeFromHandle", ref WeavingFailed); + + TypeReference NetworkWriterPoolType = Import(typeof(NetworkWriterPool)); + GetWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, assembly, Log, "Get", ref WeavingFailed); + ReturnWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, assembly, Log, "Return", ref WeavingFailed); + + TypeReference readerExtensions = Import(typeof(NetworkReaderExtensions)); + readNetworkBehaviourGeneric = Resolvers.ResolveMethod(readerExtensions, assembly, Log, (md => + { + return md.Name == nameof(NetworkReaderExtensions.ReadNetworkBehaviour) && + md.HasGenericParameters; + }), + ref WeavingFailed); + + // [InitializeOnLoadMethod] + // 'UnityEditor' is not available in builds. + // we can only import this attribute if we are in an Editor assembly. + if (Helpers.IsEditorAssembly(assembly)) + { + TypeReference initializeOnLoadMethodAttributeRef = Import(typeof(InitializeOnLoadMethodAttribute)); + initializeOnLoadMethodAttribute = initializeOnLoadMethodAttributeRef.Resolve(); + } + + // [RuntimeInitializeOnLoadMethod] + TypeReference runtimeInitializeOnLoadMethodAttributeRef = Import(typeof(RuntimeInitializeOnLoadMethodAttribute)); + runtimeInitializeOnLoadMethodAttribute = runtimeInitializeOnLoadMethodAttributeRef.Resolve(); + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/WeaverTypes.cs.meta b/Assets/Mirror/Editor/Weaver/WeaverTypes.cs.meta new file mode 100644 index 0000000..d71c33f --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/WeaverTypes.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2585961bf7fe4c10a9143f4087efdf6f +timeCreated: 1596486854 \ No newline at end of file diff --git a/Assets/Mirror/Editor/Weaver/Writers.cs b/Assets/Mirror/Editor/Weaver/Writers.cs new file mode 100644 index 0000000..8311a26 --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Writers.cs @@ -0,0 +1,341 @@ +using System; +using System.Collections.Generic; +using Mono.CecilX; +using Mono.CecilX.Cil; +// to use Mono.CecilX.Rocks here, we need to 'override references' in the +// Unity.Mirror.CodeGen assembly definition file in the Editor, and add CecilX.Rocks. +// otherwise we get an unknown import exception. +using Mono.CecilX.Rocks; + +namespace Mirror.Weaver +{ + // not static, because ILPostProcessor is multithreaded + public class Writers + { + // Writers are only for this assembly. + // can't be used from another assembly, otherwise we will get: + // "System.ArgumentException: Member ... is declared in another module and needs to be imported" + AssemblyDefinition assembly; + WeaverTypes weaverTypes; + TypeDefinition GeneratedCodeClass; + Logger Log; + + Dictionary writeFuncs = + new Dictionary(new TypeReferenceComparer()); + + public Writers(AssemblyDefinition assembly, WeaverTypes weaverTypes, TypeDefinition GeneratedCodeClass, Logger Log) + { + this.assembly = assembly; + this.weaverTypes = weaverTypes; + this.GeneratedCodeClass = GeneratedCodeClass; + this.Log = Log; + } + + public void Register(TypeReference dataType, MethodReference methodReference) + { + if (writeFuncs.ContainsKey(dataType)) + { + // TODO enable this again later. + // Writer has some obsolete functions that were renamed. + // Don't want weaver warnings for all of them. + //Log.Warning($"Registering a Write method for {dataType.FullName} when one already exists", methodReference); + } + + // we need to import type when we Initialize Writers so import here in case it is used anywhere else + TypeReference imported = assembly.MainModule.ImportReference(dataType); + writeFuncs[imported] = methodReference; + } + + void RegisterWriteFunc(TypeReference typeReference, MethodDefinition newWriterFunc) + { + Register(typeReference, newWriterFunc); + GeneratedCodeClass.Methods.Add(newWriterFunc); + } + + // Finds existing writer for type, if non exists trys to create one + public MethodReference GetWriteFunc(TypeReference variable, ref bool WeavingFailed) + { + if (writeFuncs.TryGetValue(variable, out MethodReference foundFunc)) + return foundFunc; + + // this try/catch will be removed in future PR and make `GetWriteFunc` throw instead + try + { + TypeReference importedVariable = assembly.MainModule.ImportReference(variable); + return GenerateWriter(importedVariable, ref WeavingFailed); + } + catch (GenerateWriterException e) + { + Log.Error(e.Message, e.MemberReference); + WeavingFailed = true; + return null; + } + } + + //Throws GenerateWriterException when writer could not be generated for type + MethodReference GenerateWriter(TypeReference variableReference, ref bool WeavingFailed) + { + if (variableReference.IsByReference) + { + throw new GenerateWriterException($"Cannot pass {variableReference.Name} by reference", variableReference); + } + + // Arrays are special, if we resolve them, we get the element type, + // e.g. int[] resolves to int + // therefore process this before checks below + if (variableReference.IsArray) + { + if (variableReference.IsMultidimensionalArray()) + { + throw new GenerateWriterException($"{variableReference.Name} is an unsupported type. Multidimensional arrays are not supported", variableReference); + } + TypeReference elementType = variableReference.GetElementType(); + return GenerateCollectionWriter(variableReference, elementType, nameof(NetworkWriterExtensions.WriteArray), ref WeavingFailed); + } + + if (variableReference.Resolve()?.IsEnum ?? false) + { + // serialize enum as their base type + return GenerateEnumWriteFunc(variableReference, ref WeavingFailed); + } + + // check for collections + if (variableReference.Is(typeof(ArraySegment<>))) + { + GenericInstanceType genericInstance = (GenericInstanceType)variableReference; + TypeReference elementType = genericInstance.GenericArguments[0]; + + return GenerateCollectionWriter(variableReference, elementType, nameof(NetworkWriterExtensions.WriteArraySegment), ref WeavingFailed); + } + if (variableReference.Is(typeof(List<>))) + { + GenericInstanceType genericInstance = (GenericInstanceType)variableReference; + TypeReference elementType = genericInstance.GenericArguments[0]; + + return GenerateCollectionWriter(variableReference, elementType, nameof(NetworkWriterExtensions.WriteList), ref WeavingFailed); + } + + // handle both NetworkBehaviour and inheritors. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/2939 + if (variableReference.IsDerivedFrom() || variableReference.Is()) + { + return GetNetworkBehaviourWriter(variableReference); + } + + // check for invalid types + TypeDefinition variableDefinition = variableReference.Resolve(); + if (variableDefinition == null) + { + throw new GenerateWriterException($"{variableReference.Name} is not a supported type. Use a supported type or provide a custom writer", variableReference); + } + if (variableDefinition.IsDerivedFrom()) + { + throw new GenerateWriterException($"Cannot generate writer for component type {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); + } + if (variableReference.Is()) + { + throw new GenerateWriterException($"Cannot generate writer for {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); + } + if (variableReference.Is()) + { + throw new GenerateWriterException($"Cannot generate writer for {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); + } + if (variableDefinition.HasGenericParameters) + { + throw new GenerateWriterException($"Cannot generate writer for generic type {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); + } + if (variableDefinition.IsInterface) + { + throw new GenerateWriterException($"Cannot generate writer for interface {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); + } + if (variableDefinition.IsAbstract) + { + throw new GenerateWriterException($"Cannot generate writer for abstract class {variableReference.Name}. Use a supported type or provide a custom writer", variableReference); + } + + // generate writer for class/struct + return GenerateClassOrStructWriterFunction(variableReference, ref WeavingFailed); + } + + MethodReference GetNetworkBehaviourWriter(TypeReference variableReference) + { + // all NetworkBehaviours can use the same write function + if (writeFuncs.TryGetValue(weaverTypes.Import(), out MethodReference func)) + { + // register function so it is added to writer + // use Register instead of RegisterWriteFunc because this is not a generated function + Register(variableReference, func); + + return func; + } + else + { + // this exception only happens if mirror is missing the WriteNetworkBehaviour method + throw new MissingMethodException($"Could not find writer for NetworkBehaviour"); + } + } + + MethodDefinition GenerateEnumWriteFunc(TypeReference variable, ref bool WeavingFailed) + { + MethodDefinition writerFunc = GenerateWriterFunc(variable); + + ILProcessor worker = writerFunc.Body.GetILProcessor(); + + MethodReference underlyingWriter = GetWriteFunc(variable.Resolve().GetEnumUnderlyingType(), ref WeavingFailed); + + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_1); + worker.Emit(OpCodes.Call, underlyingWriter); + + worker.Emit(OpCodes.Ret); + return writerFunc; + } + + MethodDefinition GenerateWriterFunc(TypeReference variable) + { + string functionName = $"_Write_{variable.FullName}"; + // create new writer for this type + MethodDefinition writerFunc = new MethodDefinition(functionName, + MethodAttributes.Public | + MethodAttributes.Static | + MethodAttributes.HideBySig, + weaverTypes.Import(typeof(void))); + + writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, weaverTypes.Import())); + writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, variable)); + writerFunc.Body.InitLocals = true; + + RegisterWriteFunc(variable, writerFunc); + return writerFunc; + } + + MethodDefinition GenerateClassOrStructWriterFunction(TypeReference variable, ref bool WeavingFailed) + { + MethodDefinition writerFunc = GenerateWriterFunc(variable); + + ILProcessor worker = writerFunc.Body.GetILProcessor(); + + if (!variable.Resolve().IsValueType) + WriteNullCheck(worker, ref WeavingFailed); + + if (!WriteAllFields(variable, worker, ref WeavingFailed)) + return null; + + worker.Emit(OpCodes.Ret); + return writerFunc; + } + + void WriteNullCheck(ILProcessor worker, ref bool WeavingFailed) + { + // if (value == null) + // { + // writer.WriteBoolean(false); + // return; + // } + // + + Instruction labelNotNull = worker.Create(OpCodes.Nop); + worker.Emit(OpCodes.Ldarg_1); + worker.Emit(OpCodes.Brtrue, labelNotNull); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldc_I4_0); + worker.Emit(OpCodes.Call, GetWriteFunc(weaverTypes.Import(), ref WeavingFailed)); + worker.Emit(OpCodes.Ret); + worker.Append(labelNotNull); + + // write.WriteBoolean(true); + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldc_I4_1); + worker.Emit(OpCodes.Call, GetWriteFunc(weaverTypes.Import(), ref WeavingFailed)); + } + + // Find all fields in type and write them + bool WriteAllFields(TypeReference variable, ILProcessor worker, ref bool WeavingFailed) + { + foreach (FieldDefinition field in variable.FindAllPublicFields()) + { + MethodReference writeFunc = GetWriteFunc(field.FieldType, ref WeavingFailed); + // need this null check till later PR when GetWriteFunc throws exception instead + if (writeFunc == null) { return false; } + + FieldReference fieldRef = assembly.MainModule.ImportReference(field); + + worker.Emit(OpCodes.Ldarg_0); + worker.Emit(OpCodes.Ldarg_1); + worker.Emit(OpCodes.Ldfld, fieldRef); + worker.Emit(OpCodes.Call, writeFunc); + } + + return true; + } + + MethodDefinition GenerateCollectionWriter(TypeReference variable, TypeReference elementType, string writerFunction, ref bool WeavingFailed) + { + + MethodDefinition writerFunc = GenerateWriterFunc(variable); + + MethodReference elementWriteFunc = GetWriteFunc(elementType, ref WeavingFailed); + MethodReference intWriterFunc = GetWriteFunc(weaverTypes.Import(), ref WeavingFailed); + + // need this null check till later PR when GetWriteFunc throws exception instead + if (elementWriteFunc == null) + { + Log.Error($"Cannot generate writer for {variable}. Use a supported type or provide a custom writer", variable); + WeavingFailed = true; + return writerFunc; + } + + ModuleDefinition module = assembly.MainModule; + TypeReference readerExtensions = module.ImportReference(typeof(NetworkWriterExtensions)); + MethodReference collectionWriter = Resolvers.ResolveMethod(readerExtensions, assembly, Log, writerFunction, ref WeavingFailed); + + GenericInstanceMethod methodRef = new GenericInstanceMethod(collectionWriter); + methodRef.GenericArguments.Add(elementType); + + // generates + // reader.WriteArray(array); + + ILProcessor worker = writerFunc.Body.GetILProcessor(); + worker.Emit(OpCodes.Ldarg_0); // writer + worker.Emit(OpCodes.Ldarg_1); // collection + + worker.Emit(OpCodes.Call, methodRef); // WriteArray + + worker.Emit(OpCodes.Ret); + + return writerFunc; + } + + // Save a delegate for each one of the writers into Writer{T}.write + internal void InitializeWriters(ILProcessor worker) + { + ModuleDefinition module = assembly.MainModule; + + TypeReference genericWriterClassRef = module.ImportReference(typeof(Writer<>)); + + System.Reflection.FieldInfo fieldInfo = typeof(Writer<>).GetField(nameof(Writer.write)); + FieldReference fieldRef = module.ImportReference(fieldInfo); + TypeReference networkWriterRef = module.ImportReference(typeof(NetworkWriter)); + TypeReference actionRef = module.ImportReference(typeof(Action<,>)); + MethodReference actionConstructorRef = module.ImportReference(typeof(Action<,>).GetConstructors()[0]); + + foreach (KeyValuePair kvp in writeFuncs) + { + TypeReference targetType = kvp.Key; + MethodReference writeFunc = kvp.Value; + + // create a Action delegate + worker.Emit(OpCodes.Ldnull); + worker.Emit(OpCodes.Ldftn, writeFunc); + GenericInstanceType actionGenericInstance = actionRef.MakeGenericInstanceType(networkWriterRef, targetType); + MethodReference actionRefInstance = actionConstructorRef.MakeHostInstanceGeneric(assembly.MainModule, actionGenericInstance); + worker.Emit(OpCodes.Newobj, actionRefInstance); + + // save it in Writer.write + GenericInstanceType genericInstance = genericWriterClassRef.MakeGenericInstanceType(targetType); + FieldReference specializedField = fieldRef.SpecializeField(assembly.MainModule, genericInstance); + worker.Emit(OpCodes.Stsfld, specializedField); + } + } + } +} diff --git a/Assets/Mirror/Editor/Weaver/Writers.cs.meta b/Assets/Mirror/Editor/Weaver/Writers.cs.meta new file mode 100644 index 0000000..3769f7f --- /dev/null +++ b/Assets/Mirror/Editor/Weaver/Writers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a90060ad76ea044aba613080dd922709 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Editor/Welcome.cs b/Assets/Mirror/Editor/Welcome.cs new file mode 100644 index 0000000..14e57bc --- /dev/null +++ b/Assets/Mirror/Editor/Welcome.cs @@ -0,0 +1,23 @@ +// Shows either a welcome message, only once per session. +#if UNITY_EDITOR +using UnityEditor; +using UnityEngine; + +namespace Mirror +{ + static class Welcome + { + [InitializeOnLoadMethod] + static void OnInitializeOnLoad() + { + // InitializeOnLoad is called on start and after each rebuild, + // but we only want to show this once per editor session. + if (!SessionState.GetBool("MIRROR_WELCOME", false)) + { + SessionState.SetBool("MIRROR_WELCOME", true); + Debug.Log("Mirror | mirror-networking.com | discord.gg/N9QVxbM"); + } + } + } +} +#endif diff --git a/Assets/Mirror/Editor/Welcome.cs.meta b/Assets/Mirror/Editor/Welcome.cs.meta new file mode 100644 index 0000000..9062df0 --- /dev/null +++ b/Assets/Mirror/Editor/Welcome.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 180619c3887314f56bf396769c0a23ee +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Notice.txt b/Assets/Mirror/Notice.txt new file mode 100644 index 0000000..5eeaf88 --- /dev/null +++ b/Assets/Mirror/Notice.txt @@ -0,0 +1,123 @@ +This asset is governed by the Asset Store EULA; however, the following +components are governed by the licenses indicated below: + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +Mirror +MIT License + +Copyright (c) 2015, Unity Technologies +Copyright (c) 2019, vis2k, Paul and Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +kcp2k +MIT License + +Copyright (c) 2016 limpo1989 +Copyright (c) 2020 Paul Pacheco +Copyright (c) 2020 Lymdun +Copyright (c) 2020 vis2k + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +Mono.Cecil +MIT License + +Copyright (c) 2008 - 2015 Jb Evain +Copyright (c) 2008 - 2011 Novell, Inc. + +https://github.com/jbevain/cecil + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- + +Telepathy +MIT License + +Copyright (c) 2018, vis2k + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- +-------------------------------------------------------------------------------- \ No newline at end of file diff --git a/Assets/Mirror/Notice.txt.meta b/Assets/Mirror/Notice.txt.meta new file mode 100644 index 0000000..3281bd8 --- /dev/null +++ b/Assets/Mirror/Notice.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1a7b49ad188074707b004e7bb8824857 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Plugins.meta b/Assets/Mirror/Plugins.meta new file mode 100644 index 0000000..9504239 --- /dev/null +++ b/Assets/Mirror/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 05eb4061e2eb94061b9a08c918fff99b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Plugins/Mono.Cecil.meta b/Assets/Mirror/Plugins/Mono.Cecil.meta new file mode 100644 index 0000000..a104e2e --- /dev/null +++ b/Assets/Mirror/Plugins/Mono.Cecil.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ce126b4e1a7d13b4c865cd92929f13c3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Plugins/Mono.Cecil/License.txt b/Assets/Mirror/Plugins/Mono.Cecil/License.txt new file mode 100644 index 0000000..2a9b88f --- /dev/null +++ b/Assets/Mirror/Plugins/Mono.Cecil/License.txt @@ -0,0 +1,25 @@ +Copyright (c) 2008 - 2015 Jb Evain +Copyright (c) 2008 - 2011 Novell, Inc. +Copyright vis2k + +https://github.com/jbevain/cecil +https://github.com/vis2k/cecil <- X + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Assets/Mirror/Plugins/Mono.Cecil/License.txt.meta b/Assets/Mirror/Plugins/Mono.Cecil/License.txt.meta new file mode 100644 index 0000000..9477cb6 --- /dev/null +++ b/Assets/Mirror/Plugins/Mono.Cecil/License.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ab858db5ebbb0d542a9acd197669cb5a +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll b/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll new file mode 100644 index 0000000000000000000000000000000000000000..f6815d3b41f5d04b8389ae99b07df13246c3b6da GIT binary patch literal 43520 zcmeIb3wTu3)i=J+WzL+LNkV3lOt=IH3OFPoKtKgA2m(r!n}P@`4S@_0O>$r+pctnH zZ><-+)!ORoU2C=4da1V6+Ny7DU+t@XtF;%a@@ng)+S+Pc+ghvsf4{Z&nVA6kw%_xA zp6`3U=Np)P)>?b*wbxpE?dv&bviO8cm7|n$@%`u{rM`tLKXWAgpT1Ug8s&J*~Z+~zQ*pp#`#N^H}(cy+1AR+_;@3F z*#e~&S&n+=miK=f*7lOxr!iqoRq7^CJWY*1f@>qbFX5|HwZOL4n*{1FpGHe5(D`xH zoO8*_|D~%zNy6v;hm~4N;3cKj(h+-nEL8#8ecx4T#U6Q|KxkCTFU$6UFD%1b`?II@ z1FyaTNh7|r)#wdKK8;YRHJ8t=2PV3`1b~L#f^XSp4w|bqm+c9_NL`gOKDbSgVlqdm z!;6Rk-hlo5P&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#rxPjo!fcB zM(O|CKhJ#U=5v*`co|)F9=<+)72UtFq!xXESJ3fJhEf+J@8YsNa^aQeA)jNH&tLwR zv)`UNVsX>LTkc%=N^aygKB9~%$Khx`KV{3Q* zk=GlJ=sxY(ES^o~z3S~#*7J>rDS3I;DL(}d#!kWWUsLcDVHQs=P3g<_&zL%8x8`Ww zj8`6(FPz)9{{hM<^2IKr2#k$%zW?_NFZk3qKVQG}smd2&Q26;P;l>afdVQmePpOW1 zcpRapXEB3B-mS=Hc9}Ukg%sau%N5wd0Ix15U*F886HB70BfYTOMb7JOkFJ;=-WrcGp3u1)X@_ z$Mdy~dyzC-c&6eUQ2(2O^I?pouorKh7y0MQnc8}h!*kJ6J&U0aPb2w$C{Nva%D4*H zVw~HpgPbPx@%E}*7D>rhbvET!?QgF*`HKrD{Ah+ zKLuZngPcW>u~8)OGlKIx5(IQ#1d&z`hK{4#qZ^rk;%0^;d7G5mG|prc?_Biec! zB+{q+EE9c~8o8uW->}t+=ZgQd-ZSwAC4Qp=@_72W6<+Nxv;O1k=MSXP*F($g?(x0( t`yeSd7g1Dx=b#bMH?+0(R#qJFe|qwW{(B)6I=uc**Y^ME_y4m8{y*D^#|Z!c literal 0 HcmV?d00001 diff --git a/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll.meta b/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll.meta new file mode 100644 index 0000000..d5555bf --- /dev/null +++ b/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Mdb.dll.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: a078fc7c0dc14d047a28dea9c93fd259 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: None + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll b/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll new file mode 100644 index 0000000000000000000000000000000000000000..3b58436e37e6705aa683b65555cbb77a256c82db GIT binary patch literal 87552 zcmeFa2Y4Jswl-YT-P1D~1#2|Yj3ft1wq=hsN|u~+&N(5QU@#akV2_bZ9Ld<^U>i)v zYZha2SYSy@&KTH*B`pg}T7uW)oE8?F|9wx@v_>{?_xta?|M!2-clF@Y^`3L;)Twx? ztGkEki_THDQp&-ui zu7PA1P%98W8@{;7t^hU9y%}<=0lERa&hmU1GnVSE`Yli)R+i;Y!4-vu?PM9$lI0+w zME3#}uRsb#(Tm-S>JAY!df-y?(wlh&YF88^y0cf1E+gL6 z1WHBf9km4ggFX&hHhOd&22V|{6OC7*zw(^eyl9o1?8R;ly2;+SCNP}hxH|qkC;l|F z^ZahI4;b-3$+*KP3)NW6#gvTD>;j*R(5gk&>I5~bL8^UKmL0D_3VPzlWL&Y{g{@>Q zxUr_goE3FJ4HC8!TNv`Yv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 index 0000000..3ab420f --- /dev/null +++ b/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Pdb.dll.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: 534d998d93b238041bddcd864f7f1088 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Editor: 0 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: None + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll b/Assets/Mirror/Plugins/Mono.Cecil/Mono.CecilX.Rocks.dll new file mode 100644 index 0000000000000000000000000000000000000000..7d820f0cc4eb2ead833303c0e6e2dea9f7b0eef1 GIT binary patch literal 27648 zcmeHw3w%`7wf8z_X3m_MBtvHM=9K_~Lqft+3<}6ANHpOUR8TMs$p9mhIbmjk1SBM4 zt*Euqs?~}uR%=^dS8r{7T-$=JTCMuk);_pe3%yort+lk;TUvz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*V+sMpA6{|$@_9N^LkAyW^7OmNhrzcghtJohca|QVpPN`lDcRY#JTW`BvmjD2R5m~ah9lD(i5RAnbB|aQ zUnIcJ0`ge{uzzXx$7=I4>zuI5=sFO7VtW4k+@+mK5?>&D`A?nx$@1^4`vJW>)?0u7 zcgPCA^`AcT+OPiZH-Bko`&Tyo>K|?VgSY?a^Y8qHpZ?e`uV{0sl2@YwygzP)?kFaEo}ciwvYrdNOY zKfL{i(+?fn@H4;u*Pq?~xyjpprFPr!fBKi7T>jkrj^F>oKl^9?=BC$v?vo!I`g4^- zwdt(;xcpPIEulsS`c$(Z4s4yi)qjo37-J z{pL;MXJ?nHs51|vV^*go&LcRhleOyNh4a;wIvEM7Sjjtb=>&^zK|Q=K>W_6wM~g2xT^F*()%})nR8QU zF6lXgVWVE(0G3txHwXm&`*+jqxtx+VsNh$s=-0ds#})6^y%*b5>Y~opk;Qg_%y(=j zc22EpeLJJw<=m#O@>cu!t>mpGT9n?&mqT-rM3F;8jxgZI>4x;xmKv?9s=! z{abL!=rz4L^5bGJyJwWmFfXsQ9!>*d8auyPW=Vyo9iLMW?GM@i_Yvzv@+-(^XRIckwnI<3h52fJpr<5zeyxDPLH=9NV(pBEnVp9=hEz m>yU%d1DU0u6LOc8SEtI>6JOR-v Player > Other Settings) + +Documentation: + https://mirror-networking.gitbook.io/docs/ + +Support: + Discord: https://discordapp.com/invite/N9QVxbM + Bug Reports: https://github.com/vis2k/Mirror/issues diff --git a/Assets/Mirror/Readme.txt.meta b/Assets/Mirror/Readme.txt.meta new file mode 100644 index 0000000..d52ccce --- /dev/null +++ b/Assets/Mirror/Readme.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f6d84e019c68446f28415a923b460a03 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports.meta b/Assets/Mirror/Transports.meta new file mode 100644 index 0000000..72fd20d --- /dev/null +++ b/Assets/Mirror/Transports.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d7d3068968d80427e8cc256e22b0b0b5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP.meta b/Assets/Mirror/Transports/KCP.meta new file mode 100644 index 0000000..1727b05 --- /dev/null +++ b/Assets/Mirror/Transports/KCP.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ea4ea5d03df6a49449fa679ac2390773 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/KcpTransport.cs b/Assets/Mirror/Transports/KCP/KcpTransport.cs new file mode 100644 index 0000000..1bb431f --- /dev/null +++ b/Assets/Mirror/Transports/KCP/KcpTransport.cs @@ -0,0 +1,366 @@ +//#if MIRROR <- commented out because MIRROR isn't defined on first import yet +using System; +using System.Linq; +using System.Net; +using UnityEngine; +using Mirror; +using Unity.Collections; +using UnityEngine.Serialization; + +namespace kcp2k +{ + [HelpURL("https://mirror-networking.gitbook.io/docs/transports/kcp-transport")] + [DisallowMultipleComponent] + public class KcpTransport : Transport, PortTransport + { + // scheme used by this transport + public const string Scheme = "kcp"; + + // common + [Header("Transport Configuration")] + [FormerlySerializedAs("Port")] + public ushort port = 7777; + public ushort Port { get => port; set => port=value; } + [Tooltip("DualMode listens to IPv6 and IPv4 simultaneously. Disable if the platform only supports IPv4.")] + public bool DualMode = true; + [Tooltip("NoDelay is recommended to reduce latency. This also scales better without buffers getting full.")] + public bool NoDelay = true; + [Tooltip("KCP internal update interval. 100ms is KCP default, but a lower interval is recommended to minimize latency and to scale to more networked entities.")] + public uint Interval = 10; + [Tooltip("KCP timeout in milliseconds. Note that KCP sends a ping automatically.")] + public int Timeout = 10000; + [Tooltip("Socket receive buffer size. Large buffer helps support more connections. Increase operating system socket buffer size limits if needed.")] + public int RecvBufferSize = 1024 * 1027 * 7; + [Tooltip("Socket send buffer size. Large buffer helps support more connections. Increase operating system socket buffer size limits if needed.")] + public int SendBufferSize = 1024 * 1027 * 7; + + [Header("Advanced")] + [Tooltip("KCP fastresend parameter. Faster resend for the cost of higher bandwidth. 0 in normal mode, 2 in turbo mode.")] + public int FastResend = 2; + [Tooltip("KCP congestion window. Restricts window size to reduce congestion. Results in only 2-3 MTU messages per Flush even on loopback. Best to keept his disabled.")] + /*public*/ bool CongestionWindow = false; // KCP 'NoCongestionWindow' is false by default. here we negate it for ease of use. + [Tooltip("KCP window size can be modified to support higher loads. This also increases max message size.")] + public uint ReceiveWindowSize = 4096; //Kcp.WND_RCV; 128 by default. Mirror sends a lot, so we need a lot more. + [Tooltip("KCP window size can be modified to support higher loads.")] + public uint SendWindowSize = 4096; //Kcp.WND_SND; 32 by default. Mirror sends a lot, so we need a lot more. + [Tooltip("KCP will try to retransmit lost messages up to MaxRetransmit (aka dead_link) before disconnecting.")] + public uint MaxRetransmit = Kcp.DEADLINK * 2; // default prematurely disconnects a lot of people (#3022). use 2x. + [Tooltip("Enable to automatically set client & server send/recv buffers to OS limit. Avoids issues with too small buffers under heavy load, potentially dropping connections. Increase the OS limit if this is still too small.")] + [FormerlySerializedAs("MaximizeSendReceiveBuffersToOSLimit")] + public bool MaximizeSocketBuffers = true; + + [Header("Allowed Max Message Sizes\nBased on Receive Window Size")] + [Tooltip("KCP reliable max message size shown for convenience. Can be changed via ReceiveWindowSize.")] + [ReadOnly] public int ReliableMaxMessageSize = 0; // readonly, displayed from OnValidate + [Tooltip("KCP unreliable channel max message size for convenience. Not changeable.")] + [ReadOnly] public int UnreliableMaxMessageSize = 0; // readonly, displayed from OnValidate + + // config is created from the serialized properties above. + // we can expose the config directly in the future. + // for now, let's not break people's old settings. + protected KcpConfig config; + + // use default MTU for this transport. + const int MTU = Kcp.MTU_DEF; + + // server & client + protected KcpServer server; + protected KcpClient client; + + // debugging + [Header("Debug")] + public bool debugLog; + // show statistics in OnGUI + public bool statisticsGUI; + // log statistics for headless servers that can't show them in GUI + public bool statisticsLog; + + // translate Kcp <-> Mirror channels + public static int FromKcpChannel(KcpChannel channel) => + channel == KcpChannel.Reliable ? Channels.Reliable : Channels.Unreliable; + + public static KcpChannel ToKcpChannel(int channel) => + channel == Channels.Reliable ? KcpChannel.Reliable : KcpChannel.Unreliable; + + public static TransportError ToTransportError(ErrorCode error) + { + switch(error) + { + case ErrorCode.DnsResolve: return TransportError.DnsResolve; + case ErrorCode.Timeout: return TransportError.Timeout; + case ErrorCode.Congestion: return TransportError.Congestion; + case ErrorCode.InvalidReceive: return TransportError.InvalidReceive; + case ErrorCode.InvalidSend: return TransportError.InvalidSend; + case ErrorCode.ConnectionClosed: return TransportError.ConnectionClosed; + case ErrorCode.Unexpected: return TransportError.Unexpected; + default: throw new InvalidCastException($"KCP: missing error translation for {error}"); + } + } + + protected virtual void Awake() + { + // logging + // Log.Info should use Debug.Log if enabled, or nothing otherwise + // (don't want to spam the console on headless servers) + if (debugLog) + Log.Info = Debug.Log; + else + Log.Info = _ => {}; + Log.Warning = Debug.LogWarning; + Log.Error = Debug.LogError; + + // create config from serialized settings + config = new KcpConfig(DualMode, RecvBufferSize, SendBufferSize, MTU, NoDelay, Interval, FastResend, CongestionWindow, SendWindowSize, ReceiveWindowSize, Timeout, MaxRetransmit); + + // client (NonAlloc version is not necessary anymore) + client = new KcpClient( + () => OnClientConnected.Invoke(), + (message, channel) => OnClientDataReceived.Invoke(message, FromKcpChannel(channel)), + () => OnClientDisconnected.Invoke(), + (error, reason) => OnClientError.Invoke(ToTransportError(error), reason), + config + ); + + // server + server = new KcpServer( + (connectionId) => OnServerConnected.Invoke(connectionId), + (connectionId, message, channel) => OnServerDataReceived.Invoke(connectionId, message, FromKcpChannel(channel)), + (connectionId) => OnServerDisconnected.Invoke(connectionId), + (connectionId, error, reason) => OnServerError.Invoke(connectionId, ToTransportError(error), reason), + config + ); + + if (statisticsLog) + InvokeRepeating(nameof(OnLogStatistics), 1, 1); + + Debug.Log("KcpTransport initialized!"); + } + + protected virtual void OnValidate() + { + // show max message sizes in inspector for convenience. + // 'config' isn't available in edit mode yet, so use MTU define. + ReliableMaxMessageSize = KcpPeer.ReliableMaxMessageSize(MTU, ReceiveWindowSize); + UnreliableMaxMessageSize = KcpPeer.UnreliableMaxMessageSize(MTU); + } + + // all except WebGL + public override bool Available() => + Application.platform != RuntimePlatform.WebGLPlayer; + + // client + public override bool ClientConnected() => client.connected; + public override void ClientConnect(string address) + { + client.Connect(address, Port); + } + public override void ClientConnect(Uri uri) + { + if (uri.Scheme != Scheme) + throw new ArgumentException($"Invalid url {uri}, use {Scheme}://host:port instead", nameof(uri)); + + int serverPort = uri.IsDefaultPort ? Port : uri.Port; + client.Connect(uri.Host, (ushort)serverPort); + } + public override void ClientSend(ArraySegment segment, int channelId) + { + client.Send(segment, ToKcpChannel(channelId)); + + // call event. might be null if no statistics are listening etc. + OnClientDataSent?.Invoke(segment, channelId); + } + public override void ClientDisconnect() => client.Disconnect(); + // process incoming in early update + public override void ClientEarlyUpdate() + { + // only process messages while transport is enabled. + // scene change messsages disable it to stop processing. + // (see also: https://github.com/vis2k/Mirror/pull/379) + if (enabled) client.TickIncoming(); + } + // process outgoing in late update + public override void ClientLateUpdate() => client.TickOutgoing(); + + // server + public override Uri ServerUri() + { + UriBuilder builder = new UriBuilder(); + builder.Scheme = Scheme; + builder.Host = Dns.GetHostName(); + builder.Port = Port; + return builder.Uri; + } + public override bool ServerActive() => server.IsActive(); + public override void ServerStart() => server.Start(Port); + public override void ServerSend(int connectionId, ArraySegment segment, int channelId) + { + server.Send(connectionId, segment, ToKcpChannel(channelId)); + + // call event. might be null if no statistics are listening etc. + OnServerDataSent?.Invoke(connectionId, segment, channelId); + } + public override void ServerDisconnect(int connectionId) => server.Disconnect(connectionId); + public override string ServerGetClientAddress(int connectionId) + { + IPEndPoint endPoint = server.GetClientEndPoint(connectionId); + return endPoint != null + // Map to IPv4 if "IsIPv4MappedToIPv6" + // "::ffff:127.0.0.1" -> "127.0.0.1" + ? (endPoint.Address.IsIPv4MappedToIPv6 + ? endPoint.Address.MapToIPv4().ToString() + : endPoint.Address.ToString()) + : ""; + } + public override void ServerStop() => server.Stop(); + public override void ServerEarlyUpdate() + { + // only process messages while transport is enabled. + // scene change messsages disable it to stop processing. + // (see also: https://github.com/vis2k/Mirror/pull/379) + if (enabled) server.TickIncoming(); + } + // process outgoing in late update + public override void ServerLateUpdate() => server.TickOutgoing(); + + // common + public override void Shutdown() {} + + // max message size + public override int GetMaxPacketSize(int channelId = Channels.Reliable) + { + // switch to kcp channel. + // unreliable or reliable. + // default to reliable just to be sure. + switch (channelId) + { + case Channels.Unreliable: + return KcpPeer.UnreliableMaxMessageSize(config.Mtu); + default: + return KcpPeer.ReliableMaxMessageSize(config.Mtu, ReceiveWindowSize); + } + } + + // kcp reliable channel max packet size is MTU * WND_RCV + // this allows 144kb messages. but due to head of line blocking, all + // other messages would have to wait until the maxed size one is + // delivered. batching 144kb messages each time would be EXTREMELY slow + // and fill the send queue nearly immediately when using it over the + // network. + // => instead we always use MTU sized batches. + // => people can still send maxed size if needed. + public override int GetBatchThreshold(int channelId) => + KcpPeer.UnreliableMaxMessageSize(config.Mtu); + + // server statistics + // LONG to avoid int overflows with connections.Sum. + // see also: https://github.com/vis2k/Mirror/pull/2777 + public long GetAverageMaxSendRate() => + server.connections.Count > 0 + ? server.connections.Values.Sum(conn => conn.peer.MaxSendRate) / server.connections.Count + : 0; + public long GetAverageMaxReceiveRate() => + server.connections.Count > 0 + ? server.connections.Values.Sum(conn => conn.peer.MaxReceiveRate) / server.connections.Count + : 0; + long GetTotalSendQueue() => + server.connections.Values.Sum(conn => conn.peer.SendQueueCount); + long GetTotalReceiveQueue() => + server.connections.Values.Sum(conn => conn.peer.ReceiveQueueCount); + long GetTotalSendBuffer() => + server.connections.Values.Sum(conn => conn.peer.SendBufferCount); + long GetTotalReceiveBuffer() => + server.connections.Values.Sum(conn => conn.peer.ReceiveBufferCount); + + // PrettyBytes function from DOTSNET + // pretty prints bytes as KB/MB/GB/etc. + // long to support > 2GB + // divides by floats to return "2.5MB" etc. + public static string PrettyBytes(long bytes) + { + // bytes + if (bytes < 1024) + return $"{bytes} B"; + // kilobytes + else if (bytes < 1024L * 1024L) + return $"{(bytes / 1024f):F2} KB"; + // megabytes + else if (bytes < 1024 * 1024L * 1024L) + return $"{(bytes / (1024f * 1024f)):F2} MB"; + // gigabytes + return $"{(bytes / (1024f * 1024f * 1024f)):F2} GB"; + } + + protected virtual void OnGUIStatistics() + { + GUILayout.BeginArea(new Rect(5, 110, 300, 300)); + + if (ServerActive()) + { + GUILayout.BeginVertical("Box"); + GUILayout.Label("SERVER"); + GUILayout.Label($" connections: {server.connections.Count}"); + GUILayout.Label($" MaxSendRate (avg): {PrettyBytes(GetAverageMaxSendRate())}/s"); + GUILayout.Label($" MaxRecvRate (avg): {PrettyBytes(GetAverageMaxReceiveRate())}/s"); + GUILayout.Label($" SendQueue: {GetTotalSendQueue()}"); + GUILayout.Label($" ReceiveQueue: {GetTotalReceiveQueue()}"); + GUILayout.Label($" SendBuffer: {GetTotalSendBuffer()}"); + GUILayout.Label($" ReceiveBuffer: {GetTotalReceiveBuffer()}"); + GUILayout.EndVertical(); + } + + if (ClientConnected()) + { + GUILayout.BeginVertical("Box"); + GUILayout.Label("CLIENT"); + GUILayout.Label($" MaxSendRate: {PrettyBytes(client.peer.MaxSendRate)}/s"); + GUILayout.Label($" MaxRecvRate: {PrettyBytes(client.peer.MaxReceiveRate)}/s"); + GUILayout.Label($" SendQueue: {client.peer.SendQueueCount}"); + GUILayout.Label($" ReceiveQueue: {client.peer.ReceiveQueueCount}"); + GUILayout.Label($" SendBuffer: {client.peer.SendBufferCount}"); + GUILayout.Label($" ReceiveBuffer: {client.peer.ReceiveBufferCount}"); + GUILayout.EndVertical(); + } + + GUILayout.EndArea(); + } + +// OnGUI allocates even if it does nothing. avoid in release. +#if UNITY_EDITOR || DEVELOPMENT_BUILD + protected virtual void OnGUI() + { + if (statisticsGUI) OnGUIStatistics(); + } +#endif + + protected virtual void OnLogStatistics() + { + if (ServerActive()) + { + string log = "kcp SERVER @ time: " + NetworkTime.localTime + "\n"; + log += $" connections: {server.connections.Count}\n"; + log += $" MaxSendRate (avg): {PrettyBytes(GetAverageMaxSendRate())}/s\n"; + log += $" MaxRecvRate (avg): {PrettyBytes(GetAverageMaxReceiveRate())}/s\n"; + log += $" SendQueue: {GetTotalSendQueue()}\n"; + log += $" ReceiveQueue: {GetTotalReceiveQueue()}\n"; + log += $" SendBuffer: {GetTotalSendBuffer()}\n"; + log += $" ReceiveBuffer: {GetTotalReceiveBuffer()}\n\n"; + Debug.Log(log); + } + + if (ClientConnected()) + { + string log = "kcp CLIENT @ time: " + NetworkTime.localTime + "\n"; + log += $" MaxSendRate: {PrettyBytes(client.peer.MaxSendRate)}/s\n"; + log += $" MaxRecvRate: {PrettyBytes(client.peer.MaxReceiveRate)}/s\n"; + log += $" SendQueue: {client.peer.SendQueueCount}\n"; + log += $" ReceiveQueue: {client.peer.ReceiveQueueCount}\n"; + log += $" SendBuffer: {client.peer.SendBufferCount}\n"; + log += $" ReceiveBuffer: {client.peer.ReceiveBufferCount}\n\n"; + Debug.Log(log); + } + } + + public override string ToString() => "KCP"; + } +} +//#endif MIRROR <- commented out because MIRROR isn't defined on first import yet diff --git a/Assets/Mirror/Transports/KCP/KcpTransport.cs.meta b/Assets/Mirror/Transports/KCP/KcpTransport.cs.meta new file mode 100644 index 0000000..f7280c8 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/KcpTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b0fecffa3f624585964b0d0eb21b18e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k.meta b/Assets/Mirror/Transports/KCP/kcp2k.meta new file mode 100644 index 0000000..1dceadf --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 71a1c8e8c022d4731a481c1808f37e5d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/KCP.asmdef b/Assets/Mirror/Transports/KCP/kcp2k/KCP.asmdef new file mode 100644 index 0000000..66d2148 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/KCP.asmdef @@ -0,0 +1,16 @@ +{ + "name": "kcp2k", + "rootNamespace": "", + "references": [ + "GUID:30817c1a0e6d646d99c048fc403f5979" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/KCP.asmdef.meta b/Assets/Mirror/Transports/KCP/kcp2k/KCP.asmdef.meta new file mode 100644 index 0000000..1d70e80 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/KCP.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 6806a62c384838046a3c66c44f06d75f +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/LICENSE.txt b/Assets/Mirror/Transports/KCP/kcp2k/LICENSE.txt new file mode 100644 index 0000000..c77582e --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/LICENSE.txt @@ -0,0 +1,24 @@ +MIT License + +Copyright (c) 2016 limpo1989 +Copyright (c) 2020 Paul Pacheco +Copyright (c) 2020 Lymdun +Copyright (c) 2020 vis2k + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/LICENSE.txt.meta b/Assets/Mirror/Transports/KCP/kcp2k/LICENSE.txt.meta new file mode 100644 index 0000000..49dc767 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/LICENSE.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9a3e8369060cf4e94ac117603de47aa6 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/VERSION.txt b/Assets/Mirror/Transports/KCP/kcp2k/VERSION.txt new file mode 100644 index 0000000..40a9bd0 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/VERSION.txt @@ -0,0 +1,238 @@ +V1.37 [2023-07-31] +- fix: #47 KcpServer.Stop now clears connections so they aren't carried over to the next session +- fix: KcpPeer doesn't log 'received unreliable message while not authenticated' anymore. + +V1.36 [2023-06-08] +- fix: #49 KcpPeer.RawInput message size check now considers cookie as well +- kcp.cs cleanups + +V1.35 [2023-04-05] +- fix: KcpClients now need to validate with a secure cookie in order to protect against + UDP spoofing. fixes: + https://github.com/MirrorNetworking/Mirror/issues/3286 + [disclosed by IncludeSec] +- KcpClient/Server: change callbacks to protected so inheriting classes can use them too +- KcpClient/Server: change config visibility to protected + +V1.34 [2023-03-15] +- Send/SendTo/Receive/ReceiveFrom NonBlocking extensions. + to encapsulate WouldBlock allocations, exceptions, etc. + allows for reuse when overwriting KcpServer/Client (i.e. for relays). + +V1.33 [2023-03-14] +- perf: KcpServer/Client RawReceive now call socket.Poll to avoid non-blocking + socket's allocating a new SocketException in case they WouldBlock. + fixes https://github.com/MirrorNetworking/Mirror/issues/3413 +- perf: KcpServer/Client RawSend now call socket.Poll to avoid non-blocking + socket's allocating a new SocketException in case they WouldBlock. + fixes https://github.com/MirrorNetworking/Mirror/issues/3413 + +V1.32 [2023-03-12] +- fix: KcpPeer RawInput now doesn't disconnect in case of random internet noise + +V1.31 [2023-03-05] +- KcpClient: Tick/Incoming/Outgoing can now be overwritten (virtual) +- breaking: KcpClient now takes KcpConfig in constructor instead of in Connect. + cleaner, and prepares for KcpConfig.MTU setting. +- KcpConfig now includes MTU; KcpPeer now works with KcpConfig's MTU, KcpServer/Client + buffers are now created with config's MTU. + +V1.30 [2023-02-20] +- fix: set send/recv buffer sizes directly instead of iterating to find the limit. + fixes: https://github.com/MirrorNetworking/Mirror/issues/3390 +- fix: server & client sockets are now always non-blocking to ensure main thread never + blocks on socket.recv/send. Send() now also handles WouldBlock. +- fix: socket.Receive/From directly with non-blocking sockets and handle WouldBlock, + instead of socket.Poll. faster, more obvious, and fixes Poll() looping forever while + socket is in error state. fixes: https://github.com/MirrorNetworking/Mirror/issues/2733 + +V1.29 [2023-01-28] +- fix: KcpServer.CreateServerSocket now handles NotSupportedException when setting DualMode + https://github.com/MirrorNetworking/Mirror/issues/3358 + +V1.28 [2023-01-28] +- fix: KcpClient.Connect now resolves hostname before creating peer + https://github.com/MirrorNetworking/Mirror/issues/3361 + +V1.27 [2023-01-08] +- KcpClient.Connect: invoke own events directly instead of going through peer, + which calls our own events anyway +- fix: KcpPeer/Client/Server callbacks are readonly and assigned in constructor + to ensure they are safe to use at all times. + fixes https://github.com/MirrorNetworking/Mirror/issues/3337 + +V1.26 [2022-12-22] +- KcpPeer.RawInput: fix compile error in old Unity Mono versions +- fix: KcpServer sets up a new connection's OnError immediately. + fixes KcpPeer throwing NullReferenceException when attempting to call OnError + after authentication errors. +- improved log messages + +V1.25 [2022-12-14] +- breaking: removed where-allocation. use IL2CPP on servers instead. +- breaking: KcpConfig to simplify configuration +- high level cleanups + +V1.24 [2022-12-14] +- KcpClient: fixed NullReferenceException when connection without a server. + added test coverage to ensure this never happens again. + +V1.23 [2022-12-07] +- KcpClient: rawReceiveBuffer exposed +- fix: KcpServer RawSend uses connection.remoteEndPoint instead of the helper + 'newClientEP'. fixes clients receiving the wrong messages meant for others. + https://github.com/MirrorNetworking/Mirror/issues/3296 + +V1.22 [2022-11-30] +- high level refactor, part two. + +V1.21 [2022-11-24] +- high level refactor, part one. + - KcpPeer instead of KcpConnection, KcpClientConnection, KcpServerConnection + - RawSend/Receive can now easily be overwritten in KcpClient/Server. + for non-alloc, relays, etc. + +V1.20 [2022-11-22] +- perf: KcpClient receive allocation was removed entirely. + reduces Mirror benchmark client sided allocations from 4.9 KB / 1.7 KB (non-alloc) to 0B. +- fix: KcpConnection.Disconnect does not check socket.Connected anymore. + UDP sockets don't have a connection. + fixes Disconnects not being sent to clients in netcore. +- KcpConnection.SendReliable: added OnError instead of logs + +V1.19 [2022-05-12] +- feature: OnError ErrorCodes + +V1.18 [2022-05-08] +- feature: OnError to allow higher level to show popups etc. +- feature: KcpServer.GetClientAddress is now GetClientEndPoint in order to + expose more details +- ResolveHostname: include exception in log for easier debugging +- fix: KcpClientConnection.RawReceive now logs the SocketException even if + it was expected. makes debugging easier. +- fix: KcpServer.TickIncoming now logs the SocketException even if it was + expected. makes debugging easier. +- fix: KcpClientConnection.RawReceive now calls Disconnect() if the other end + has closed the connection. better than just remaining in a state with unusable + sockets. + +V1.17 [2022-01-09] +- perf: server/client MaximizeSendReceiveBuffersToOSLimit option to set send/recv + buffer sizes to OS limit. avoids drops due to small buffers under heavy load. + +V1.16 [2022-01-06] +- fix: SendUnreliable respects ArraySegment.Offset +- fix: potential bug with negative length (see PR #2) +- breaking: removed pause handling because it's not necessary for Mirror anymore + +V1.15 [2021-12-11] +- feature: feature: MaxRetransmits aka dead_link now configurable +- dead_link disconnect message improved to show exact retransmit count + +V1.14 [2021-11-30] +- fix: Send() now throws an exception for messages which require > 255 fragments +- fix: ReliableMaxMessageSize is now limited to messages which require <= 255 fragments + +V1.13 [2021-11-28] +- fix: perf: uncork max message size from 144 KB to as much as we want based on + receive window size. + fixes https://github.com/vis2k/kcp2k/issues/22 + fixes https://github.com/skywind3000/kcp/pull/291 +- feature: OnData now includes channel it was received on + +V1.12 [2021-07-16] +- Tests: don't depend on Unity anymore +- fix: #26 - Kcp now catches exception if host couldn't be resolved, and calls + OnDisconnected to let the user now. +- fix: KcpServer.DualMode is now configurable in the constructor instead of + using #if UNITY_SWITCH. makes it run on all other non dual mode platforms too. +- fix: where-allocation made optional via virtuals and inheriting + KcpServer/Client/Connection NonAlloc classes. fixes a bug where some platforms + might not support where-allocation. + +V1.11 rollback [2021-06-01] +- perf: Segment MemoryStream initial capacity set to MTU to avoid early runtime + resizing/allocations + +V1.10 [2021-05-28] +- feature: configurable Timeout +- allocations explained with comments (C# ReceiveFrom / IPEndPoint.GetHashCode) +- fix: #17 KcpConnection.ReceiveNextReliable now assigns message default so it + works in .net too +- fix: Segment pool is not static anymore. Each kcp instance now has it's own + Pool. fixes #18 concurrency issues + +V1.9 [2021-03-02] +- Tick() split into TickIncoming()/TickOutgoing() to use in Mirror's new update + functions. allows to minimize latency. + => original Tick() is still supported for convenience. simply processes both! + +V1.8 [2021-02-14] +- fix: Unity IPv6 errors on Nintendo Switch +- fix: KcpConnection now disconnects if data message was received without content. + previously it would call OnData with an empty ArraySegment, causing all kinds of + weird behaviour in Mirror/DOTSNET. Added tests too. +- fix: KcpConnection.SendData: don't allow sending empty messages anymore. disconnect + and log a warning to make it completely obvious. + +V1.7 [2021-01-13] +- fix: unreliable messages reset timeout now too +- perf: KcpConnection OnCheckEnabled callback changed to a simple 'paused' boolean. + This is faster than invoking a Func every time and allows us to fix #8 more + easily later by calling .Pause/.Unpause from OnEnable/OnDisable in MirrorTransport. +- fix #8: Unpause now resets timeout to fix a bug where Mirror would pause kcp, + change the scene which took >10s, then unpause and kcp would detect the lack of + any messages for >10s as timeout. Added test to make sure it never happens again. +- MirrorTransport: statistics logging for headless servers +- Mirror Transport: Send/Receive window size increased once more from 2048 to 4096. + +V1.6 [2021-01-10] +- Unreliable channel added! +- perf: KcpHeader byte added to every kcp message to indicate + Handshake/Data/Ping/Disconnect instead of scanning each message for Hello/Byte/Ping + content via SegmentEquals. It's a lot cleaner, should be faster and should avoid + edge cases where a message content would equal Hello/Ping/Bye sequence accidentally. +- Kcp.Input: offset moved to parameters for cases where it's needed +- Kcp.SetMtu from original Kcp.c + +V1.5 [2021-01-07] +- KcpConnection.MaxSend/ReceiveRate calculation based on the article +- MirrorTransport: large send/recv window size defaults to avoid high latencies caused + by packets not being processed fast enough +- MirrorTransport: show MaxSend/ReceiveRate in debug gui +- MirrorTransport: don't Log.Info to console in headless mode if debug log is disabled + +V1.4 [2020-11-27] +- fix: OnCheckEnabled added. KcpConnection message processing while loop can now + be interrupted immediately. fixes Mirror Transport scene changes which need to stop + processing any messages immediately after a scene message) +- perf: Mirror KcpTransport: FastResend enabled by default. turbo mode according to: + https://github.com/skywind3000/kcp/blob/master/README.en.md#protocol-configuration +- perf: Mirror KcpTransport: CongestionControl disabled by default (turbo mode) + +V1.3 [2020-11-17] +- Log.Info/Warning/Error so logging doesn't depend on UnityEngine anymore +- fix: Server.Tick catches SocketException which happens if Android client is killed +- MirrorTransport: debugLog option added that can be checked in Unity Inspector +- Utils.Clamp so Kcp.cs doesn't depend on UnityEngine +- Utils.SegmentsEqual: use Linq SequenceEqual so it doesn't depend on UnityEngine +=> kcp2k can now be used in any C# project even without Unity + +V1.2 [2020-11-10] +- more tests added +- fix: raw receive buffers are now all of MTU size +- fix: raw receive detects error where buffer was too small for msgLength and + result in excess data being dropped silently +- KcpConnection.MaxMessageSize added for use in high level +- KcpConnection.MaxMessageSize increased from 1200 bytes to to maximum allowed + message size of 145KB for kcp (based on mtu, overhead, wnd_rcv) + +V1.1 [2020-10-30] +- high level cleanup, fixes, improvements + +V1.0 [2020-10-22] +- Kcp.cs now mirrors original Kcp.c behaviour + (this fixes dozens of bugs) + +V0.1 +- initial kcp-csharp based version \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/VERSION.txt.meta b/Assets/Mirror/Transports/KCP/kcp2k/VERSION.txt.meta new file mode 100644 index 0000000..2a07daa --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/VERSION.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ed3f2cf1bbf1b4d53a6f2c103d311f71 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty.meta b/Assets/Mirror/Transports/KCP/kcp2k/empty.meta new file mode 100644 index 0000000..ae61673 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d9ce2267cb8a4a1c9632025287e8da88 +timeCreated: 1669162433 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnection.cs b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnection.cs new file mode 100644 index 0000000..7926893 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnection.cs @@ -0,0 +1 @@ +// removed 2022-11-23 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnection.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnection.cs.meta new file mode 100644 index 0000000..3369918 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnection.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 96512e74aa8214a6faa8a412a7a07877 +timeCreated: 1602601237 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnectionNonAlloc.cs b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnectionNonAlloc.cs new file mode 100644 index 0000000..8c3864d --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnectionNonAlloc.cs @@ -0,0 +1 @@ +// removed 2022-11-22 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnectionNonAlloc.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnectionNonAlloc.cs.meta new file mode 100644 index 0000000..9d4a42e --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientConnectionNonAlloc.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4c1b235bbe054706bef6d092f361006e +timeCreated: 1626430539 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientNonAlloc.cs b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientNonAlloc.cs new file mode 100644 index 0000000..8c3864d --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientNonAlloc.cs @@ -0,0 +1 @@ +// removed 2022-11-22 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientNonAlloc.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientNonAlloc.cs.meta new file mode 100644 index 0000000..266dafb --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpClientNonAlloc.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2cf0ccf7d551480bb5af08fcbe169f84 +timeCreated: 1626435264 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerConnectionNonAlloc.cs b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerConnectionNonAlloc.cs new file mode 100644 index 0000000..7926893 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerConnectionNonAlloc.cs @@ -0,0 +1 @@ +// removed 2022-11-23 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerConnectionNonAlloc.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerConnectionNonAlloc.cs.meta new file mode 100644 index 0000000..383fe02 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerConnectionNonAlloc.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4e1b74cc224b4c83a0f6c8d8da9090ab +timeCreated: 1626430608 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerNonAlloc.cs b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerNonAlloc.cs new file mode 100644 index 0000000..4623b53 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerNonAlloc.cs @@ -0,0 +1 @@ +// removed 2022-12-13 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerNonAlloc.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerNonAlloc.cs.meta new file mode 100644 index 0000000..a878cc1 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/empty/KcpServerNonAlloc.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 54b8398dcd544c8a93bcad846214cc40 +timeCreated: 1626432191 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel.meta new file mode 100644 index 0000000..1c11c3d --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5a54d18b954cb4407a28b633fc32ea6d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Common.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Common.cs new file mode 100644 index 0000000..ea5140f --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Common.cs @@ -0,0 +1,75 @@ +using System; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; + +namespace kcp2k +{ + public static class Common + { + // helper function to resolve host to IPAddress + public static bool ResolveHostname(string hostname, out IPAddress[] addresses) + { + try + { + // NOTE: dns lookup is blocking. this can take a second. + addresses = Dns.GetHostAddresses(hostname); + return addresses.Length >= 1; + } + catch (SocketException exception) + { + Log.Info($"Failed to resolve host: {hostname} reason: {exception}"); + addresses = null; + return false; + } + } + + // if connections drop under heavy load, increase to OS limit. + // if still not enough, increase the OS limit. + public static void ConfigureSocketBuffers(Socket socket, int recvBufferSize, int sendBufferSize) + { + // log initial size for comparison. + // remember initial size for log comparison + int initialReceive = socket.ReceiveBufferSize; + int initialSend = socket.SendBufferSize; + + // set to configured size + try + { + socket.ReceiveBufferSize = recvBufferSize; + socket.SendBufferSize = sendBufferSize; + } + catch (SocketException) + { + Log.Warning($"Kcp: failed to set Socket RecvBufSize = {recvBufferSize} SendBufSize = {sendBufferSize}"); + } + + + Log.Info($"Kcp: RecvBuf = {initialReceive}=>{socket.ReceiveBufferSize} ({socket.ReceiveBufferSize/initialReceive}x) SendBuf = {initialSend}=>{socket.SendBufferSize} ({socket.SendBufferSize/initialSend}x)"); + } + + // generate a connection hash from IP+Port. + // + // NOTE: IPEndPoint.GetHashCode() allocates. + // it calls m_Address.GetHashCode(). + // m_Address is an IPAddress. + // GetHashCode() allocates for IPv6: + // https://github.com/mono/mono/blob/bdd772531d379b4e78593587d15113c37edd4a64/mcs/class/referencesource/System/net/System/Net/IPAddress.cs#L699 + // + // => using only newClientEP.Port wouldn't work, because + // different connections can have the same port. + public static int ConnectionHash(EndPoint endPoint) => + endPoint.GetHashCode(); + + // cookies need to be generated with a secure random generator. + // we don't want them to be deterministic / predictable. + // RNG is cached to avoid runtime allocations. + static readonly RNGCryptoServiceProvider cryptoRandom = new RNGCryptoServiceProvider(); + static readonly byte[] cryptoRandomBuffer = new byte[4]; + public static uint GenerateCookie() + { + cryptoRandom.GetBytes(cryptoRandomBuffer); + return BitConverter.ToUInt32(cryptoRandomBuffer, 0); + } + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Common.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Common.cs.meta new file mode 100644 index 0000000..e349d86 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Common.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9ced451c2954435f88cf718bcba020cb +timeCreated: 1669135138 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/ErrorCode.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/ErrorCode.cs new file mode 100644 index 0000000..15b872f --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/ErrorCode.cs @@ -0,0 +1,15 @@ +// kcp specific error codes to allow for error switching, localization, +// translation to Mirror errors, etc. +namespace kcp2k +{ + public enum ErrorCode : byte + { + DnsResolve, // failed to resolve a host name + Timeout, // ping timeout or dead link + Congestion, // more messages than transport / network can process + InvalidReceive, // recv invalid packet (possibly intentional attack) + InvalidSend, // user tried to send invalid data + ConnectionClosed, // connection closed voluntarily or lost involuntarily + Unexpected // unexpected error / exception, requires fix. + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/ErrorCode.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/ErrorCode.cs.meta new file mode 100644 index 0000000..42f163f --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/ErrorCode.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3abbeffc1d794f11a45b7fcf110353f5 +timeCreated: 1652320712 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Extensions.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Extensions.cs new file mode 100644 index 0000000..20725a9 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Extensions.cs @@ -0,0 +1,166 @@ +using System; +using System.Net; +using System.Net.Sockets; + +namespace kcp2k +{ + public static class Extensions + { + // ArraySegment as HexString for convenience + public static string ToHexString(this ArraySegment segment) => + BitConverter.ToString(segment.Array, segment.Offset, segment.Count); + + // non-blocking UDP send. + // allows for reuse when overwriting KcpServer/Client (i.e. for relays). + // => wrapped with Poll to avoid WouldBlock allocating new SocketException. + // => wrapped with try-catch to ignore WouldBlock exception. + // make sure to set socket.Blocking = false before using this! + public static bool SendToNonBlocking(this Socket socket, ArraySegment data, EndPoint remoteEP) + { + try + { + // when using non-blocking sockets, SendTo may return WouldBlock. + // in C#, WouldBlock throws a SocketException, which is expected. + // unfortunately, creating the SocketException allocates in C#. + // let's poll first to avoid the WouldBlock allocation. + // note that this entirely to avoid allocations. + // non-blocking UDP doesn't need Poll in other languages. + // and the code still works without the Poll call. + if (!socket.Poll(0, SelectMode.SelectWrite)) return false; + + // send to the the endpoint. + // do not send to 'newClientEP', as that's always reused. + // fixes https://github.com/MirrorNetworking/Mirror/issues/3296 + socket.SendTo(data.Array, data.Offset, data.Count, SocketFlags.None, remoteEP); + return true; + } + catch (SocketException e) + { + // for non-blocking sockets, SendTo may throw WouldBlock. + // in that case, simply drop the message. it's UDP, it's fine. + if (e.SocketErrorCode == SocketError.WouldBlock) return false; + + // otherwise it's a real socket error. throw it. + throw; + } + } + + // non-blocking UDP send. + // allows for reuse when overwriting KcpServer/Client (i.e. for relays). + // => wrapped with Poll to avoid WouldBlock allocating new SocketException. + // => wrapped with try-catch to ignore WouldBlock exception. + // make sure to set socket.Blocking = false before using this! + public static bool SendNonBlocking(this Socket socket, ArraySegment data) + { + try + { + // when using non-blocking sockets, SendTo may return WouldBlock. + // in C#, WouldBlock throws a SocketException, which is expected. + // unfortunately, creating the SocketException allocates in C#. + // let's poll first to avoid the WouldBlock allocation. + // note that this entirely to avoid allocations. + // non-blocking UDP doesn't need Poll in other languages. + // and the code still works without the Poll call. + if (!socket.Poll(0, SelectMode.SelectWrite)) return false; + + // SendTo allocates. we used bound Send. + socket.Send(data.Array, data.Offset, data.Count, SocketFlags.None); + return true; + } + catch (SocketException e) + { + // for non-blocking sockets, SendTo may throw WouldBlock. + // in that case, simply drop the message. it's UDP, it's fine. + if (e.SocketErrorCode == SocketError.WouldBlock) return false; + + // otherwise it's a real socket error. throw it. + throw; + } + } + + // non-blocking UDP receive. + // allows for reuse when overwriting KcpServer/Client (i.e. for relays). + // => wrapped with Poll to avoid WouldBlock allocating new SocketException. + // => wrapped with try-catch to ignore WouldBlock exception. + // make sure to set socket.Blocking = false before using this! + public static bool ReceiveFromNonBlocking(this Socket socket, byte[] recvBuffer, out ArraySegment data, ref EndPoint remoteEP) + { + data = default; + + try + { + // when using non-blocking sockets, ReceiveFrom may return WouldBlock. + // in C#, WouldBlock throws a SocketException, which is expected. + // unfortunately, creating the SocketException allocates in C#. + // let's poll first to avoid the WouldBlock allocation. + // note that this entirely to avoid allocations. + // non-blocking UDP doesn't need Poll in other languages. + // and the code still works without the Poll call. + if (!socket.Poll(0, SelectMode.SelectRead)) return false; + + // NOTE: ReceiveFrom allocates. + // we pass our IPEndPoint to ReceiveFrom. + // receive from calls newClientEP.Create(socketAddr). + // IPEndPoint.Create always returns a new IPEndPoint. + // https://github.com/mono/mono/blob/f74eed4b09790a0929889ad7fc2cf96c9b6e3757/mcs/class/System/System.Net.Sockets/Socket.cs#L1761 + // + // throws SocketException if datagram was larger than buffer. + // https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.receive?view=net-6.0 + int size = socket.ReceiveFrom(recvBuffer, 0, recvBuffer.Length, SocketFlags.None, ref remoteEP); + data = new ArraySegment(recvBuffer, 0, size); + return true; + } + catch (SocketException e) + { + // for non-blocking sockets, Receive throws WouldBlock if there is + // no message to read. that's okay. only log for other errors. + if (e.SocketErrorCode == SocketError.WouldBlock) return false; + + // otherwise it's a real socket error. throw it. + throw; + } + } + + // non-blocking UDP receive. + // allows for reuse when overwriting KcpServer/Client (i.e. for relays). + // => wrapped with Poll to avoid WouldBlock allocating new SocketException. + // => wrapped with try-catch to ignore WouldBlock exception. + // make sure to set socket.Blocking = false before using this! + public static bool ReceiveNonBlocking(this Socket socket, byte[] recvBuffer, out ArraySegment data) + { + data = default; + + try + { + // when using non-blocking sockets, ReceiveFrom may return WouldBlock. + // in C#, WouldBlock throws a SocketException, which is expected. + // unfortunately, creating the SocketException allocates in C#. + // let's poll first to avoid the WouldBlock allocation. + // note that this entirely to avoid allocations. + // non-blocking UDP doesn't need Poll in other languages. + // and the code still works without the Poll call. + if (!socket.Poll(0, SelectMode.SelectRead)) return false; + + // ReceiveFrom allocates. we used bound Receive. + // returns amount of bytes written into buffer. + // throws SocketException if datagram was larger than buffer. + // https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.receive?view=net-6.0 + // + // throws SocketException if datagram was larger than buffer. + // https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.receive?view=net-6.0 + int size = socket.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None); + data = new ArraySegment(recvBuffer, 0, size); + return true; + } + catch (SocketException e) + { + // for non-blocking sockets, Receive throws WouldBlock if there is + // no message to read. that's okay. only log for other errors. + if (e.SocketErrorCode == SocketError.WouldBlock) return false; + + // otherwise it's a real socket error. throw it. + throw; + } + } + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Extensions.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Extensions.cs.meta new file mode 100644 index 0000000..36d3193 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Extensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c0649195e5ba4fcf8e0e1231fee7d5f6 +timeCreated: 1641701011 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpChannel.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpChannel.cs new file mode 100644 index 0000000..c085e17 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpChannel.cs @@ -0,0 +1,10 @@ +namespace kcp2k +{ + // channel type and header for raw messages + public enum KcpChannel : byte + { + // don't react on 0x00. might help to filter out random noise. + Reliable = 1, + Unreliable = 2 + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpChannel.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpChannel.cs.meta new file mode 100644 index 0000000..2721025 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpChannel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9e852b2532fb248d19715cfebe371db3 +timeCreated: 1610081248 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs new file mode 100644 index 0000000..788d065 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs @@ -0,0 +1,226 @@ +// kcp client logic abstracted into a class. +// for use in Mirror, DOTSNET, testing, etc. +using System; +using System.Net; +using System.Net.Sockets; + +namespace kcp2k +{ + public class KcpClient + { + // kcp + // public so that bandwidth statistics can be accessed from the outside + public KcpPeer peer; + + // IO + protected Socket socket; + public EndPoint remoteEndPoint; + + // config + protected readonly KcpConfig config; + + // raw receive buffer always needs to be of 'MTU' size, even if + // MaxMessageSize is larger. kcp always sends in MTU segments and having + // a buffer smaller than MTU would silently drop excess data. + // => we need the MTU to fit channel + message! + // => protected because someone may overwrite RawReceive but still wants + // to reuse the buffer. + protected readonly byte[] rawReceiveBuffer; + + // callbacks + // even for errors, to allow liraries to show popups etc. + // instead of logging directly. + // (string instead of Exception for ease of use and to avoid user panic) + // + // events are readonly, set in constructor. + // this ensures they are always initialized when used. + // fixes https://github.com/MirrorNetworking/Mirror/issues/3337 and more + protected readonly Action OnConnected; + protected readonly Action, KcpChannel> OnData; + protected readonly Action OnDisconnected; + protected readonly Action OnError; + + // state + public bool connected; + + public KcpClient(Action OnConnected, + Action, KcpChannel> OnData, + Action OnDisconnected, + Action OnError, + KcpConfig config) + { + // initialize callbacks first to ensure they can be used safely. + this.OnConnected = OnConnected; + this.OnData = OnData; + this.OnDisconnected = OnDisconnected; + this.OnError = OnError; + this.config = config; + + // create mtu sized receive buffer + rawReceiveBuffer = new byte[config.Mtu]; + } + + public void Connect(string address, ushort port) + { + if (connected) + { + Log.Warning("KcpClient: already connected!"); + return; + } + + // resolve host name before creating peer. + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3361 + if (!Common.ResolveHostname(address, out IPAddress[] addresses)) + { + // pass error to user callback. no need to log it manually. + OnError(ErrorCode.DnsResolve, $"Failed to resolve host: {address}"); + OnDisconnected(); + return; + } + + // create fresh peer for each new session + // client doesn't need secure cookie. + peer = new KcpPeer(RawSend, OnAuthenticatedWrap, OnData, OnDisconnectedWrap, OnError, config, 0); + + // some callbacks need to wrapped with some extra logic + void OnAuthenticatedWrap() + { + Log.Info($"KcpClient: OnConnected"); + connected = true; + OnConnected(); + } + void OnDisconnectedWrap() + { + Log.Info($"KcpClient: OnDisconnected"); + connected = false; + peer = null; + socket?.Close(); + socket = null; + remoteEndPoint = null; + OnDisconnected(); + } + + Log.Info($"KcpClient: connect to {address}:{port}"); + + // create socket + remoteEndPoint = new IPEndPoint(addresses[0], port); + socket = new Socket(remoteEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + + // recv & send are called from main thread. + // need to ensure this never blocks. + // even a 1ms block per connection would stop us from scaling. + socket.Blocking = false; + + // configure buffer sizes + Common.ConfigureSocketBuffers(socket, config.RecvBufferSize, config.SendBufferSize); + + // bind to endpoint so we can use send/recv instead of sendto/recvfrom. + socket.Connect(remoteEndPoint); + + // client should send handshake to server as very first message + peer.SendHandshake(); + } + + // io - input. + // virtual so it may be modified for relays, etc. + // call this while it returns true, to process all messages this tick. + // returned ArraySegment is valid until next call to RawReceive. + protected virtual bool RawReceive(out ArraySegment segment) + { + segment = default; + if (socket == null) return false; + + try + { + return socket.ReceiveNonBlocking(rawReceiveBuffer, out segment); + } + // for non-blocking sockets, Receive throws WouldBlock if there is + // no message to read. that's okay. only log for other errors. + catch (SocketException e) + { + // the other end closing the connection is not an 'error'. + // but connections should never just end silently. + // at least log a message for easier debugging. + // for example, his can happen when connecting without a server. + // see test: ConnectWithoutServer(). + Log.Info($"KcpClient: looks like the other end has closed the connection. This is fine: {e}"); + peer.Disconnect(); + return false; + } + } + + // io - output. + // virtual so it may be modified for relays, etc. + protected virtual void RawSend(ArraySegment data) + { + try + { + socket.SendNonBlocking(data); + } + catch (SocketException e) + { + Log.Error($"KcpClient: Send failed: {e}"); + } + } + + public void Send(ArraySegment segment, KcpChannel channel) + { + if (!connected) + { + Log.Warning("KcpClient: can't send because not connected!"); + return; + } + + peer.SendData(segment, channel); + } + + public void Disconnect() + { + // only if connected + // otherwise we end up in a deadlock because of an open Mirror bug: + // https://github.com/vis2k/Mirror/issues/2353 + if (!connected) return; + + // call Disconnect and let the connection handle it. + // DO NOT set it to null yet. it needs to be updated a few more + // times first. let the connection handle it! + peer?.Disconnect(); + } + + // process incoming messages. should be called before updating the world. + // virtual because relay may need to inject their own ping or similar. + public virtual void TickIncoming() + { + // recv on socket first, then process incoming + // (even if we didn't receive anything. need to tick ping etc.) + // (connection is null if not active) + if (peer != null) + { + + while (RawReceive(out ArraySegment segment)) + peer.RawInput(segment); + } + + // RawReceive may have disconnected peer. null check again. + peer?.TickIncoming(); + } + + // process outgoing messages. should be called after updating the world. + // virtual because relay may need to inject their own ping or similar. + public virtual void TickOutgoing() + { + // process outgoing + // (connection is null if not active) + peer?.TickOutgoing(); + } + + // process incoming and outgoing for convenience + // => ideally call ProcessIncoming() before updating the world and + // ProcessOutgoing() after updating the world for minimum latency + public virtual void Tick() + { + TickIncoming(); + TickOutgoing(); + } + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs.meta new file mode 100644 index 0000000..e55306b --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpClient.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6aa069a28ed24fedb533c102d9742b36 +timeCreated: 1603786960 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConfig.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConfig.cs new file mode 100644 index 0000000..382d06b --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConfig.cs @@ -0,0 +1,97 @@ +// common config struct, instead of passing 10 parameters manually every time. +using System; + +namespace kcp2k +{ + // [Serializable] to show it in Unity inspector. + // 'class' so we can set defaults easily. + [Serializable] + public class KcpConfig + { + // socket configuration //////////////////////////////////////////////// + // DualMode uses both IPv6 and IPv4. not all platforms support it. + // (Nintendo Switch, etc.) + public bool DualMode; + + // UDP servers use only one socket. + // maximize buffer to handle as many connections as possible. + // + // M1 mac pro: + // recv buffer default: 786896 (771 KB) + // send buffer default: 9216 (9 KB) + // max configurable: ~7 MB + public int RecvBufferSize; + public int SendBufferSize; + + // kcp configuration /////////////////////////////////////////////////// + // configurable MTU in case kcp sits on top of other abstractions like + // encrypted transports, relays, etc. + public int Mtu; + + // NoDelay is recommended to reduce latency. This also scales better + // without buffers getting full. + public bool NoDelay; + + // KCP internal update interval. 100ms is KCP default, but a lower + // interval is recommended to minimize latency and to scale to more + // networked entities. + public uint Interval; + + // KCP fastresend parameter. Faster resend for the cost of higher + // bandwidth. + public int FastResend; + + // KCP congestion window heavily limits messages flushed per update. + // congestion window may actually be broken in kcp: + // - sending max sized message @ M1 mac flushes 2-3 messages per update + // - even with super large send/recv window, it requires thousands of + // update calls + // best to leave this disabled, as it may significantly increase latency. + public bool CongestionWindow; + + // KCP window size can be modified to support higher loads. + // for example, Mirror Benchmark requires: + // 128, 128 for 4k monsters + // 512, 512 for 10k monsters + // 8192, 8192 for 20k monsters + public uint SendWindowSize; + public uint ReceiveWindowSize; + + // timeout in milliseconds + public int Timeout; + + // maximum retransmission attempts until dead_link + public uint MaxRetransmits; + + // constructor ///////////////////////////////////////////////////////// + // constructor with defaults for convenience. + // makes it easy to define "new KcpConfig(DualMode=false)" etc. + public KcpConfig( + bool DualMode = true, + int RecvBufferSize = 1024 * 1024 * 7, + int SendBufferSize = 1024 * 1024 * 7, + int Mtu = Kcp.MTU_DEF, + bool NoDelay = true, + uint Interval = 10, + int FastResend = 0, + bool CongestionWindow = false, + uint SendWindowSize = Kcp.WND_SND, + uint ReceiveWindowSize = Kcp.WND_RCV, + int Timeout = KcpPeer.DEFAULT_TIMEOUT, + uint MaxRetransmits = Kcp.DEADLINK) + { + this.DualMode = DualMode; + this.RecvBufferSize = RecvBufferSize; + this.SendBufferSize = SendBufferSize; + this.Mtu = Mtu; + this.NoDelay = NoDelay; + this.Interval = Interval; + this.FastResend = FastResend; + this.CongestionWindow = CongestionWindow; + this.SendWindowSize = SendWindowSize; + this.ReceiveWindowSize = ReceiveWindowSize; + this.Timeout = Timeout; + this.MaxRetransmits = MaxRetransmits; + } + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConfig.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConfig.cs.meta new file mode 100644 index 0000000..a687e23 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 99692f99c45c4b47b0500e7abbfd12da +timeCreated: 1670946969 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpHeader.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpHeader.cs new file mode 100644 index 0000000..7817796 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpHeader.cs @@ -0,0 +1,19 @@ +namespace kcp2k +{ + // header for messages processed by kcp. + // this is NOT for the raw receive messages(!) because handshake/disconnect + // need to be sent reliably. it's not enough to have those in rawreceive + // because those messages might get lost without being resent! + public enum KcpHeader : byte + { + // don't react on 0x00. might help to filter out random noise. + Handshake = 1, + // ping goes over reliable & KcpHeader for now. could go over unreliable + // too. there is no real difference except that this is easier because + // we already have a KcpHeader for reliable messages. + // ping is only used to keep it alive, so latency doesn't matter. + Ping = 2, + Data = 3, + Disconnect = 4 + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpHeader.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpHeader.cs.meta new file mode 100644 index 0000000..9e81c94 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpHeader.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 91b5edac31224a49bd76f960ae018942 +timeCreated: 1610081248 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpPeer.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpPeer.cs new file mode 100644 index 0000000..e78261e --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpPeer.cs @@ -0,0 +1,819 @@ +// Kcp Peer, similar to UDP Peer but wrapped with reliability, channels, +// timeouts, authentication, state, etc. +// +// still IO agnostic to work with udp, nonalloc, relays, native, etc. +using System; +using System.Diagnostics; +using System.Net.Sockets; + +namespace kcp2k +{ + enum KcpState { Connected, Authenticated, Disconnected } + + public class KcpPeer + { + // kcp reliability algorithm + internal Kcp kcp; + + // security cookie to prevent UDP spoofing. + // credits to IncludeSec for disclosing the issue. + // + // server passes the expected cookie to the client's KcpPeer. + // KcpPeer sends cookie to the connected client. + // KcpPeer only accepts packets which contain the cookie. + // => cookie can be a random number, but it needs to be cryptographically + // secure random that can't be easily predicted. + // => cookie can be hash(ip, port) BUT only if salted to be not predictable + readonly uint cookie; + + // this is the cookie that the other end received during handshake. + // store byte[] representation to avoid runtime int->byte[] conversions. + internal readonly byte[] receivedCookie = new byte[4]; + + // IO agnostic + readonly Action> RawSend; + + // state: connected as soon as we create the peer. + // leftover from KcpConnection. remove it after refactoring later. + KcpState state = KcpState.Connected; + + // events are readonly, set in constructor. + // this ensures they are always initialized when used. + // fixes https://github.com/MirrorNetworking/Mirror/issues/3337 and more + readonly Action OnAuthenticated; + readonly Action, KcpChannel> OnData; + readonly Action OnDisconnected; + // error callback instead of logging. + // allows libraries to show popups etc. + // (string instead of Exception for ease of use and to avoid user panic) + readonly Action OnError; + + // If we don't receive anything these many milliseconds + // then consider us disconnected + public const int DEFAULT_TIMEOUT = 10000; + public int timeout; + uint lastReceiveTime; + + // internal time. + // StopWatch offers ElapsedMilliSeconds and should be more precise than + // Unity's time.deltaTime over long periods. + readonly Stopwatch watch = new Stopwatch(); + + // we need to subtract the channel and cookie bytes from every + // MaxMessageSize calculation. + // we also need to tell kcp to use MTU-1 to leave space for the byte. + const int CHANNEL_HEADER_SIZE = 1; + const int COOKIE_HEADER_SIZE = 4; + const int METADATA_SIZE = CHANNEL_HEADER_SIZE + COOKIE_HEADER_SIZE; + + // reliable channel (= kcp) MaxMessageSize so the outside knows largest + // allowed message to send. the calculation in Send() is not obvious at + // all, so let's provide the helper here. + // + // kcp does fragmentation, so max message is way larger than MTU. + // + // -> runtime MTU changes are disabled: mss is always MTU_DEF-OVERHEAD + // -> Send() checks if fragment count < rcv_wnd, so we use rcv_wnd - 1. + // NOTE that original kcp has a bug where WND_RCV default is used + // instead of configured rcv_wnd, limiting max message size to 144 KB + // https://github.com/skywind3000/kcp/pull/291 + // we fixed this in kcp2k. + // -> we add 1 byte KcpHeader enum to each message, so -1 + // + // IMPORTANT: max message is MTU * rcv_wnd, in other words it completely + // fills the receive window! due to head of line blocking, + // all other messages have to wait while a maxed size message + // is being delivered. + // => in other words, DO NOT use max size all the time like + // for batching. + // => sending UNRELIABLE max message size most of the time is + // best for performance (use that one for batching!) + static int ReliableMaxMessageSize_Unconstrained(int mtu, uint rcv_wnd) => + (mtu - Kcp.OVERHEAD - METADATA_SIZE) * ((int)rcv_wnd - 1) - 1; + + // kcp encodes 'frg' as 1 byte. + // max message size can only ever allow up to 255 fragments. + // WND_RCV gives 127 fragments. + // WND_RCV * 2 gives 255 fragments. + // so we can limit max message size by limiting rcv_wnd parameter. + public static int ReliableMaxMessageSize(int mtu, uint rcv_wnd) => + ReliableMaxMessageSize_Unconstrained(mtu, Math.Min(rcv_wnd, Kcp.FRG_MAX)); + + // unreliable max message size is simply MTU - channel header size + public static int UnreliableMaxMessageSize(int mtu) => + mtu - METADATA_SIZE; + + // buffer to receive kcp's processed messages (avoids allocations). + // IMPORTANT: this is for KCP messages. so it needs to be of size: + // 1 byte header + MaxMessageSize content + readonly byte[] kcpMessageBuffer;// = new byte[1 + ReliableMaxMessageSize]; + + // send buffer for handing user messages to kcp for processing. + // (avoids allocations). + // IMPORTANT: needs to be of size: + // 1 byte header + MaxMessageSize content + readonly byte[] kcpSendBuffer;// = new byte[1 + ReliableMaxMessageSize]; + + // raw send buffer is exactly MTU. + readonly byte[] rawSendBuffer; + + // send a ping occasionally so we don't time out on the other end. + // for example, creating a character in an MMO could easily take a + // minute of no data being sent. which doesn't mean we want to time out. + // same goes for slow paced card games etc. + public const int PING_INTERVAL = 1000; + uint lastPingTime; + + // if we send more than kcp can handle, we will get ever growing + // send/recv buffers and queues and minutes of latency. + // => if a connection can't keep up, it should be disconnected instead + // to protect the server under heavy load, and because there is no + // point in growing to gigabytes of memory or minutes of latency! + // => 2k isn't enough. we reach 2k when spawning 4k monsters at once + // easily, but it does recover over time. + // => 10k seems safe. + // + // note: we have a ChokeConnectionAutoDisconnects test for this too! + internal const int QueueDisconnectThreshold = 10000; + + // getters for queue and buffer counts, used for debug info + public int SendQueueCount => kcp.snd_queue.Count; + public int ReceiveQueueCount => kcp.rcv_queue.Count; + public int SendBufferCount => kcp.snd_buf.Count; + public int ReceiveBufferCount => kcp.rcv_buf.Count; + + // maximum send rate per second can be calculated from kcp parameters + // source: https://translate.google.com/translate?sl=auto&tl=en&u=https://wetest.qq.com/lab/view/391.html + // + // KCP can send/receive a maximum of WND*MTU per interval. + // multiple by 1000ms / interval to get the per-second rate. + // + // example: + // WND(32) * MTU(1400) = 43.75KB + // => 43.75KB * 1000 / INTERVAL(10) = 4375KB/s + // + // returns bytes/second! + public uint MaxSendRate => kcp.snd_wnd * kcp.mtu * 1000 / kcp.interval; + public uint MaxReceiveRate => kcp.rcv_wnd * kcp.mtu * 1000 / kcp.interval; + + // calculate max message sizes based on mtu and wnd only once + public readonly int unreliableMax; + public readonly int reliableMax; + + // SetupKcp creates and configures a new KCP instance. + // => useful to start from a fresh state every time the client connects + // => NoDelay, interval, wnd size are the most important configurations. + // let's force require the parameters so we don't forget it anywhere. + public KcpPeer( + Action> output, + Action OnAuthenticated, + Action, KcpChannel> OnData, + Action OnDisconnected, + Action OnError, + KcpConfig config, + uint cookie) + { + // initialize callbacks first to ensure they can be used safely. + this.OnAuthenticated = OnAuthenticated; + this.OnData = OnData; + this.OnDisconnected = OnDisconnected; + this.OnError = OnError; + this.RawSend = output; + + // set up kcp over reliable channel (that's what kcp is for) + kcp = new Kcp(0, RawSendReliable); + + // security cookie + this.cookie = cookie; + + // set nodelay. + // note that kcp uses 'nocwnd' internally so we negate the parameter + kcp.SetNoDelay(config.NoDelay ? 1u : 0u, config.Interval, config.FastResend, !config.CongestionWindow); + kcp.SetWindowSize(config.SendWindowSize, config.ReceiveWindowSize); + + // IMPORTANT: high level needs to add 1 channel byte to each raw + // message. so while Kcp.MTU_DEF is perfect, we actually need to + // tell kcp to use MTU-1 so we can still put the header into the + // message afterwards. + kcp.SetMtu((uint)config.Mtu - METADATA_SIZE); + + // create mtu sized send buffer + rawSendBuffer = new byte[config.Mtu]; + + // calculate max message sizes once + unreliableMax = UnreliableMaxMessageSize(config.Mtu); + reliableMax = ReliableMaxMessageSize(config.Mtu, config.ReceiveWindowSize); + + // set maximum retransmits (aka dead_link) + kcp.dead_link = config.MaxRetransmits; + + // create message buffers AFTER window size is set + // see comments on buffer definition for the "+1" part + kcpMessageBuffer = new byte[1 + reliableMax]; + kcpSendBuffer = new byte[1 + reliableMax]; + + timeout = config.Timeout; + + watch.Start(); + } + + void HandleTimeout(uint time) + { + // note: we are also sending a ping regularly, so timeout should + // only ever happen if the connection is truly gone. + if (time >= lastReceiveTime + timeout) + { + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.Timeout, $"KcpPeer: Connection timed out after not receiving any message for {timeout}ms. Disconnecting."); + Disconnect(); + } + } + + void HandleDeadLink() + { + // kcp has 'dead_link' detection. might as well use it. + if (kcp.state == -1) + { + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.Timeout, $"KcpPeer: dead_link detected: a message was retransmitted {kcp.dead_link} times without ack. Disconnecting."); + Disconnect(); + } + } + + // send a ping occasionally in order to not time out on the other end. + void HandlePing(uint time) + { + // enough time elapsed since last ping? + if (time >= lastPingTime + PING_INTERVAL) + { + // ping again and reset time + //Log.Debug("KCP: sending ping..."); + SendPing(); + lastPingTime = time; + } + } + + void HandleChoked() + { + // disconnect connections that can't process the load. + // see QueueSizeDisconnect comments. + // => include all of kcp's buffers and the unreliable queue! + int total = kcp.rcv_queue.Count + kcp.snd_queue.Count + + kcp.rcv_buf.Count + kcp.snd_buf.Count; + if (total >= QueueDisconnectThreshold) + { + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.Congestion, + $"KcpPeer: disconnecting connection because it can't process data fast enough.\n" + + $"Queue total {total}>{QueueDisconnectThreshold}. rcv_queue={kcp.rcv_queue.Count} snd_queue={kcp.snd_queue.Count} rcv_buf={kcp.rcv_buf.Count} snd_buf={kcp.snd_buf.Count}\n" + + $"* Try to Enable NoDelay, decrease INTERVAL, disable Congestion Window (= enable NOCWND!), increase SEND/RECV WINDOW or compress data.\n" + + $"* Or perhaps the network is simply too slow on our end, or on the other end."); + + // let's clear all pending sends before disconnting with 'Bye'. + // otherwise a single Flush in Disconnect() won't be enough to + // flush thousands of messages to finally deliver 'Bye'. + // this is just faster and more robust. + kcp.snd_queue.Clear(); + + Disconnect(); + } + } + + // reads the next reliable message type & content from kcp. + // -> to avoid buffering, unreliable messages call OnData directly. + bool ReceiveNextReliable(out KcpHeader header, out ArraySegment message) + { + message = default; + header = KcpHeader.Disconnect; + + int msgSize = kcp.PeekSize(); + if (msgSize <= 0) return false; + + // only allow receiving up to buffer sized messages. + // otherwise we would get BlockCopy ArgumentException anyway. + if (msgSize > kcpMessageBuffer.Length) + { + // we don't allow sending messages > Max, so this must be an + // attacker. let's disconnect to avoid allocation attacks etc. + // pass error to user callback. no need to log it manually. + OnError(ErrorCode.InvalidReceive, $"KcpPeer: possible allocation attack for msgSize {msgSize} > buffer {kcpMessageBuffer.Length}. Disconnecting the connection."); + Disconnect(); + return false; + } + + // receive from kcp + int received = kcp.Receive(kcpMessageBuffer, msgSize); + if (received < 0) + { + // if receive failed, close everything + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.InvalidReceive, $"KcpPeer: Receive failed with error={received}. closing connection."); + Disconnect(); + return false; + } + + // extract header & content without header + header = (KcpHeader)kcpMessageBuffer[0]; + message = new ArraySegment(kcpMessageBuffer, 1, msgSize - 1); + lastReceiveTime = (uint)watch.ElapsedMilliseconds; + return true; + } + + void TickIncoming_Connected(uint time) + { + // detect common events & ping + HandleTimeout(time); + HandleDeadLink(); + HandlePing(time); + HandleChoked(); + + // any reliable kcp message received? + if (ReceiveNextReliable(out KcpHeader header, out ArraySegment message)) + { + // message type FSM. no default so we never miss a case. + switch (header) + { + case KcpHeader.Handshake: + { + // we were waiting for a handshake. + // it proves that the other end speaks our protocol. + + // parse the cookie + if (message.Count != 4) + { + // pass error to user callback. no need to log it manually. + OnError(ErrorCode.InvalidReceive, $"KcpPeer: received invalid handshake message with size {message.Count} != 4. Disconnecting the connection."); + Disconnect(); + return; + } + + // store the cookie bytes to avoid int->byte[] conversions when sending. + // still convert to uint once, just for prettier logging. + Buffer.BlockCopy(message.Array, message.Offset, receivedCookie, 0, 4); + uint prettyCookie = BitConverter.ToUInt32(message.Array, message.Offset); + + Log.Info($"KcpPeer: received handshake with cookie={prettyCookie}"); + state = KcpState.Authenticated; + OnAuthenticated?.Invoke(); + break; + } + case KcpHeader.Ping: + { + // ping keeps kcp from timing out. do nothing. + break; + } + case KcpHeader.Data: + case KcpHeader.Disconnect: + { + // everything else is not allowed during handshake! + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.InvalidReceive, $"KcpPeer: received invalid header {header} while Connected. Disconnecting the connection."); + Disconnect(); + break; + } + } + } + } + + void TickIncoming_Authenticated(uint time) + { + // detect common events & ping + HandleTimeout(time); + HandleDeadLink(); + HandlePing(time); + HandleChoked(); + + // process all received messages + while (ReceiveNextReliable(out KcpHeader header, out ArraySegment message)) + { + // message type FSM. no default so we never miss a case. + switch (header) + { + case KcpHeader.Handshake: + { + // should never receive another handshake after auth + // GetType() shows Server/ClientConn instead of just Connection. + Log.Warning($"KcpPeer: received invalid header {header} while Authenticated. Disconnecting the connection."); + Disconnect(); + break; + } + case KcpHeader.Data: + { + // call OnData IF the message contained actual data + if (message.Count > 0) + { + //Log.Warning($"Kcp recv msg: {BitConverter.ToString(message.Array, message.Offset, message.Count)}"); + OnData?.Invoke(message, KcpChannel.Reliable); + } + // empty data = attacker, or something went wrong + else + { + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.InvalidReceive, $"KcpPeer: received empty Data message while Authenticated. Disconnecting the connection."); + Disconnect(); + } + break; + } + case KcpHeader.Ping: + { + // ping keeps kcp from timing out. do nothing. + break; + } + case KcpHeader.Disconnect: + { + // disconnect might happen + // GetType() shows Server/ClientConn instead of just Connection. + Log.Info($"KcpPeer: received disconnect message"); + Disconnect(); + break; + } + } + } + } + + public void TickIncoming() + { + uint time = (uint)watch.ElapsedMilliseconds; + + try + { + switch (state) + { + case KcpState.Connected: + { + TickIncoming_Connected(time); + break; + } + case KcpState.Authenticated: + { + TickIncoming_Authenticated(time); + break; + } + case KcpState.Disconnected: + { + // do nothing while disconnected + break; + } + } + } + // TODO KcpConnection is IO agnostic. move this to outside later. + catch (SocketException exception) + { + // this is ok, the connection was closed + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.ConnectionClosed, $"KcpPeer: Disconnecting because {exception}. This is fine."); + Disconnect(); + } + catch (ObjectDisposedException exception) + { + // fine, socket was closed + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.ConnectionClosed, $"KcpPeer: Disconnecting because {exception}. This is fine."); + Disconnect(); + } + catch (Exception exception) + { + // unexpected + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.Unexpected, $"KcpPeer: unexpected Exception: {exception}"); + Disconnect(); + } + } + + public void TickOutgoing() + { + uint time = (uint)watch.ElapsedMilliseconds; + + try + { + switch (state) + { + case KcpState.Connected: + case KcpState.Authenticated: + { + // update flushes out messages + kcp.Update(time); + break; + } + case KcpState.Disconnected: + { + // do nothing while disconnected + break; + } + } + } + // TODO KcpConnection is IO agnostic. move this to outside later. + catch (SocketException exception) + { + // this is ok, the connection was closed + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.ConnectionClosed, $"KcpPeer: Disconnecting because {exception}. This is fine."); + Disconnect(); + } + catch (ObjectDisposedException exception) + { + // fine, socket was closed + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.ConnectionClosed, $"KcpPeer: Disconnecting because {exception}. This is fine."); + Disconnect(); + } + catch (Exception exception) + { + // unexpected + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.Unexpected, $"KcpPeer: unexpected exception: {exception}"); + Disconnect(); + } + } + + void OnRawInputReliable(ArraySegment message) + { + // input into kcp, but skip channel byte + int input = kcp.Input(message.Array, message.Offset, message.Count); + if (input != 0) + { + // GetType() shows Server/ClientConn instead of just Connection. + Log.Warning($"KcpPeer: Input failed with error={input} for buffer with length={message.Count - 1}"); + } + } + + void OnRawInputUnreliable(ArraySegment message) + { + // ideally we would queue all unreliable messages and + // then process them in ReceiveNext() together with the + // reliable messages, but: + // -> queues/allocations/pools are slow and complex. + // -> DOTSNET 10k is actually slower if we use pooled + // unreliable messages for transform messages. + // + // DOTSNET 10k benchmark: + // reliable-only: 170 FPS + // unreliable queued: 130-150 FPS + // unreliable direct: 183 FPS(!) + // + // DOTSNET 50k benchmark: + // reliable-only: FAILS (queues keep growing) + // unreliable direct: 18-22 FPS(!) + // + // -> all unreliable messages are DATA messages anyway. + // -> let's skip the magic and call OnData directly if + // the current state allows it. + if (state == KcpState.Authenticated) + { + OnData?.Invoke(message, KcpChannel.Unreliable); + + // set last receive time to avoid timeout. + // -> we do this in ANY case even if not enabled. + // a message is a message. + // -> we set last receive time for both reliable and + // unreliable messages. both count. + // otherwise a connection might time out even + // though unreliable were received, but no + // reliable was received. + lastReceiveTime = (uint)watch.ElapsedMilliseconds; + } + else + { + // it's common to receive unreliable messages before being + // authenticated, for example: + // - random internet noise + // - game server may send an unreliable message after authenticating, + // and the unreliable message arrives on the client before the + // 'auth_ok' message. this can be avoided by sending a final + // 'ready' message after being authenticated, but this would + // add another 'round trip time' of latency to the handshake. + // + // it's best to simply ignore invalid unreliable messages here. + // Log.Info($"KcpPeer: received unreliable message while not authenticated."); + } + } + + // insert raw IO. usually from socket.Receive. + // offset is useful for relays, where we may parse a header and then + // feed the rest to kcp. + public void RawInput(ArraySegment segment) + { + // ensure valid size: at least 1 byte for channel + 4 bytes for cookie + if (segment.Count <= 5) return; + + // parse channel + // byte channel = segment[0]; ArraySegment[i] isn't supported in some older Unity Mono versions + byte channel = segment.Array[segment.Offset + 0]; + + // parse cookie + uint messageCookie = BitConverter.ToUInt32(segment.Array, segment.Offset + 1); + + // compare cookie to protect against UDP spoofing. + // messages won't have a cookie until after handshake. + // so only compare if we are authenticated. + // simply drop the message if the cookie doesn't match. + if (state == KcpState.Authenticated && messageCookie != cookie) + { + Log.Warning($"KcpPeer: dropped message with invalid cookie: {messageCookie} expected: {cookie}."); + return; + } + + // parse message + ArraySegment message = new ArraySegment(segment.Array, segment.Offset + 1+4, segment.Count - 1-4); + + switch (channel) + { + case (byte)KcpChannel.Reliable: + { + OnRawInputReliable(message); + break; + } + case (byte)KcpChannel.Unreliable: + { + OnRawInputUnreliable(message); + break; + } + default: + { + // invalid channel indicates random internet noise. + // servers may receive random UDP data. + // just ignore it, but log for easier debugging. + Log.Warning($"KcpPeer: invalid channel header: {channel}, likely internet noise"); + break; + } + } + } + + // raw send called by kcp + void RawSendReliable(byte[] data, int length) + { + // write channel header + // from 0, with 1 byte + rawSendBuffer[0] = (byte)KcpChannel.Reliable; + + // write handshake cookie to protect against UDP spoofing. + // from 1, with 4 bytes + Buffer.BlockCopy(receivedCookie, 0, rawSendBuffer, 1, 4); + + // write data + // from 5, with N bytes + Buffer.BlockCopy(data, 0, rawSendBuffer, 1+4, length); + + // IO send + ArraySegment segment = new ArraySegment(rawSendBuffer, 0, length + 1+4); + RawSend(segment); + } + + void SendReliable(KcpHeader header, ArraySegment content) + { + // 1 byte header + content needs to fit into send buffer + if (1 + content.Count > kcpSendBuffer.Length) // TODO + { + // otherwise content is larger than MaxMessageSize. let user know! + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.InvalidSend, $"KcpPeer: Failed to send reliable message of size {content.Count} because it's larger than ReliableMaxMessageSize={reliableMax}"); + return; + } + + // write channel header + kcpSendBuffer[0] = (byte)header; + + // write data (if any) + if (content.Count > 0) + Buffer.BlockCopy(content.Array, content.Offset, kcpSendBuffer, 1, content.Count); + + // send to kcp for processing + int sent = kcp.Send(kcpSendBuffer, 0, 1 + content.Count); + if (sent < 0) + { + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.InvalidSend, $"KcpPeer: Send failed with error={sent} for content with length={content.Count}"); + } + } + + void SendUnreliable(ArraySegment message) + { + // message size needs to be <= unreliable max size + if (message.Count > unreliableMax) + { + // otherwise content is larger than MaxMessageSize. let user know! + // GetType() shows Server/ClientConn instead of just Connection. + Log.Error($"KcpPeer: Failed to send unreliable message of size {message.Count} because it's larger than UnreliableMaxMessageSize={unreliableMax}"); + return; + } + + // write channel header + // from 0, with 1 byte + rawSendBuffer[0] = (byte)KcpChannel.Unreliable; + + // write handshake cookie to protect against UDP spoofing. + // from 1, with 4 bytes + Buffer.BlockCopy(receivedCookie, 0, rawSendBuffer, 1, 4); + + // write data + // from 5, with N bytes + Buffer.BlockCopy(message.Array, message.Offset, rawSendBuffer, 1 + 4, message.Count); + + // IO send + ArraySegment segment = new ArraySegment(rawSendBuffer, 0, message.Count + 1 + 4); + RawSend(segment); + } + + // server & client need to send handshake at different times, so we need + // to expose the function. + // * client should send it immediately. + // * server should send it as reply to client's handshake, not before + // (server should not reply to random internet messages with handshake) + // => handshake info needs to be delivered, so it goes over reliable. + public void SendHandshake() + { + // server includes a random cookie in handshake. + // client is expected to include in every message. + // this avoid UDP spoofing. + // KcpPeer simply always sends a cookie. + // in case client -> server cookies are ever implemented, etc. + + // TODO nonalloc + byte[] cookieBytes = BitConverter.GetBytes(cookie); + + // GetType() shows Server/ClientConn instead of just Connection. + Log.Info($"KcpPeer: sending Handshake to other end with cookie={cookie}!"); + SendReliable(KcpHeader.Handshake, new ArraySegment(cookieBytes)); + } + + public void SendData(ArraySegment data, KcpChannel channel) + { + // sending empty segments is not allowed. + // nobody should ever try to send empty data. + // it means that something went wrong, e.g. in Mirror/DOTSNET. + // let's make it obvious so it's easy to debug. + if (data.Count == 0) + { + // pass error to user callback. no need to log it manually. + // GetType() shows Server/ClientConn instead of just Connection. + OnError(ErrorCode.InvalidSend, $"KcpPeer: tried sending empty message. This should never happen. Disconnecting."); + Disconnect(); + return; + } + + switch (channel) + { + case KcpChannel.Reliable: + SendReliable(KcpHeader.Data, data); + break; + case KcpChannel.Unreliable: + SendUnreliable(data); + break; + } + } + + // ping goes through kcp to keep it from timing out, so it goes over the + // reliable channel. + void SendPing() => SendReliable(KcpHeader.Ping, default); + + // disconnect info needs to be delivered, so it goes over reliable + void SendDisconnect() => SendReliable(KcpHeader.Disconnect, default); + + // disconnect this connection + public void Disconnect() + { + // only if not disconnected yet + if (state == KcpState.Disconnected) + return; + + // send a disconnect message + try + { + SendDisconnect(); + kcp.Flush(); + } + // TODO KcpConnection is IO agnostic. move this to outside later. + catch (SocketException) + { + // this is ok, the connection was already closed + } + catch (ObjectDisposedException) + { + // this is normal when we stop the server + // the socket is stopped so we can't send anything anymore + // to the clients + + // the clients will eventually timeout and realize they + // were disconnected + } + + // set as Disconnected, call event + // GetType() shows Server/ClientConn instead of just Connection. + Log.Info($"KcpPeer: Disconnected."); + state = KcpState.Disconnected; + OnDisconnected?.Invoke(); + } + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpPeer.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpPeer.cs.meta new file mode 100644 index 0000000..fa5dcff --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpPeer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3915c7c62b72d4dc2a9e4e76c94fc484 +timeCreated: 1602600432 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServer.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServer.cs new file mode 100644 index 0000000..64b990c --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServer.cs @@ -0,0 +1,377 @@ +// kcp server logic abstracted into a class. +// for use in Mirror, DOTSNET, testing, etc. +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; + +namespace kcp2k +{ + public class KcpServer + { + // callbacks + // even for errors, to allow liraries to show popups etc. + // instead of logging directly. + // (string instead of Exception for ease of use and to avoid user panic) + // + // events are readonly, set in constructor. + // this ensures they are always initialized when used. + // fixes https://github.com/MirrorNetworking/Mirror/issues/3337 and more + protected readonly Action OnConnected; + protected readonly Action, KcpChannel> OnData; + protected readonly Action OnDisconnected; + protected readonly Action OnError; + + // configuration + protected readonly KcpConfig config; + + // state + protected Socket socket; + EndPoint newClientEP; + + // raw receive buffer always needs to be of 'MTU' size, even if + // MaxMessageSize is larger. kcp always sends in MTU segments and having + // a buffer smaller than MTU would silently drop excess data. + // => we need the mtu to fit channel + message! + protected readonly byte[] rawReceiveBuffer; + + // connections where connectionId is EndPoint.GetHashCode + public Dictionary connections = + new Dictionary(); + + public KcpServer(Action OnConnected, + Action, KcpChannel> OnData, + Action OnDisconnected, + Action OnError, + KcpConfig config) + { + // initialize callbacks first to ensure they can be used safely. + this.OnConnected = OnConnected; + this.OnData = OnData; + this.OnDisconnected = OnDisconnected; + this.OnError = OnError; + this.config = config; + + // create mtu sized receive buffer + rawReceiveBuffer = new byte[config.Mtu]; + + // create newClientEP either IPv4 or IPv6 + newClientEP = config.DualMode + ? new IPEndPoint(IPAddress.IPv6Any, 0) + : new IPEndPoint(IPAddress.Any, 0); + } + + public virtual bool IsActive() => socket != null; + + static Socket CreateServerSocket(bool DualMode, ushort port) + { + if (DualMode) + { + // IPv6 socket with DualMode @ "::" : port + Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); + // settings DualMode may throw: + // https://learn.microsoft.com/en-us/dotnet/api/System.Net.Sockets.Socket.DualMode?view=net-7.0 + // attempt it, otherwise log but continue + // fixes: https://github.com/MirrorNetworking/Mirror/issues/3358 + try + { + socket.DualMode = true; + } + catch (NotSupportedException e) + { + Log.Warning($"Failed to set Dual Mode, continuing with IPv6 without Dual Mode. Error: {e}"); + } + socket.Bind(new IPEndPoint(IPAddress.IPv6Any, port)); + return socket; + } + else + { + // IPv4 socket @ "0.0.0.0" : port + Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Any, port)); + return socket; + } + } + + public virtual void Start(ushort port) + { + // only start once + if (socket != null) + { + Log.Warning("KcpServer: already started!"); + return; + } + + // listen + socket = CreateServerSocket(config.DualMode, port); + + // recv & send are called from main thread. + // need to ensure this never blocks. + // even a 1ms block per connection would stop us from scaling. + socket.Blocking = false; + + // configure buffer sizes + Common.ConfigureSocketBuffers(socket, config.RecvBufferSize, config.SendBufferSize); + } + + public void Send(int connectionId, ArraySegment segment, KcpChannel channel) + { + if (connections.TryGetValue(connectionId, out KcpServerConnection connection)) + { + connection.peer.SendData(segment, channel); + } + } + + public void Disconnect(int connectionId) + { + if (connections.TryGetValue(connectionId, out KcpServerConnection connection)) + { + connection.peer.Disconnect(); + } + } + + // expose the whole IPEndPoint, not just the IP address. some need it. + public IPEndPoint GetClientEndPoint(int connectionId) + { + if (connections.TryGetValue(connectionId, out KcpServerConnection connection)) + { + return connection.remoteEndPoint as IPEndPoint; + } + return null; + } + + // io - input. + // virtual so it may be modified for relays, nonalloc workaround, etc. + // https://github.com/vis2k/where-allocation + // bool return because not all receives may be valid. + // for example, relay may expect a certain header. + protected virtual bool RawReceiveFrom(out ArraySegment segment, out int connectionId) + { + segment = default; + connectionId = 0; + if (socket == null) return false; + + try + { + if (socket.ReceiveFromNonBlocking(rawReceiveBuffer, out segment, ref newClientEP)) + { + // set connectionId to hash from endpoint + connectionId = Common.ConnectionHash(newClientEP); + return true; + } + } + catch (SocketException e) + { + // NOTE: SocketException is not a subclass of IOException. + // the other end closing the connection is not an 'error'. + // but connections should never just end silently. + // at least log a message for easier debugging. + Log.Info($"KcpServer: ReceiveFrom failed: {e}"); + } + + return false; + } + + // io - out. + // virtual so it may be modified for relays, nonalloc workaround, etc. + // relays may need to prefix connId (and remoteEndPoint would be same for all) + protected virtual void RawSend(int connectionId, ArraySegment data) + { + // get the connection's endpoint + if (!connections.TryGetValue(connectionId, out KcpServerConnection connection)) + { + Log.Warning($"KcpServer: RawSend invalid connectionId={connectionId}"); + return; + } + + try + { + socket.SendToNonBlocking(data, connection.remoteEndPoint); + } + catch (SocketException e) + { + Log.Error($"KcpServer: SendTo failed: {e}"); + } + } + + protected virtual KcpServerConnection CreateConnection(int connectionId) + { + // events need to be wrapped with connectionIds + Action> RawSendWrap = + data => RawSend(connectionId, data); + + // create empty connection without peer first. + // we need it to set up peer callbacks. + // afterwards we assign the peer. + KcpServerConnection connection = new KcpServerConnection(newClientEP); + + // generate a random cookie for this connection to avoid UDP spoofing. + // needs to be random, but without allocations to avoid GC. + uint cookie = Common.GenerateCookie(); + + // set up peer with callbacks + KcpPeer peer = new KcpPeer(RawSendWrap, OnAuthenticatedWrap, OnDataWrap, OnDisconnectedWrap, OnErrorWrap, config, cookie); + + // assign peer to connection + connection.peer = peer; + return connection; + + // setup authenticated event that also adds to connections + void OnAuthenticatedWrap() + { + // only send handshake to client AFTER we received his + // handshake in OnAuthenticated. + // we don't want to reply to random internet messages + // with handshakes each time. + connection.peer.SendHandshake(); + + // add to connections dict after being authenticated. + connections.Add(connectionId, connection); + Log.Info($"KcpServer: added connection({connectionId})"); + + // setup Data + Disconnected events only AFTER the + // handshake. we don't want to fire OnServerDisconnected + // every time we receive invalid random data from the + // internet. + + // setup data event + + + // finally, call mirror OnConnected event + Log.Info($"KcpServer: OnConnected({connectionId})"); + OnConnected(connectionId); + } + + void OnDataWrap(ArraySegment message, KcpChannel channel) + { + // call mirror event + //Log.Info($"KCP: OnServerDataReceived({connectionId}, {BitConverter.ToString(message.Array, message.Offset, message.Count)})"); + OnData(connectionId, message, channel); + } + + void OnDisconnectedWrap() + { + // flag for removal + // (can't remove directly because connection is updated + // and event is called while iterating all connections) + connectionsToRemove.Add(connectionId); + + // call mirror event + Log.Info($"KcpServer: OnDisconnected({connectionId})"); + OnDisconnected(connectionId); + } + + void OnErrorWrap(ErrorCode error, string reason) + { + OnError(connectionId, error, reason); + } + } + + // receive + add + process once. + // best to call this as long as there is more data to receive. + void ProcessMessage(ArraySegment segment, int connectionId) + { + //Log.Info($"KCP: server raw recv {msgLength} bytes = {BitConverter.ToString(buffer, 0, msgLength)}"); + + // is this a new connection? + if (!connections.TryGetValue(connectionId, out KcpServerConnection connection)) + { + // create a new KcpConnection based on last received + // EndPoint. can be overwritten for where-allocation. + connection = CreateConnection(connectionId); + + // DO NOT add to connections yet. only if the first message + // is actually the kcp handshake. otherwise it's either: + // * random data from the internet + // * or from a client connection that we just disconnected + // but that hasn't realized it yet, still sending data + // from last session that we should absolutely ignore. + // + // + // TODO this allocates a new KcpConnection for each new + // internet connection. not ideal, but C# UDP Receive + // already allocated anyway. + // + // expecting a MAGIC byte[] would work, but sending the raw + // UDP message without kcp's reliability will have low + // probability of being received. + // + // for now, this is fine. + + + // now input the message & process received ones + // connected event was set up. + // tick will process the first message and adds the + // connection if it was the handshake. + connection.peer.RawInput(segment); + connection.peer.TickIncoming(); + + // again, do not add to connections. + // if the first message wasn't the kcp handshake then + // connection will simply be garbage collected. + } + // existing connection: simply input the message into kcp + else + { + connection.peer.RawInput(segment); + } + } + + // process incoming messages. should be called before updating the world. + // virtual because relay may need to inject their own ping or similar. + readonly HashSet connectionsToRemove = new HashSet(); + public virtual void TickIncoming() + { + // input all received messages into kcp + while (RawReceiveFrom(out ArraySegment segment, out int connectionId)) + { + ProcessMessage(segment, connectionId); + } + + // process inputs for all server connections + // (even if we didn't receive anything. need to tick ping etc.) + foreach (KcpServerConnection connection in connections.Values) + { + connection.peer.TickIncoming(); + } + + // remove disconnected connections + // (can't do it in connection.OnDisconnected because Tick is called + // while iterating connections) + foreach (int connectionId in connectionsToRemove) + { + connections.Remove(connectionId); + } + connectionsToRemove.Clear(); + } + + // process outgoing messages. should be called after updating the world. + // virtual because relay may need to inject their own ping or similar. + public virtual void TickOutgoing() + { + // flush all server connections + foreach (KcpServerConnection connection in connections.Values) + { + connection.peer.TickOutgoing(); + } + } + + // process incoming and outgoing for convenience. + // => ideally call ProcessIncoming() before updating the world and + // ProcessOutgoing() after updating the world for minimum latency + public virtual void Tick() + { + TickIncoming(); + TickOutgoing(); + } + + public virtual void Stop() + { + // need to clear connections, otherwise they are in next session. + // fixes https://github.com/vis2k/kcp2k/pull/47 + connections.Clear(); + socket?.Close(); + socket = null; + } + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServer.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServer.cs.meta new file mode 100644 index 0000000..ef720d4 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9759159c6589494a9037f5e130a867ed +timeCreated: 1603787747 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServerConnection.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServerConnection.cs new file mode 100644 index 0000000..5b9c888 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServerConnection.cs @@ -0,0 +1,22 @@ +// server needs to store a separate KcpPeer for each connection. +// as well as remoteEndPoint so we know where to send data to. +using System.Net; + +namespace kcp2k +{ + // struct to avoid memory indirection + public struct KcpServerConnection + { + // peer can't be set from constructor at the moment. + // because peer callbacks need to know 'connection'. + // see KcpServer.CreateConnection. + public KcpPeer peer; + public readonly EndPoint remoteEndPoint; + + public KcpServerConnection(EndPoint remoteEndPoint) + { + peer = null; + this.remoteEndPoint = remoteEndPoint; + } + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServerConnection.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServerConnection.cs.meta new file mode 100644 index 0000000..10d9803 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/KcpServerConnection.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 80a9b1ce9a6f14abeb32bfa9921d097b +timeCreated: 1602601483 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Log.cs b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Log.cs new file mode 100644 index 0000000..c28d8b8 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Log.cs @@ -0,0 +1,14 @@ +// A simple logger class that uses Console.WriteLine by default. +// Can also do Logger.LogMethod = Debug.Log for Unity etc. +// (this way we don't have to depend on UnityEngine) +using System; + +namespace kcp2k +{ + public static class Log + { + public static Action Info = Console.WriteLine; + public static Action Warning = Console.WriteLine; + public static Action Error = Console.Error.WriteLine; + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Log.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Log.cs.meta new file mode 100644 index 0000000..333bee5 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/highlevel/Log.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7b5e1de98d6d84c3793a61cf7d8da9a4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp.meta b/Assets/Mirror/Transports/KCP/kcp2k/kcp.meta new file mode 100644 index 0000000..a7d6e11 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5cafb8851a0084f3e94a580c207b3923 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/AckItem.cs b/Assets/Mirror/Transports/KCP/kcp2k/kcp/AckItem.cs new file mode 100644 index 0000000..820f451 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/AckItem.cs @@ -0,0 +1,8 @@ +namespace kcp2k +{ + internal struct AckItem + { + internal uint serialNumber; + internal uint timestamp; + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/AckItem.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/kcp/AckItem.cs.meta new file mode 100644 index 0000000..301e2eb --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/AckItem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 71f47cb11125d429e84e188a150f3ae5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/AssemblyInfo.cs b/Assets/Mirror/Transports/KCP/kcp2k/kcp/AssemblyInfo.cs new file mode 100644 index 0000000..5fe5547 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("kcp2k.Tests")] \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/AssemblyInfo.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/kcp/AssemblyInfo.cs.meta new file mode 100644 index 0000000..6b442a9 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/AssemblyInfo.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: aec6a15ac7bd43129317ea1f01f19782 +timeCreated: 1602665988 \ No newline at end of file diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/Kcp.cs b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Kcp.cs new file mode 100644 index 0000000..851faaa --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Kcp.cs @@ -0,0 +1,1118 @@ +// Kcp based on https://github.com/skywind3000/kcp +// Kept as close to original as possible. +using System; +using System.Collections.Generic; + +namespace kcp2k +{ + public class Kcp + { + // original Kcp has a define option, which is not defined by default: + // #define FASTACK_CONSERVE + + public const int RTO_NDL = 30; // no delay min rto + public const int RTO_MIN = 100; // normal min rto + public const int RTO_DEF = 200; // default RTO + public const int RTO_MAX = 60000; // maximum RTO + public const int CMD_PUSH = 81; // cmd: push data + public const int CMD_ACK = 82; // cmd: ack + public const int CMD_WASK = 83; // cmd: window probe (ask) + public const int CMD_WINS = 84; // cmd: window size (tell/insert) + public const int ASK_SEND = 1; // need to send CMD_WASK + public const int ASK_TELL = 2; // need to send CMD_WINS + public const int WND_SND = 32; // default send window + public const int WND_RCV = 128; // default receive window. must be >= max fragment size + public const int MTU_DEF = 1200; // default MTU (reduced to 1200 to fit all cases: https://en.wikipedia.org/wiki/Maximum_transmission_unit ; steam uses 1200 too!) + public const int ACK_FAST = 3; + public const int INTERVAL = 100; + public const int OVERHEAD = 24; + public const int FRG_MAX = byte.MaxValue; // kcp encodes 'frg' as byte. so we can only ever send up to 255 fragments. + public const int DEADLINK = 20; // default maximum amount of 'xmit' retransmissions until a segment is considered lost + public const int THRESH_INIT = 2; + public const int THRESH_MIN = 2; + public const int PROBE_INIT = 7000; // 7 secs to probe window size + public const int PROBE_LIMIT = 120000; // up to 120 secs to probe window + public const int FASTACK_LIMIT = 5; // max times to trigger fastack + + // kcp members. + internal int state; + readonly uint conv; // conversation + internal uint mtu; + internal uint mss; // maximum segment size := MTU - OVERHEAD + internal uint snd_una; // unacknowledged. e.g. snd_una is 9 it means 8 has been confirmed, 9 and 10 have been sent + internal uint snd_nxt; // forever growing send counter for sequence numbers + internal uint rcv_nxt; // forever growing receive counter for sequence numbers + internal uint ssthresh; // slow start threshold + internal int rx_rttval; // average deviation of rtt, used to measure the jitter of rtt + internal int rx_srtt; // smoothed round trip time (a weighted average of rtt) + internal int rx_rto; + internal int rx_minrto; + internal uint snd_wnd; // send window + internal uint rcv_wnd; // receive window + internal uint rmt_wnd; // remote window + internal uint cwnd; // congestion window + internal uint probe; + internal uint interval; + internal uint ts_flush; // last flush timestamp in milliseconds + internal uint xmit; + internal uint nodelay; // not a bool. original Kcp has '<2 else' check. + internal bool updated; + internal uint ts_probe; // probe timestamp + internal uint probe_wait; + internal uint dead_link; // maximum amount of 'xmit' retransmissions until a segment is considered lost + internal uint incr; + internal uint current; // current time (milliseconds). set by Update. + + internal int fastresend; + internal int fastlimit; + internal bool nocwnd; // congestion control, negated. heavily restricts send/recv window sizes. + internal readonly Queue snd_queue = new Queue(16); // send queue + internal readonly Queue rcv_queue = new Queue(16); // receive queue + // snd_buffer needs index removals. + // C# LinkedList allocates for each entry, so let's keep List for now. + internal readonly List snd_buf = new List(16); // send buffer + // rcv_buffer needs index insertions and backwards iteration. + // C# LinkedList allocates for each entry, so let's keep List for now. + internal readonly List rcv_buf = new List(16); // receive buffer + internal readonly List acklist = new List(16); + + // memory buffer + // size depends on MTU. + // MTU can be changed at runtime, which resizes the buffer. + internal byte[] buffer; + + // output function of type + readonly Action output; + + // segment pool to avoid allocations in C#. + // this is not part of the original C code. + readonly Pool SegmentPool = new Pool( + // create new segment + () => new Segment(), + // reset segment before reuse + (segment) => segment.Reset(), + // initial capacity + 32 + ); + + // ikcp_create + // create a new kcp control object, 'conv' must equal in two endpoint + // from the same connection. + public Kcp(uint conv, Action output) + { + this.conv = conv; + this.output = output; + snd_wnd = WND_SND; + rcv_wnd = WND_RCV; + rmt_wnd = WND_RCV; + mtu = MTU_DEF; + mss = mtu - OVERHEAD; + rx_rto = RTO_DEF; + rx_minrto = RTO_MIN; + interval = INTERVAL; + ts_flush = INTERVAL; + ssthresh = THRESH_INIT; + fastlimit = FASTACK_LIMIT; + dead_link = DEADLINK; + buffer = new byte[(mtu + OVERHEAD) * 3]; + } + + // ikcp_segment_new + // we keep the original function and add our pooling to it. + // this way we'll never miss it anywhere. + Segment SegmentNew() => SegmentPool.Take(); + + // ikcp_segment_delete + // we keep the original function and add our pooling to it. + // this way we'll never miss it anywhere. + void SegmentDelete(Segment seg) => SegmentPool.Return(seg); + + // calculate how many packets are waiting to be sent + public int WaitSnd => snd_buf.Count + snd_queue.Count; + + // ikcp_wnd_unused + // returns the remaining space in receive window (rcv_wnd - rcv_queue) + internal uint WndUnused() + { + if (rcv_queue.Count < rcv_wnd) + return rcv_wnd - (uint)rcv_queue.Count; + return 0; + } + + // ikcp_recv + // receive data from kcp state machine + // returns number of bytes read. + // returns negative on error. + // note: pass negative length to peek. + public int Receive(byte[] buffer, int len) + { + // kcp's ispeek feature is not supported. + // this makes 'merge fragment' code significantly easier because + // we can iterate while queue.Count > 0 and dequeue each time. + // if we had to consider ispeek then count would always be > 0 and + // we would have to remove only after the loop. + // + //bool ispeek = len < 0; + if (len < 0) + throw new NotSupportedException("Receive ispeek for negative len is not supported!"); + + if (rcv_queue.Count == 0) + return -1; + + if (len < 0) len = -len; + + int peeksize = PeekSize(); + + if (peeksize < 0) + return -2; + + if (peeksize > len) + return -3; + + bool recover = rcv_queue.Count >= rcv_wnd; + + // merge fragment. + int offset = 0; + len = 0; + // original KCP iterates rcv_queue and deletes if !ispeek. + // removing from a c# queue while iterating is not possible, but + // we can change to 'while Count > 0' and remove every time. + // (we can remove every time because we removed ispeek support!) + while (rcv_queue.Count > 0) + { + // unlike original kcp, we dequeue instead of just getting the + // entry. this is fine because we remove it in ANY case. + Segment seg = rcv_queue.Dequeue(); + + // copy segment data into our buffer + Buffer.BlockCopy(seg.data.GetBuffer(), 0, buffer, offset, (int)seg.data.Position); + offset += (int)seg.data.Position; + + len += (int)seg.data.Position; + uint fragment = seg.frg; + + // note: ispeek is not supported in order to simplify this loop + + // unlike original kcp, we don't need to remove seg from queue + // because we already dequeued it. + // simply delete it + SegmentDelete(seg); + + if (fragment == 0) + break; + } + + // move available data from rcv_buf -> rcv_queue + int removed = 0; + foreach (Segment seg in rcv_buf) + { + if (seg.sn == rcv_nxt && rcv_queue.Count < rcv_wnd) + { + // can't remove while iterating. remember how many to remove + // and do it after the loop. + // note: don't return segment. we only add it to rcv_queue + ++removed; + // add + rcv_queue.Enqueue(seg); + // increase sequence number for next segment + rcv_nxt++; + } + else + { + break; + } + } + rcv_buf.RemoveRange(0, removed); + + // fast recover + if (rcv_queue.Count < rcv_wnd && recover) + { + // ready to send back CMD_WINS in flush + // tell remote my window size + probe |= ASK_TELL; + } + + return len; + } + + // ikcp_peeksize + // check the size of next message in the recv queue. + // returns -1 if there is no message, or if the message is still incomplete. + public int PeekSize() + { + int length = 0; + + // empty queue? + if (rcv_queue.Count == 0) return -1; + + // peek the first segment + Segment seq = rcv_queue.Peek(); + + // seg.frg is 0 if the message requires no fragmentation. + // in that case, the segment's size is the final message size. + if (seq.frg == 0) return (int)seq.data.Position; + + // check if all fragment parts were received yet. + // seg.frg is the n-th fragment, but in reverse. + // this way the first received segment tells us how many fragments there are for the message. + // for example, if a message contains 3 segments: + // first segment: .frg is 2 (index in reverse) + // second segment: .frg is 1 (index in reverse) + // third segment: .frg is 0 (index in reverse) + if (rcv_queue.Count < seq.frg + 1) return -1; + + // recv_queue contains all the fragments necessary to reconstruct the message. + // sum all fragment's sizes to get the full message size. + foreach (Segment seg in rcv_queue) + { + length += (int)seg.data.Position; + if (seg.frg == 0) break; + } + + return length; + } + + // ikcp_send + // splits message into MTU sized fragments, adds them to snd_queue. + public int Send(byte[] buffer, int offset, int len) + { + // fragment count + int count; + + if (len < 0) return -1; + + // streaming mode: removed. we never want to send 'hello' and + // receive 'he' 'll' 'o'. we want to always receive 'hello'. + + // calculate amount of fragments necessary for 'len' + if (len <= mss) count = 1; + else count = (int)((len + mss - 1) / mss); + + // IMPORTANT kcp encodes 'frg' as 1 byte. + // so we can only support up to 255 fragments. + // (which limits max message size to around 288 KB) + // this is difficult to debug. let's make this 100% obvious. + if (count > FRG_MAX) + throw new Exception($"Send len={len} requires {count} fragments, but kcp can only handle up to {FRG_MAX} fragments."); + + // original kcp uses WND_RCV const instead of rcv_wnd runtime: + // https://github.com/skywind3000/kcp/pull/291/files + // which always limits max message size to 144 KB: + //if (count >= WND_RCV) return -2; + // using configured rcv_wnd uncorks max message size to 'any': + if (count >= rcv_wnd) return -2; + + if (count == 0) count = 1; + + // fragment + for (int i = 0; i < count; i++) + { + int size = len > (int)mss ? (int)mss : len; + Segment seg = SegmentNew(); + + if (len > 0) + { + seg.data.Write(buffer, offset, size); + } + // seg.len = size: WriteBytes sets segment.Position! + + // set fragment number. + // if the message requires no fragmentation, then + // seg.frg becomes 1-0-1 = 0 + seg.frg = (uint)(count - i - 1); + snd_queue.Enqueue(seg); + offset += size; + len -= size; + } + + return 0; + } + + // ikcp_update_ack + void UpdateAck(int rtt) // round trip time + { + // https://tools.ietf.org/html/rfc6298 + if (rx_srtt == 0) + { + rx_srtt = rtt; + rx_rttval = rtt / 2; + } + else + { + int delta = rtt - rx_srtt; + if (delta < 0) delta = -delta; + rx_rttval = (3 * rx_rttval + delta) / 4; + rx_srtt = (7 * rx_srtt + rtt) / 8; + if (rx_srtt < 1) rx_srtt = 1; + } + int rto = rx_srtt + Math.Max((int)interval, 4 * rx_rttval); + rx_rto = Utils.Clamp(rto, rx_minrto, RTO_MAX); + } + + // ikcp_shrink_buf + internal void ShrinkBuf() + { + if (snd_buf.Count > 0) + { + Segment seg = snd_buf[0]; + snd_una = seg.sn; + } + else + { + snd_una = snd_nxt; + } + } + + // ikcp_parse_ack + // removes the segment with 'sn' from send buffer + internal void ParseAck(uint sn) + { + if (Utils.TimeDiff(sn, snd_una) < 0 || Utils.TimeDiff(sn, snd_nxt) >= 0) + return; + + // for-int so we can erase while iterating + for (int i = 0; i < snd_buf.Count; ++i) + { + // is this the segment? + Segment seg = snd_buf[i]; + if (sn == seg.sn) + { + // remove and return + snd_buf.RemoveAt(i); + SegmentDelete(seg); + break; + } + if (Utils.TimeDiff(sn, seg.sn) < 0) + { + break; + } + } + } + + // ikcp_parse_una + // removes all unacknowledged segments with sequence numbers < una from send buffer + internal void ParseUna(uint una) + { + int removed = 0; + foreach (Segment seg in snd_buf) + { + // if (Utils.TimeDiff(una, seg.sn) > 0) + if (seg.sn < una) + { + // can't remove while iterating. remember how many to remove + // and do it after the loop. + ++removed; + SegmentDelete(seg); + } + else + { + break; + } + } + snd_buf.RemoveRange(0, removed); + } + + // ikcp_parse_fastack + internal void ParseFastack(uint sn, uint ts) // serial number, timestamp + { + // sn needs to be between snd_una and snd_nxt + // if !(snd_una <= sn && sn < snd_nxt) return; + + // if (Utils.TimeDiff(sn, snd_una) < 0) + if (sn < snd_una) + return; + + // if (Utils.TimeDiff(sn, snd_nxt) >= 0) + if (sn >= snd_nxt) + return; + + foreach (Segment seg in snd_buf) + { + // if (Utils.TimeDiff(sn, seg.sn) < 0) + if (sn < seg.sn) + { + break; + } + else if (sn != seg.sn) + { +#if !FASTACK_CONSERVE + seg.fastack++; +#else + if (Utils.TimeDiff(ts, seg.ts) >= 0) + seg.fastack++; +#endif + } + } + } + + // ikcp_ack_push + // appends an ack. + void AckPush(uint sn, uint ts) // serial number, timestamp + { + acklist.Add(new AckItem{ serialNumber = sn, timestamp = ts }); + } + + // ikcp_parse_data + void ParseData(Segment newseg) + { + uint sn = newseg.sn; + + if (Utils.TimeDiff(sn, rcv_nxt + rcv_wnd) >= 0 || + Utils.TimeDiff(sn, rcv_nxt) < 0) + { + SegmentDelete(newseg); + return; + } + + InsertSegmentInReceiveBuffer(newseg); + MoveReceiveBufferReadySegmentsToQueue(); + } + + // inserts the segment into rcv_buf, ordered by seg.sn. + // drops the segment if one with the same seg.sn already exists. + // goes through receive buffer in reverse order for performance. + // + // note: see KcpTests.InsertSegmentInReceiveBuffer test! + // note: 'insert or delete' can be done in different ways, but let's + // keep consistency with original C kcp. + internal void InsertSegmentInReceiveBuffer(Segment newseg) + { + bool repeat = false; // 'duplicate' + + // original C iterates backwards, so we need to do that as well. + // note if rcv_buf.Count == 0, i becomes -1 and no looping happens. + int i; + for (i = rcv_buf.Count - 1; i >= 0; i--) + { + Segment seg = rcv_buf[i]; + if (seg.sn == newseg.sn) + { + // duplicate segment found. nothing will be added. + repeat = true; + break; + } + if (Utils.TimeDiff(newseg.sn, seg.sn) > 0) + { + // this entry's sn is < newseg.sn, so let's stop + break; + } + } + + // no duplicate? then insert. + if (!repeat) + { + rcv_buf.Insert(i + 1, newseg); + } + // duplicate. just delete it. + else + { + SegmentDelete(newseg); + } + } + + // move ready segments from rcv_buf -> rcv_queue. + // moves only the ready segments which are in rcv_nxt sequence order. + // some may still be missing an inserted later. + void MoveReceiveBufferReadySegmentsToQueue() + { + int removed = 0; + foreach (Segment seg in rcv_buf) + { + // move segments while they are in 'rcv_nxt' sequence order. + // some may still be missing and inserted later, in this case it stops immediately + // because segments always need to be received in the exact sequence order. + if (seg.sn == rcv_nxt && rcv_queue.Count < rcv_wnd) + { + // can't remove while iterating. remember how many to remove + // and do it after the loop. + ++removed; + rcv_queue.Enqueue(seg); + // increase sequence number for next segment + rcv_nxt++; + } + else + { + break; + } + } + rcv_buf.RemoveRange(0, removed); + } + + // ikcp_input + // used when you receive a low level packet (e.g. UDP packet) + // => original kcp uses offset=0, we made it a parameter so that high + // level can skip the channel byte more easily + public int Input(byte[] data, int offset, int size) + { + uint prev_una = snd_una; + uint maxack = 0; + uint latest_ts = 0; + int flag = 0; + + if (data == null || size < OVERHEAD) return -1; + + while (true) + { + // enough data left to decode segment (aka OVERHEAD bytes)? + if (size < OVERHEAD) break; + + // decode segment + offset += Utils.Decode32U(data, offset, out uint conv_); + if (conv_ != conv) return -1; + + offset += Utils.Decode8u(data, offset, out byte cmd); + // IMPORTANT kcp encodes 'frg' as 1 byte. + // so we can only support up to 255 fragments. + // (which limits max message size to around 288 KB) + offset += Utils.Decode8u(data, offset, out byte frg); + offset += Utils.Decode16U(data, offset, out ushort wnd); + offset += Utils.Decode32U(data, offset, out uint ts); + offset += Utils.Decode32U(data, offset, out uint sn); + offset += Utils.Decode32U(data, offset, out uint una); + offset += Utils.Decode32U(data, offset, out uint len); + + // reduce remaining size by what was read + size -= OVERHEAD; + + // enough remaining to read 'len' bytes of the actual payload? + // note: original kcp casts uint len to int for <0 check. + if (size < len || (int)len < 0) return -2; + + // validate command type + if (cmd != CMD_PUSH && cmd != CMD_ACK && + cmd != CMD_WASK && cmd != CMD_WINS) + return -3; + + rmt_wnd = wnd; + ParseUna(una); + ShrinkBuf(); + + if (cmd == CMD_ACK) + { + if (Utils.TimeDiff(current, ts) >= 0) + { + UpdateAck(Utils.TimeDiff(current, ts)); + } + ParseAck(sn); + ShrinkBuf(); + if (flag == 0) + { + flag = 1; + maxack = sn; + latest_ts = ts; + } + else + { + if (Utils.TimeDiff(sn, maxack) > 0) + { +#if !FASTACK_CONSERVE + maxack = sn; + latest_ts = ts; +#else + if (Utils.TimeDiff(ts, latest_ts) > 0) + { + maxack = sn; + latest_ts = ts; + } +#endif + } + } + } + else if (cmd == CMD_PUSH) + { + if (Utils.TimeDiff(sn, rcv_nxt + rcv_wnd) < 0) + { + AckPush(sn, ts); + if (Utils.TimeDiff(sn, rcv_nxt) >= 0) + { + Segment seg = SegmentNew(); + seg.conv = conv_; + seg.cmd = cmd; + seg.frg = frg; + seg.wnd = wnd; + seg.ts = ts; + seg.sn = sn; + seg.una = una; + if (len > 0) + { + seg.data.Write(data, offset, (int)len); + } + ParseData(seg); + } + } + } + else if (cmd == CMD_WASK) + { + // ready to send back CMD_WINS in flush + // tell remote my window size + probe |= ASK_TELL; + } + else if (cmd == CMD_WINS) + { + // do nothing + } + else + { + return -3; + } + + offset += (int)len; + size -= (int)len; + } + + if (flag != 0) + { + ParseFastack(maxack, latest_ts); + } + + // cwnd update when packet arrived + if (Utils.TimeDiff(snd_una, prev_una) > 0) + { + if (cwnd < rmt_wnd) + { + if (cwnd < ssthresh) + { + cwnd++; + incr += mss; + } + else + { + if (incr < mss) incr = mss; + incr += (mss * mss) / incr + (mss / 16); + if ((cwnd + 1) * mss <= incr) + { + cwnd = (incr + mss - 1) / ((mss > 0) ? mss : 1); + } + } + if (cwnd > rmt_wnd) + { + cwnd = rmt_wnd; + incr = rmt_wnd * mss; + } + } + } + + return 0; + } + + // flush helper function + void MakeSpace(ref int size, int space) + { + if (size + space > mtu) + { + output(buffer, size); + size = 0; + } + } + + // flush helper function + void FlushBuffer(int size) + { + // flush buffer up to 'offset' (<= MTU) + if (size > 0) + { + output(buffer, size); + } + } + + // ikcp_flush + // flush remain ack segments. + // flush may output multiple <= MTU messages from MakeSpace / FlushBuffer. + // the amount of messages depends on the sliding window. + // configured by send/receive window sizes + congestion control. + // with congestion control, the window will be extremely small(!). + public void Flush() + { + int size = 0; // amount of bytes to flush. 'buffer ptr' in C. + bool lost = false; // lost segments + + // update needs to be called before flushing + if (!updated) return; + + // kcp only stack allocates a segment here for performance, leaving + // its data buffer null because this segment's data buffer is never + // used. that's fine in C, but in C# our segment is a class so we + // need to allocate and most importantly, not forget to deallocate + // it before returning. + Segment seg = SegmentNew(); + seg.conv = conv; + seg.cmd = CMD_ACK; + seg.wnd = WndUnused(); + seg.una = rcv_nxt; + + // flush acknowledges + foreach (AckItem ack in acklist) + { + MakeSpace(ref size, OVERHEAD); + // ikcp_ack_get assigns ack[i] to seg.sn, seg.ts + seg.sn = ack.serialNumber; + seg.ts = ack.timestamp; + size += seg.Encode(buffer, size); + } + acklist.Clear(); + + // probe window size (if remote window size equals zero) + if (rmt_wnd == 0) + { + if (probe_wait == 0) + { + probe_wait = PROBE_INIT; + ts_probe = current + probe_wait; + } + else + { + if (Utils.TimeDiff(current, ts_probe) >= 0) + { + if (probe_wait < PROBE_INIT) + probe_wait = PROBE_INIT; + probe_wait += probe_wait / 2; + if (probe_wait > PROBE_LIMIT) + probe_wait = PROBE_LIMIT; + ts_probe = current + probe_wait; + probe |= ASK_SEND; + } + } + } + else + { + ts_probe = 0; + probe_wait = 0; + } + + // flush window probing commands + if ((probe & ASK_SEND) != 0) + { + seg.cmd = CMD_WASK; + MakeSpace(ref size, OVERHEAD); + size += seg.Encode(buffer, size); + } + + // flush window probing commands + if ((probe & ASK_TELL) != 0) + { + seg.cmd = CMD_WINS; + MakeSpace(ref size, OVERHEAD); + size += seg.Encode(buffer, size); + } + + probe = 0; + + // calculate the window size which is currently safe to send. + // it's send window, or remote window, whatever is smaller. + // for our max + uint cwnd_ = Math.Min(snd_wnd, rmt_wnd); + + // double negative: if congestion window is enabled: + // limit window size to cwnd. + // + // note this may heavily limit window sizes. + // for our max message size test with super large windows of 32k, + // 'congestion window' limits it down from 32.000 to 2. + if (!nocwnd) cwnd_ = Math.Min(cwnd, cwnd_); + + // move cwnd_ 'window size' messages from snd_queue to snd_buf + // 'snd_nxt' is what we want to send. + // 'snd_una' is what hasn't been acked yet. + // copy up to 'cwnd_' difference between them (sliding window) + while (Utils.TimeDiff(snd_nxt, snd_una + cwnd_) < 0) + { + if (snd_queue.Count == 0) break; + + Segment newseg = snd_queue.Dequeue(); + + newseg.conv = conv; + newseg.cmd = CMD_PUSH; + newseg.wnd = seg.wnd; + newseg.ts = current; + newseg.sn = snd_nxt; + snd_nxt += 1; // increase sequence number for next segment + newseg.una = rcv_nxt; + newseg.resendts = current; + newseg.rto = rx_rto; + newseg.fastack = 0; + newseg.xmit = 0; + snd_buf.Add(newseg); + } + + // calculate resent + uint resent = fastresend > 0 ? (uint)fastresend : 0xffffffff; + uint rtomin = nodelay == 0 ? (uint)rx_rto >> 3 : 0; + + // flush data segments + int change = 0; + foreach (Segment segment in snd_buf) + { + bool needsend = false; + + // initial transmit + if (segment.xmit == 0) + { + needsend = true; + segment.xmit++; + segment.rto = rx_rto; + segment.resendts = current + (uint)segment.rto + rtomin; + } + // RTO + else if (Utils.TimeDiff(current, segment.resendts) >= 0) + { + needsend = true; + segment.xmit++; + xmit++; + if (nodelay == 0) + { + segment.rto += Math.Max(segment.rto, rx_rto); + } + else + { + int step = (nodelay < 2) ? segment.rto : rx_rto; + segment.rto += step / 2; + } + segment.resendts = current + (uint)segment.rto; + lost = true; + } + // fast retransmit + else if (segment.fastack >= resent) + { + if (segment.xmit <= fastlimit || fastlimit <= 0) + { + needsend = true; + segment.xmit++; + segment.fastack = 0; + segment.resendts = current + (uint)segment.rto; + change++; + } + } + + if (needsend) + { + segment.ts = current; + segment.wnd = seg.wnd; + segment.una = rcv_nxt; + + int need = OVERHEAD + (int)segment.data.Position; + MakeSpace(ref size, need); + + size += segment.Encode(buffer, size); + + if (segment.data.Position > 0) + { + Buffer.BlockCopy(segment.data.GetBuffer(), 0, buffer, size, (int)segment.data.Position); + size += (int)segment.data.Position; + } + + // dead link happens if a message was resent N times, but an + // ack was still not received. + if (segment.xmit >= dead_link) + { + state = -1; + } + } + } + + // kcp stackallocs 'seg'. our C# segment is a class though, so we + // need to properly delete and return it to the pool now that we are + // done with it. + SegmentDelete(seg); + + // flush remaining segments + FlushBuffer(size); + + // update ssthresh + // rate halving, https://tools.ietf.org/html/rfc6937 + if (change > 0) + { + uint inflight = snd_nxt - snd_una; + ssthresh = inflight / 2; + if (ssthresh < THRESH_MIN) + ssthresh = THRESH_MIN; + cwnd = ssthresh + resent; + incr = cwnd * mss; + } + + // congestion control, https://tools.ietf.org/html/rfc5681 + if (lost) + { + // original C uses 'cwnd', not kcp->cwnd! + ssthresh = cwnd_ / 2; + if (ssthresh < THRESH_MIN) + ssthresh = THRESH_MIN; + cwnd = 1; + incr = mss; + } + + if (cwnd < 1) + { + cwnd = 1; + incr = mss; + } + } + + // ikcp_update + // update state (call it repeatedly, every 10ms-100ms), or you can ask + // Check() when to call it again (without Input/Send calling). + // + // 'current' - current timestamp in millisec. pass it to Kcp so that + // Kcp doesn't have to do any stopwatch/deltaTime/etc. code + // + // time as uint, likely to minimize bandwidth. + // uint.max = 4294967295 ms = 1193 hours = 49 days + public void Update(uint currentTimeMilliSeconds) + { + current = currentTimeMilliSeconds; + + // not updated yet? then set updated and last flush time. + if (!updated) + { + updated = true; + ts_flush = current; + } + + // slap is time since last flush in milliseconds + int slap = Utils.TimeDiff(current, ts_flush); + + // hard limit: if 10s elapsed, always flush no matter what + if (slap >= 10000 || slap < -10000) + { + ts_flush = current; + slap = 0; + } + + // last flush is increased by 'interval' each time. + // so slap >= is a strange way to check if interval has elapsed yet. + if (slap >= 0) + { + // increase last flush time by one interval + ts_flush += interval; + + // if last flush is still behind, increase it to current + interval + // if (Utils.TimeDiff(current, ts_flush) >= 0) // original kcp.c + if (current >= ts_flush) // less confusing + { + ts_flush = current + interval; + } + Flush(); + } + } + + // ikcp_check + // Determine when should you invoke update + // Returns when you should invoke update in millisec, if there is no + // input/send calling. you can call update in that time, instead of + // call update repeatly. + // + // Important to reduce unnecessary update invoking. use it to schedule + // update (e.g. implementing an epoll-like mechanism, or optimize update + // when handling massive kcp connections). + public uint Check(uint current_) + { + uint ts_flush_ = ts_flush; + // int tm_flush = 0x7fffffff; original kcp: useless assignment + int tm_packet = 0x7fffffff; + + if (!updated) + { + return current_; + } + + if (Utils.TimeDiff(current_, ts_flush_) >= 10000 || + Utils.TimeDiff(current_, ts_flush_) < -10000) + { + ts_flush_ = current_; + } + + if (Utils.TimeDiff(current_, ts_flush_) >= 0) + { + return current_; + } + + int tm_flush = Utils.TimeDiff(ts_flush_, current_); + + foreach (Segment seg in snd_buf) + { + int diff = Utils.TimeDiff(seg.resendts, current_); + if (diff <= 0) + { + return current_; + } + if (diff < tm_packet) tm_packet = diff; + } + + uint minimal = (uint)(tm_packet < tm_flush ? tm_packet : tm_flush); + if (minimal >= interval) minimal = interval; + + return current_ + minimal; + } + + // ikcp_setmtu + // Change MTU (Maximum Transmission Unit) size. + public void SetMtu(uint mtu) + { + if (mtu < 50 || mtu < OVERHEAD) + throw new ArgumentException("MTU must be higher than 50 and higher than OVERHEAD"); + + buffer = new byte[(mtu + OVERHEAD) * 3]; + this.mtu = mtu; + mss = mtu - OVERHEAD; + } + + // ikcp_interval + public void SetInterval(uint interval) + { + // clamp interval between 10 and 5000 + if (interval > 5000) interval = 5000; + else if (interval < 10) interval = 10; + this.interval = interval; + } + + // ikcp_nodelay + // configuration: https://github.com/skywind3000/kcp/blob/master/README.en.md#protocol-configuration + // nodelay : Whether nodelay mode is enabled, 0 is not enabled; 1 enabled. + // interval :Protocol internal work interval, in milliseconds, such as 10 ms or 20 ms. + // resend :Fast retransmission mode, 0 represents off by default, 2 can be set (2 ACK spans will result in direct retransmission) + // nc :Whether to turn off flow control, 0 represents “Do not turn off” by default, 1 represents “Turn off”. + // Normal Mode: ikcp_nodelay(kcp, 0, 40, 0, 0); + // Turbo Mode: ikcp_nodelay(kcp, 1, 10, 2, 1); + public void SetNoDelay(uint nodelay, uint interval = INTERVAL, int resend = 0, bool nocwnd = false) + { + this.nodelay = nodelay; + if (nodelay != 0) + { + rx_minrto = RTO_NDL; + } + else + { + rx_minrto = RTO_MIN; + } + + if (interval >= 0) + { + // clamp interval between 10 and 5000 + if (interval > 5000) interval = 5000; + else if (interval < 10) interval = 10; + this.interval = interval; + } + + if (resend >= 0) + { + fastresend = resend; + } + + this.nocwnd = nocwnd; + } + + // ikcp_wndsize + public void SetWindowSize(uint sendWindow, uint receiveWindow) + { + if (sendWindow > 0) + { + snd_wnd = sendWindow; + } + + if (receiveWindow > 0) + { + // must >= max fragment size + rcv_wnd = Math.Max(receiveWindow, WND_RCV); + } + } + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/Kcp.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Kcp.cs.meta new file mode 100644 index 0000000..935b423 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Kcp.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a59b1cae10a334faf807432ab472f212 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/Pool.cs b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Pool.cs new file mode 100644 index 0000000..81b5289 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Pool.cs @@ -0,0 +1,46 @@ +// Pool to avoid allocations (from libuv2k & Mirror) +using System; +using System.Collections.Generic; + +namespace kcp2k +{ + public class Pool + { + // Mirror is single threaded, no need for concurrent collections + readonly Stack objects = new Stack(); + + // some types might need additional parameters in their constructor, so + // we use a Func generator + readonly Func objectGenerator; + + // some types might need additional cleanup for returned objects + readonly Action objectResetter; + + public Pool(Func objectGenerator, Action objectResetter, int initialCapacity) + { + this.objectGenerator = objectGenerator; + this.objectResetter = objectResetter; + + // allocate an initial pool so we have fewer (if any) + // allocations in the first few frames (or seconds). + for (int i = 0; i < initialCapacity; ++i) + objects.Push(objectGenerator()); + } + + // take an element from the pool, or create a new one if empty + public T Take() => objects.Count > 0 ? objects.Pop() : objectGenerator(); + + // return an element to the pool + public void Return(T item) + { + objectResetter(item); + objects.Push(item); + } + + // clear the pool + public void Clear() => objects.Clear(); + + // count to see how many objects are in the pool. useful for tests. + public int Count => objects.Count; + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/Pool.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Pool.cs.meta new file mode 100644 index 0000000..5eba0e0 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Pool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35c07818fc4784bb4ba472c8e5029002 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/Segment.cs b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Segment.cs new file mode 100644 index 0000000..d7e4131 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Segment.cs @@ -0,0 +1,78 @@ +using System.IO; + +namespace kcp2k +{ + // KCP Segment Definition + internal class Segment + { + internal uint conv; // conversation + internal uint cmd; // command, e.g. Kcp.CMD_ACK etc. + // fragment (sent as 1 byte). + // 0 if unfragmented, otherwise fragment numbers in reverse: N,..,32,1,0 + // this way the first received segment tells us how many fragments there are. + internal uint frg; + internal uint wnd; // window size that the receive can currently receive + internal uint ts; // timestamp + internal uint sn; // sequence number + internal uint una; + internal uint resendts; // resend timestamp + internal int rto; + internal uint fastack; + internal uint xmit; // retransmit count + + // we need an auto scaling byte[] with a WriteBytes function. + // MemoryStream does that perfectly, no need to reinvent the wheel. + // note: no need to pool it, because Segment is already pooled. + // -> default MTU as initial capacity to avoid most runtime resizing/allocations + // + // .data is only used for Encode(), which always fits it into a buffer. + // the buffer is always Kcp.buffer. Kcp ctor creates the buffer of size: + // (mtu + OVERHEAD) * 3 bytes. + // in other words, Encode only ever writes up to the above amount of bytes. + internal MemoryStream data = new MemoryStream(Kcp.MTU_DEF); + + // ikcp_encode_seg + // encode a segment into buffer. + // buffer is always Kcp.buffer. Kcp ctor creates the buffer of size: + // (mtu + OVERHEAD) * 3 bytes. + // in other words, Encode only ever writes up to the above amount of bytes. + internal int Encode(byte[] ptr, int offset) + { + int previousPosition = offset; + + offset += Utils.Encode32U(ptr, offset, conv); + offset += Utils.Encode8u(ptr, offset, (byte)cmd); + // IMPORTANT kcp encodes 'frg' as 1 byte. + // so we can only support up to 255 fragments. + // (which limits max message size to around 288 KB) + offset += Utils.Encode8u(ptr, offset, (byte)frg); + offset += Utils.Encode16U(ptr, offset, (ushort)wnd); + offset += Utils.Encode32U(ptr, offset, ts); + offset += Utils.Encode32U(ptr, offset, sn); + offset += Utils.Encode32U(ptr, offset, una); + offset += Utils.Encode32U(ptr, offset, (uint)data.Position); + + int written = offset - previousPosition; + return written; + } + + // reset to return a fresh segment to the pool + internal void Reset() + { + conv = 0; + cmd = 0; + frg = 0; + wnd = 0; + ts = 0; + sn = 0; + una = 0; + rto = 0; + xmit = 0; + resendts = 0; + fastack = 0; + + // keep buffer for next pool usage, but reset length (= bytes written) + data.SetLength(0); + } + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/Segment.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Segment.cs.meta new file mode 100644 index 0000000..d14dc1a --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Segment.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fc58706a05dd3442c8fde858d5266855 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/Utils.cs b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Utils.cs new file mode 100644 index 0000000..2cb7462 --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Utils.cs @@ -0,0 +1,76 @@ +using System.Runtime.CompilerServices; + +namespace kcp2k +{ + public static partial class Utils + { + // Clamp so we don't have to depend on UnityEngine + public static int Clamp(int value, int min, int max) + { + if (value < min) return min; + if (value > max) return max; + return value; + } + + // encode 8 bits unsigned int + public static int Encode8u(byte[] p, int offset, byte value) + { + p[0 + offset] = value; + return 1; + } + + // decode 8 bits unsigned int + public static int Decode8u(byte[] p, int offset, out byte value) + { + value = p[0 + offset]; + return 1; + } + + // encode 16 bits unsigned int (lsb) + public static int Encode16U(byte[] p, int offset, ushort value) + { + p[0 + offset] = (byte)(value >> 0); + p[1 + offset] = (byte)(value >> 8); + return 2; + } + + // decode 16 bits unsigned int (lsb) + public static int Decode16U(byte[] p, int offset, out ushort value) + { + ushort result = 0; + result |= p[0 + offset]; + result |= (ushort)(p[1 + offset] << 8); + value = result; + return 2; + } + + // encode 32 bits unsigned int (lsb) + public static int Encode32U(byte[] p, int offset, uint value) + { + p[0 + offset] = (byte)(value >> 0); + p[1 + offset] = (byte)(value >> 8); + p[2 + offset] = (byte)(value >> 16); + p[3 + offset] = (byte)(value >> 24); + return 4; + } + + // decode 32 bits unsigned int (lsb) + public static int Decode32U(byte[] p, int offset, out uint value) + { + uint result = 0; + result |= p[0 + offset]; + result |= (uint)(p[1 + offset] << 8); + result |= (uint)(p[2 + offset] << 16); + result |= (uint)(p[3 + offset] << 24); + value = result; + return 4; + } + + // timediff was a macro in original Kcp. let's inline it if possible. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int TimeDiff(uint later, uint earlier) + { + return (int)(later - earlier); + } + } +} diff --git a/Assets/Mirror/Transports/KCP/kcp2k/kcp/Utils.cs.meta b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Utils.cs.meta new file mode 100644 index 0000000..86118bc --- /dev/null +++ b/Assets/Mirror/Transports/KCP/kcp2k/kcp/Utils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ef959eb716205bd48b050f010a9a35ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Latency.meta b/Assets/Mirror/Transports/Latency.meta new file mode 100644 index 0000000..07d138e --- /dev/null +++ b/Assets/Mirror/Transports/Latency.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 397bb578e2bb049ebac1e29effa9d298 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Latency/LatencySimulation.cs b/Assets/Mirror/Transports/Latency/LatencySimulation.cs new file mode 100644 index 0000000..af819f1 --- /dev/null +++ b/Assets/Mirror/Transports/Latency/LatencySimulation.cs @@ -0,0 +1,319 @@ +// wraps around a transport and adds latency/loss/scramble simulation. +// +// reliable: latency +// unreliable: latency, loss, scramble (unreliable isn't ordered so we scramble) +// +// IMPORTANT: use Time.unscaledTime instead of Time.time. +// some games might have Time.timeScale modified. +// see also: https://github.com/vis2k/Mirror/issues/2907 +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Serialization; + +namespace Mirror +{ + struct QueuedMessage + { + public int connectionId; + public byte[] bytes; + public double time; + } + + [HelpURL("https://mirror-networking.gitbook.io/docs/transports/latency-simulaton-transport")] + [DisallowMultipleComponent] + public class LatencySimulation : Transport + { + public Transport wrap; + + [Header("Common")] + [Tooltip("Jitter latency via perlin(Time * jitterSpeed) * jitter")] + [FormerlySerializedAs("latencySpikeMultiplier")] + [Range(0, 1)] public float jitter = 0.02f; + [Tooltip("Jitter latency via perlin(Time * jitterSpeed) * jitter")] + [FormerlySerializedAs("latencySpikeSpeedMultiplier")] + public float jitterSpeed = 1; + + [Header("Reliable Messages")] + [Tooltip("Reliable latency in milliseconds (1000 = 1 second)")] + [Range(0, 10000)] public float reliableLatency = 100; + // note: packet loss over reliable manifests itself in latency. + // don't need (and can't add) a loss option here. + // note: reliable is ordered by definition. no need to scramble. + + [Header("Unreliable Messages")] + [Tooltip("Packet loss in %\n2% recommended for long term play testing, upto 5% for short bursts.\nAnything higher, or for a prolonged amount of time, suggests user has a connection fault.")] + [Range(0, 100)] public float unreliableLoss = 2; + [Tooltip("Unreliable latency in milliseconds (1000 = 1 second) \n100ms recommended for long term play testing, upto 500ms for short bursts.\nAnything higher, or for a prolonged amount of time, suggests user has a connection fault.")] + [Range(0, 10000)] public float unreliableLatency = 100; + [Tooltip("Scramble % of unreliable messages, just like over the real network. Mirror unreliable is unordered.")] + [Range(0, 100)] public float unreliableScramble = 2; + + // message queues + // list so we can insert randomly (scramble) + List reliableClientToServer = new List(); + List reliableServerToClient = new List(); + List unreliableClientToServer = new List(); + List unreliableServerToClient = new List(); + + // random + // UnityEngine.Random.value is [0, 1] with both upper and lower bounds inclusive + // but we need the upper bound to be exclusive, so using System.Random instead. + // => NextDouble() is NEVER < 0 so loss=0 never drops! + // => NextDouble() is ALWAYS < 1 so loss=1 always drops! + System.Random random = new System.Random(); + + public void Awake() + { + if (wrap == null) + throw new Exception("LatencySimulationTransport requires an underlying transport to wrap around."); + } + + // forward enable/disable to the wrapped transport + void OnEnable() { wrap.enabled = true; } + void OnDisable() { wrap.enabled = false; } + + // noise function can be replaced if needed + protected virtual float Noise(float time) => Mathf.PerlinNoise(time, time); + + // helper function to simulate latency + float SimulateLatency(int channeldId) + { + // spike over perlin noise. + // no spikes isn't realistic. + // sin is too predictable / no realistic. + // perlin is still deterministic and random enough. +#if !UNITY_2020_3_OR_NEWER + float spike = Noise((float)NetworkTime.localTime * jitterSpeed) * jitter; +#else + float spike = Noise((float)Time.unscaledTimeAsDouble * jitterSpeed) * jitter; +#endif + + // base latency + switch (channeldId) + { + case Channels.Reliable: + return reliableLatency/1000 + spike; + case Channels.Unreliable: + return unreliableLatency/1000 + spike; + default: + return 0; + } + } + + // helper function to simulate a send with latency/loss/scramble + void SimulateSend( + int connectionId, + ArraySegment segment, + int channelId, + float latency, + List reliableQueue, + List unreliableQueue) + { + // segment is only valid after returning. copy it. + // (allocates for now. it's only for testing anyway.) + byte[] bytes = new byte[segment.Count]; + Buffer.BlockCopy(segment.Array, segment.Offset, bytes, 0, segment.Count); + + // enqueue message. send after latency interval. + QueuedMessage message = new QueuedMessage + { + connectionId = connectionId, + bytes = bytes, +#if !UNITY_2020_3_OR_NEWER + time = NetworkTime.localTime + latency +#else + time = Time.unscaledTimeAsDouble + latency +#endif + }; + + switch (channelId) + { + case Channels.Reliable: + // simulate latency + reliableQueue.Add(message); + break; + case Channels.Unreliable: + // simulate packet loss + bool drop = random.NextDouble() < unreliableLoss/100; + if (!drop) + { + // simulate scramble (Random.Next is < max, so +1) + bool scramble = random.NextDouble() < unreliableScramble/100; + int last = unreliableQueue.Count; + int index = scramble ? random.Next(0, last + 1) : last; + + // simulate latency + unreliableQueue.Insert(index, message); + } + break; + default: + Debug.LogError($"{nameof(LatencySimulation)} unexpected channelId: {channelId}"); + break; + } + } + + public override bool Available() => wrap.Available(); + + public override void ClientConnect(string address) + { + wrap.OnClientConnected = OnClientConnected; + wrap.OnClientDataReceived = OnClientDataReceived; + wrap.OnClientError = OnClientError; + wrap.OnClientDisconnected = OnClientDisconnected; + wrap.ClientConnect(address); + } + + public override void ClientConnect(Uri uri) + { + wrap.OnClientConnected = OnClientConnected; + wrap.OnClientDataReceived = OnClientDataReceived; + wrap.OnClientError = OnClientError; + wrap.OnClientDisconnected = OnClientDisconnected; + wrap.ClientConnect(uri); + } + + public override bool ClientConnected() => wrap.ClientConnected(); + + public override void ClientDisconnect() + { + wrap.ClientDisconnect(); + reliableClientToServer.Clear(); + unreliableClientToServer.Clear(); + } + + public override void ClientSend(ArraySegment segment, int channelId) + { + float latency = SimulateLatency(channelId); + SimulateSend(0, segment, channelId, latency, reliableClientToServer, unreliableClientToServer); + } + + public override Uri ServerUri() => wrap.ServerUri(); + + public override bool ServerActive() => wrap.ServerActive(); + + public override string ServerGetClientAddress(int connectionId) => wrap.ServerGetClientAddress(connectionId); + + public override void ServerDisconnect(int connectionId) => wrap.ServerDisconnect(connectionId); + + public override void ServerSend(int connectionId, ArraySegment segment, int channelId) + { + float latency = SimulateLatency(channelId); + SimulateSend(connectionId, segment, channelId, latency, reliableServerToClient, unreliableServerToClient); + } + + public override void ServerStart() + { + wrap.OnServerConnected = OnServerConnected; + wrap.OnServerDataReceived = OnServerDataReceived; + wrap.OnServerError = OnServerError; + wrap.OnServerDisconnected = OnServerDisconnected; + wrap.ServerStart(); + } + + public override void ServerStop() + { + wrap.ServerStop(); + reliableServerToClient.Clear(); + unreliableServerToClient.Clear(); + } + + public override void ClientEarlyUpdate() => wrap.ClientEarlyUpdate(); + public override void ServerEarlyUpdate() => wrap.ServerEarlyUpdate(); + public override void ClientLateUpdate() + { + // flush reliable messages after latency. + // need to iterate all, since queue isn't a sortedlist. + for (int i = 0; i < reliableClientToServer.Count; ++i) + { + // message ready to be sent? + QueuedMessage message = reliableClientToServer[i]; +#if !UNITY_2020_3_OR_NEWER + if (message.time <= NetworkTime.localTime) +#else + if (message.time <= Time.unscaledTimeAsDouble) +#endif + { + // send and eat + wrap.ClientSend(new ArraySegment(message.bytes), Channels.Reliable); + reliableClientToServer.RemoveAt(i); + --i; + } + } + + // flush unreliable messages after latency. + // need to iterate all, since queue isn't a sortedlist. + for (int i = 0; i < unreliableClientToServer.Count; ++i) + { + // message ready to be sent? + QueuedMessage message = unreliableClientToServer[i]; +#if !UNITY_2020_3_OR_NEWER + if (message.time <= NetworkTime.localTime) +#else + if (message.time <= Time.unscaledTimeAsDouble) +#endif + { + // send and eat + wrap.ClientSend(new ArraySegment(message.bytes), Channels.Reliable); + unreliableClientToServer.RemoveAt(i); + --i; + } + } + + // update wrapped transport too + wrap.ClientLateUpdate(); + } + public override void ServerLateUpdate() + { + + // flush reliable messages after latency. + // need to iterate all, since queue isn't a sortedlist. + for (int i = 0; i < reliableServerToClient.Count; ++i) + { + // message ready to be sent? + QueuedMessage message = reliableServerToClient[i]; +#if !UNITY_2020_3_OR_NEWER + if (message.time <= NetworkTime.localTime) +#else + if (message.time <= Time.unscaledTimeAsDouble) +#endif + { + // send and eat + wrap.ServerSend(message.connectionId, new ArraySegment(message.bytes), Channels.Reliable); + reliableServerToClient.RemoveAt(i); + --i; + } + } + + + // flush unreliable messages after latency. + // need to iterate all, since queue isn't a sortedlist. + for (int i = 0; i < unreliableServerToClient.Count; ++i) + { + // message ready to be sent? + QueuedMessage message = unreliableServerToClient[i]; +#if !UNITY_2020_3_OR_NEWER + if (message.time <= NetworkTime.localTime) +#else + if (message.time <= Time.unscaledTimeAsDouble) +#endif + { + // send and eat + wrap.ServerSend(message.connectionId, new ArraySegment(message.bytes), Channels.Reliable); + unreliableServerToClient.RemoveAt(i); + --i; + } + } + + // update wrapped transport too + wrap.ServerLateUpdate(); + } + + public override int GetBatchThreshold(int channelId) => wrap.GetBatchThreshold(channelId); + public override int GetMaxPacketSize(int channelId = 0) => wrap.GetMaxPacketSize(channelId); + + public override void Shutdown() => wrap.Shutdown(); + + public override string ToString() => $"{nameof(LatencySimulation)} {wrap}"; + } +} diff --git a/Assets/Mirror/Transports/Latency/LatencySimulation.cs.meta b/Assets/Mirror/Transports/Latency/LatencySimulation.cs.meta new file mode 100644 index 0000000..eabbe4a --- /dev/null +++ b/Assets/Mirror/Transports/Latency/LatencySimulation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 96b149f511061407fb54895c057b7736 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Middleware.meta b/Assets/Mirror/Transports/Middleware.meta new file mode 100644 index 0000000..3038832 --- /dev/null +++ b/Assets/Mirror/Transports/Middleware.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 69344c174fdaf432e9ff0cdaf2e2ba21 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Middleware/MiddlewareTransport.cs b/Assets/Mirror/Transports/Middleware/MiddlewareTransport.cs new file mode 100644 index 0000000..7dd934a --- /dev/null +++ b/Assets/Mirror/Transports/Middleware/MiddlewareTransport.cs @@ -0,0 +1,61 @@ +using System; +using UnityEngine; + +namespace Mirror +{ + ///

+ /// Allows Middleware to override some of the transport methods or let the inner transport handle them. + /// + [DisallowMultipleComponent] + public abstract class MiddlewareTransport : Transport + { + /// + /// Transport to call to after middleware + /// + public Transport inner; + + public override bool Available() => inner.Available(); + public override int GetMaxPacketSize(int channelId = 0) => inner.GetMaxPacketSize(channelId); + public override int GetBatchThreshold(int channelId = Channels.Reliable) => inner.GetBatchThreshold(channelId); + public override void Shutdown() => inner.Shutdown(); + + #region Client + public override void ClientConnect(string address) + { + inner.OnClientConnected = OnClientConnected; + inner.OnClientDataReceived = OnClientDataReceived; + inner.OnClientDisconnected = OnClientDisconnected; + inner.OnClientError = OnClientError; + inner.ClientConnect(address); + } + + public override bool ClientConnected() => inner.ClientConnected(); + public override void ClientDisconnect() => inner.ClientDisconnect(); + public override void ClientSend(ArraySegment segment, int channelId) => inner.ClientSend(segment, channelId); + + public override void ClientEarlyUpdate() => inner.ClientEarlyUpdate(); + public override void ClientLateUpdate() => inner.ClientLateUpdate(); + #endregion + + #region Server + public override bool ServerActive() => inner.ServerActive(); + public override void ServerStart() + { + inner.OnServerConnected = OnServerConnected; + inner.OnServerDataReceived = OnServerDataReceived; + inner.OnServerDisconnected = OnServerDisconnected; + inner.OnServerError = OnServerError; + inner.ServerStart(); + } + + public override void ServerStop() => inner.ServerStop(); + public override void ServerSend(int connectionId, ArraySegment segment, int channelId) => inner.ServerSend(connectionId, segment, channelId); + public override void ServerDisconnect(int connectionId) => inner.ServerDisconnect(connectionId); + public override string ServerGetClientAddress(int connectionId) => inner.ServerGetClientAddress(connectionId); + public override Uri ServerUri() => inner.ServerUri(); + + public override void ServerEarlyUpdate() => inner.ServerEarlyUpdate(); + public override void ServerLateUpdate() => inner.ServerLateUpdate(); + #endregion + } +} diff --git a/Assets/Mirror/Transports/Middleware/MiddlewareTransport.cs.meta b/Assets/Mirror/Transports/Middleware/MiddlewareTransport.cs.meta new file mode 100644 index 0000000..dce8378 --- /dev/null +++ b/Assets/Mirror/Transports/Middleware/MiddlewareTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46f20ede74658e147a1af57172710de2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Mirror.Transports.asmdef b/Assets/Mirror/Transports/Mirror.Transports.asmdef new file mode 100644 index 0000000..3a67a0a --- /dev/null +++ b/Assets/Mirror/Transports/Mirror.Transports.asmdef @@ -0,0 +1,19 @@ +{ + "name": "Mirror.Transports", + "rootNamespace": "", + "references": [ + "GUID:30817c1a0e6d646d99c048fc403f5979", + "GUID:6806a62c384838046a3c66c44f06d75f", + "GUID:725ee7191c021de4dbf9269590ded755", + "GUID:3b5390adca4e2bb4791cb930316d6f3e" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/Mirror.Transports.asmdef.meta b/Assets/Mirror/Transports/Mirror.Transports.asmdef.meta new file mode 100644 index 0000000..d180ef1 --- /dev/null +++ b/Assets/Mirror/Transports/Mirror.Transports.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 627104647b9c04b4ebb8978a92ecac63 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Multiplex.meta b/Assets/Mirror/Transports/Multiplex.meta new file mode 100644 index 0000000..59c257e --- /dev/null +++ b/Assets/Mirror/Transports/Multiplex.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 28d5150129fea43048bbdd23ea6e2446 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Multiplex/MultiplexTransport.cs b/Assets/Mirror/Transports/Multiplex/MultiplexTransport.cs new file mode 100644 index 0000000..0797e7a --- /dev/null +++ b/Assets/Mirror/Transports/Multiplex/MultiplexTransport.cs @@ -0,0 +1,331 @@ +using System; +using System.Collections.Generic; +using System.Text; +using UnityEngine; + +namespace Mirror +{ + // a transport that can listen to multiple underlying transport at the same time + [DisallowMultipleComponent] + public class MultiplexTransport : Transport + { + public Transport[] transports; + + Transport available; + + // underlying transport connectionId to multiplexed connectionId lookup. + // + // originally we used a formula to map the connectionId: + // connectionId * transportAmount + transportId + // + // if we have 3 transports, then + // transport 0 will produce connection ids [0, 3, 6, 9, ...] + // transport 1 will produce connection ids [1, 4, 7, 10, ...] + // transport 2 will produce connection ids [2, 5, 8, 11, ...] + // + // however, some transports like kcp may give very large connectionIds. + // if they are near int.max, then "* transprotAmount + transportIndex" + // will overflow, resulting in connIds which can't be projected back. + // https://github.com/vis2k/Mirror/issues/3280 + // + // instead, use a simple lookup with 0-indexed ids. + // with initial capacity to avoid runtime allocations. + + // (original connectionId, transport#) to multiplexed connectionId + readonly Dictionary, int> originalToMultiplexedId = + new Dictionary, int>(100); + + // multiplexed connectionId to (original connectionId, transport#) + readonly Dictionary> multiplexedToOriginalId = + new Dictionary>(100); + + // next multiplexed id counter. start at 1 because 0 is reserved for host. + int nextMultiplexedId = 1; + + // add to bidirection lookup. returns the multiplexed connectionId. + public int AddToLookup(int originalConnectionId, int transportIndex) + { + // add to both + KeyValuePair pair = new KeyValuePair(originalConnectionId, transportIndex); + int multiplexedId = nextMultiplexedId++; + + originalToMultiplexedId[pair] = multiplexedId; + multiplexedToOriginalId[multiplexedId] = pair; + + return multiplexedId; + } + + public void RemoveFromLookup(int originalConnectionId, int transportIndex) + { + // remove from both + KeyValuePair pair = new KeyValuePair(originalConnectionId, transportIndex); + int multiplexedId = originalToMultiplexedId[pair]; + + originalToMultiplexedId.Remove(pair); + multiplexedToOriginalId.Remove(multiplexedId); + } + + public void OriginalId(int multiplexId, out int originalConnectionId, out int transportIndex) + { + KeyValuePair pair = multiplexedToOriginalId[multiplexId]; + originalConnectionId = pair.Key; + transportIndex = pair.Value; + } + + public int MultiplexId(int originalConnectionId, int transportIndex) + { + KeyValuePair pair = new KeyValuePair(originalConnectionId, transportIndex); + return originalToMultiplexedId[pair]; + } + + //////////////////////////////////////////////////////////////////////// + + public void Awake() + { + if (transports == null || transports.Length == 0) + { + Debug.LogError("[Multiplexer] Multiplex transport requires at least 1 underlying transport"); + } + } + + public override void ClientEarlyUpdate() + { + foreach (Transport transport in transports) + transport.ClientEarlyUpdate(); + } + + public override void ServerEarlyUpdate() + { + foreach (Transport transport in transports) + transport.ServerEarlyUpdate(); + } + + public override void ClientLateUpdate() + { + foreach (Transport transport in transports) + transport.ClientLateUpdate(); + } + + public override void ServerLateUpdate() + { + foreach (Transport transport in transports) + transport.ServerLateUpdate(); + } + + void OnEnable() + { + foreach (Transport transport in transports) + transport.enabled = true; + } + + void OnDisable() + { + foreach (Transport transport in transports) + transport.enabled = false; + } + + public override bool Available() + { + // available if any of the transports is available + foreach (Transport transport in transports) + if (transport.Available()) + return true; + + return false; + } + + #region Client + + public override void ClientConnect(string address) + { + foreach (Transport transport in transports) + { + if (transport.Available()) + { + available = transport; + transport.OnClientConnected = OnClientConnected; + transport.OnClientDataReceived = OnClientDataReceived; + transport.OnClientError = OnClientError; + transport.OnClientDisconnected = OnClientDisconnected; + transport.ClientConnect(address); + return; + } + } + throw new ArgumentException("[Multiplexer] No transport suitable for this platform"); + } + + public override void ClientConnect(Uri uri) + { + foreach (Transport transport in transports) + { + if (transport.Available()) + { + try + { + available = transport; + transport.OnClientConnected = OnClientConnected; + transport.OnClientDataReceived = OnClientDataReceived; + transport.OnClientError = OnClientError; + transport.OnClientDisconnected = OnClientDisconnected; + transport.ClientConnect(uri); + return; + } + catch (ArgumentException) + { + // transport does not support the schema, just move on to the next one + } + } + } + throw new ArgumentException("[Multiplexer] No transport suitable for this platform"); + } + + public override bool ClientConnected() + { + return (object)available != null && available.ClientConnected(); + } + + public override void ClientDisconnect() + { + if ((object)available != null) + available.ClientDisconnect(); + } + + public override void ClientSend(ArraySegment segment, int channelId) + { + available.ClientSend(segment, channelId); + } + + #endregion + + #region Server + void AddServerCallbacks() + { + // all underlying transports should call the multiplex transport's events + for (int i = 0; i < transports.Length; i++) + { + // this is required for the handlers, if I use i directly + // then all the handlers will use the last i + int transportIndex = i; + Transport transport = transports[i]; + + transport.OnServerConnected = (originalConnectionId => + { + // invoke Multiplex event with multiplexed connectionId + int multiplexedId = AddToLookup(originalConnectionId, transportIndex); + OnServerConnected.Invoke(multiplexedId); + }); + + transport.OnServerDataReceived = (originalConnectionId, data, channel) => + { + // invoke Multiplex event with multiplexed connectionId + int multiplexedId = MultiplexId(originalConnectionId, transportIndex); + OnServerDataReceived.Invoke(multiplexedId, data, channel); + }; + + transport.OnServerError = (originalConnectionId, error, reason) => + { + // invoke Multiplex event with multiplexed connectionId + int multiplexedId = MultiplexId(originalConnectionId, transportIndex); + OnServerError.Invoke(multiplexedId, error, reason); + }; + + transport.OnServerDisconnected = originalConnectionId => + { + // invoke Multiplex event with multiplexed connectionId + int multiplexedId = MultiplexId(originalConnectionId, transportIndex); + OnServerDisconnected.Invoke(multiplexedId); + RemoveFromLookup(originalConnectionId, transportIndex); + }; + } + } + + // for now returns the first uri, + // should we return all available uris? + public override Uri ServerUri() => + transports[0].ServerUri(); + + public override bool ServerActive() + { + // avoid Linq.All allocations + foreach (Transport transport in transports) + if (!transport.ServerActive()) + return false; + + return true; + } + + public override string ServerGetClientAddress(int connectionId) + { + // convert multiplexed connectionId to original id & transport index + OriginalId(connectionId, out int originalConnectionId, out int transportIndex); + return transports[transportIndex].ServerGetClientAddress(originalConnectionId); + } + + public override void ServerDisconnect(int connectionId) + { + // convert multiplexed connectionId to original id & transport index + OriginalId(connectionId, out int originalConnectionId, out int transportIndex); + transports[transportIndex].ServerDisconnect(originalConnectionId); + } + + public override void ServerSend(int connectionId, ArraySegment segment, int channelId) + { + // convert multiplexed connectionId to original transport + connId + OriginalId(connectionId, out int originalConnectionId, out int transportIndex); + transports[transportIndex].ServerSend(originalConnectionId, segment, channelId); + } + + public override void ServerStart() + { + AddServerCallbacks(); + + foreach (Transport transport in transports) + transport.ServerStart(); + } + + public override void ServerStop() + { + foreach (Transport transport in transports) + transport.ServerStop(); + } + #endregion + + public override int GetMaxPacketSize(int channelId = 0) + { + // finding the max packet size in a multiplex environment has to be + // done very carefully: + // * servers run multiple transports at the same time + // * different clients run different transports + // * there should only ever be ONE true max packet size for everyone, + // otherwise a spawn message might be sent to all tcp sockets, but + // be too big for some udp sockets. that would be a debugging + // nightmare and allow for possible exploits and players on + // different platforms seeing a different game state. + // => the safest solution is to use the smallest max size for all + // transports. that will never fail. + int mininumAllowedSize = int.MaxValue; + foreach (Transport transport in transports) + { + int size = transport.GetMaxPacketSize(channelId); + mininumAllowedSize = Mathf.Min(size, mininumAllowedSize); + } + return mininumAllowedSize; + } + + public override void Shutdown() + { + foreach (Transport transport in transports) + transport.Shutdown(); + } + + public override string ToString() + { + StringBuilder builder = new StringBuilder(); + + foreach (Transport transport in transports) + builder.AppendLine(transport.ToString()); + + return builder.ToString().Trim(); + } + } +} diff --git a/Assets/Mirror/Transports/Multiplex/MultiplexTransport.cs.meta b/Assets/Mirror/Transports/Multiplex/MultiplexTransport.cs.meta new file mode 100644 index 0000000..6e97b28 --- /dev/null +++ b/Assets/Mirror/Transports/Multiplex/MultiplexTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 929e3234c7db540b899f00183fc2b1fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb.meta b/Assets/Mirror/Transports/SimpleWeb.meta new file mode 100644 index 0000000..5baa80f --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a3ba68af305d809418d6c6a804939290 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb.meta new file mode 100644 index 0000000..c2852a8 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8ae237a052b29fc4b8d000f48e545bb7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/AssemblyInfo.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/AssemblyInfo.cs new file mode 100644 index 0000000..c0df7fe --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/AssemblyInfo.cs @@ -0,0 +1,7 @@ +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyVersion("1.6.0")] + +[assembly: InternalsVisibleTo("SimpleWebTransport.Tests.Runtime")] +[assembly: InternalsVisibleTo("SimpleWebTransport.Tests.Editor")] diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/AssemblyInfo.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/AssemblyInfo.cs.meta new file mode 100644 index 0000000..028a307 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ee9e76201f7665244bd6ab8ea343a83f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/CHANGELOG.md b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/CHANGELOG.md new file mode 100644 index 0000000..d98f014 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/CHANGELOG.md @@ -0,0 +1,48 @@ +# [1.3.0](https://github.com/James-Frowen/SimpleWebTransport/compare/v1.2.7...v1.3.0) (2022-02-12) + + +### Features + +* Allowing max message size to be increase to int32.max ([#2](https://github.com/James-Frowen/SimpleWebTransport/issues/2)) ([4cc60fd](https://github.com/James-Frowen/SimpleWebTransport/commit/4cc60fd67f3c65d90ced0e6f9f97d15d0368076d)) + +## [1.2.7](https://github.com/James-Frowen/SimpleWebTransport/compare/v1.2.6...v1.2.7) (2022-02-12) + + +### Bug Fixes + +* fixing ObjectDisposedException in toString ([426de52](https://github.com/James-Frowen/SimpleWebTransport/commit/426de52ee4e98ac6212713b2b2272e3affb8fc99)) + +## [1.2.6](https://github.com/James-Frowen/SimpleWebTransport/compare/v1.2.5...v1.2.6) (2022-02-02) + + +### Bug Fixes + +* fixing Runtime is not defined for unity 2021 ([945b50d](https://github.com/James-Frowen/SimpleWebTransport/commit/945b50dbad5b71c43e2bdaa4033f87d3f62c5572)) + +## [1.2.5](https://github.com/James-Frowen/SimpleWebTransport/compare/v1.2.4...v1.2.5) (2022-02-02) + + +### Bug Fixes + +* updating Pointer_stringify to UTF8ToString ([2f5a74b](https://github.com/James-Frowen/SimpleWebTransport/commit/2f5a74ba10865e934be8d3b54ebfdeb14ca491f6)) + +## [1.2.4](https://github.com/James-Frowen/SimpleWebTransport/compare/v1.2.3...v1.2.4) (2021-12-16) + + +### Bug Fixes + +* adding meta file for changelog ([ba5b164](https://github.com/James-Frowen/SimpleWebTransport/commit/ba5b1647aa5cc69ca80f5b52c542a9b5ee749c7f)) + +## [1.2.3](https://github.com/James-Frowen/SimpleWebTransport/compare/v1.2.2...v1.2.3) (2021-12-16) + + +### Bug Fixes + +* fixing compile error in assemblyInfo ([7ee8380](https://github.com/James-Frowen/SimpleWebTransport/commit/7ee8380b4daf34d4e12017de55d8be481690046f)) + +## [1.2.2](https://github.com/James-Frowen/SimpleWebTransport/compare/v1.2.1...v1.2.2) (2021-12-16) + + +### Bug Fixes + +* fixing release with empty commit ([068af74](https://github.com/James-Frowen/SimpleWebTransport/commit/068af74f7399354081f25181f90fb060b0fa1524)) diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/CHANGELOG.md.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/CHANGELOG.md.meta new file mode 100644 index 0000000..bc43099 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/CHANGELOG.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b0ef23ac1c6a62546bbad5529b3bfdad +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client.meta new file mode 100644 index 0000000..e6e2943 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5faa957b8d9fc314ab7596ccf14750d9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/SimpleWebClient.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/SimpleWebClient.cs new file mode 100644 index 0000000..7732cd5 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/SimpleWebClient.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Concurrent; +using UnityEngine; + +namespace Mirror.SimpleWeb +{ + public enum ClientState + { + NotConnected = 0, + Connecting = 1, + Connected = 2, + Disconnecting = 3, + } + + /// + /// Client used to control websockets + /// Base class used by WebSocketClientWebGl and WebSocketClientStandAlone + /// + public abstract class SimpleWebClient + { + public static SimpleWebClient Create(int maxMessageSize, int maxMessagesPerTick, TcpConfig tcpConfig) + { +#if UNITY_WEBGL && !UNITY_EDITOR + return new WebSocketClientWebGl(maxMessageSize, maxMessagesPerTick); +#else + return new WebSocketClientStandAlone(maxMessageSize, maxMessagesPerTick, tcpConfig); +#endif + } + + readonly int maxMessagesPerTick; + protected readonly int maxMessageSize; + public readonly ConcurrentQueue receiveQueue = new ConcurrentQueue(); + protected readonly BufferPool bufferPool; + + protected ClientState state; + + protected SimpleWebClient(int maxMessageSize, int maxMessagesPerTick) + { + this.maxMessageSize = maxMessageSize; + this.maxMessagesPerTick = maxMessagesPerTick; + bufferPool = new BufferPool(5, 20, maxMessageSize); + } + + public ClientState ConnectionState => state; + + public event Action onConnect; + public event Action onDisconnect; + public event Action> onData; + public event Action onError; + + /// + /// Processes all new messages + /// + public void ProcessMessageQueue() + { + ProcessMessageQueue(null); + } + + /// + /// Processes all messages while is enabled + /// + /// + public void ProcessMessageQueue(MonoBehaviour behaviour) + { + int processedCount = 0; + bool skipEnabled = behaviour == null; + // check enabled every time in case behaviour was disabled after data + while ( + (skipEnabled || behaviour.enabled) && + processedCount < maxMessagesPerTick && + // Dequeue last + receiveQueue.TryDequeue(out Message next) + ) + { + processedCount++; + + switch (next.type) + { + case EventType.Connected: + onConnect?.Invoke(); + break; + case EventType.Data: + onData?.Invoke(next.data.ToSegment()); + next.data.Release(); + break; + case EventType.Disconnected: + onDisconnect?.Invoke(); + break; + case EventType.Error: + onError?.Invoke(next.exception); + break; + } + } + if (receiveQueue.Count > 0) + Debug.LogWarning($"SimpleWebClient ProcessMessageQueue has {receiveQueue.Count} remaining."); + } + + public abstract void Connect(Uri serverAddress); + public abstract void Disconnect(); + public abstract void Send(ArraySegment segment); + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/SimpleWebClient.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/SimpleWebClient.cs.meta new file mode 100644 index 0000000..90c361b --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/SimpleWebClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 13131761a0bf5a64dadeccd700fe26e5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone.meta new file mode 100644 index 0000000..bf320c6 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a9c19d05220a87c4cbbe4d1e422da0aa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientHandshake.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientHandshake.cs new file mode 100644 index 0000000..666f25b --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientHandshake.cs @@ -0,0 +1,88 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Mirror.SimpleWeb +{ + /// + /// Handles Handshake to the server when it first connects + /// The client handshake does not need buffers to reduce allocations since it only happens once + /// + internal class ClientHandshake + { + public bool TryHandshake(Connection conn, Uri uri) + { + try + { + Stream stream = conn.stream; + + byte[] keyBuffer = new byte[16]; + using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) + rng.GetBytes(keyBuffer); + + string key = Convert.ToBase64String(keyBuffer); + string keySum = key + Constants.HandshakeGUID; + byte[] keySumBytes = Encoding.ASCII.GetBytes(keySum); + Log.Verbose($"[SimpleWebTransport] Handshake Hashing {Encoding.ASCII.GetString(keySumBytes)}"); + + // SHA-1 is the websocket standard: + // https://www.rfc-editor.org/rfc/rfc6455 + // we should follow the standard, even though SHA1 is considered weak: + // https://stackoverflow.com/questions/38038841/why-is-sha-1-considered-insecure + byte[] keySumHash = SHA1.Create().ComputeHash(keySumBytes); + + string expectedResponse = Convert.ToBase64String(keySumHash); + string handshake = + $"GET {uri.PathAndQuery} HTTP/1.1\r\n" + + $"Host: {uri.Host}:{uri.Port}\r\n" + + $"Upgrade: websocket\r\n" + + $"Connection: Upgrade\r\n" + + $"Sec-WebSocket-Key: {key}\r\n" + + $"Sec-WebSocket-Version: 13\r\n" + + "\r\n"; + byte[] encoded = Encoding.ASCII.GetBytes(handshake); + stream.Write(encoded, 0, encoded.Length); + + byte[] responseBuffer = new byte[1000]; + + int? lengthOrNull = ReadHelper.SafeReadTillMatch(stream, responseBuffer, 0, responseBuffer.Length, Constants.endOfHandshake); + + if (!lengthOrNull.HasValue) + { + Log.Error("[SimpleWebTransport] Connection closed before handshake"); + return false; + } + + string responseString = Encoding.ASCII.GetString(responseBuffer, 0, lengthOrNull.Value); + Log.Verbose($"[SimpleWebTransport] Handshake Response {responseString}"); + + string acceptHeader = "Sec-WebSocket-Accept: "; + int startIndex = responseString.IndexOf(acceptHeader, StringComparison.InvariantCultureIgnoreCase); + + if (startIndex < 0) + { + Log.Error($"[SimpleWebTransport] Unexpected Handshake Response {responseString}"); + return false; + } + + startIndex += acceptHeader.Length; + int endIndex = responseString.IndexOf("\r\n", startIndex); + string responseKey = responseString.Substring(startIndex, endIndex - startIndex); + + if (responseKey != expectedResponse) + { + Log.Error($"[SimpleWebTransport] Response key incorrect\nResponse:{responseKey}\nExpected:{expectedResponse}"); + return false; + } + + return true; + } + catch (Exception e) + { + Log.Exception(e); + return false; + } + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientHandshake.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientHandshake.cs.meta new file mode 100644 index 0000000..ad3d40d --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientHandshake.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3ffdcabc9e28f764a94fc4efc82d3e8b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientSslHelper.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientSslHelper.cs new file mode 100644 index 0000000..78ce2bb --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientSslHelper.cs @@ -0,0 +1,47 @@ +using System; +using System.IO; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Cryptography.X509Certificates; + +namespace Mirror.SimpleWeb +{ + internal class ClientSslHelper + { + internal bool TryCreateStream(Connection conn, Uri uri) + { + NetworkStream stream = conn.client.GetStream(); + if (uri.Scheme != "wss") + { + conn.stream = stream; + return true; + } + + try + { + conn.stream = CreateStream(stream, uri); + return true; + } + catch (Exception e) + { + Log.Error($"[SimpleWebTransport] Create SSLStream Failed: {e}", false); + return false; + } + } + + Stream CreateStream(NetworkStream stream, Uri uri) + { + SslStream sslStream = new SslStream(stream, true, ValidateServerCertificate); + sslStream.AuthenticateAsClient(uri.Host); + return sslStream; + } + + static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + // Do not allow this client to communicate with unauthenticated servers. + + // only accept if no errors + return sslPolicyErrors == SslPolicyErrors.None; + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientSslHelper.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientSslHelper.cs.meta new file mode 100644 index 0000000..d6be2bb --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/ClientSslHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46055a75559a79849a750f39a766db61 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/WebSocketClientStandAlone.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/WebSocketClientStandAlone.cs new file mode 100644 index 0000000..b787bf9 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/WebSocketClientStandAlone.cs @@ -0,0 +1,140 @@ +using System; +using System.Net.Sockets; +using System.Threading; + +namespace Mirror.SimpleWeb +{ + public class WebSocketClientStandAlone : SimpleWebClient + { + readonly ClientSslHelper sslHelper; + readonly ClientHandshake handshake; + readonly TcpConfig tcpConfig; + Connection conn; + + internal WebSocketClientStandAlone(int maxMessageSize, int maxMessagesPerTick, TcpConfig tcpConfig) : base(maxMessageSize, maxMessagesPerTick) + { +#if UNITY_WEBGL && !UNITY_EDITOR + throw new NotSupportedException(); +#else + sslHelper = new ClientSslHelper(); + handshake = new ClientHandshake(); + this.tcpConfig = tcpConfig; +#endif + } + + public override void Connect(Uri serverAddress) + { + state = ClientState.Connecting; + + // create connection here before thread so that send queue exist before connected + TcpClient client = new TcpClient(); + tcpConfig.ApplyTo(client); + + // create connection object here so dispose correctly disconnects on failed connect + conn = new Connection(client, AfterConnectionDisposed); + + Thread receiveThread = new Thread(() => ConnectAndReceiveLoop(serverAddress)); + receiveThread.IsBackground = true; + receiveThread.Start(); + } + + void ConnectAndReceiveLoop(Uri serverAddress) + { + try + { + // connection created above + TcpClient client = conn.client; + conn.receiveThread = Thread.CurrentThread; + + try + { + client.Connect(serverAddress.Host, serverAddress.Port); + } + catch (SocketException) + { + client.Dispose(); + throw; + } + + + bool success = sslHelper.TryCreateStream(conn, serverAddress); + if (!success) + { + Log.Warn($"[SimpleWebTransport] Failed to create Stream with {serverAddress}"); + conn.Dispose(); + return; + } + + success = handshake.TryHandshake(conn, serverAddress); + if (!success) + { + Log.Warn($"[SimpleWebTransport] Failed Handshake with {serverAddress}"); + conn.Dispose(); + return; + } + + Log.Info($"[SimpleWebTransport] HandShake Successful with {serverAddress}"); + + state = ClientState.Connected; + + receiveQueue.Enqueue(new Message(EventType.Connected)); + + Thread sendThread = new Thread(() => + { + SendLoop.Config sendConfig = new SendLoop.Config( + conn, + bufferSize: Constants.HeaderSize + Constants.MaskSize + maxMessageSize, + setMask: true); + + SendLoop.Loop(sendConfig); + }); + + conn.sendThread = sendThread; + sendThread.IsBackground = true; + sendThread.Start(); + + ReceiveLoop.Config config = new ReceiveLoop.Config(conn, + maxMessageSize, + false, + receiveQueue, + bufferPool); + ReceiveLoop.Loop(config); + } + catch (ThreadInterruptedException e) { Log.InfoException(e); } + catch (ThreadAbortException e) { Log.InfoException(e); } + catch (Exception e) { Log.Exception(e); } + finally + { + // close here in case connect fails + conn?.Dispose(); + } + } + + void AfterConnectionDisposed(Connection conn) + { + state = ClientState.NotConnected; + // make sure Disconnected event is only called once + receiveQueue.Enqueue(new Message(EventType.Disconnected)); + } + + public override void Disconnect() + { + state = ClientState.Disconnecting; + Log.Info("[SimpleWebTransport] Disconnect Called"); + + if (conn == null) + state = ClientState.NotConnected; + else + conn?.Dispose(); + } + + public override void Send(ArraySegment segment) + { + ArrayBuffer buffer = bufferPool.Take(segment.Count); + buffer.CopyFrom(segment); + + conn.sendQueue.Enqueue(buffer); + conn.sendPending.Set(); + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/WebSocketClientStandAlone.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/WebSocketClientStandAlone.cs.meta new file mode 100644 index 0000000..37229d3 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/StandAlone/WebSocketClientStandAlone.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 05a9c87dea309e241a9185e5aa0d72ab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl.meta new file mode 100644 index 0000000..2d81f7f --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7142349d566213c4abc763afaf4d91a1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/SimpleWebJSLib.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/SimpleWebJSLib.cs new file mode 100644 index 0000000..6af4671 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/SimpleWebJSLib.cs @@ -0,0 +1,34 @@ +using System; +#if UNITY_WEBGL +using System.Runtime.InteropServices; +#endif + +namespace Mirror.SimpleWeb +{ + internal static class SimpleWebJSLib + { +#if UNITY_WEBGL + [DllImport("__Internal")] + internal static extern bool IsConnected(int index); + +#pragma warning disable CA2101 // Specify marshaling for P/Invoke string arguments + [DllImport("__Internal")] +#pragma warning restore CA2101 // Specify marshaling for P/Invoke string arguments + internal static extern int Connect(string address, Action openCallback, Action closeCallBack, Action messageCallback, Action errorCallback); + + [DllImport("__Internal")] + internal static extern void Disconnect(int index); + + [DllImport("__Internal")] + internal static extern bool Send(int index, byte[] array, int offset, int length); +#else + internal static bool IsConnected(int index) => throw new NotSupportedException(); + + internal static int Connect(string address, Action openCallback, Action closeCallBack, Action messageCallback, Action errorCallback) => throw new NotSupportedException(); + + internal static void Disconnect(int index) => throw new NotSupportedException(); + + internal static bool Send(int index, byte[] array, int offset, int length) => throw new NotSupportedException(); +#endif + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/SimpleWebJSLib.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/SimpleWebJSLib.cs.meta new file mode 100644 index 0000000..9dfa12e --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/SimpleWebJSLib.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 97b96a0b65c104443977473323c2ff35 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/WebSocketClientWebGl.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/WebSocketClientWebGl.cs new file mode 100644 index 0000000..cabb7ff --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/WebSocketClientWebGl.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using AOT; + +namespace Mirror.SimpleWeb +{ +#if !UNITY_2021_3_OR_NEWER + + // Unity 2019 doesn't have ArraySegment.ToArray() yet. + public static class Extensions + { + public static byte[] ToArray(this ArraySegment segment) + { + byte[] array = new byte[segment.Count]; + Array.Copy(segment.Array, segment.Offset, array, 0, segment.Count); + return array; + } + } + +#endif + + public class WebSocketClientWebGl : SimpleWebClient + { + static readonly Dictionary instances = new Dictionary(); + + /// + /// key for instances sent between c# and js + /// + int index; + + /// + /// Queue for messages sent by high level while still connecting, they will be sent after onOpen is called. + /// + /// This is a workaround for anything that calls Send immediately after Connect. + /// Without this the JS websocket will give errors. + /// + /// + Queue ConnectingSendQueue; + + internal WebSocketClientWebGl(int maxMessageSize, int maxMessagesPerTick) : base(maxMessageSize, maxMessagesPerTick) + { +#if !UNITY_WEBGL || UNITY_EDITOR + throw new NotSupportedException(); +#endif + } + + public bool CheckJsConnected() => SimpleWebJSLib.IsConnected(index); + + public override void Connect(Uri serverAddress) + { + index = SimpleWebJSLib.Connect(serverAddress.ToString(), OpenCallback, CloseCallBack, MessageCallback, ErrorCallback); + instances.Add(index, this); + state = ClientState.Connecting; + } + + public override void Disconnect() + { + state = ClientState.Disconnecting; + // disconnect should cause closeCallback and OnDisconnect to be called + SimpleWebJSLib.Disconnect(index); + } + + public override void Send(ArraySegment segment) + { + if (segment.Count > maxMessageSize) + { + Log.Error($"[SimpleWebTransport] Cant send message with length {segment.Count} because it is over the max size of {maxMessageSize}"); + return; + } + + if (state == ClientState.Connected) + { + SimpleWebJSLib.Send(index, segment.Array, segment.Offset, segment.Count); + } + else + { + if (ConnectingSendQueue == null) + ConnectingSendQueue = new Queue(); + + ConnectingSendQueue.Enqueue(segment.ToArray()); + } + } + + void onOpen() + { + receiveQueue.Enqueue(new Message(EventType.Connected)); + state = ClientState.Connected; + + if (ConnectingSendQueue != null) + { + while (ConnectingSendQueue.Count > 0) + { + byte[] next = ConnectingSendQueue.Dequeue(); + SimpleWebJSLib.Send(index, next, 0, next.Length); + } + + ConnectingSendQueue = null; + } + } + + void onClose() + { + // this code should be last in this class + + receiveQueue.Enqueue(new Message(EventType.Disconnected)); + state = ClientState.NotConnected; + instances.Remove(index); + } + + void onMessage(IntPtr bufferPtr, int count) + { + try + { + ArrayBuffer buffer = bufferPool.Take(count); + buffer.CopyFrom(bufferPtr, count); + + receiveQueue.Enqueue(new Message(buffer)); + } + catch (Exception e) + { + Log.Error($"[SimpleWebTransport] onMessage {e.GetType()}: {e.Message}\n{e.StackTrace}"); + receiveQueue.Enqueue(new Message(e)); + } + } + + void onErr() + { + receiveQueue.Enqueue(new Message(new Exception("Javascript Websocket error"))); + Disconnect(); + } + + [MonoPInvokeCallback(typeof(Action))] + static void OpenCallback(int index) => instances[index].onOpen(); + + [MonoPInvokeCallback(typeof(Action))] + static void CloseCallBack(int index) => instances[index].onClose(); + + [MonoPInvokeCallback(typeof(Action))] + static void MessageCallback(int index, IntPtr bufferPtr, int count) => instances[index].onMessage(bufferPtr, count); + + [MonoPInvokeCallback(typeof(Action))] + static void ErrorCallback(int index) => instances[index].onErr(); + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/WebSocketClientWebGl.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/WebSocketClientWebGl.cs.meta new file mode 100644 index 0000000..3827d3a --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/WebSocketClientWebGl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 015c5b1915fd1a64cbe36444d16b2f7d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin.meta new file mode 100644 index 0000000..b516a8f --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1999985791b91b9458059e88404885a7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin/SimpleWeb.jslib b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin/SimpleWeb.jslib new file mode 100644 index 0000000..02e6b93 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin/SimpleWeb.jslib @@ -0,0 +1,114 @@ +// this will create a global object +const SimpleWeb = { + webSockets: [], + next: 1, + GetWebSocket: function (index) { + return SimpleWeb.webSockets[index] + }, + AddNextSocket: function (webSocket) { + var index = SimpleWeb.next; + SimpleWeb.next++; + SimpleWeb.webSockets[index] = webSocket; + return index; + }, + RemoveSocket: function (index) { + SimpleWeb.webSockets[index] = undefined; + }, +}; + +function IsConnected(index) { + var webSocket = SimpleWeb.GetWebSocket(index); + if (webSocket) { + return webSocket.readyState === webSocket.OPEN; + } + else { + return false; + } +} + +function Connect(addressPtr, openCallbackPtr, closeCallBackPtr, messageCallbackPtr, errorCallbackPtr) { + // fix for unity 2021 because unity bug in .jslib + if (typeof Runtime === "undefined") { + // if unity doesn't create Runtime, then make it here + // dont ask why this works, just be happy that it does + Runtime = { + dynCall: dynCall + } + } + + const address = UTF8ToString(addressPtr); + console.log("Connecting to " + address); + // Create webSocket connection. + webSocket = new WebSocket(address); + webSocket.binaryType = 'arraybuffer'; + const index = SimpleWeb.AddNextSocket(webSocket); + + // Connection opened + webSocket.addEventListener('open', function (event) { + console.log("Connected to " + address); + Runtime.dynCall('vi', openCallbackPtr, [index]); + }); + webSocket.addEventListener('close', function (event) { + console.log("Disconnected from " + address); + Runtime.dynCall('vi', closeCallBackPtr, [index]); + }); + + // Listen for messages + webSocket.addEventListener('message', function (event) { + if (event.data instanceof ArrayBuffer) { + // TODO dont alloc each time + var array = new Uint8Array(event.data); + var arrayLength = array.length; + + var bufferPtr = _malloc(arrayLength); + var dataBuffer = new Uint8Array(HEAPU8.buffer, bufferPtr, arrayLength); + dataBuffer.set(array); + + Runtime.dynCall('viii', messageCallbackPtr, [index, bufferPtr, arrayLength]); + _free(bufferPtr); + } + else { + console.error("message type not supported") + } + }); + + webSocket.addEventListener('error', function (event) { + console.error('Socket Error', event); + + Runtime.dynCall('vi', errorCallbackPtr, [index]); + }); + + return index; +} + +function Disconnect(index) { + var webSocket = SimpleWeb.GetWebSocket(index); + if (webSocket) { + webSocket.close(1000, "Disconnect Called by Mirror"); + } + + SimpleWeb.RemoveSocket(index); +} + +function Send(index, arrayPtr, offset, length) { + var webSocket = SimpleWeb.GetWebSocket(index); + if (webSocket) { + const start = arrayPtr + offset; + const end = start + length; + const data = HEAPU8.buffer.slice(start, end); + webSocket.send(data); + return true; + } + return false; +} + + +const SimpleWebLib = { + $SimpleWeb: SimpleWeb, + IsConnected, + Connect, + Disconnect, + Send +}; +autoAddDeps(SimpleWebLib, '$SimpleWeb'); +mergeInto(LibraryManager.library, SimpleWebLib); diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin/SimpleWeb.jslib.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin/SimpleWeb.jslib.meta new file mode 100644 index 0000000..cc1319e --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Client/Webgl/plugin/SimpleWeb.jslib.meta @@ -0,0 +1,37 @@ +fileFormatVersion: 2 +guid: 54452a8c6d2ca9b49a8c79f81b50305c +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Facebook: WebGL + second: + enabled: 1 + settings: {} + - first: + WebGL: WebGL + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common.meta new file mode 100644 index 0000000..078faaa --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 564d2cd3eee5b21419553c0528739d1b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/BufferPool.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/BufferPool.cs new file mode 100644 index 0000000..6231c22 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/BufferPool.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Mirror.SimpleWeb +{ + public interface IBufferOwner + { + void Return(ArrayBuffer buffer); + } + + public sealed class ArrayBuffer : IDisposable + { + readonly IBufferOwner owner; + + public readonly byte[] array; + + /// + /// number of bytes written to buffer + /// + public int count { get; internal set; } + + /// + /// How many times release needs to be called before buffer is returned to pool + /// This allows the buffer to be used in multiple places at the same time + /// + public void SetReleasesRequired(int required) + { + releasesRequired = required; + } + + /// + /// How many times release needs to be called before buffer is returned to pool + /// This allows the buffer to be used in multiple places at the same time + /// + /// + /// This value is normally 0, but can be changed to require release to be called multiple times + /// + int releasesRequired; + + public ArrayBuffer(IBufferOwner owner, int size) + { + this.owner = owner; + array = new byte[size]; + } + + public void Release() + { + int newValue = Interlocked.Decrement(ref releasesRequired); + if (newValue <= 0) + { + count = 0; + owner?.Return(this); + } + } + public void Dispose() + { + Release(); + } + + + public void CopyTo(byte[] target, int offset) + { + if (count > (target.Length + offset)) + throw new ArgumentException($"{nameof(count)} was greater than {nameof(target)}.length", nameof(target)); + + Buffer.BlockCopy(array, 0, target, offset, count); + } + + public void CopyFrom(ArraySegment segment) + { + CopyFrom(segment.Array, segment.Offset, segment.Count); + } + + public void CopyFrom(byte[] source, int offset, int length) + { + if (length > array.Length) + throw new ArgumentException($"{nameof(length)} was greater than {nameof(array)}.length", nameof(length)); + + count = length; + Buffer.BlockCopy(source, offset, array, 0, length); + } + + public void CopyFrom(IntPtr bufferPtr, int length) + { + if (length > array.Length) + throw new ArgumentException($"{nameof(length)} was greater than {nameof(array)}.length", nameof(length)); + + count = length; + Marshal.Copy(bufferPtr, array, 0, length); + } + + public ArraySegment ToSegment() => new ArraySegment(array, 0, count); + + [Conditional("UNITY_ASSERTIONS")] + internal void Validate(int arraySize) + { + if (array.Length != arraySize) + Log.Error("[SimpleWebTransport] Buffer that was returned had an array of the wrong size"); + } + } + + internal class BufferBucket : IBufferOwner + { + public readonly int arraySize; + readonly ConcurrentQueue buffers; + + /// + /// keeps track of how many arrays are taken vs returned + /// + internal int _current = 0; + + public BufferBucket(int arraySize) + { + this.arraySize = arraySize; + buffers = new ConcurrentQueue(); + } + + public ArrayBuffer Take() + { + IncrementCreated(); + if (buffers.TryDequeue(out ArrayBuffer buffer)) + return buffer; + else + { + Log.Verbose($"[SimpleWebTransport] BufferBucket({arraySize}) create new"); + return new ArrayBuffer(this, arraySize); + } + } + + public void Return(ArrayBuffer buffer) + { + DecrementCreated(); + buffer.Validate(arraySize); + buffers.Enqueue(buffer); + } + + [Conditional("DEBUG")] + void IncrementCreated() + { + int next = Interlocked.Increment(ref _current); + // Log.Verbose($"[SimpleWebTransport] BufferBucket({arraySize}) count:{next}"); + } + [Conditional("DEBUG")] + void DecrementCreated() + { + int next = Interlocked.Decrement(ref _current); + // Log.Verbose($"[SimpleWebTransport] BufferBucket({arraySize}) count:{next}"); + } + } + + /// + /// Collection of different sized buffers + /// + /// + /// + /// Problem:
+ /// * Need to cached byte[] so that new ones aren't created each time
+ /// * Arrays sent are multiple different sizes
+ /// * Some message might be big so need buffers to cover that size
+ /// * Most messages will be small compared to max message size
+ ///
+ ///
+ /// + /// Solution:
+ /// * Create multiple groups of buffers covering the range of allowed sizes
+ /// * Split range exponentially (using math.log) so that there are more groups for small buffers
+ ///
+ ///
+ public class BufferPool + { + internal readonly BufferBucket[] buckets; + readonly int bucketCount; + readonly int smallest; + readonly int largest; + + public BufferPool(int bucketCount, int smallest, int largest) + { + if (bucketCount < 2) throw new ArgumentException("Count must be at least 2"); + if (smallest < 1) throw new ArgumentException("Smallest must be at least 1"); + if (largest < smallest) throw new ArgumentException("Largest must be greater than smallest"); + + this.bucketCount = bucketCount; + this.smallest = smallest; + this.largest = largest; + + // split range over log scale (more buckets for smaller sizes) + double minLog = Math.Log(this.smallest); + double maxLog = Math.Log(this.largest); + double range = maxLog - minLog; + double each = range / (bucketCount - 1); + + buckets = new BufferBucket[bucketCount]; + + for (int i = 0; i < bucketCount; i++) + { + double size = smallest * Math.Pow(Math.E, each * i); + buckets[i] = new BufferBucket((int)Math.Ceiling(size)); + } + + + Validate(); + + // Example + // 5 count + // 20 smallest + // 16400 largest + + // 3.0 log 20 + // 9.7 log 16400 + + // 6.7 range 9.7 - 3 + // 1.675 each 6.7 / (5-1) + + // 20 e^ (3 + 1.675 * 0) + // 107 e^ (3 + 1.675 * 1) + // 572 e^ (3 + 1.675 * 2) + // 3056 e^ (3 + 1.675 * 3) + // 16,317 e^ (3 + 1.675 * 4) + + // precision wont be lose when using doubles + } + + [Conditional("UNITY_ASSERTIONS")] + void Validate() + { + if (buckets[0].arraySize != smallest) + Log.Error($"[SimpleWebTransport] BufferPool Failed to create bucket for smallest. bucket:{buckets[0].arraySize} smallest{smallest}"); + + int largestBucket = buckets[bucketCount - 1].arraySize; + // rounded using Ceiling, so allowed to be 1 more that largest + if (largestBucket != largest && largestBucket != largest + 1) + Log.Error($"[SimpleWebTransport] BufferPool Failed to create bucket for largest. bucket:{largestBucket} smallest{largest}"); + } + + public ArrayBuffer Take(int size) + { + if (size > largest) { throw new ArgumentException($"Size ({size}) is greatest that largest ({largest})"); } + + for (int i = 0; i < bucketCount; i++) + if (size <= buckets[i].arraySize) + return buckets[i].Take(); + + throw new ArgumentException($"Size ({size}) is greatest that largest ({largest})"); + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/BufferPool.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/BufferPool.cs.meta new file mode 100644 index 0000000..0b1070f --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/BufferPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 94ae50f3ec35667469b861b12cd72f92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Connection.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Connection.cs new file mode 100644 index 0000000..c8081c4 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Connection.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace Mirror.SimpleWeb +{ + internal sealed class Connection : IDisposable + { + public const int IdNotSet = -1; + private readonly object disposedLock = new object(); + + public TcpClient client; + + public int connId = IdNotSet; + + /// + /// Connect request, sent from client to start handshake + /// Only valid on server + /// + public Request request; + /// + /// RemoteEndpoint address or address from request header + /// Only valid on server + /// + public string remoteAddress; + + + public Stream stream; + public Thread receiveThread; + public Thread sendThread; + + public ManualResetEventSlim sendPending = new ManualResetEventSlim(false); + public ConcurrentQueue sendQueue = new ConcurrentQueue(); + + public Action onDispose; + private volatile bool hasDisposed; + + public Connection(TcpClient client, Action onDispose) + { + this.client = client ?? throw new ArgumentNullException(nameof(client)); + this.onDispose = onDispose; + } + + /// + /// disposes client and stops threads + /// + public void Dispose() + { + Log.Verbose($"[SimpleWebTransport] Dispose {ToString()}"); + + // check hasDisposed first to stop ThreadInterruptedException on lock + if (hasDisposed) return; + + Log.Info($"[SimpleWebTransport] Connection Close: {ToString()}"); + + lock (disposedLock) + { + // check hasDisposed again inside lock to make sure no other object has called this + if (hasDisposed) return; + + hasDisposed = true; + + // stop threads first so they don't try to use disposed objects + receiveThread.Interrupt(); + sendThread?.Interrupt(); + + try + { + // stream + stream?.Dispose(); + stream = null; + client.Dispose(); + client = null; + } + catch (Exception e) + { + Log.Exception(e); + } + + sendPending.Dispose(); + + // release all buffers in send queue + while (sendQueue.TryDequeue(out ArrayBuffer buffer)) + buffer.Release(); + + onDispose.Invoke(this); + } + } + + public override string ToString() + { + if (hasDisposed) + return $"[Conn:{connId}, Disposed]"; + else + try + { + System.Net.EndPoint endpoint = client?.Client?.RemoteEndPoint; + return $"[Conn:{connId}, endPoint:{endpoint}]"; + } + catch (SocketException) + { + return $"[Conn:{connId}, endPoint:n/a]"; + } + } + + /// + /// Gets the address based on the and RemoteEndPoint + /// Called after ServerHandShake is accepted + /// + internal string CalculateAddress() + { + if (request.Headers.TryGetValue("X-Forwarded-For", out string forwardFor)) + { + string actualClientIP = forwardFor.ToString().Split(',').First(); + // Remove the port number from the address + return actualClientIP.Split(':').First(); + } + else + { + IPEndPoint ipEndPoint = (IPEndPoint)client.Client.RemoteEndPoint; + IPAddress ipAddress = ipEndPoint.Address; + if (ipAddress.IsIPv4MappedToIPv6) + ipAddress = ipAddress.MapToIPv4(); + + return ipAddress.ToString(); + } + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Connection.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Connection.cs.meta new file mode 100644 index 0000000..d48a835 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Connection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a13073c2b49d39943888df45174851bd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Constants.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Constants.cs new file mode 100644 index 0000000..3aa16c3 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Constants.cs @@ -0,0 +1,77 @@ +using System.Text; + +namespace Mirror.SimpleWeb +{ + /// + /// Constant values that should never change + /// + /// Some values are from https://tools.ietf.org/html/rfc6455 + /// + /// + internal static class Constants + { + /// + /// Header is at most 4 bytes + /// + /// If message is less than 125 then header is 2 bytes, else header is 4 bytes + /// + /// + public const int HeaderSize = 4; + + /// + /// Smallest size of header + /// + /// If message is less than 125 then header is 2 bytes, else header is 4 bytes + /// + /// + public const int HeaderMinSize = 2; + + /// + /// bytes for short length + /// + public const int ShortLength = 2; + + /// + /// bytes for long length + /// + public const int LongLength = 8; + + /// + /// Message mask is always 4 bytes + /// + public const int MaskSize = 4; + + /// + /// Max size of a message for length to be 1 byte long + /// + /// payload length between 0-125 + /// + /// + public const int BytePayloadLength = 125; + + /// + /// if payload length is 126 when next 2 bytes will be the length + /// + public const int UshortPayloadLength = 126; + + /// + /// if payload length is 127 when next 8 bytes will be the length + /// + public const int UlongPayloadLength = 127; + + + /// + /// Guid used for WebSocket Protocol + /// + public const string HandshakeGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + + public static readonly int HandshakeGUIDLength = HandshakeGUID.Length; + + public static readonly byte[] HandshakeGUIDBytes = Encoding.ASCII.GetBytes(HandshakeGUID); + + /// + /// Handshake messages will end with \r\n\r\n + /// + public static readonly byte[] endOfHandshake = new byte[4] { (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n' }; + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Constants.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Constants.cs.meta new file mode 100644 index 0000000..ece602e --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Constants.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 85d110a089d6ad348abf2d073ebce7cd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/EventType.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/EventType.cs new file mode 100644 index 0000000..3a9d185 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/EventType.cs @@ -0,0 +1,10 @@ +namespace Mirror.SimpleWeb +{ + public enum EventType + { + Connected, + Data, + Disconnected, + Error + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/EventType.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/EventType.cs.meta new file mode 100644 index 0000000..a91403a --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/EventType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d9cd7d2b5229ab42a12e82ae17d0347 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Log.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Log.cs new file mode 100644 index 0000000..e0c5309 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Log.cs @@ -0,0 +1,108 @@ +using System; +using UnityEngine; +using Conditional = System.Diagnostics.ConditionalAttribute; + +namespace Mirror.SimpleWeb +{ + public static class Log + { + public enum Levels + { + none = 0, + error = 1, + warn = 2, + info = 3, + verbose = 4, + } + + public static ILogger logger = Debug.unityLogger; + public static Levels level = Levels.none; + + public static string BufferToString(byte[] buffer, int offset = 0, int? length = null) + { + return BitConverter.ToString(buffer, offset, length ?? buffer.Length); + } + + public static void DumpBuffer(string label, byte[] buffer, int offset, int length) + { + if (level < Levels.verbose) + return; + + logger.Log(LogType.Log, $"[SimpleWebTransport] VERBOSE: {label}: {BufferToString(buffer, offset, length)}"); + } + + public static void DumpBuffer(string label, ArrayBuffer arrayBuffer) + { + if (level < Levels.verbose) + return; + + logger.Log(LogType.Log, $"[SimpleWebTransport] VERBOSE: {label}: {BufferToString(arrayBuffer.array, 0, arrayBuffer.count)}"); + } + + public static void Verbose(string msg, bool showColor = true) + { + if (level < Levels.verbose) + return; + + if (showColor) + logger.Log(LogType.Log, $"[SimpleWebTransport] VERBOSE: {msg}"); + else + logger.Log(LogType.Log, $"[SimpleWebTransport] VERBOSE: {msg}"); + } + + public static void Info(string msg, bool showColor = true) + { + if (level < Levels.info) + return; + + if (showColor) + logger.Log(LogType.Log, $"[SimpleWebTransport] INFO: {msg}"); + else + logger.Log(LogType.Log, $"[SimpleWebTransport] INFO: {msg}"); + } + + public static void InfoException(Exception e) + { + if (level < Levels.info) + return; + +#if UNITY_SERVER + logger.Log(LogType.Log, $"[SimpleWebTransport] INFO_EXCEPTION: {e.GetType().Name} Message: {e.Message}\n{e.StackTrace}\n\n"); +#else + logger.Log(LogType.Log, $"[SimpleWebTransport] INFO_EXCEPTION: {e.GetType().Name} Message: {e.Message}\n{e.StackTrace}\n\n"); +#endif + } + + public static void Warn(string msg, bool showColor = true) + { + if (level < Levels.warn) + return; + + if (showColor) + logger.Log(LogType.Warning, $"[SimpleWebTransport] WARN: {msg}"); + else + logger.Log(LogType.Warning, $"[SimpleWebTransport] WARN: {msg}"); + } + + public static void Error(string msg, bool showColor = true) + { + if (level < Levels.error) + return; + + if (showColor) + logger.Log(LogType.Error, $"[SimpleWebTransport] ERROR: {msg}"); + else + logger.Log(LogType.Error, $"[SimpleWebTransport] ERROR: {msg}"); + } + + public static void Exception(Exception e) + { + // always log Exceptions +#if UNITY_SERVER + logger.Log(LogType.Error, $"[SimpleWebTransport] EXCEPTION: {e.GetType().Name} Message: {e.Message}\n{e.StackTrace}\n\n"); +#else + logger.Log(LogType.Error, $"[SimpleWebTransport] EXCEPTION: {e.GetType().Name} Message: {e.Message}\n{e.StackTrace}\n\n"); +#endif + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Log.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Log.cs.meta new file mode 100644 index 0000000..beb2883 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Log.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3cf1521098e04f74fbea0fe2aa0439f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Message.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Message.cs new file mode 100644 index 0000000..29b4849 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Message.cs @@ -0,0 +1,49 @@ +using System; + +namespace Mirror.SimpleWeb +{ + public struct Message + { + public readonly int connId; + public readonly EventType type; + public readonly ArrayBuffer data; + public readonly Exception exception; + + public Message(EventType type) : this() + { + this.type = type; + } + + public Message(ArrayBuffer data) : this() + { + type = EventType.Data; + this.data = data; + } + + public Message(Exception exception) : this() + { + type = EventType.Error; + this.exception = exception; + } + + public Message(int connId, EventType type) : this() + { + this.connId = connId; + this.type = type; + } + + public Message(int connId, ArrayBuffer data) : this() + { + this.connId = connId; + type = EventType.Data; + this.data = data; + } + + public Message(int connId, Exception exception) : this() + { + this.connId = connId; + type = EventType.Error; + this.exception = exception; + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Message.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Message.cs.meta new file mode 100644 index 0000000..3286a2c --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Message.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f5d05d71b09d2714b96ffe80bc3d2a77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/MessageProcessor.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/MessageProcessor.cs new file mode 100644 index 0000000..e3269f3 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/MessageProcessor.cs @@ -0,0 +1,175 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; + +namespace Mirror.SimpleWeb +{ + public static class MessageProcessor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static byte FirstLengthByte(byte[] buffer) => (byte)(buffer[1] & 0b0111_1111); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool NeedToReadShortLength(byte[] buffer) + { + byte lenByte = FirstLengthByte(buffer); + return lenByte == Constants.UshortPayloadLength; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool NeedToReadLongLength(byte[] buffer) + { + byte lenByte = FirstLengthByte(buffer); + return lenByte == Constants.UlongPayloadLength; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetOpcode(byte[] buffer) => buffer[0] & 0b0000_1111; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetPayloadLength(byte[] buffer) => GetMessageLength(buffer, 0, FirstLengthByte(buffer)); + + /// + /// Has full message been sent + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Finished(byte[] buffer) => (buffer[0] & 0b1000_0000) != 0; + + public static void ValidateHeader(byte[] buffer, int maxLength, bool expectMask, bool opCodeContinuation = false) + { + bool finished = Finished(buffer); + bool hasMask = (buffer[1] & 0b1000_0000) != 0; // true from clients, false from server, "All messages from the client to the server have this bit set" + + int opcode = buffer[0] & 0b0000_1111; // expecting 1 - text message + byte lenByte = FirstLengthByte(buffer); + + ThrowIfMaskNotExpected(hasMask, expectMask); + ThrowIfBadOpCode(opcode, finished, opCodeContinuation); + + int msglen = GetMessageLength(buffer, 0, lenByte); + + ThrowIfLengthZero(msglen); + ThrowIfMsgLengthTooLong(msglen, maxLength); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToggleMask(byte[] src, int sourceOffset, int messageLength, byte[] maskBuffer, int maskOffset) + { + ToggleMask(src, sourceOffset, src, sourceOffset, messageLength, maskBuffer, maskOffset); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToggleMask(byte[] src, int sourceOffset, ArrayBuffer dst, int messageLength, byte[] maskBuffer, int maskOffset) + { + ToggleMask(src, sourceOffset, dst.array, 0, messageLength, maskBuffer, maskOffset); + dst.count = messageLength; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToggleMask(byte[] src, int srcOffset, byte[] dst, int dstOffset, int messageLength, byte[] maskBuffer, int maskOffset) + { + for (int i = 0; i < messageLength; i++) + { + byte maskByte = maskBuffer[maskOffset + i % Constants.MaskSize]; + dst[dstOffset + i] = (byte)(src[srcOffset + i] ^ maskByte); + } + } + + /// + static int GetMessageLength(byte[] buffer, int offset, byte lenByte) + { + if (lenByte == Constants.UshortPayloadLength) + { + // header is 2 bytes + ushort value = 0; + value |= (ushort)(buffer[offset + 2] << 8); + value |= buffer[offset + 3]; + + return value; + } + else if (lenByte == Constants.UlongPayloadLength) + { + // header is 8 bytes + ulong value = 0; + value |= ((ulong)buffer[offset + 2] << 56); + value |= ((ulong)buffer[offset + 3] << 48); + value |= ((ulong)buffer[offset + 4] << 40); + value |= ((ulong)buffer[offset + 5] << 32); + value |= ((ulong)buffer[offset + 6] << 24); + value |= ((ulong)buffer[offset + 7] << 16); + value |= ((ulong)buffer[offset + 8] << 8); + value |= ((ulong)buffer[offset + 9] << 0); + + if (value > int.MaxValue) + throw new NotSupportedException($"Can't receive payloads larger that int.max: {int.MaxValue}"); + + return (int)value; + } + else // is less than 126 + { + // header is 2 bytes long + return lenByte; + } + } + + /// + static void ThrowIfMaskNotExpected(bool hasMask, bool expectMask) + { + if (hasMask != expectMask) + throw new InvalidDataException($"Message expected mask to be {expectMask} but was {hasMask}"); + } + + /// + static void ThrowIfBadOpCode(int opcode, bool finished, bool opCodeContinuation) + { + // 0 = continuation + // 2 = binary + // 8 = close + + // do we expect Continuation? + if (opCodeContinuation) + { + // good it was Continuation + if (opcode == 0) + return; + + // bad, wasn't Continuation + throw new InvalidDataException("Expected opcode to be Continuation"); + } + else if (!finished) + { + // fragmented message, should be binary + if (opcode == 2) + return; + + throw new InvalidDataException("Expected opcode to be binary"); + } + else + { + // normal message, should be binary or close + if (opcode == 2 || opcode == 8) + return; + + throw new InvalidDataException("Expected opcode to be binary or close"); + } + } + + /// + static void ThrowIfLengthZero(int msglen) + { + if (msglen == 0) + throw new InvalidDataException("Message length was zero"); + } + + /// + /// need to check this so that data from previous buffer isn't used + /// + public static void ThrowIfMsgLengthTooLong(int msglen, int maxLength) + { + if (msglen > maxLength) + throw new InvalidDataException("Message length is greater than max length"); + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/MessageProcessor.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/MessageProcessor.cs.meta new file mode 100644 index 0000000..7e3a7c4 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/MessageProcessor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4c1f218a2b16ca846aaf23260078e549 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReadHelper.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReadHelper.cs new file mode 100644 index 0000000..f8b5c3b --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReadHelper.cs @@ -0,0 +1,123 @@ +using System; +using System.IO; +using System.Runtime.Serialization; + +namespace Mirror.SimpleWeb +{ + public static class ReadHelper + { + /// + /// Reads exactly length from stream + /// + /// outOffset + length + /// + public static int Read(Stream stream, byte[] outBuffer, int outOffset, int length) + { + int received = 0; + try + { + while (received < length) + { + int read = stream.Read(outBuffer, outOffset + received, length - received); + if (read == 0) + throw new ReadHelperException("returned 0"); + + received += read; + } + } + catch (AggregateException ae) + { + // if interrupt is called we don't care about Exceptions + Utils.CheckForInterupt(); + + // rethrow + ae.Handle(e => false); + } + + if (received != length) + throw new ReadHelperException("returned not equal to length"); + + return outOffset + received; + } + + /// + /// Reads and returns results. This should never throw an exception + /// + public static bool TryRead(Stream stream, byte[] outBuffer, int outOffset, int length) + { + try + { + Read(stream, outBuffer, outOffset, length); + return true; + } + catch (ReadHelperException) + { + return false; + } + catch (IOException) + { + return false; + } + catch (Exception e) + { + Log.Exception(e); + return false; + } + } + + public static int? SafeReadTillMatch(Stream stream, byte[] outBuffer, int outOffset, int maxLength, byte[] endOfHeader) + { + try + { + int read = 0; + int endIndex = 0; + int endLength = endOfHeader.Length; + while (true) + { + int next = stream.ReadByte(); + if (next == -1) // closed + return null; + + if (read >= maxLength) + { + Log.Error("[SimpleWebTransport] SafeReadTillMatch exceeded maxLength"); + return null; + } + + outBuffer[outOffset + read] = (byte)next; + read++; + + // if n is match, check n+1 next + if (endOfHeader[endIndex] == next) + { + endIndex++; + // when all is match return with read length + if (endIndex >= endLength) + return read; + } + // if n not match reset to 0 + else + endIndex = 0; + } + } + catch (IOException e) + { + Log.InfoException(e); + return null; + } + catch (Exception e) + { + Log.Exception(e); + return null; + } + } + } + + [Serializable] + public class ReadHelperException : Exception + { + public ReadHelperException(string message) : base(message) { } + + protected ReadHelperException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReadHelper.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReadHelper.cs.meta new file mode 100644 index 0000000..77d09c1 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReadHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9f4fa5d324e708c46a55810a97de75bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReceiveLoop.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReceiveLoop.cs new file mode 100644 index 0000000..21ef782 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReceiveLoop.cs @@ -0,0 +1,254 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using UnityEngine.Profiling; + +namespace Mirror.SimpleWeb +{ + internal static class ReceiveLoop + { + public struct Config + { + public readonly Connection conn; + public readonly int maxMessageSize; + public readonly bool expectMask; + public readonly ConcurrentQueue queue; + public readonly BufferPool bufferPool; + + public Config(Connection conn, int maxMessageSize, bool expectMask, ConcurrentQueue queue, BufferPool bufferPool) + { + this.conn = conn ?? throw new ArgumentNullException(nameof(conn)); + this.maxMessageSize = maxMessageSize; + this.expectMask = expectMask; + this.queue = queue ?? throw new ArgumentNullException(nameof(queue)); + this.bufferPool = bufferPool ?? throw new ArgumentNullException(nameof(bufferPool)); + } + + public void Deconstruct(out Connection conn, out int maxMessageSize, out bool expectMask, out ConcurrentQueue queue, out BufferPool bufferPool) + { + conn = this.conn; + maxMessageSize = this.maxMessageSize; + expectMask = this.expectMask; + queue = this.queue; + bufferPool = this.bufferPool; + } + } + + struct Header + { + public int payloadLength; + public int offset; + public int opcode; + public bool finished; + } + + public static void Loop(Config config) + { + (Connection conn, int maxMessageSize, bool expectMask, ConcurrentQueue queue, BufferPool _) = config; + + Profiler.BeginThreadProfiling("SimpleWeb", $"ReceiveLoop {conn.connId}"); + + byte[] readBuffer = new byte[Constants.HeaderSize + (expectMask ? Constants.MaskSize : 0) + maxMessageSize]; + try + { + try + { + TcpClient client = conn.client; + + while (client.Connected) + ReadOneMessage(config, readBuffer); + + Log.Info($"[SimpleWebTransport] {conn} Not Connected"); + } + catch (Exception) + { + // if interrupted we don't care about other exceptions + Utils.CheckForInterupt(); + throw; + } + } + catch (ThreadInterruptedException e) { Log.InfoException(e); } + catch (ThreadAbortException e) { Log.InfoException(e); } + catch (ObjectDisposedException e) { Log.InfoException(e); } + catch (ReadHelperException e) + { + Log.InfoException(e); + } + catch (SocketException e) + { + // this could happen if wss client closes stream + Log.Warn($"[SimpleWebTransport] ReceiveLoop SocketException\n{e.Message}", false); + queue.Enqueue(new Message(conn.connId, e)); + } + catch (IOException e) + { + // this could happen if client disconnects + Log.Warn($"[SimpleWebTransport] ReceiveLoop IOException\n{e.Message}", false); + queue.Enqueue(new Message(conn.connId, e)); + } + catch (InvalidDataException e) + { + Log.Error($"[SimpleWebTransport] Invalid data from {conn}: {e.Message}"); + queue.Enqueue(new Message(conn.connId, e)); + } + catch (Exception e) + { + Log.Exception(e); + queue.Enqueue(new Message(conn.connId, e)); + } + finally + { + Profiler.EndThreadProfiling(); + conn.Dispose(); + } + } + + static void ReadOneMessage(Config config, byte[] buffer) + { + (Connection conn, int maxMessageSize, bool expectMask, ConcurrentQueue queue, BufferPool bufferPool) = config; + Stream stream = conn.stream; + + Header header = ReadHeader(config, buffer); + + int msgOffset = header.offset; + header.offset = ReadHelper.Read(stream, buffer, header.offset, header.payloadLength); + + if (header.finished) + { + switch (header.opcode) + { + case 2: + HandleArrayMessage(config, buffer, msgOffset, header.payloadLength); + break; + case 8: + HandleCloseMessage(config, buffer, msgOffset, header.payloadLength); + break; + } + } + else + { + // todo cache this to avoid allocations + Queue fragments = new Queue(); + fragments.Enqueue(CopyMessageToBuffer(bufferPool, expectMask, buffer, msgOffset, header.payloadLength)); + int totalSize = header.payloadLength; + + while (!header.finished) + { + header = ReadHeader(config, buffer, opCodeContinuation: true); + + msgOffset = header.offset; + header.offset = ReadHelper.Read(stream, buffer, header.offset, header.payloadLength); + fragments.Enqueue(CopyMessageToBuffer(bufferPool, expectMask, buffer, msgOffset, header.payloadLength)); + + totalSize += header.payloadLength; + MessageProcessor.ThrowIfMsgLengthTooLong(totalSize, maxMessageSize); + } + + + ArrayBuffer msg = bufferPool.Take(totalSize); + msg.count = 0; + while (fragments.Count > 0) + { + ArrayBuffer part = fragments.Dequeue(); + + part.CopyTo(msg.array, msg.count); + msg.count += part.count; + + part.Release(); + } + + // dump after mask off + Log.DumpBuffer($"[SimpleWebTransport] Message", msg); + + queue.Enqueue(new Message(conn.connId, msg)); + } + } + + static Header ReadHeader(Config config, byte[] buffer, bool opCodeContinuation = false) + { + (Connection conn, int maxMessageSize, bool expectMask, ConcurrentQueue queue, BufferPool bufferPool) = config; + Stream stream = conn.stream; + Header header = new Header(); + + // read 2 + header.offset = ReadHelper.Read(stream, buffer, header.offset, Constants.HeaderMinSize); + // log after first blocking call + // Log.Verbose($"[SimpleWebTransport] Message From {conn}"); + + if (MessageProcessor.NeedToReadShortLength(buffer)) + header.offset = ReadHelper.Read(stream, buffer, header.offset, Constants.ShortLength); + if (MessageProcessor.NeedToReadLongLength(buffer)) + header.offset = ReadHelper.Read(stream, buffer, header.offset, Constants.LongLength); + + // Log.DumpBuffer($"[SimpleWebTransport] Raw Header", buffer, 0, header.offset); + + MessageProcessor.ValidateHeader(buffer, maxMessageSize, expectMask, opCodeContinuation); + + if (expectMask) + header.offset = ReadHelper.Read(stream, buffer, header.offset, Constants.MaskSize); + + header.opcode = MessageProcessor.GetOpcode(buffer); + header.payloadLength = MessageProcessor.GetPayloadLength(buffer); + header.finished = MessageProcessor.Finished(buffer); + + // Log.Verbose($"[SimpleWebTransport] Header ln:{header.payloadLength} op:{header.opcode} mask:{expectMask}"); + + return header; + } + + static void HandleArrayMessage(Config config, byte[] buffer, int msgOffset, int payloadLength) + { + (Connection conn, int _, bool expectMask, ConcurrentQueue queue, BufferPool bufferPool) = config; + + ArrayBuffer arrayBuffer = CopyMessageToBuffer(bufferPool, expectMask, buffer, msgOffset, payloadLength); + + // dump after mask off + Log.DumpBuffer($"[SimpleWebTransport] Message", arrayBuffer); + + queue.Enqueue(new Message(conn.connId, arrayBuffer)); + } + + static ArrayBuffer CopyMessageToBuffer(BufferPool bufferPool, bool expectMask, byte[] buffer, int msgOffset, int payloadLength) + { + ArrayBuffer arrayBuffer = bufferPool.Take(payloadLength); + + if (expectMask) + { + int maskOffset = msgOffset - Constants.MaskSize; + // write the result of toggle directly into arrayBuffer to avoid 2nd copy call + MessageProcessor.ToggleMask(buffer, msgOffset, arrayBuffer, payloadLength, buffer, maskOffset); + } + else + arrayBuffer.CopyFrom(buffer, msgOffset, payloadLength); + + return arrayBuffer; + } + + static void HandleCloseMessage(Config config, byte[] buffer, int msgOffset, int payloadLength) + { + (Connection conn, int _, bool expectMask, ConcurrentQueue _, BufferPool _) = config; + + if (expectMask) + { + int maskOffset = msgOffset - Constants.MaskSize; + MessageProcessor.ToggleMask(buffer, msgOffset, payloadLength, buffer, maskOffset); + } + + // dump after mask off + // Log.DumpBuffer($"[SimpleWebTransport] Message", buffer, msgOffset, payloadLength); + Log.Info($"[SimpleWebTransport] Close: {GetCloseCode(buffer, msgOffset)} message:{GetCloseMessage(buffer, msgOffset, payloadLength)}"); + + conn.Dispose(); + } + + static string GetCloseMessage(byte[] buffer, int msgOffset, int payloadLength) + => Encoding.UTF8.GetString(buffer, msgOffset + 2, payloadLength - 2); + + static int GetCloseCode(byte[] buffer, int msgOffset) + => buffer[msgOffset + 0] << 8 | buffer[msgOffset + 1]; + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReceiveLoop.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReceiveLoop.cs.meta new file mode 100644 index 0000000..47c6ff5 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/ReceiveLoop.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a26c2815f58431c4a98c158c8b655ffd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Request.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Request.cs new file mode 100644 index 0000000..705b957 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Request.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Mirror.SimpleWeb +{ + /// + /// Represents a client's request to the Websockets server, which is the first message from the client. + /// + public class Request + { + private static readonly char[] lineSplitChars = new char[] { '\r', '\n' }; + private static readonly char[] headerSplitChars = new char[] { ':' }; + public string RequestLine; + public Dictionary Headers = new Dictionary(); + + public Request(string message) + { + string[] all = message.Split(lineSplitChars, StringSplitOptions.RemoveEmptyEntries); + RequestLine = all.First(); + Headers = all.Skip(1) + .Select(header => header.Split(headerSplitChars, 2, StringSplitOptions.RemoveEmptyEntries)) + .ToDictionary(split => split[0].Trim(), split => split[1].Trim()); + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Request.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Request.cs.meta new file mode 100644 index 0000000..8baf222 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Request.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 50b41ad63d4956a42a073bad5158fe09 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/SendLoop.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/SendLoop.cs new file mode 100644 index 0000000..31c6726 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/SendLoop.cs @@ -0,0 +1,225 @@ +using System; +using System.IO; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Threading; +using UnityEngine.Profiling; + +namespace Mirror.SimpleWeb +{ + public static class SendLoopConfig + { + public static volatile bool batchSend = false; + public static volatile bool sleepBeforeSend = false; + } + internal static class SendLoop + { + public struct Config + { + public readonly Connection conn; + public readonly int bufferSize; + public readonly bool setMask; + + public Config(Connection conn, int bufferSize, bool setMask) + { + this.conn = conn ?? throw new ArgumentNullException(nameof(conn)); + this.bufferSize = bufferSize; + this.setMask = setMask; + } + + public void Deconstruct(out Connection conn, out int bufferSize, out bool setMask) + { + conn = this.conn; + bufferSize = this.bufferSize; + setMask = this.setMask; + } + } + + public static void Loop(Config config) + { + (Connection conn, int bufferSize, bool setMask) = config; + + Profiler.BeginThreadProfiling("SimpleWeb", $"SendLoop {conn.connId}"); + + // create write buffer for this thread + byte[] writeBuffer = new byte[bufferSize]; + MaskHelper maskHelper = setMask ? new MaskHelper() : null; + try + { + TcpClient client = conn.client; + Stream stream = conn.stream; + + // null check in case disconnect while send thread is starting + if (client == null) + return; + + while (client.Connected) + { + // wait for message + conn.sendPending.Wait(); + // wait for 1ms for mirror to send other messages + if (SendLoopConfig.sleepBeforeSend) + Thread.Sleep(1); + + conn.sendPending.Reset(); + + if (SendLoopConfig.batchSend) + { + int offset = 0; + while (conn.sendQueue.TryDequeue(out ArrayBuffer msg)) + { + // check if connected before sending message + if (!client.Connected) + { + Log.Info($"[SimpleWebTransport] SendLoop {conn} not connected"); + msg.Release(); + return; + } + + int maxLength = msg.count + Constants.HeaderSize + Constants.MaskSize; + + // if next writer could overflow, write to stream and clear buffer + if (offset + maxLength > bufferSize) + { + stream.Write(writeBuffer, 0, offset); + offset = 0; + } + + offset = SendMessage(writeBuffer, offset, msg, setMask, maskHelper); + msg.Release(); + } + + // after no message in queue, send remaining messages + // don't need to check offset > 0 because last message in queue will always be sent here + + stream.Write(writeBuffer, 0, offset); + } + else + { + while (conn.sendQueue.TryDequeue(out ArrayBuffer msg)) + { + // check if connected before sending message + if (!client.Connected) + { + Log.Info($"[SimpleWebTransport] SendLoop {conn} not connected"); + msg.Release(); + return; + } + + int length = SendMessage(writeBuffer, 0, msg, setMask, maskHelper); + stream.Write(writeBuffer, 0, length); + msg.Release(); + } + } + } + + Log.Info($"[SimpleWebTransport] {conn} Not Connected"); + } + catch (ThreadInterruptedException e) { Log.InfoException(e); } + catch (ThreadAbortException e) { Log.InfoException(e); } + catch (Exception e) + { + Log.Exception(e); + } + finally + { + Profiler.EndThreadProfiling(); + conn.Dispose(); + maskHelper?.Dispose(); + } + } + + /// new offset in buffer + static int SendMessage(byte[] buffer, int startOffset, ArrayBuffer msg, bool setMask, MaskHelper maskHelper) + { + int msgLength = msg.count; + int offset = WriteHeader(buffer, startOffset, msgLength, setMask); + + if (setMask) + { + offset = maskHelper.WriteMask(buffer, offset); + } + + msg.CopyTo(buffer, offset); + offset += msgLength; + + // dump before mask on + // Log.DumpBuffer("[SimpleWebTransport] Send", buffer, startOffset, offset); + + if (setMask) + { + int messageOffset = offset - msgLength; + MessageProcessor.ToggleMask(buffer, messageOffset, msgLength, buffer, messageOffset - Constants.MaskSize); + } + + return offset; + } + + public static int WriteHeader(byte[] buffer, int startOffset, int msgLength, bool setMask) + { + int sendLength = 0; + const byte finished = 128; + const byte byteOpCode = 2; + + buffer[startOffset + 0] = finished | byteOpCode; + sendLength++; + + if (msgLength <= Constants.BytePayloadLength) + { + buffer[startOffset + 1] = (byte)msgLength; + sendLength++; + } + else if (msgLength <= ushort.MaxValue) + { + buffer[startOffset + 1] = 126; + buffer[startOffset + 2] = (byte)(msgLength >> 8); + buffer[startOffset + 3] = (byte)msgLength; + sendLength += 3; + } + else + { + buffer[startOffset + 1] = 127; + // must be 64 bytes, but we only have 32 bit length, so first 4 bits are 0 + buffer[startOffset + 2] = 0; + buffer[startOffset + 3] = 0; + buffer[startOffset + 4] = 0; + buffer[startOffset + 5] = 0; + buffer[startOffset + 6] = (byte)(msgLength >> 24); + buffer[startOffset + 7] = (byte)(msgLength >> 16); + buffer[startOffset + 8] = (byte)(msgLength >> 8); + buffer[startOffset + 9] = (byte)msgLength; + + sendLength += 9; + } + + if (setMask) + buffer[startOffset + 1] |= 0b1000_0000; + + return sendLength + startOffset; + } + + } + sealed class MaskHelper : IDisposable + { + readonly byte[] maskBuffer; + readonly RNGCryptoServiceProvider random; + + public MaskHelper() + { + maskBuffer = new byte[4]; + random = new RNGCryptoServiceProvider(); + } + public void Dispose() + { + random.Dispose(); + } + + public int WriteMask(byte[] buffer, int offset) + { + random.GetBytes(maskBuffer); + Buffer.BlockCopy(maskBuffer, 0, buffer, offset, 4); + + return offset + 4; + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/SendLoop.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/SendLoop.cs.meta new file mode 100644 index 0000000..09dfd1e --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/SendLoop.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f87dd81736d9c824db67f808ac71841d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/TcpConfig.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/TcpConfig.cs new file mode 100644 index 0000000..230cd7a --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/TcpConfig.cs @@ -0,0 +1,26 @@ +using System.Net.Sockets; + +namespace Mirror.SimpleWeb +{ + [System.Serializable] + public struct TcpConfig + { + public readonly bool noDelay; + public readonly int sendTimeout; + public readonly int receiveTimeout; + + public TcpConfig(bool noDelay, int sendTimeout, int receiveTimeout) + { + this.noDelay = noDelay; + this.sendTimeout = sendTimeout; + this.receiveTimeout = receiveTimeout; + } + + public void ApplyTo(TcpClient client) + { + client.SendTimeout = sendTimeout; + client.ReceiveTimeout = receiveTimeout; + client.NoDelay = noDelay; + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/TcpConfig.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/TcpConfig.cs.meta new file mode 100644 index 0000000..62ba232 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/TcpConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 81ac8d35f28fab14b9edda5cd9d4fc86 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Utils.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Utils.cs new file mode 100644 index 0000000..b8a860c --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Utils.cs @@ -0,0 +1,13 @@ +using System.Threading; + +namespace Mirror.SimpleWeb +{ + internal static class Utils + { + public static void CheckForInterupt() + { + // sleep in order to check for ThreadInterruptedException + Thread.Sleep(1); + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Utils.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Utils.cs.meta new file mode 100644 index 0000000..79a1583 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Common/Utils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4643ffb4cb0562847b1ae925d07e15b6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/LICENSE b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/LICENSE new file mode 100644 index 0000000..d2b4728 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 James Frowen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/LICENSE.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/LICENSE.meta new file mode 100644 index 0000000..8ece59e --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/LICENSE.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0a0cf751b4a201242ac60b4adbc54657 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/README.txt b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/README.txt new file mode 100644 index 0000000..fd59b3d --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/README.txt @@ -0,0 +1,19 @@ +SimpleWebTransport is a Transport that implements websocket for Webgl +Can be used in High level networking solution like Mirror or Mirage +This transport can also work on standalone builds and has support for +encryption with websocket secure. + +Requirements: + Unity 2019.4 LTS + +Documentation: + https://mirror-networking.gitbook.io/docs/ + https://github.com/James-Frowen/SimpleWebTransport/blob/master/README.md + +Support: + Discord: https://discord.gg/BZTQcftBkE + Bug Reports: https://github.com/James-Frowen/SimpleWebTransport/issues + + +**To get most recent updates and fixes download from github** +https://github.com/James-Frowen/SimpleWebTransport/releases diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/README.txt.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/README.txt.meta new file mode 100644 index 0000000..b63fe39 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/README.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0e3971d5783109f4d9ce93c7a689d701 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server.meta new file mode 100644 index 0000000..31f317f --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0e599e92544d43344a9a9060052add28 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerHandshake.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerHandshake.cs new file mode 100644 index 0000000..e603b83 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerHandshake.cs @@ -0,0 +1,156 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Mirror.SimpleWeb +{ + /// + /// Handles Handshakes from new clients on the server + /// The server handshake has buffers to reduce allocations when clients connect + /// + internal class ServerHandshake + { + const int GetSize = 3; + const int ResponseLength = 129; + const int KeyLength = 24; + const int MergedKeyLength = 60; + const string KeyHeaderString = "\r\nSec-WebSocket-Key: "; + // this isn't an official max, just a reasonable size for a websocket handshake + readonly int maxHttpHeaderSize = 3000; + + // SHA-1 is the websocket standard: + // https://www.rfc-editor.org/rfc/rfc6455 + // we should follow the standard, even though SHA1 is considered weak: + // https://stackoverflow.com/questions/38038841/why-is-sha-1-considered-insecure + readonly SHA1 sha1 = SHA1.Create(); + readonly BufferPool bufferPool; + + public ServerHandshake(BufferPool bufferPool, int handshakeMaxSize) + { + this.bufferPool = bufferPool; + maxHttpHeaderSize = handshakeMaxSize; + } + + ~ServerHandshake() + { + sha1.Dispose(); + } + + public bool TryHandshake(Connection conn) + { + Stream stream = conn.stream; + + using (ArrayBuffer getHeader = bufferPool.Take(GetSize)) + { + if (!ReadHelper.TryRead(stream, getHeader.array, 0, GetSize)) + return false; + + getHeader.count = GetSize; + + if (!IsGet(getHeader.array)) + { + Log.Warn($"[SimpleWebTransport] First bytes from client was not 'GET' for handshake, instead was {Log.BufferToString(getHeader.array, 0, GetSize)}", false); + return false; + } + } + + string msg = ReadToEndForHandshake(stream); + + if (string.IsNullOrEmpty(msg)) + return false; + + try + { + AcceptHandshake(stream, msg); + + conn.request = new Request(msg); + conn.remoteAddress = conn.CalculateAddress(); + + return true; + } + catch (ArgumentException e) + { + Log.InfoException(e); + return false; + } + } + + string ReadToEndForHandshake(Stream stream) + { + using (ArrayBuffer readBuffer = bufferPool.Take(maxHttpHeaderSize)) + { + int? readCountOrFail = ReadHelper.SafeReadTillMatch(stream, readBuffer.array, 0, maxHttpHeaderSize, Constants.endOfHandshake); + if (!readCountOrFail.HasValue) + return null; + + int readCount = readCountOrFail.Value; + + string msg = Encoding.ASCII.GetString(readBuffer.array, 0, readCount); + // GET isn't in the bytes we read here, so we need to add it back + msg = $"GET{msg}"; + Log.Info($"Client Handshake Message:\r\n{msg}", false); + + return msg; + } + } + + static bool IsGet(byte[] getHeader) + { + // just check bytes here instead of using Encoding.ASCII + return getHeader[0] == 71 && // G + getHeader[1] == 69 && // E + getHeader[2] == 84; // T + } + + void AcceptHandshake(Stream stream, string msg) + { + using ( + ArrayBuffer keyBuffer = bufferPool.Take(KeyLength + Constants.HandshakeGUIDLength), + responseBuffer = bufferPool.Take(ResponseLength)) + { + GetKey(msg, keyBuffer.array); + AppendGuid(keyBuffer.array); + byte[] keyHash = CreateHash(keyBuffer.array); + CreateResponse(keyHash, responseBuffer.array); + + stream.Write(responseBuffer.array, 0, ResponseLength); + } + } + + static void GetKey(string msg, byte[] keyBuffer) + { + int start = msg.IndexOf(KeyHeaderString, StringComparison.InvariantCultureIgnoreCase) + KeyHeaderString.Length; + + Log.Verbose($"[SimpleWebTransport] Handshake Key: {msg.Substring(start, KeyLength)}", false); + Encoding.ASCII.GetBytes(msg, start, KeyLength, keyBuffer, 0); + } + + static void AppendGuid(byte[] keyBuffer) + { + Buffer.BlockCopy(Constants.HandshakeGUIDBytes, 0, keyBuffer, KeyLength, Constants.HandshakeGUIDLength); + } + + byte[] CreateHash(byte[] keyBuffer) + { + Log.Verbose($"[SimpleWebTransport] Handshake Hashing {Encoding.ASCII.GetString(keyBuffer, 0, MergedKeyLength)}", false); + return sha1.ComputeHash(keyBuffer, 0, MergedKeyLength); + } + + static void CreateResponse(byte[] keyHash, byte[] responseBuffer) + { + string keyHashString = Convert.ToBase64String(keyHash); + + // compiler should merge these strings into 1 string before format + string message = string.Format( + "HTTP/1.1 101 Switching Protocols\r\n" + + "Connection: Upgrade\r\n" + + "Upgrade: websocket\r\n" + + "Sec-WebSocket-Accept: {0}\r\n\r\n", + keyHashString); + + Log.Verbose($"[SimpleWebTransport] Handshake Response length {message.Length}, IsExpected {message.Length == ResponseLength}", false); + Encoding.ASCII.GetBytes(message, 0, ResponseLength, responseBuffer, 0); + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerHandshake.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerHandshake.cs.meta new file mode 100644 index 0000000..6fa74da --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerHandshake.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6268509ac4fb48141b9944c03295da11 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerSslHelper.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerSslHelper.cs new file mode 100644 index 0000000..97daca2 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerSslHelper.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; + +namespace Mirror.SimpleWeb +{ + public struct SslConfig + { + public readonly bool enabled; + public readonly string certPath; + public readonly string certPassword; + public readonly SslProtocols sslProtocols; + + public SslConfig(bool enabled, string certPath, string certPassword, SslProtocols sslProtocols) + { + this.enabled = enabled; + this.certPath = certPath; + this.certPassword = certPassword; + this.sslProtocols = sslProtocols; + } + } + internal class ServerSslHelper + { + readonly SslConfig config; + readonly X509Certificate2 certificate; + + public ServerSslHelper(SslConfig sslConfig) + { + Console.Clear(); + + config = sslConfig; + if (config.enabled) + { + certificate = new X509Certificate2(config.certPath, config.certPassword); + + Console.ForegroundColor = ConsoleColor.Cyan; + Console.WriteLine($"[SimpleWebTransport] SSL Certificate {certificate.Subject} loaded with expiration of {certificate.GetExpirationDateString()}"); + Console.ResetColor(); + } + } + + internal bool TryCreateStream(Connection conn) + { + NetworkStream stream = conn.client.GetStream(); + if (config.enabled) + { + try + { + conn.stream = CreateStream(stream); + return true; + } + catch (Exception e) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"[SimpleWebTransport] Create SSLStream Failed: {e.Message}"); + Console.ResetColor(); + + return false; + } + } + else + { + conn.stream = stream; + return true; + } + } + + Stream CreateStream(NetworkStream stream) + { + SslStream sslStream = new SslStream(stream, true, acceptClient); + sslStream.AuthenticateAsServer(certificate, false, config.sslProtocols, false); + + return sslStream; + } + + // always accept client + bool acceptClient(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true; + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerSslHelper.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerSslHelper.cs.meta new file mode 100644 index 0000000..e0d133c --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/ServerSslHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 11061fee528ebdd43817a275b1e4a317 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/SimpleWebServer.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/SimpleWebServer.cs new file mode 100644 index 0000000..3013994 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/SimpleWebServer.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace Mirror.SimpleWeb +{ + public class SimpleWebServer + { + public event Action onConnect; + public event Action onDisconnect; + public event Action> onData; + public event Action onError; + + readonly int maxMessagesPerTick; + readonly WebSocketServer server; + readonly BufferPool bufferPool; + + public bool Active { get; private set; } + + public SimpleWebServer(int maxMessagesPerTick, TcpConfig tcpConfig, int maxMessageSize, int handshakeMaxSize, SslConfig sslConfig) + { + this.maxMessagesPerTick = maxMessagesPerTick; + // use max because bufferpool is used for both messages and handshake + int max = Math.Max(maxMessageSize, handshakeMaxSize); + bufferPool = new BufferPool(5, 20, max); + server = new WebSocketServer(tcpConfig, maxMessageSize, handshakeMaxSize, sslConfig, bufferPool); + } + + public void Start(ushort port) + { + server.Listen(port); + Active = true; + } + + public void Stop() + { + server.Stop(); + Active = false; + } + + public void SendAll(List connectionIds, ArraySegment source) + { + ArrayBuffer buffer = bufferPool.Take(source.Count); + buffer.CopyFrom(source); + buffer.SetReleasesRequired(connectionIds.Count); + + // make copy of array before for each, data sent to each client is the same + foreach (int id in connectionIds) + server.Send(id, buffer); + } + + public void SendOne(int connectionId, ArraySegment source) + { + ArrayBuffer buffer = bufferPool.Take(source.Count); + buffer.CopyFrom(source); + server.Send(connectionId, buffer); + } + + public bool KickClient(int connectionId) => server.CloseConnection(connectionId); + + public string GetClientAddress(int connectionId) => server.GetClientAddress(connectionId); + + public Request GetClientRequest(int connectionId) => server.GetClientRequest(connectionId); + + /// + /// Processes all new messages + /// + public void ProcessMessageQueue() + { + ProcessMessageQueue(null); + } + + /// + /// Processes all messages while is enabled + /// + /// + public void ProcessMessageQueue(MonoBehaviour behaviour) + { + int processedCount = 0; + bool skipEnabled = behaviour == null; + // check enabled every time in case behaviour was disabled after data + while ( + (skipEnabled || behaviour.enabled) && + processedCount < maxMessagesPerTick && + // Dequeue last + server.receiveQueue.TryDequeue(out Message next) + ) + { + processedCount++; + + switch (next.type) + { + case EventType.Connected: + onConnect?.Invoke(next.connId); + break; + case EventType.Data: + onData?.Invoke(next.connId, next.data.ToSegment()); + next.data.Release(); + break; + case EventType.Disconnected: + onDisconnect?.Invoke(next.connId); + break; + case EventType.Error: + onError?.Invoke(next.connId, next.exception); + break; + } + } + + if (server.receiveQueue.Count > 0) + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine($"SimpleWebServer ProcessMessageQueue has {server.receiveQueue.Count} remaining."); + Console.ResetColor(); + } + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/SimpleWebServer.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/SimpleWebServer.cs.meta new file mode 100644 index 0000000..c8c6f5a --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/SimpleWebServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd51d7896f55a5e48b41a4b526562b0e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/WebSocketServer.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/WebSocketServer.cs new file mode 100644 index 0000000..f3d515e --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/WebSocketServer.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Net.Sockets; +using System.Threading; + +namespace Mirror.SimpleWeb +{ + public class WebSocketServer + { + public readonly ConcurrentQueue receiveQueue = new ConcurrentQueue(); + + readonly TcpConfig tcpConfig; + readonly int maxMessageSize; + + TcpListener listener; + Thread acceptThread; + bool serverStopped; + readonly ServerHandshake handShake; + readonly ServerSslHelper sslHelper; + readonly BufferPool bufferPool; + readonly ConcurrentDictionary connections = new ConcurrentDictionary(); + + int _idCounter = 0; + + public WebSocketServer(TcpConfig tcpConfig, int maxMessageSize, int handshakeMaxSize, SslConfig sslConfig, BufferPool bufferPool) + { + this.tcpConfig = tcpConfig; + this.maxMessageSize = maxMessageSize; + sslHelper = new ServerSslHelper(sslConfig); + this.bufferPool = bufferPool; + handShake = new ServerHandshake(this.bufferPool, handshakeMaxSize); + } + + public void Listen(int port) + { + listener = TcpListener.Create(port); + listener.Start(); + + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine($"[SimpleWebTransport] Server Started on {port}!"); + Console.ResetColor(); + + acceptThread = new Thread(acceptLoop); + acceptThread.IsBackground = true; + acceptThread.Start(); + } + + public void Stop() + { + serverStopped = true; + + // Interrupt then stop so that Exception is handled correctly + acceptThread?.Interrupt(); + listener?.Stop(); + acceptThread = null; + + Console.WriteLine($"[SimpleWebTransport] Server stopped...closing all connections."); + + // make copy so that foreach doesn't break if values are removed + Connection[] connectionsCopy = connections.Values.ToArray(); + foreach (Connection conn in connectionsCopy) + conn.Dispose(); + + connections.Clear(); + } + + void acceptLoop() + { + try + { + try + { + while (true) + { + TcpClient client = listener.AcceptTcpClient(); + tcpConfig.ApplyTo(client); + + // TODO keep track of connections before they are in connections dictionary + // this might not be a problem as HandshakeAndReceiveLoop checks for stop + // and returns/disposes before sending message to queue + Connection conn = new Connection(client, AfterConnectionDisposed); + Console.WriteLine($"[SimpleWebTransport] A client connected {conn}", false); + + // handshake needs its own thread as it needs to wait for message from client + Thread receiveThread = new Thread(() => HandshakeAndReceiveLoop(conn)); + + conn.receiveThread = receiveThread; + + receiveThread.IsBackground = true; + receiveThread.Start(); + } + } + catch (SocketException) + { + // check for Interrupted/Abort + Utils.CheckForInterupt(); + throw; + } + } + catch (ThreadInterruptedException e) { Log.InfoException(e); } + catch (ThreadAbortException e) { Log.InfoException(e); } + catch (Exception e) { Log.Exception(e); } + } + + void HandshakeAndReceiveLoop(Connection conn) + { + try + { + bool success = sslHelper.TryCreateStream(conn); + if (!success) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"[SimpleWebTransport] Failed to create SSL Stream {conn}"); + Console.ResetColor(); + conn.Dispose(); + return; + } + + success = handShake.TryHandshake(conn); + + if (success) + Console.WriteLine($"[SimpleWebTransport] Sent Handshake {conn}, false"); + else + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"[SimpleWebTransport] Handshake Failed {conn}"); + Console.ResetColor(); + conn.Dispose(); + return; + } + + // check if Stop has been called since accepting this client + if (serverStopped) + { + Console.WriteLine("[SimpleWebTransport] Server stops after successful handshake", false); + return; + } + + conn.connId = Interlocked.Increment(ref _idCounter); + connections.TryAdd(conn.connId, conn); + + receiveQueue.Enqueue(new Message(conn.connId, EventType.Connected)); + + Thread sendThread = new Thread(() => + { + SendLoop.Config sendConfig = new SendLoop.Config( + conn, + bufferSize: Constants.HeaderSize + maxMessageSize, + setMask: false); + + SendLoop.Loop(sendConfig); + }); + + conn.sendThread = sendThread; + sendThread.IsBackground = true; + sendThread.Name = $"SendThread {conn.connId}"; + sendThread.Start(); + + ReceiveLoop.Config receiveConfig = new ReceiveLoop.Config( + conn, + maxMessageSize, + expectMask: true, + receiveQueue, + bufferPool); + + ReceiveLoop.Loop(receiveConfig); + } + catch (ThreadInterruptedException e) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"[SimpleWebTransport] Handshake ThreadInterruptedException {e.Message}"); + Console.ResetColor(); + } + catch (ThreadAbortException e) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"[SimpleWebTransport] Handshake ThreadAbortException {e.Message}"); + Console.ResetColor(); + } + catch (Exception e) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine($"[SimpleWebTransport] Handshake Exception {e.Message}"); + Console.ResetColor(); + } + finally + { + // close here in case connect fails + conn.Dispose(); + } + } + + void AfterConnectionDisposed(Connection conn) + { + if (conn.connId != Connection.IdNotSet) + { + receiveQueue.Enqueue(new Message(conn.connId, EventType.Disconnected)); + connections.TryRemove(conn.connId, out Connection _); + } + } + + public void Send(int id, ArrayBuffer buffer) + { + if (connections.TryGetValue(id, out Connection conn)) + { + conn.sendQueue.Enqueue(buffer); + conn.sendPending.Set(); + } + else + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine($"[SimpleWebTransport] Cannot send message to {id} because connection was not found in dictionary. Maybe it disconnected."); + Console.ResetColor(); + } + } + + public bool CloseConnection(int id) + { + if (connections.TryGetValue(id, out Connection conn)) + { + Console.ForegroundColor = ConsoleColor.Magenta; + Console.WriteLine($"[SimpleWebTransport] Kicking connection {id}"); + Console.ResetColor(); + conn.Dispose(); + return true; + } + else + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine($"[SimpleWebTransport] Failed to kick {id} because id not found."); + Console.ResetColor(); + + return false; + } + } + + public string GetClientAddress(int id) + { + if (!connections.TryGetValue(id, out Connection conn)) + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine($"[SimpleWebTransport] Cannot get address of connection {id} because connection was not found in dictionary."); + Console.ResetColor(); + return null; + } + + return conn.remoteAddress; + } + + public Request GetClientRequest(int id) + { + if (!connections.TryGetValue(id, out Connection conn)) + { + Console.ForegroundColor = ConsoleColor.Yellow; + Console.WriteLine($"[SimpleWebTransport] Cant get request of connection {id} because connection was not found in dictionary."); + Console.ResetColor(); + return null; + } + + return conn.request; + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/WebSocketServer.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/WebSocketServer.cs.meta new file mode 100644 index 0000000..0a76a9f --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/Server/WebSocketServer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c434db044777d2439bae5a57d4e8ee7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SimpleWebTransport.asmdef b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SimpleWebTransport.asmdef new file mode 100644 index 0000000..dfb91ea --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SimpleWebTransport.asmdef @@ -0,0 +1,14 @@ +{ + "name": "SimpleWebTransport", + "rootNamespace": "", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SimpleWebTransport.asmdef.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SimpleWebTransport.asmdef.meta new file mode 100644 index 0000000..99755b6 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SimpleWebTransport.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 3b5390adca4e2bb4791cb930316d6f3e +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SslConfigLoader.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SslConfigLoader.cs new file mode 100644 index 0000000..9996793 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SslConfigLoader.cs @@ -0,0 +1,49 @@ +using System.IO; +using System.Security.Authentication; +using UnityEngine; + +namespace Mirror.SimpleWeb +{ + + public class SslConfigLoader + { + internal struct Cert + { + public string path; + public string password; + } + public static SslConfig Load(bool sslEnabled, string sslCertJson, SslProtocols sslProtocols) + { + // don't need to load anything if ssl is not enabled + if (!sslEnabled) + return default; + + string certJsonPath = sslCertJson; + + Cert cert = LoadCertJson(certJsonPath); + + return new SslConfig( + enabled: sslEnabled, + sslProtocols: sslProtocols, + certPath: cert.path, + certPassword: cert.password + ); + } + + internal static Cert LoadCertJson(string certJsonPath) + { + string json = File.ReadAllText(certJsonPath); + Cert cert = JsonUtility.FromJson(json); + + if (string.IsNullOrWhiteSpace(cert.path)) + throw new InvalidDataException("Cert Json didn't not contain \"path\""); + + // don't use IsNullOrWhiteSpace here because whitespace could be a valid password for a cert + // password can also be empty + if (string.IsNullOrEmpty(cert.password)) + cert.password = string.Empty; + + return cert; + } + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SslConfigLoader.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SslConfigLoader.cs.meta new file mode 100644 index 0000000..e653532 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWeb/SslConfigLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dfdb6b97a48a48b498e563e857342da1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWebTransport.cs b/Assets/Mirror/Transports/SimpleWeb/SimpleWebTransport.cs new file mode 100644 index 0000000..45ac066 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWebTransport.cs @@ -0,0 +1,304 @@ +using System; +using System.Net; +using System.Security.Authentication; +using UnityEngine; +using UnityEngine.Serialization; + +namespace Mirror.SimpleWeb +{ + [DisallowMultipleComponent] + public class SimpleWebTransport : Transport, PortTransport + { + public const string NormalScheme = "ws"; + public const string SecureScheme = "wss"; + + [Tooltip("Port to use for server and client")] + public ushort port = 7778; + public ushort Port { get => port; set => port=value; } + + [Tooltip("Tells the client to use the default port. This is useful when connecting to reverse proxy rather than directly to websocket server")] + public bool ClientUseDefaultPort; + + [Tooltip("Protect against allocation attacks by keeping the max message size small. Otherwise an attacker might send multiple fake packets with 2GB headers, causing the server to run out of memory after allocating multiple large packets.")] + public int maxMessageSize = 16 * 1024; + + [Tooltip("Max size for http header send as handshake for websockets")] + public int handshakeMaxSize = 3000; + + [Tooltip("disables nagle algorithm. lowers CPU% and latency but increases bandwidth")] + public bool noDelay = true; + + [Tooltip("Send would stall forever if the network is cut off during a send, so we need a timeout (in milliseconds)")] + public int sendTimeout = 5000; + + [Tooltip("How long without a message before disconnecting (in milliseconds)")] + public int receiveTimeout = 20000; + + [Tooltip("Caps the number of messages the server will process per tick. Allows LateUpdate to finish to let the reset of unity continue in case more messages arrive before they are processed")] + public int serverMaxMessagesPerTick = 10000; + + [Tooltip("Caps the number of messages the client will process per tick. Allows LateUpdate to finish to let the reset of unity continue in case more messages arrive before they are processed")] + public int clientMaxMessagesPerTick = 1000; + + [Header("Server settings")] + + [Tooltip("Groups messages in queue before calling Stream.Send")] + public bool batchSend = true; + + [Tooltip("Waits for 1ms before grouping and sending messages.\n" + + "This gives time for mirror to finish adding message to queue so that less groups need to be made.\n" + + "If WaitBeforeSend is true then BatchSend Will also be set to true")] + public bool waitBeforeSend = true; + + [Header("Ssl Settings")] + [Tooltip("Sets connect scheme to wss. Useful when client needs to connect using wss when TLS is outside of transport.\nNOTE: if sslEnabled is true clientUseWss is also true")] + public bool clientUseWss; + + [Tooltip("Requires wss connections on server, only to be used with SSL cert.json, never with reverse proxy.\nNOTE: if sslEnabled is true clientUseWss is also true")] + public bool sslEnabled; + + [Tooltip("Path to json file that contains path to cert and its password\nUse Json file so that cert password is not included in client builds\nSee Assets/Mirror/Transports/.cert.example.Json")] + public string sslCertJson = "./cert.json"; + + [Tooltip("Protocols that SSL certificate is created to support.")] + public SslProtocols sslProtocols = SslProtocols.Tls12; + + [Header("Debug")] + [Tooltip("Log functions uses ConditionalAttribute which will effect which log methods are allowed.")] + [FormerlySerializedAs("logLevels")] + [SerializeField] Log.Levels _logLevels = Log.Levels.warn; + + /// + /// Gets _logLevels field + /// Sets _logLevels and Log.level fields + /// + public Log.Levels LogLevels + { + get => _logLevels; + set + { + _logLevels = value; + Log.level = _logLevels; + } + } + + SimpleWebClient client; + SimpleWebServer server; + + TcpConfig TcpConfig => new TcpConfig(noDelay, sendTimeout, receiveTimeout); + + void Awake() + { + Log.level = _logLevels; + } + + void OnValidate() + { + Log.level = _logLevels; + } + + public override bool Available() => true; + + public override int GetMaxPacketSize(int channelId = 0) => maxMessageSize; + + public override void Shutdown() + { + client?.Disconnect(); + client = null; + server?.Stop(); + server = null; + } + + #region Client + + string GetClientScheme() => (sslEnabled || clientUseWss) ? SecureScheme : NormalScheme; + + public override bool ClientConnected() + { + // not null and not NotConnected (we want to return true if connecting or disconnecting) + return client != null && client.ConnectionState != ClientState.NotConnected; + } + + public override void ClientConnect(string hostname) + { + UriBuilder builder = new UriBuilder + { + Scheme = GetClientScheme(), + Host = hostname, + }; + // https://github.com/MirrorNetworking/Mirror/pull/3477 + if (!ClientUseDefaultPort) + builder.Port = Port; + + ClientConnect(builder.Uri); + } + + public override void ClientConnect(Uri uri) + { + // connecting or connected + if (ClientConnected()) + { + Debug.LogError("[SimpleWebTransport] Already Connected"); + return; + } + + client = SimpleWebClient.Create(maxMessageSize, clientMaxMessagesPerTick, TcpConfig); + if (client == null) + return; + + client.onConnect += OnClientConnected.Invoke; + + client.onDisconnect += () => + { + OnClientDisconnected.Invoke(); + // clear client here after disconnect event has been sent + // there should be no more messages after disconnect + client = null; + }; + + client.onData += (ArraySegment data) => OnClientDataReceived.Invoke(data, Channels.Reliable); + + client.onError += (Exception e) => + { + OnClientError.Invoke(TransportError.Unexpected, e.ToString()); + ClientDisconnect(); + }; + + client.Connect(uri); + } + + public override void ClientDisconnect() + { + // don't set client null here of messages wont be processed + client?.Disconnect(); + } + + public override void ClientSend(ArraySegment segment, int channelId) + { + if (!ClientConnected()) + { + Debug.LogError("[SimpleWebTransport] Not Connected"); + return; + } + + if (segment.Count > maxMessageSize) + { + Log.Error("[SimpleWebTransport] Message greater than max size"); + return; + } + + if (segment.Count == 0) + { + Log.Error("[SimpleWebTransport] Message count was zero"); + return; + } + + client.Send(segment); + + // call event. might be null if no statistics are listening etc. + OnClientDataSent?.Invoke(segment, Channels.Reliable); + } + + // messages should always be processed in early update + public override void ClientEarlyUpdate() + { + client?.ProcessMessageQueue(this); + } + + #endregion + + #region Server + + string GetServerScheme() => sslEnabled ? SecureScheme : NormalScheme; + + public override Uri ServerUri() + { + UriBuilder builder = new UriBuilder + { + Scheme = GetServerScheme(), + Host = Dns.GetHostName(), + Port = port + }; + return builder.Uri; + } + + public override bool ServerActive() + { + return server != null && server.Active; + } + + public override void ServerStart() + { + if (ServerActive()) + Debug.LogError("[SimpleWebTransport] Server Already Started"); + + SslConfig config = SslConfigLoader.Load(sslEnabled, sslCertJson, sslProtocols); + server = new SimpleWebServer(serverMaxMessagesPerTick, TcpConfig, maxMessageSize, handshakeMaxSize, config); + + server.onConnect += OnServerConnected.Invoke; + server.onDisconnect += OnServerDisconnected.Invoke; + server.onData += (int connId, ArraySegment data) => OnServerDataReceived.Invoke(connId, data, Channels.Reliable); + server.onError += (connId, exception) => OnServerError(connId, TransportError.Unexpected, exception.ToString()); + + SendLoopConfig.batchSend = batchSend || waitBeforeSend; + SendLoopConfig.sleepBeforeSend = waitBeforeSend; + + server.Start(port); + } + + public override void ServerStop() + { + if (!ServerActive()) + Debug.LogError("[SimpleWebTransport] Server Not Active"); + + server.Stop(); + server = null; + } + + public override void ServerDisconnect(int connectionId) + { + if (!ServerActive()) + Debug.LogError("[SimpleWebTransport] Server Not Active"); + + server.KickClient(connectionId); + } + + public override void ServerSend(int connectionId, ArraySegment segment, int channelId) + { + if (!ServerActive()) + { + Log.Error("[SimpleWebTransport] Server Not Active", false); + return; + } + + if (segment.Count > maxMessageSize) + { + Log.Error("[SimpleWebTransport] Message greater than max size", false); + return; + } + + if (segment.Count == 0) + { + Log.Error("[SimpleWebTransport] Message count was zero", false); + return; + } + + server.SendOne(connectionId, segment); + + // call event. might be null if no statistics are listening etc. + OnServerDataSent?.Invoke(connectionId, segment, Channels.Reliable); + } + + public override string ServerGetClientAddress(int connectionId) => server.GetClientAddress(connectionId); + + public Request ServerGetClientRequest(int connectionId) => server.GetClientRequest(connectionId); + + // messages should always be processed in early update + public override void ServerEarlyUpdate() + { + server?.ProcessMessageQueue(this); + } + + #endregion + } +} diff --git a/Assets/Mirror/Transports/SimpleWeb/SimpleWebTransport.cs.meta b/Assets/Mirror/Transports/SimpleWeb/SimpleWebTransport.cs.meta new file mode 100644 index 0000000..381a5c7 --- /dev/null +++ b/Assets/Mirror/Transports/SimpleWeb/SimpleWebTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0110f245bfcfc7d459681f7bd9ebc590 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy.meta b/Assets/Mirror/Transports/Telepathy.meta new file mode 100644 index 0000000..ede2d0e --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 552b3d8382916438d81fe7f39e18db72 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy.meta b/Assets/Mirror/Transports/Telepathy/Telepathy.meta new file mode 100644 index 0000000..345a638 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a1233408bc4b145fb8f6f5a8e95790e0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Client.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Client.cs new file mode 100644 index 0000000..44fa0b5 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Client.cs @@ -0,0 +1,361 @@ +using System; +using System.Net.Sockets; +using System.Threading; + +namespace Telepathy +{ + // ClientState OBJECT that can be handed to the ReceiveThread safely. + // => allows us to create a NEW OBJECT every time we connect and start a + // receive thread. + // => perfectly protects us against data races. fixes all the flaky tests + // where .Connecting or .client would still be used by a dieing thread + // while attempting to use it for a new connection attempt etc. + // => creating a fresh client state each time is the best solution against + // data races here! + class ClientConnectionState : ConnectionState + { + public Thread receiveThread; + + // TcpClient.Connected doesn't check if socket != null, which + // results in NullReferenceExceptions if connection was closed. + // -> let's check it manually instead + public bool Connected => client != null && + client.Client != null && + client.Client.Connected; + + // TcpClient has no 'connecting' state to check. We need to keep track + // of it manually. + // -> checking 'thread.IsAlive && !Connected' is not enough because the + // thread is alive and connected is false for a short moment after + // disconnecting, so this would cause race conditions. + // -> we use a threadsafe bool wrapper so that ThreadFunction can remain + // static (it needs a common lock) + // => Connecting is true from first Connect() call in here, through the + // thread start, until TcpClient.Connect() returns. Simple and clear. + // => bools are atomic according to + // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables + // made volatile so the compiler does not reorder access to it + public volatile bool Connecting; + + // thread safe pipe for received messages + // => inside client connection state so that we can create a new state + // each time we connect + // (unlike server which has one receive pipe for all connections) + public readonly MagnificentReceivePipe receivePipe; + + // constructor always creates new TcpClient for client connection! + public ClientConnectionState(int MaxMessageSize) : base(new TcpClient(), MaxMessageSize) + { + // create receive pipe with max message size for pooling + receivePipe = new MagnificentReceivePipe(MaxMessageSize); + } + + // dispose all the state safely + public void Dispose() + { + // close client + client.Close(); + + // wait until thread finished. this is the only way to guarantee + // that we can call Connect() again immediately after Disconnect + // -> calling .Join would sometimes wait forever, e.g. when + // calling Disconnect while trying to connect to a dead end + receiveThread?.Interrupt(); + + // we interrupted the receive Thread, so we can't guarantee that + // connecting was reset. let's do it manually. + Connecting = false; + + // clear send pipe. no need to hold on to elements. + // (unlike receiveQueue, which is still needed to process the + // latest Disconnected message, etc.) + sendPipe.Clear(); + + // IMPORTANT: DO NOT CLEAR RECEIVE PIPE. + // we still want to process disconnect messages in Tick()! + + // let go of this client completely. the thread ended, no one uses + // it anymore and this way Connected is false again immediately. + client = null; + } + } + + public class Client : Common + { + // events to hook into + // => OnData uses ArraySegment for allocation free receives later + public Action OnConnected; + public Action> OnData; + public Action OnDisconnected; + + // disconnect if send queue gets too big. + // -> avoids ever growing queue memory if network is slower than input + // -> disconnecting is great for load balancing. better to disconnect + // one connection than risking every connection / the whole server + // -> huge queue would introduce multiple seconds of latency anyway + // + // Mirror/DOTSNET use MaxMessageSize batching, so for a 16kb max size: + // limit = 1,000 means 16 MB of memory/connection + // limit = 10,000 means 160 MB of memory/connection + public int SendQueueLimit = 10000; + public int ReceiveQueueLimit = 10000; + + // all client state wrapped into an object that is passed to ReceiveThread + // => we create a new one each time we connect to avoid data races with + // old dieing threads still using the previous object! + ClientConnectionState state; + + // Connected & Connecting + public bool Connected => state != null && state.Connected; + public bool Connecting => state != null && state.Connecting; + + // pipe count, useful for debugging / benchmarks + public int ReceivePipeCount => state != null ? state.receivePipe.TotalCount : 0; + + // constructor + public Client(int MaxMessageSize) : base(MaxMessageSize) {} + + // the thread function + // STATIC to avoid sharing state! + // => pass ClientState object. a new one is created for each new thread! + // => avoids data races where an old dieing thread might still modify + // the current thread's state :/ + static void ReceiveThreadFunction(ClientConnectionState state, string ip, int port, int MaxMessageSize, bool NoDelay, int SendTimeout, int ReceiveTimeout, int ReceiveQueueLimit) + + { + Thread sendThread = null; + + // absolutely must wrap with try/catch, otherwise thread + // exceptions are silent + try + { + // connect (blocking) + state.client.Connect(ip, port); + state.Connecting = false; // volatile! + + // set socket options after the socket was created in Connect() + // (not after the constructor because we clear the socket there) + state.client.NoDelay = NoDelay; + state.client.SendTimeout = SendTimeout; + state.client.ReceiveTimeout = ReceiveTimeout; + + // start send thread only after connected + // IMPORTANT: DO NOT SHARE STATE ACROSS MULTIPLE THREADS! + sendThread = new Thread(() => { ThreadFunctions.SendLoop(0, state.client, state.sendPipe, state.sendPending); }); + sendThread.IsBackground = true; + sendThread.Start(); + + // run the receive loop + // (receive pipe is shared across all loops) + ThreadFunctions.ReceiveLoop(0, state.client, MaxMessageSize, state.receivePipe, ReceiveQueueLimit); + } + catch (SocketException exception) + { + // this happens if (for example) the ip address is correct + // but there is no server running on that ip/port + Log.Info("[Telepathy] Client Recv: failed to connect to ip=" + ip + " port=" + port + " reason=" + exception); + } + catch (ThreadInterruptedException) + { + // expected if Disconnect() aborts it + } + catch (ThreadAbortException) + { + // expected if Disconnect() aborts it + } + catch (ObjectDisposedException) + { + // expected if Disconnect() aborts it and disposed the client + // while ReceiveThread is in a blocking Connect() call + } + catch (Exception exception) + { + // something went wrong. probably important. + Log.Error("[Telepathy] Client Recv Exception: " + exception); + } + // add 'Disconnected' event to receive pipe so that the caller + // knows that the Connect failed. otherwise they will never know + state.receivePipe.Enqueue(0, EventType.Disconnected, default); + + // sendthread might be waiting on ManualResetEvent, + // so let's make sure to end it if the connection + // closed. + // otherwise the send thread would only end if it's + // actually sending data while the connection is + // closed. + sendThread?.Interrupt(); + + // Connect might have failed. thread might have been closed. + // let's reset connecting state no matter what. + state.Connecting = false; + + // if we got here then we are done. ReceiveLoop cleans up already, + // but we may never get there if connect fails. so let's clean up + // here too. + state.client?.Close(); + } + + public void Connect(string ip, int port) + { + // not if already started + if (Connecting || Connected) + { + Log.Warning("[Telepathy] Client can not create connection because an existing connection is connecting or connected"); + return; + } + + // overwrite old thread's state object. create a new one to avoid + // data races where an old dieing thread might still modify the + // current state! fixes all the flaky tests! + state = new ClientConnectionState(MaxMessageSize); + + // We are connecting from now until Connect succeeds or fails + state.Connecting = true; + + // create a TcpClient with perfect IPv4, IPv6 and hostname resolving + // support. + // + // * TcpClient(hostname, port): works but would connect (and block) + // already + // * TcpClient(AddressFamily.InterNetworkV6): takes Ipv4 and IPv6 + // addresses but only connects to IPv6 servers (e.g. Telepathy). + // does NOT connect to IPv4 servers (e.g. Mirror Booster), even + // with DualMode enabled. + // * TcpClient(): creates IPv4 socket internally, which would force + // Connect() to only use IPv4 sockets. + // + // => the trick is to clear the internal IPv4 socket so that Connect + // resolves the hostname and creates either an IPv4 or an IPv6 + // socket as needed (see TcpClient source) + state.client.Client = null; // clear internal IPv4 socket until Connect() + + // client.Connect(ip, port) is blocking. let's call it in the thread + // and return immediately. + // -> this way the application doesn't hang for 30s if connect takes + // too long, which is especially good in games + // -> this way we don't async client.BeginConnect, which seems to + // fail sometimes if we connect too many clients too fast + state.receiveThread = new Thread(() => { + ReceiveThreadFunction(state, ip, port, MaxMessageSize, NoDelay, SendTimeout, ReceiveTimeout, ReceiveQueueLimit); + }); + state.receiveThread.IsBackground = true; + state.receiveThread.Start(); + } + + public void Disconnect() + { + // only if started + if (Connecting || Connected) + { + // dispose all the state safely + state.Dispose(); + + // IMPORTANT: DO NOT set state = null! + // we still want to process the pipe's disconnect message etc.! + } + } + + // send message to server using socket connection. + // arraysegment for allocation free sends later. + // -> the segment's array is only used until Send() returns! + public bool Send(ArraySegment message) + { + if (Connected) + { + // respect max message size to avoid allocation attacks. + if (message.Count <= MaxMessageSize) + { + // check send pipe limit + if (state.sendPipe.Count < SendQueueLimit) + { + // add to thread safe send pipe and return immediately. + // calling Send here would be blocking (sometimes for long + // times if other side lags or wire was disconnected) + state.sendPipe.Enqueue(message); + state.sendPending.Set(); // interrupt SendThread WaitOne() + return true; + } + // disconnect if send queue gets too big. + // -> avoids ever growing queue memory if network is slower + // than input + // -> avoids ever growing latency as well + // + // note: while SendThread always grabs the WHOLE send queue + // immediately, it's still possible that the sending + // blocks for so long that the send queue just gets + // way too big. have a limit - better safe than sorry. + else + { + // log the reason + Log.Warning($"[Telepathy] Client.Send: sendPipe reached limit of {SendQueueLimit}. This can happen if we call send faster than the network can process messages. Disconnecting to avoid ever growing memory & latency."); + + // just close it. send thread will take care of the rest. + state.client.Close(); + return false; + } + } + Log.Error("[Telepathy] Client.Send: message too big: " + message.Count + ". Limit: " + MaxMessageSize); + return false; + } + Log.Warning("[Telepathy] Client.Send: not connected!"); + return false; + } + + // tick: processes up to 'limit' messages + // => limit parameter to avoid deadlocks / too long freezes if server or + // client is too slow to process network load + // => Mirror & DOTSNET need to have a process limit anyway. + // might as well do it here and make life easier. + // => returns amount of remaining messages to process, so the caller + // can call tick again as many times as needed (or up to a limit) + // + // Tick() may process multiple messages, but Mirror needs a way to stop + // processing immediately if a scene change messages arrives. Mirror + // can't process any other messages during a scene change. + // (could be useful for others too) + // => make sure to allocate the lambda only once in transports + public int Tick(int processLimit, Func checkEnabled = null) + { + // only if state was created yet (after connect()) + // note: we don't check 'only if connected' because we want to still + // process Disconnect messages afterwards too! + if (state == null) + return 0; + + // process up to 'processLimit' messages + for (int i = 0; i < processLimit; ++i) + { + // check enabled in case a Mirror scene message arrived + if (checkEnabled != null && !checkEnabled()) + break; + + // peek first. allows us to process the first queued entry while + // still keeping the pooled byte[] alive by not removing anything. + if (state.receivePipe.TryPeek(out int _, out EventType eventType, out ArraySegment message)) + { + switch (eventType) + { + case EventType.Connected: + OnConnected?.Invoke(); + break; + case EventType.Data: + OnData?.Invoke(message); + break; + case EventType.Disconnected: + OnDisconnected?.Invoke(); + break; + } + + // IMPORTANT: now dequeue and return it to pool AFTER we are + // done processing the event. + state.receivePipe.TryDequeue(); + } + // no more messages. stop the loop. + else break; + } + + // return what's left to process for next time + return state.receivePipe.TotalCount; + } + } +} diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Client.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Client.cs.meta new file mode 100644 index 0000000..1b6d222 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Client.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a5b95294cc4ec4b15aacba57531c7985 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Common.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Common.cs new file mode 100644 index 0000000..15265f9 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Common.cs @@ -0,0 +1,39 @@ +// common code used by server and client +namespace Telepathy +{ + public abstract class Common + { + // IMPORTANT: DO NOT SHARE STATE ACROSS SEND/RECV LOOPS (DATA RACES) + // (except receive pipe which is used for all threads) + + // NoDelay disables nagle algorithm. lowers CPU% and latency but + // increases bandwidth + public bool NoDelay = true; + + // Prevent allocation attacks. Each packet is prefixed with a length + // header, so an attacker could send a fake packet with length=2GB, + // causing the server to allocate 2GB and run out of memory quickly. + // -> simply increase max packet size if you want to send around bigger + // files! + // -> 16KB per message should be more than enough. + public readonly int MaxMessageSize; + + // Send would stall forever if the network is cut off during a send, so + // we need a timeout (in milliseconds) + public int SendTimeout = 5000; + + // Default TCP receive time out can be huge (minutes). + // That's way too much for games, let's make it configurable. + // we need a timeout (in milliseconds) + // => '0' means disabled + // => disabled by default because some people might use Telepathy + // without Mirror and without sending pings, so timeouts are likely + public int ReceiveTimeout = 0; + + // constructor + protected Common(int MaxMessageSize) + { + this.MaxMessageSize = MaxMessageSize; + } + } +} diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Common.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Common.cs.meta new file mode 100644 index 0000000..5d8ab5b --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Common.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c4d56322cf0e248a89103c002a505dab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/ConnectionState.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/ConnectionState.cs new file mode 100644 index 0000000..cdfe3c0 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/ConnectionState.cs @@ -0,0 +1,35 @@ +// both server and client need a connection state object. +// -> server needs it to keep track of multiple connections +// -> client needs it to safely create a new connection state on every new +// connect in order to avoid data races where a dieing thread might still +// modify the current state. can't happen if we create a new state each time! +// (fixes all the flaky tests) +// +// ... besides, it also allows us to share code! +using System.Net.Sockets; +using System.Threading; + +namespace Telepathy +{ + public class ConnectionState + { + public TcpClient client; + + // thread safe pipe to send messages from main thread to send thread + public readonly MagnificentSendPipe sendPipe; + + // ManualResetEvent to wake up the send thread. better than Thread.Sleep + // -> call Set() if everything was sent + // -> call Reset() if there is something to send again + // -> call WaitOne() to block until Reset was called + public ManualResetEvent sendPending = new ManualResetEvent(false); + + public ConnectionState(TcpClient client, int MaxMessageSize) + { + this.client = client; + + // create send pipe with max message size for pooling + sendPipe = new MagnificentSendPipe(MaxMessageSize); + } + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/ConnectionState.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/ConnectionState.cs.meta new file mode 100644 index 0000000..3dcceaf --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/ConnectionState.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: af95e2b6f6343411aa8bdf871abd7b1b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Empty.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty.meta new file mode 100644 index 0000000..1bc9652 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 885e89897e3a03241827ab7a14fe5fa0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Logger.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Logger.cs new file mode 100644 index 0000000..4f7722a --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Logger.cs @@ -0,0 +1 @@ +// removed 2021-02-04 \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Logger.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Logger.cs.meta new file mode 100644 index 0000000..304866f --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Logger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aa8d703f0b73f4d6398b76812719b68b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Message.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Message.cs new file mode 100644 index 0000000..4f7722a --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Message.cs @@ -0,0 +1 @@ +// removed 2021-02-04 \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Message.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Message.cs.meta new file mode 100644 index 0000000..5937bb9 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/Message.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aedf812e9637b4f92a35db1aedca8c92 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/SafeQueue.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/SafeQueue.cs new file mode 100644 index 0000000..7899911 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/SafeQueue.cs @@ -0,0 +1 @@ +// removed 2021-02-04 diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/SafeQueue.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/SafeQueue.cs.meta new file mode 100644 index 0000000..f3a9310 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/SafeQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8fc06e2fb29854a0c9e90c0188d36a08 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/ThreadExtensions.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/ThreadExtensions.cs new file mode 100644 index 0000000..85dece4 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/ThreadExtensions.cs @@ -0,0 +1 @@ +// removed 2021-02-04 diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/ThreadExtensions.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/ThreadExtensions.cs.meta new file mode 100644 index 0000000..77c885d --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Empty/ThreadExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 64df4eaebe4ff9a43a9fb318c3e8e321 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/EventType.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/EventType.cs new file mode 100644 index 0000000..66bc3b4 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/EventType.cs @@ -0,0 +1,9 @@ +namespace Telepathy +{ + public enum EventType + { + Connected, + Data, + Disconnected + } +} diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/EventType.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/EventType.cs.meta new file mode 100644 index 0000000..ac88c1b --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/EventType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 49f1a330755814803be5f27f493e1910 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/LICENSE b/Assets/Mirror/Transports/Telepathy/Telepathy/LICENSE new file mode 100644 index 0000000..680deef --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018, vis2k + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/LICENSE.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/LICENSE.meta new file mode 100644 index 0000000..4d7664e --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/LICENSE.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0ba11103b95fd4721bffbb08440d5b8e +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Log.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Log.cs new file mode 100644 index 0000000..2d50aa3 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Log.cs @@ -0,0 +1,15 @@ +// A simple logger class that uses Console.WriteLine by default. +// Can also do Logger.LogMethod = Debug.Log for Unity etc. +// (this way we don't have to depend on UnityEngine.DLL and don't need a +// different version for every UnityEngine version here) +using System; + +namespace Telepathy +{ + public static class Log + { + public static Action Info = Console.WriteLine; + public static Action Warning = Console.WriteLine; + public static Action Error = Console.Error.WriteLine; + } +} diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Log.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Log.cs.meta new file mode 100644 index 0000000..8f78650 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Log.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0a123d054bef34d059057ac2ce936605 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentReceivePipe.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentReceivePipe.cs new file mode 100644 index 0000000..2e10318 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentReceivePipe.cs @@ -0,0 +1,222 @@ +// a magnificent receive pipe to shield us from all of life's complexities. +// safely sends messages from receive thread to main thread. +// -> thread safety built in +// -> byte[] pooling coming in the future +// +// => hides all the complexity from telepathy +// => easy to switch between stack/queue/concurrentqueue/etc. +// => easy to test +using System; +using System.Collections.Generic; + +namespace Telepathy +{ + public class MagnificentReceivePipe + { + // queue entry message. only used in here. + // -> byte arrays are always of 4 + MaxMessageSize + // -> ArraySegment indicates the actual message content + struct Entry + { + public int connectionId; + public EventType eventType; + public ArraySegment data; + public Entry(int connectionId, EventType eventType, ArraySegment data) + { + this.connectionId = connectionId; + this.eventType = eventType; + this.data = data; + } + } + + // message queue + // ConcurrentQueue allocates. lock{} instead. + // + // IMPORTANT: lock{} all usages! + readonly Queue queue = new Queue(); + + // byte[] pool to avoid allocations + // Take & Return is beautifully encapsulated in the pipe. + // the outside does not need to worry about anything. + // and it can be tested easily. + // + // IMPORTANT: lock{} all usages! + Pool pool; + + // unfortunately having one receive pipe per connetionId is way slower + // in CCU tests. right now we have one pipe for all connections. + // => we still need to limit queued messages per connection to avoid one + // spamming connection being able to slow down everyone else since + // the queue would be full of just this connection's messages forever + // => let's use a simpler per-connectionId counter for now + Dictionary queueCounter = new Dictionary(); + + // constructor + public MagnificentReceivePipe(int MaxMessageSize) + { + // initialize pool to create max message sized byte[]s each time + pool = new Pool(() => new byte[MaxMessageSize]); + } + + // return amount of queued messages for this connectionId. + // for statistics. don't call Count and assume that it's the same after + // the call. + public int Count(int connectionId) + { + lock (this) + { + return queueCounter.TryGetValue(connectionId, out int count) + ? count + : 0; + } + } + + // total count + public int TotalCount + { + get { lock (this) { return queue.Count; } } + } + + // pool count for testing + public int PoolCount + { + get { lock (this) { return pool.Count(); } } + } + + // enqueue a message + // -> ArraySegment to avoid allocations later + // -> parameters passed directly so it's more obvious that we don't just + // queue a passed 'Message', instead we copy the ArraySegment into + // a byte[] and store it internally, etc.) + public void Enqueue(int connectionId, EventType eventType, ArraySegment message) + { + // pool & queue usage always needs to be locked + lock (this) + { + // does this message have a data array content? + ArraySegment segment = default; + if (message != default) + { + // ArraySegment is only valid until returning. + // copy it into a byte[] that we can store. + // ArraySegment array is only valid until returning, so copy + // it into a byte[] that we can queue safely. + + // get one from the pool first to avoid allocations + byte[] bytes = pool.Take(); + + // copy into it + Buffer.BlockCopy(message.Array, message.Offset, bytes, 0, message.Count); + + // indicate which part is the message + segment = new ArraySegment(bytes, 0, message.Count); + } + + // enqueue it + // IMPORTANT: pass the segment around pool byte[], + // NOT the 'message' that is only valid until returning! + Entry entry = new Entry(connectionId, eventType, segment); + queue.Enqueue(entry); + + // increase counter for this connectionId + int oldCount = Count(connectionId); + queueCounter[connectionId] = oldCount + 1; + } + } + + // peek the next message + // -> allows the caller to process it while pipe still holds on to the + // byte[] + // -> TryDequeue should be called after processing, so that the message + // is actually dequeued and the byte[] is returned to pool! + // => see TryDequeue comments! + // + // IMPORTANT: TryPeek & Dequeue need to be called from the SAME THREAD! + public bool TryPeek(out int connectionId, out EventType eventType, out ArraySegment data) + { + connectionId = 0; + eventType = EventType.Disconnected; + data = default; + + // pool & queue usage always needs to be locked + lock (this) + { + if (queue.Count > 0) + { + Entry entry = queue.Peek(); + connectionId = entry.connectionId; + eventType = entry.eventType; + data = entry.data; + return true; + } + return false; + } + } + + // dequeue the next message + // -> simply dequeues and returns the byte[] to pool (if any) + // -> use Peek to actually process the first element while the pipe + // still holds on to the byte[] + // -> doesn't return the element because the byte[] needs to be returned + // to the pool in dequeue. caller can't be allowed to work with a + // byte[] that is already returned to pool. + // => Peek & Dequeue is the most simple, clean solution for receive + // pipe pooling to avoid allocations! + // + // IMPORTANT: TryPeek & Dequeue need to be called from the SAME THREAD! + public bool TryDequeue() + { + // pool & queue usage always needs to be locked + lock (this) + { + if (queue.Count > 0) + { + // dequeue from queue + Entry entry = queue.Dequeue(); + + // return byte[] to pool (if any). + // not all message types have byte[] contents. + if (entry.data != default) + { + pool.Return(entry.data.Array); + } + + // decrease counter for this connectionId + queueCounter[entry.connectionId]--; + + // remove if zero. don't want to keep old connectionIds in + // there forever, it would cause slowly growing memory. + if (queueCounter[entry.connectionId] == 0) + queueCounter.Remove(entry.connectionId); + + return true; + } + return false; + } + } + + public void Clear() + { + // pool & queue usage always needs to be locked + lock (this) + { + // clear queue, but via dequeue to return each byte[] to pool + while (queue.Count > 0) + { + // dequeue + Entry entry = queue.Dequeue(); + + // return byte[] to pool (if any). + // not all message types have byte[] contents. + if (entry.data != default) + { + pool.Return(entry.data.Array); + } + } + + // clear counter too + queueCounter.Clear(); + } + } + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentReceivePipe.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentReceivePipe.cs.meta new file mode 100644 index 0000000..614bab6 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentReceivePipe.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 010a208972a9a4e0cb0e7c18a60b4494 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentSendPipe.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentSendPipe.cs new file mode 100644 index 0000000..be456a0 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentSendPipe.cs @@ -0,0 +1,165 @@ +// a magnificent send pipe to shield us from all of life's complexities. +// safely sends messages from main thread to send thread. +// -> thread safety built in +// -> byte[] pooling coming in the future +// +// => hides all the complexity from telepathy +// => easy to switch between stack/queue/concurrentqueue/etc. +// => easy to test + +using System; +using System.Collections.Generic; + +namespace Telepathy +{ + public class MagnificentSendPipe + { + // message queue + // ConcurrentQueue allocates. lock{} instead. + // -> byte arrays are always of MaxMessageSize + // -> ArraySegment indicates the actual message content + // + // IMPORTANT: lock{} all usages! + readonly Queue> queue = new Queue>(); + + // byte[] pool to avoid allocations + // Take & Return is beautifully encapsulated in the pipe. + // the outside does not need to worry about anything. + // and it can be tested easily. + // + // IMPORTANT: lock{} all usages! + Pool pool; + + // constructor + public MagnificentSendPipe(int MaxMessageSize) + { + // initialize pool to create max message sized byte[]s each time + pool = new Pool(() => new byte[MaxMessageSize]); + } + + // for statistics. don't call Count and assume that it's the same after + // the call. + public int Count + { + get { lock (this) { return queue.Count; } } + } + + // pool count for testing + public int PoolCount + { + get { lock (this) { return pool.Count(); } } + } + + // enqueue a message + // arraysegment for allocation free sends later. + // -> the segment's array is only used until Enqueue() returns! + public void Enqueue(ArraySegment message) + { + // pool & queue usage always needs to be locked + lock (this) + { + // ArraySegment array is only valid until returning, so copy + // it into a byte[] that we can queue safely. + + // get one from the pool first to avoid allocations + byte[] bytes = pool.Take(); + + // copy into it + Buffer.BlockCopy(message.Array, message.Offset, bytes, 0, message.Count); + + // indicate which part is the message + ArraySegment segment = new ArraySegment(bytes, 0, message.Count); + + // now enqueue it + queue.Enqueue(segment); + } + } + + // send threads need to dequeue each byte[] and write it into the socket + // -> dequeueing one byte[] after another works, but it's WAY slower + // than dequeueing all immediately (locks only once) + // lock{} & DequeueAll is WAY faster than ConcurrentQueue & dequeue + // one after another: + // + // uMMORPG 450 CCU + // SafeQueue: 900-1440ms latency + // ConcurrentQueue: 2000ms latency + // + // -> the most obvious solution is to just return a list with all byte[] + // (which allocates) and then write each one into the socket + // -> a faster solution is to serialize each one into one payload buffer + // and pass that to the socket only once. fewer socket calls always + // give WAY better CPU performance(!) + // -> to avoid allocating a new list of entries each time, we simply + // serialize all entries into the payload here already + // => having all this complexity built into the pipe makes testing and + // modifying the algorithm super easy! + // + // IMPORTANT: serializing in here will allow us to return the byte[] + // entries back to a pool later to completely avoid + // allocations! + public bool DequeueAndSerializeAll(ref byte[] payload, out int packetSize) + { + // pool & queue usage always needs to be locked + lock (this) + { + // do nothing if empty + packetSize = 0; + if (queue.Count == 0) + return false; + + // we might have multiple pending messages. merge into one + // packet to avoid TCP overheads and improve performance. + // + // IMPORTANT: Mirror & DOTSNET already batch into MaxMessageSize + // chunks, but we STILL pack all pending messages + // into one large payload so we only give it to TCP + // ONCE. This is HUGE for performance so we keep it! + packetSize = 0; + foreach (ArraySegment message in queue) + packetSize += 4 + message.Count; // header + content + + // create payload buffer if not created yet or previous one is + // too small + // IMPORTANT: payload.Length might be > packetSize! don't use it! + if (payload == null || payload.Length < packetSize) + payload = new byte[packetSize]; + + // dequeue all byte[] messages and serialize into the packet + int position = 0; + while (queue.Count > 0) + { + // dequeue + ArraySegment message = queue.Dequeue(); + + // write header (size) into buffer at position + Utils.IntToBytesBigEndianNonAlloc(message.Count, payload, position); + position += 4; + + // copy message into payload at position + Buffer.BlockCopy(message.Array, message.Offset, payload, position, message.Count); + position += message.Count; + + // return to pool so it can be reused (avoids allocations!) + pool.Return(message.Array); + } + + // we did serialize something + return true; + } + } + + public void Clear() + { + // pool & queue usage always needs to be locked + lock (this) + { + // clear queue, but via dequeue to return each byte[] to pool + while (queue.Count > 0) + { + pool.Return(queue.Dequeue().Array); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentSendPipe.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentSendPipe.cs.meta new file mode 100644 index 0000000..cf1415f --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/MagnificentSendPipe.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d490021c2e6a64374bc88168cec75c70 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/NetworkStreamExtensions.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/NetworkStreamExtensions.cs new file mode 100644 index 0000000..7cfd73c --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/NetworkStreamExtensions.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; +using System.Net.Sockets; + +namespace Telepathy +{ + public static class NetworkStreamExtensions + { + // .Read returns '0' if remote closed the connection but throws an + // IOException if we voluntarily closed our own connection. + // + // let's add a ReadSafely method that returns '0' in both cases so we don't + // have to worry about exceptions, since a disconnect is a disconnect... + public static int ReadSafely(this NetworkStream stream, byte[] buffer, int offset, int size) + { + try + { + return stream.Read(buffer, offset, size); + } + // IOException happens if we voluntarily closed our own connection. + catch (IOException) + { + return 0; + } + // ObjectDisposedException can be thrown if Client.Disconnect() + // disposes the stream, while we are still trying to read here. + // catching it fixes https://github.com/vis2k/Telepathy/pull/104 + catch (ObjectDisposedException) + { + return 0; + } + } + + // helper function to read EXACTLY 'n' bytes + // -> default .Read reads up to 'n' bytes. this function reads exactly + // 'n' bytes + // -> this is blocking until 'n' bytes were received + // -> immediately returns false in case of disconnects + public static bool ReadExactly(this NetworkStream stream, byte[] buffer, int amount) + { + // there might not be enough bytes in the TCP buffer for .Read to read + // the whole amount at once, so we need to keep trying until we have all + // the bytes (blocking) + // + // note: this just is a faster version of reading one after another: + // for (int i = 0; i < amount; ++i) + // if (stream.Read(buffer, i, 1) == 0) + // return false; + // return true; + int bytesRead = 0; + while (bytesRead < amount) + { + // read up to 'remaining' bytes with the 'safe' read extension + int remaining = amount - bytesRead; + int result = stream.ReadSafely(buffer, bytesRead, remaining); + + // .Read returns 0 if disconnected + if (result == 0) + return false; + + // otherwise add to bytes read + bytesRead += result; + } + return true; + } + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/NetworkStreamExtensions.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/NetworkStreamExtensions.cs.meta new file mode 100644 index 0000000..e7e5744 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/NetworkStreamExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a8076c43fa8d4d45831adae232d4d3c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Pool.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Pool.cs new file mode 100644 index 0000000..4ec4fd2 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Pool.cs @@ -0,0 +1,34 @@ +// pool to avoid allocations. originally from libuv2k. +using System; +using System.Collections.Generic; + +namespace Telepathy +{ + public class Pool + { + // objects + readonly Stack objects = new Stack(); + + // some types might need additional parameters in their constructor, so + // we use a Func generator + readonly Func objectGenerator; + + // constructor + public Pool(Func objectGenerator) + { + this.objectGenerator = objectGenerator; + } + + // take an element from the pool, or create a new one if empty + public T Take() => objects.Count > 0 ? objects.Pop() : objectGenerator(); + + // return an element to the pool + public void Return(T item) => objects.Push(item); + + // clear the pool with the disposer function applied to each object + public void Clear() => objects.Clear(); + + // count to see how many objects are in the pool. useful for tests. + public int Count() => objects.Count; + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Pool.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Pool.cs.meta new file mode 100644 index 0000000..9a7dafc --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Pool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d3e530f6872642ec81e9b8b76277c93 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Server.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Server.cs new file mode 100644 index 0000000..687b90e --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Server.cs @@ -0,0 +1,402 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace Telepathy +{ + public class Server : Common + { + // events to hook into + // => OnData uses ArraySegment for allocation free receives later + public Action OnConnected; + public Action> OnData; + public Action OnDisconnected; + + // listener + public TcpListener listener; + Thread listenerThread; + + // disconnect if send queue gets too big. + // -> avoids ever growing queue memory if network is slower than input + // -> disconnecting is great for load balancing. better to disconnect + // one connection than risking every connection / the whole server + // -> huge queue would introduce multiple seconds of latency anyway + // + // Mirror/DOTSNET use MaxMessageSize batching, so for a 16kb max size: + // limit = 1,000 means 16 MB of memory/connection + // limit = 10,000 means 160 MB of memory/connection + public int SendQueueLimit = 10000; + public int ReceiveQueueLimit = 10000; + + // thread safe pipe for received messages + // IMPORTANT: unfortunately using one pipe per connection is way slower + // when testing 150 CCU. we need to use one pipe for all + // connections. this scales beautifully. + protected MagnificentReceivePipe receivePipe; + + // pipe count, useful for debugging / benchmarks + public int ReceivePipeTotalCount => receivePipe.TotalCount; + + // clients with + readonly ConcurrentDictionary clients = new ConcurrentDictionary(); + + // connectionId counter + int counter; + + // public next id function in case someone needs to reserve an id + // (e.g. if hostMode should always have 0 connection and external + // connections should start at 1, etc.) + public int NextConnectionId() + { + int id = Interlocked.Increment(ref counter); + + // it's very unlikely that we reach the uint limit of 2 billion. + // even with 1 new connection per second, this would take 68 years. + // -> but if it happens, then we should throw an exception because + // the caller probably should stop accepting clients. + // -> it's hardly worth using 'bool Next(out id)' for that case + // because it's just so unlikely. + if (id == int.MaxValue) + { + throw new Exception("connection id limit reached: " + id); + } + + return id; + } + + // check if the server is running + public bool Active => listenerThread != null && listenerThread.IsAlive; + + // constructor + public Server(int MaxMessageSize) : base(MaxMessageSize) {} + + // the listener thread's listen function + // note: no maxConnections parameter. high level API should handle that. + // (Transport can't send a 'too full' message anyway) + void Listen(int port) + { + // absolutely must wrap with try/catch, otherwise thread + // exceptions are silent + try + { + // start listener on all IPv4 and IPv6 address via .Create + listener = TcpListener.Create(port); + listener.Server.NoDelay = NoDelay; + // IMPORTANT: do not set send/receive timeouts on listener. + // On linux setting the recv timeout will cause the blocking + // Accept call to timeout with EACCEPT (which mono interprets + // as EWOULDBLOCK). + // https://stackoverflow.com/questions/1917814/eagain-error-for-accept-on-blocking-socket/1918118#1918118 + // => fixes https://github.com/vis2k/Mirror/issues/2695 + // + //listener.Server.SendTimeout = SendTimeout; + //listener.Server.ReceiveTimeout = ReceiveTimeout; + listener.Start(); + Log.Info($"[Telepathy] Starting server on port {port}"); + + // keep accepting new clients + while (true) + { + // wait and accept new client + // note: 'using' sucks here because it will try to + // dispose after thread was started but we still need it + // in the thread + TcpClient client = listener.AcceptTcpClient(); + + // set socket options + client.NoDelay = NoDelay; + client.SendTimeout = SendTimeout; + client.ReceiveTimeout = ReceiveTimeout; + + // generate the next connection id (thread safely) + int connectionId = NextConnectionId(); + + // add to dict immediately + ConnectionState connection = new ConnectionState(client, MaxMessageSize); + clients[connectionId] = connection; + + // spawn a send thread for each client + Thread sendThread = new Thread(() => + { + // wrap in try-catch, otherwise Thread exceptions + // are silent + try + { + // run the send loop + // IMPORTANT: DO NOT SHARE STATE ACROSS MULTIPLE THREADS! + ThreadFunctions.SendLoop(connectionId, client, connection.sendPipe, connection.sendPending); + } + catch (ThreadAbortException) + { + // happens on stop. don't log anything. + // (we catch it in SendLoop too, but it still gets + // through to here when aborting. don't show an + // error.) + } + catch (Exception exception) + { + Log.Error("[Telepathy] Server send thread exception: " + exception); + } + }); + sendThread.IsBackground = true; + sendThread.Start(); + + // spawn a receive thread for each client + Thread receiveThread = new Thread(() => + { + // wrap in try-catch, otherwise Thread exceptions + // are silent + try + { + // run the receive loop + // (receive pipe is shared across all loops) + ThreadFunctions.ReceiveLoop(connectionId, client, MaxMessageSize, receivePipe, ReceiveQueueLimit); + + // IMPORTANT: do NOT remove from clients after the + // thread ends. need to do it in Tick() so that the + // disconnect event in the pipe is still processed. + // (removing client immediately would mean that the + // pipe is lost and the disconnect event is never + // processed) + + // sendthread might be waiting on ManualResetEvent, + // so let's make sure to end it if the connection + // closed. + // otherwise the send thread would only end if it's + // actually sending data while the connection is + // closed. + sendThread.Interrupt(); + } + catch (Exception exception) + { + Log.Error("[Telepathy] Server client thread exception: " + exception); + } + }); + receiveThread.IsBackground = true; + receiveThread.Start(); + } + } + catch (ThreadAbortException exception) + { + // UnityEditor causes AbortException if thread is still + // running when we press Play again next time. that's okay. + Log.Info("[Telepathy] Server thread aborted. That's okay. " + exception); + } + catch (SocketException exception) + { + // calling StopServer will interrupt this thread with a + // 'SocketException: interrupted'. that's okay. + Log.Info("[Telepathy] Server Thread stopped. That's okay. " + exception); + } + catch (Exception exception) + { + // something went wrong. probably important. + Log.Error("[Telepathy] Server Exception: " + exception); + } + } + + // start listening for new connections in a background thread and spawn + // a new thread for each one. + public bool Start(int port) + { + // not if already started + if (Active) return false; + + // create receive pipe with max message size for pooling + // => create new pipes every time! + // if an old receive thread is still finishing up, it might still + // be using the old pipes. we don't want to risk any old data for + // our new start here. + receivePipe = new MagnificentReceivePipe(MaxMessageSize); + + // start the listener thread + // (on low priority. if main thread is too busy then there is not + // much value in accepting even more clients) + Log.Info($"[Telepathy] Starting server on port {port}"); + + listenerThread = new Thread(() => { Listen(port); }); + listenerThread.IsBackground = true; + listenerThread.Priority = ThreadPriority.BelowNormal; + listenerThread.Start(); + return true; + } + + public void Stop() + { + // only if started + if (!Active) return; + + Log.Info("[Telepathy] Server: stopping..."); + + // stop listening to connections so that no one can connect while we + // close the client connections + // (might be null if we call Stop so quickly after Start that the + // thread was interrupted before even creating the listener) + listener?.Stop(); + + // kill listener thread at all costs. only way to guarantee that + // .Active is immediately false after Stop. + // -> calling .Join would sometimes wait forever + listenerThread?.Interrupt(); + listenerThread = null; + + // close all client connections + foreach (KeyValuePair kvp in clients) + { + TcpClient client = kvp.Value.client; + // close the stream if not closed yet. it may have been closed + // by a disconnect already, so use try/catch + try { client.GetStream().Close(); } catch {} + client.Close(); + } + + // clear clients list + clients.Clear(); + + // reset the counter in case we start up again so + // clients get connection ID's starting from 1 + counter = 0; + } + + // send message to client using socket connection. + // arraysegment for allocation free sends later. + // -> the segment's array is only used until Send() returns! + public bool Send(int connectionId, ArraySegment message) + { + // respect max message size to avoid allocation attacks. + if (message.Count <= MaxMessageSize) + { + // find the connection + if (clients.TryGetValue(connectionId, out ConnectionState connection)) + { + // check send pipe limit + if (connection.sendPipe.Count < SendQueueLimit) + { + // add to thread safe send pipe and return immediately. + // calling Send here would be blocking (sometimes for long + // times if other side lags or wire was disconnected) + connection.sendPipe.Enqueue(message); + connection.sendPending.Set(); // interrupt SendThread WaitOne() + return true; + } + // disconnect if send queue gets too big. + // -> avoids ever growing queue memory if network is slower + // than input + // -> disconnecting is great for load balancing. better to + // disconnect one connection than risking every + // connection / the whole server + // + // note: while SendThread always grabs the WHOLE send queue + // immediately, it's still possible that the sending + // blocks for so long that the send queue just gets + // way too big. have a limit - better safe than sorry. + else + { + // log the reason + Log.Warning($"[Telepathy] Server.Send: sendPipe for connection {connectionId} reached limit of {SendQueueLimit}. This can happen if we call send faster than the network can process messages. Disconnecting this connection for load balancing."); + + // just close it. send thread will take care of the rest. + connection.client.Close(); + return false; + } + } + + // sending to an invalid connectionId is expected sometimes. + // for example, if a client disconnects, the server might still + // try to send for one frame before it calls GetNextMessages + // again and realizes that a disconnect happened. + // so let's not spam the console with log messages. + //Logger.Log("Server.Send: invalid connectionId: " + connectionId); + return false; + } + Log.Error("[Telepathy] Server.Send: message too big: " + message.Count + ". Limit: " + MaxMessageSize); + return false; + } + + // client's ip is sometimes needed by the server, e.g. for bans + public string GetClientAddress(int connectionId) + { + // find the connection + if (clients.TryGetValue(connectionId, out ConnectionState connection)) + { + return ((IPEndPoint)connection.client.Client.RemoteEndPoint).Address.ToString(); + } + return ""; + } + + // disconnect (kick) a client + public bool Disconnect(int connectionId) + { + // find the connection + if (clients.TryGetValue(connectionId, out ConnectionState connection)) + { + // just close it. send thread will take care of the rest. + connection.client.Close(); + Log.Info("[Telepathy] Server.Disconnect connectionId:" + connectionId); + return true; + } + return false; + } + + // tick: processes up to 'limit' messages for each connection + // => limit parameter to avoid deadlocks / too long freezes if server or + // client is too slow to process network load + // => Mirror & DOTSNET need to have a process limit anyway. + // might as well do it here and make life easier. + // => returns amount of remaining messages to process, so the caller + // can call tick again as many times as needed (or up to a limit) + // + // Tick() may process multiple messages, but Mirror needs a way to stop + // processing immediately if a scene change messages arrives. Mirror + // can't process any other messages during a scene change. + // (could be useful for others too) + // => make sure to allocate the lambda only once in transports + public int Tick(int processLimit, Func checkEnabled = null) + { + // only if pipe was created yet (after start()) + if (receivePipe == null) + return 0; + + // process up to 'processLimit' messages for this connection + for (int i = 0; i < processLimit; ++i) + { + // check enabled in case a Mirror scene message arrived + if (checkEnabled != null && !checkEnabled()) + break; + + // peek first. allows us to process the first queued entry while + // still keeping the pooled byte[] alive by not removing anything. + if (receivePipe.TryPeek(out int connectionId, out EventType eventType, out ArraySegment message)) + { + switch (eventType) + { + case EventType.Connected: + OnConnected?.Invoke(connectionId); + break; + case EventType.Data: + OnData?.Invoke(connectionId, message); + break; + case EventType.Disconnected: + OnDisconnected?.Invoke(connectionId); + // remove disconnected connection now that the final + // disconnected message was processed. + clients.TryRemove(connectionId, out ConnectionState _); + break; + } + + // IMPORTANT: now dequeue and return it to pool AFTER we are + // done processing the event. + receivePipe.TryDequeue(); + } + // no more messages. stop the loop. + else break; + } + + // return what's left to process for next time + return receivePipe.TotalCount; + } + } +} diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Server.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Server.cs.meta new file mode 100644 index 0000000..9cee8b7 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Server.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb98a16841ccc4338a7e0b4e59136563 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Telepathy.asmdef b/Assets/Mirror/Transports/Telepathy/Telepathy/Telepathy.asmdef new file mode 100644 index 0000000..cd8d16a --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Telepathy.asmdef @@ -0,0 +1,12 @@ +{ + "name": "Telepathy", + "references": [], + "optionalUnityReferences": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [] +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Telepathy.asmdef.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Telepathy.asmdef.meta new file mode 100644 index 0000000..572c127 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Telepathy.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 725ee7191c021de4dbf9269590ded755 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/ThreadFunctions.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/ThreadFunctions.cs new file mode 100644 index 0000000..a5f0324 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/ThreadFunctions.cs @@ -0,0 +1,244 @@ +// IMPORTANT +// force all thread functions to be STATIC. +// => Common.Send/ReceiveLoop is EXTREMELY DANGEROUS because it's too easy to +// accidentally share Common state between threads. +// => header buffer, payload etc. were accidentally shared once after changing +// the thread functions from static to non static +// => C# does not automatically detect data races. best we can do is move all of +// our thread code into static functions and pass all state into them +// +// let's even keep them in a STATIC CLASS so it's 100% obvious that this should +// NOT EVER be changed to non static! +using System; +using System.Net.Sockets; +using System.Threading; + +namespace Telepathy +{ + public static class ThreadFunctions + { + // send message (via stream) with the message structure + // this function is blocking sometimes! + // (e.g. if someone has high latency or wire was cut off) + // -> payload is of multiple < parts + public static bool SendMessagesBlocking(NetworkStream stream, byte[] payload, int packetSize) + { + // stream.Write throws exceptions if client sends with high + // frequency and the server stops + try + { + // write the whole thing + stream.Write(payload, 0, packetSize); + return true; + } + catch (Exception exception) + { + // log as regular message because servers do shut down sometimes + Log.Info("[Telepathy] Send: stream.Write exception: " + exception); + return false; + } + } + // read message (via stream) blocking. + // writes into byte[] and returns bytes written to avoid allocations. + public static bool ReadMessageBlocking(NetworkStream stream, int MaxMessageSize, byte[] headerBuffer, byte[] payloadBuffer, out int size) + { + size = 0; + + // buffer needs to be of Header + MaxMessageSize + if (payloadBuffer.Length != 4 + MaxMessageSize) + { + Log.Error($"[Telepathy] ReadMessageBlocking: payloadBuffer needs to be of size 4 + MaxMessageSize = {4 + MaxMessageSize} instead of {payloadBuffer.Length}"); + return false; + } + + // read exactly 4 bytes for header (blocking) + if (!stream.ReadExactly(headerBuffer, 4)) + return false; + + // convert to int + size = Utils.BytesToIntBigEndian(headerBuffer); + + // protect against allocation attacks. an attacker might send + // multiple fake '2GB header' packets in a row, causing the server + // to allocate multiple 2GB byte arrays and run out of memory. + // + // also protect against size <= 0 which would cause issues + if (size > 0 && size <= MaxMessageSize) + { + // read exactly 'size' bytes for content (blocking) + return stream.ReadExactly(payloadBuffer, size); + } + Log.Warning("[Telepathy] ReadMessageBlocking: possible header attack with a header of: " + size + " bytes."); + return false; + } + + // thread receive function is the same for client and server's clients + public static void ReceiveLoop(int connectionId, TcpClient client, int MaxMessageSize, MagnificentReceivePipe receivePipe, int QueueLimit) + { + // get NetworkStream from client + NetworkStream stream = client.GetStream(); + + // every receive loop needs it's own receive buffer of + // HeaderSize + MaxMessageSize + // to avoid runtime allocations. + // + // IMPORTANT: DO NOT make this a member, otherwise every connection + // on the server would use the same buffer simulatenously + byte[] receiveBuffer = new byte[4 + MaxMessageSize]; + + // avoid header[4] allocations + // + // IMPORTANT: DO NOT make this a member, otherwise every connection + // on the server would use the same buffer simulatenously + byte[] headerBuffer = new byte[4]; + + // absolutely must wrap with try/catch, otherwise thread exceptions + // are silent + try + { + // add connected event to pipe + receivePipe.Enqueue(connectionId, EventType.Connected, default); + + // let's talk about reading data. + // -> normally we would read as much as possible and then + // extract as many , messages + // as we received this time. this is really complicated + // and expensive to do though + // -> instead we use a trick: + // Read(2) -> size + // Read(size) -> content + // repeat + // Read is blocking, but it doesn't matter since the + // best thing to do until the full message arrives, + // is to wait. + // => this is the most elegant AND fast solution. + // + no resizing + // + no extra allocations, just one for the content + // + no crazy extraction logic + while (true) + { + // read the next message (blocking) or stop if stream closed + if (!ReadMessageBlocking(stream, MaxMessageSize, headerBuffer, receiveBuffer, out int size)) + // break instead of return so stream close still happens! + break; + + // create arraysegment for the read message + ArraySegment message = new ArraySegment(receiveBuffer, 0, size); + + // send to main thread via pipe + // -> it'll copy the message internally so we can reuse the + // receive buffer for next read! + receivePipe.Enqueue(connectionId, EventType.Data, message); + + // disconnect if receive pipe gets too big for this connectionId. + // -> avoids ever growing queue memory if network is slower + // than input + // -> disconnecting is great for load balancing. better to + // disconnect one connection than risking every + // connection / the whole server + if (receivePipe.Count(connectionId) >= QueueLimit) + { + // log the reason + Log.Warning($"[Telepathy] ReceivePipe reached limit of {QueueLimit} for connectionId {connectionId}. This can happen if network messages come in way faster than we manage to process them. Disconnecting this connection for load balancing."); + + // IMPORTANT: do NOT clear the whole queue. we use one + // queue for all connections. + //receivePipe.Clear(); + + // just break. the finally{} will close everything. + break; + } + } + } + catch (Exception exception) + { + // something went wrong. the thread was interrupted or the + // connection closed or we closed our own connection or ... + // -> either way we should stop gracefully + Log.Info("[Telepathy] ReceiveLoop finished receive function for connectionId=" + connectionId + " reason: " + exception); + } + finally + { + // clean up no matter what + stream.Close(); + client.Close(); + + // add 'Disconnected' message after disconnecting properly. + // -> always AFTER closing the streams to avoid a race condition + // where Disconnected -> Reconnect wouldn't work because + // Connected is still true for a short moment before the stream + // would be closed. + receivePipe.Enqueue(connectionId, EventType.Disconnected, default); + } + } + // thread send function + // note: we really do need one per connection, so that if one connection + // blocks, the rest will still continue to get sends + public static void SendLoop(int connectionId, TcpClient client, MagnificentSendPipe sendPipe, ManualResetEvent sendPending) + { + // get NetworkStream from client + NetworkStream stream = client.GetStream(); + + // avoid payload[packetSize] allocations. size increases dynamically as + // needed for batching. + // + // IMPORTANT: DO NOT make this a member, otherwise every connection + // on the server would use the same buffer simulatenously + byte[] payload = null; + + try + { + while (client.Connected) // try this. client will get closed eventually. + { + // reset ManualResetEvent before we do anything else. this + // way there is no race condition. if Send() is called again + // while in here then it will be properly detected next time + // -> otherwise Send might be called right after dequeue but + // before .Reset, which would completely ignore it until + // the next Send call. + sendPending.Reset(); // WaitOne() blocks until .Set() again + + // dequeue & serialize all + // a locked{} TryDequeueAll is twice as fast as + // ConcurrentQueue, see SafeQueue.cs! + if (sendPipe.DequeueAndSerializeAll(ref payload, out int packetSize)) + { + // send messages (blocking) or stop if stream is closed + if (!SendMessagesBlocking(stream, payload, packetSize)) + // break instead of return so stream close still happens! + break; + } + + // don't choke up the CPU: wait until queue not empty anymore + sendPending.WaitOne(); + } + } + catch (ThreadAbortException) + { + // happens on stop. don't log anything. + } + catch (ThreadInterruptedException) + { + // happens if receive thread interrupts send thread. + } + catch (Exception exception) + { + // something went wrong. the thread was interrupted or the + // connection closed or we closed our own connection or ... + // -> either way we should stop gracefully + Log.Info("[Telepathy] SendLoop Exception: connectionId=" + connectionId + " reason: " + exception); + } + finally + { + // clean up no matter what + // we might get SocketExceptions when sending if the 'host has + // failed to respond' - in which case we should close the connection + // which causes the ReceiveLoop to end and fire the Disconnected + // message. otherwise the connection would stay alive forever even + // though we can't send anymore. + stream.Close(); + client.Close(); + } + } + } +} \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/ThreadFunctions.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/ThreadFunctions.cs.meta new file mode 100644 index 0000000..ea536ac --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/ThreadFunctions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d01598bf851164dc48a24c26913460b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Utils.cs b/Assets/Mirror/Transports/Telepathy/Telepathy/Utils.cs new file mode 100644 index 0000000..8f04fe9 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Utils.cs @@ -0,0 +1,23 @@ +namespace Telepathy +{ + public static class Utils + { + // IntToBytes version that doesn't allocate a new byte[4] each time. + // -> important for MMO scale networking performance. + public static void IntToBytesBigEndianNonAlloc(int value, byte[] bytes, int offset = 0) + { + bytes[offset + 0] = (byte)(value >> 24); + bytes[offset + 1] = (byte)(value >> 16); + bytes[offset + 2] = (byte)(value >> 8); + bytes[offset + 3] = (byte)value; + } + + public static int BytesToIntBigEndian(byte[] bytes) + { + return (bytes[0] << 24) | + (bytes[1] << 16) | + (bytes[2] << 8) | + bytes[3]; + } + } +} diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/Utils.cs.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/Utils.cs.meta new file mode 100644 index 0000000..0a9253b --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/Utils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 951d08c05297f4b3e8feb5bfcab86531 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/VERSION b/Assets/Mirror/Transports/Telepathy/Telepathy/VERSION new file mode 100644 index 0000000..9ec0736 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/VERSION @@ -0,0 +1,62 @@ +V1.8 [2021-06-02] +- fix: Do not set timeouts on listener (fixes https://github.com/vis2k/Mirror/issues/2695) +- fix: #104 - ReadSafely now catches ObjectDisposedException too + +V1.7 [2021-02-20] +- ReceiveTimeout: disabled by default for cases where people use Telepathy by + itself without pings etc. + +V1.6 [2021-02-10] +- configurable ReceiveTimeout to avoid TCPs high default timeout +- Server/Client receive queue limit now disconnects instead of showing a + warning. this is necessary for load balancing to avoid situations where one + spamming connection might fill the queue and slow down everyone else. + +V1.5 [2021-02-05] +- fix: client data races & flaky tests fixed by creating a new client state + object every time we connect. fixes data race where an old dieing thread + might still try to modify the current state +- fix: Client.ReceiveThreadFunction catches and ignores ObjectDisposedException + which can happen if Disconnect() closes and disposes the client, while the + ReceiveThread just starts up and still uses the client. +- Server/Client Tick() optional enabled check for Mirror scene changing + +V1.4 [2021-02-03] +- Server/Client.Tick: limit parameter added to process up to 'limit' messages. + makes Mirror & DOTSNET transports easier to implement +- stability: Server/Client send queue limit disconnects instead of showing a + warning. allows for load balancing. better to kick one connection and keep + the server running than slowing everything down for everyone. + +V1.3 [2021-02-02] +- perf: ReceivePipe: byte[] pool for allocation free receives (╯°□°)╯︵ ┻━┻ +- fix: header buffer, payload buffer data races because they were made non + static earlier. server threads would all access the same ones. + => all threaded code was moved into a static ThreadFunctions class to make it + 100% obvious that there should be no shared state in the future + +V1.2 [2021-02-02] +- Client/Server Tick & OnConnected/OnData/OnDisconnected events instead of + having the outside process messages via GetNextMessage. That's easier for + Mirror/DOTSNET and allows for allocation free data message processing later. +- MagnificientSend/RecvPipe to shield Telepathy from all the complexity +- perf: SendPipe: byte[] pool for allocation free sends (╯°□°)╯︵ ┻━┻ + +V1.1 [2021-02-01] +- stability: added more tests +- breaking: Server/Client.Send: ArraySegment parameter and copy internally so + that Transports don't need to worry about it +- perf: Buffer.BlockCopy instead of Array.Copy +- perf: SendMessageBlocking puts message header directly into payload now +- perf: receiveQueues use SafeQueue instead of ConcurrentQueue to avoid + allocations +- Common: removed static state +- perf: SafeQueue.TryDequeueAll: avoid queue.ToArray() allocations. copy into a + list instead. +- Logger.Log/LogWarning/LogError renamed to Log.Info/Warning/Error +- MaxMessageSize is now specified in constructor to prepare for pooling +- flaky tests are ignored for now +- smaller improvements + +V1.0 +- first stable release \ No newline at end of file diff --git a/Assets/Mirror/Transports/Telepathy/Telepathy/VERSION.meta b/Assets/Mirror/Transports/Telepathy/Telepathy/VERSION.meta new file mode 100644 index 0000000..04c1c8a --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/Telepathy/VERSION.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d942af06608be434dbeeaa58207d20bd +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Transports/Telepathy/TelepathyTransport.cs b/Assets/Mirror/Transports/Telepathy/TelepathyTransport.cs new file mode 100644 index 0000000..fabc189 --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/TelepathyTransport.cs @@ -0,0 +1,274 @@ +// wraps Telepathy for use as HLAPI TransportLayer +using System; +using System.Net; +using System.Net.Sockets; +using UnityEngine; + +// Replaced by Kcp November 2020 +namespace Mirror +{ + [HelpURL("https://github.com/vis2k/Telepathy/blob/master/README.md")] + [DisallowMultipleComponent] + public class TelepathyTransport : Transport, PortTransport + { + // scheme used by this transport + // "tcp4" means tcp with 4 bytes header, network byte order + public const string Scheme = "tcp4"; + + public ushort port = 7777; + public ushort Port { get => port; set => port=value; } + + [Header("Common")] + [Tooltip("Nagle Algorithm can be disabled by enabling NoDelay")] + public bool NoDelay = true; + + [Tooltip("Send timeout in milliseconds.")] + public int SendTimeout = 5000; + + [Tooltip("Receive timeout in milliseconds. High by default so users don't time out during scene changes.")] + public int ReceiveTimeout = 30000; + + [Header("Server")] + [Tooltip("Protect against allocation attacks by keeping the max message size small. Otherwise an attacker might send multiple fake packets with 2GB headers, causing the server to run out of memory after allocating multiple large packets.")] + public int serverMaxMessageSize = 16 * 1024; + + [Tooltip("Server processes a limit amount of messages per tick to avoid a deadlock where it might end up processing forever if messages come in faster than we can process them.")] + public int serverMaxReceivesPerTick = 10000; + + [Tooltip("Server send queue limit per connection for pending messages. Telepathy will disconnect a connection's queues reach that limit for load balancing. Better to kick one slow client than slowing down the whole server.")] + public int serverSendQueueLimitPerConnection = 10000; + + [Tooltip("Server receive queue limit per connection for pending messages. Telepathy will disconnect a connection's queues reach that limit for load balancing. Better to kick one slow client than slowing down the whole server.")] + public int serverReceiveQueueLimitPerConnection = 10000; + + [Header("Client")] + [Tooltip("Protect against allocation attacks by keeping the max message size small. Otherwise an attacker host might send multiple fake packets with 2GB headers, causing the connected clients to run out of memory after allocating multiple large packets.")] + public int clientMaxMessageSize = 16 * 1024; + + [Tooltip("Client processes a limit amount of messages per tick to avoid a deadlock where it might end up processing forever if messages come in faster than we can process them.")] + public int clientMaxReceivesPerTick = 1000; + + [Tooltip("Client send queue limit for pending messages. Telepathy will disconnect if the connection's queues reach that limit in order to avoid ever growing latencies.")] + public int clientSendQueueLimit = 10000; + + [Tooltip("Client receive queue limit for pending messages. Telepathy will disconnect if the connection's queues reach that limit in order to avoid ever growing latencies.")] + public int clientReceiveQueueLimit = 10000; + + Telepathy.Client client; + Telepathy.Server server; + + // scene change message needs to halt message processing immediately + // Telepathy.Tick() has a enabledCheck parameter that we can use, but + // let's only allocate it once. + Func enabledCheck; + + void Awake() + { + // tell Telepathy to use Unity's Debug.Log + Telepathy.Log.Info = Debug.Log; + Telepathy.Log.Warning = Debug.LogWarning; + Telepathy.Log.Error = Debug.LogError; + + // allocate enabled check only once + enabledCheck = () => enabled; + + Debug.Log("TelepathyTransport initialized!"); + } + + public override bool Available() + { + // C#'s built in TCP sockets run everywhere except on WebGL + return Application.platform != RuntimePlatform.WebGLPlayer; + } + + // client + private void CreateClient() + { + // create client + client = new Telepathy.Client(clientMaxMessageSize); + // client hooks + // other systems hook into transport events in OnCreate or + // OnStartRunning in no particular order. the only way to avoid + // race conditions where telepathy uses OnConnected before another + // system's hook (e.g. statistics OnData) was added is to wrap + // them all in a lambda and always call the latest hook. + // (= lazy call) + client.OnConnected = () => OnClientConnected.Invoke(); + client.OnData = (segment) => OnClientDataReceived.Invoke(segment, Channels.Reliable); + // fix: https://github.com/vis2k/Mirror/issues/3287 + // Telepathy may call OnDisconnected twice. + // Mirror may have cleared the callback already, so use "?." here. + client.OnDisconnected = () => OnClientDisconnected?.Invoke(); + + // client configuration + client.NoDelay = NoDelay; + client.SendTimeout = SendTimeout; + client.ReceiveTimeout = ReceiveTimeout; + client.SendQueueLimit = clientSendQueueLimit; + client.ReceiveQueueLimit = clientReceiveQueueLimit; + } + public override bool ClientConnected() => client != null && client.Connected; + public override void ClientConnect(string address) + { + CreateClient(); + client.Connect(address, port); + } + + public override void ClientConnect(Uri uri) + { + CreateClient(); + if (uri.Scheme != Scheme) + throw new ArgumentException($"Invalid url {uri}, use {Scheme}://host:port instead", nameof(uri)); + + int serverPort = uri.IsDefaultPort ? port : uri.Port; + client.Connect(uri.Host, serverPort); + } + public override void ClientSend(ArraySegment segment, int channelId) + { + client?.Send(segment); + + // call event. might be null if no statistics are listening etc. + OnClientDataSent?.Invoke(segment, Channels.Reliable); + } + public override void ClientDisconnect() + { + client?.Disconnect(); + client = null; + // client triggers the disconnected event in client.Tick() which won't be run anymore + OnClientDisconnected?.Invoke(); + } + + // messages should always be processed in early update + public override void ClientEarlyUpdate() + { + // note: we need to check enabled in case we set it to false + // when LateUpdate already started. + // (https://github.com/vis2k/Mirror/pull/379) + if (!enabled) return; + + // process a maximum amount of client messages per tick + // IMPORTANT: check .enabled to stop processing immediately after a + // scene change message arrives! + client?.Tick(clientMaxReceivesPerTick, enabledCheck); + } + + // server + public override Uri ServerUri() + { + UriBuilder builder = new UriBuilder(); + builder.Scheme = Scheme; + builder.Host = Dns.GetHostName(); + builder.Port = port; + return builder.Uri; + } + public override bool ServerActive() => server != null && server.Active; + public override void ServerStart() + { + // create server + server = new Telepathy.Server(serverMaxMessageSize); + + // server hooks + // other systems hook into transport events in OnCreate or + // OnStartRunning in no particular order. the only way to avoid + // race conditions where telepathy uses OnConnected before another + // system's hook (e.g. statistics OnData) was added is to wrap + // them all in a lambda and always call the latest hook. + // (= lazy call) + server.OnConnected = (connectionId) => OnServerConnected.Invoke(connectionId); + server.OnData = (connectionId, segment) => OnServerDataReceived.Invoke(connectionId, segment, Channels.Reliable); + server.OnDisconnected = (connectionId) => OnServerDisconnected.Invoke(connectionId); + + // server configuration + server.NoDelay = NoDelay; + server.SendTimeout = SendTimeout; + server.ReceiveTimeout = ReceiveTimeout; + server.SendQueueLimit = serverSendQueueLimitPerConnection; + server.ReceiveQueueLimit = serverReceiveQueueLimitPerConnection; + + server.Start(port); + } + + public override void ServerSend(int connectionId, ArraySegment segment, int channelId) + { + server?.Send(connectionId, segment); + + // call event. might be null if no statistics are listening etc. + OnServerDataSent?.Invoke(connectionId, segment, Channels.Reliable); + } + public override void ServerDisconnect(int connectionId) => server?.Disconnect(connectionId); + public override string ServerGetClientAddress(int connectionId) + { + try + { + return server?.GetClientAddress(connectionId); + } + catch (SocketException) + { + // using server.listener.LocalEndpoint causes an Exception + // in UWP + Unity 2019: + // Exception thrown at 0x00007FF9755DA388 in UWF.exe: + // Microsoft C++ exception: Il2CppExceptionWrapper at memory + // location 0x000000E15A0FCDD0. SocketException: An address + // incompatible with the requested protocol was used at + // System.Net.Sockets.Socket.get_LocalEndPoint () + // so let's at least catch it and recover + return "unknown"; + } + } + public override void ServerStop() + { + server?.Stop(); + server = null; + } + + // messages should always be processed in early update + public override void ServerEarlyUpdate() + { + // note: we need to check enabled in case we set it to false + // when LateUpdate already started. + // (https://github.com/vis2k/Mirror/pull/379) + if (!enabled) return; + + // process a maximum amount of server messages per tick + // IMPORTANT: check .enabled to stop processing immediately after a + // scene change message arrives! + server?.Tick(serverMaxReceivesPerTick, enabledCheck); + } + + // common + public override void Shutdown() + { + Debug.Log("TelepathyTransport Shutdown()"); + client?.Disconnect(); + client = null; + server?.Stop(); + server = null; + } + + public override int GetMaxPacketSize(int channelId) + { + return serverMaxMessageSize; + } + + public override string ToString() + { + if (server != null && server.Active && server.listener != null) + { + // printing server.listener.LocalEndpoint causes an Exception + // in UWP + Unity 2019: + // Exception thrown at 0x00007FF9755DA388 in UWF.exe: + // Microsoft C++ exception: Il2CppExceptionWrapper at memory + // location 0x000000E15A0FCDD0. SocketException: An address + // incompatible with the requested protocol was used at + // System.Net.Sockets.Socket.get_LocalEndPoint () + // so let's use the regular port instead. + return $"Telepathy Server port: {port}"; + } + else if (client != null && (client.Connecting || client.Connected)) + { + return $"Telepathy Client port: {port}"; + } + return "Telepathy (inactive/disconnected)"; + } + } +} diff --git a/Assets/Mirror/Transports/Telepathy/TelepathyTransport.cs.meta b/Assets/Mirror/Transports/Telepathy/TelepathyTransport.cs.meta new file mode 100644 index 0000000..99cde3e --- /dev/null +++ b/Assets/Mirror/Transports/Telepathy/TelepathyTransport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c7424c1070fad4ba2a7a96b02fbeb4bb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 1000 + icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Mirror/Version.txt b/Assets/Mirror/Version.txt new file mode 100644 index 0000000..18b6a57 --- /dev/null +++ b/Assets/Mirror/Version.txt @@ -0,0 +1 @@ +81.4.0 \ No newline at end of file diff --git a/Assets/Mirror/Version.txt.meta b/Assets/Mirror/Version.txt.meta new file mode 100644 index 0000000..097f259 --- /dev/null +++ b/Assets/Mirror/Version.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: c6b1f72568a9340178b4c34608fbdbc3 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: